Skip to content

Instantly share code, notes, and snippets.

@henrikbjorn
Created September 5, 2011 10:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrikbjorn/1194683 to your computer and use it in GitHub Desktop.
Save henrikbjorn/1194683 to your computer and use it in GitHub Desktop.
Symfony2 autotest runner (Using everzet ResourceWatcher component)
<?php
namespace Diveshare\DiveshareBundle\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Diveshare\DiveshareBundle\Test\Autorunner;
class AutotestCommand extends \Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand
{
protected function configure()
{
$this
->setName('diveshare:autotest')
->setDescription('Autorun your PHPUnit tests when a .php file is modified.')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$runner = new Autorunner($this->getContainer()->getParameter('kernel.root_dir') . '/../src');
$runner->run($output);
}
}
<?php
namespace Diveshare\DiveshareBundle\Test;
use Symfony\Component\ResourceWatcher\ResourceWatcher;
use Symfony\Component\ResourceWatcher\Event\Event;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Watches resources and runs phpunit cli when a php file changes.
*
* @package DiveshareBundle
*/
class Autorunner
{
/**
* @var string
*/
protected $dir;
public function __construct($dir)
{
$this->dir = realpath($dir);
}
public function run(OutputInterface $output)
{
$watcher = new ResourceWatcher();
$watcher->track(new DirectoryResource(realpath($this->dir)), function ($event) use ($output) {
$fileName = (string) $event->getResource();
if (preg_match('/^(.*Bundle\/)(.*)(\.php)$/', $fileName, $matches)) {
if ('Test' !== substr($matches[2], -4)) {
$fileName = $matches[1] . 'Tests/' . $matches[2] . 'Test' . $matches[3];
}
$process = new Process('phpunit ' . escapeshellarg($fileName), $this->dir . '/../');
$process->run(function ($type, $data) use ($output) {
$output->writeln($data);
});
}
});
$watcher->start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment