d7940ac94b3283073389ae73fb76d9b14376036c
[yaffs-website] / vendor / consolidation / robo / src / Task / Base / Watch.php
1 <?php
2 namespace Robo\Task\Base;
3
4 use Lurker\Event\FilesystemEvent;
5 use Lurker\ResourceWatcher;
6 use Robo\Result;
7 use Robo\Task\BaseTask;
8
9 /**
10  * Runs task when specified file or dir was changed.
11  * Uses Lurker library.
12  *
13  * ``` php
14  * <?php
15  * $this->taskWatch()
16  *  ->monitor('composer.json', function() {
17  *      $this->taskComposerUpdate()->run();
18  * })->monitor('src', function() {
19  *      $this->taskExec('phpunit')->run();
20  * })->run();
21  * ?>
22  * ```
23  */
24 class Watch extends BaseTask
25 {
26     /**
27      * @var \Closure
28      */
29     protected $closure;
30
31     /**
32      * @var array
33      */
34     protected $monitor = [];
35
36     /**
37      * @var object
38      */
39     protected $bindTo;
40
41     /**
42      * @param $bindTo
43      */
44     public function __construct($bindTo)
45     {
46         $this->bindTo = $bindTo;
47     }
48
49     /**
50      * @param string|string[] $paths
51      * @param \Closure $callable
52      *
53      * @return $this
54      */
55     public function monitor($paths, \Closure $callable)
56     {
57         if (!is_array($paths)) {
58             $paths = [$paths];
59         }
60         $this->monitor[] = [$paths, $callable];
61         return $this;
62     }
63
64     /**
65      * {@inheritdoc}
66      */
67     public function run()
68     {
69         if (!class_exists('Lurker\\ResourceWatcher')) {
70             return Result::errorMissingPackage($this, 'ResourceWatcher', 'henrikbjorn/lurker');
71         }
72
73         $watcher = new ResourceWatcher();
74
75         foreach ($this->monitor as $k => $monitor) {
76             /** @var \Closure $closure */
77             $closure = $monitor[1];
78             $closure->bindTo($this->bindTo);
79             foreach ($monitor[0] as $i => $dir) {
80                 $watcher->track("fs.$k.$i", $dir, FilesystemEvent::MODIFY);
81                 $this->printTaskInfo('Watching {dir} for changes...', ['dir' => $dir]);
82                 $watcher->addListener("fs.$k.$i", $closure);
83             }
84         }
85
86         $watcher->start();
87         return Result::success($this);
88     }
89 }