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