WatchTask   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 153
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 8

Importance

Changes 0
Metric Value
wmc 21
cbo 8
dl 0
loc 153
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A configure() 0 9 1
B run() 0 17 5
B watchForChanges() 0 27 4
A checkFile() 0 8 2
A getJobs() 0 10 2
A fetchJobs() 0 5 1
B buildJobs() 0 17 5
1
<?php
2
3
/**
4
 * This file is part of Bldr.io
5
 *
6
 * (c) Aaron Scherer <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE
10
 */
11
12
namespace Bldr\Block\Watch\Task;
13
14
use Bldr\Block\Core\Task\AbstractTask;
15
use Bldr\Block\Core\Task\Traits\FinderAwareTrait;
16
use Bldr\Definition\JobDefinition;
17
use Bldr\Definition\TaskDefinition;
18
use Bldr\Exception\TaskRuntimeException;
19
use Bldr\Registry\JobRegistry;
20
use Symfony\Component\Console\Output\OutputInterface;
21
use Symfony\Component\Finder\SplFileInfo;
22
23
/**
24
 * @author Aaron Scherer <[email protected]>
25
 */
26
class WatchTask extends AbstractTask
27
{
28
    use FinderAwareTrait;
29
30
    /**
31
     * @var JobRegistry $registry
32
     */
33
    private $registry;
34
35
    /**
36
     * @var array $config
37
     */
38
    private $config;
39
40
    /**
41
     * @param JobRegistry $registry
42
     * @param array       $config
43
     */
44
    public function __construct(JobRegistry $registry, array $config)
45
    {
46
        $this->registry = $registry;
47
        $this->config   = $config;
48
    }
49
50
    /**
51
     * Configures the Task
52
     */
53
    public function configure()
54
    {
55
        $this->setName('watch')
56
            ->setDescription('Watches the filesystem for changes')
57
            ->addParameter('src', true, 'Source to watch')
58
            ->addParameter('profile', false, 'Profile to run on filesystem change')
59
            ->addParameter('job', false, 'Job to run on filesystem change')
60
        ;
61
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66
    public function run(OutputInterface $output)
67
    {
68
        if (getenv('TRAVIS')) {
69
            throw new \RuntimeException("Travis does not support running the watch task.");
70
        }
71
72
        if (!$this->hasParameter('task') && !$this->hasParameter('profile')) {
73
            throw new \Exception("Watch must have either a task, or a profile");
74
        }
75
76
        $source = $this->getParameter('src');
77
        if (!is_array($source)) {
78
            throw new TaskRuntimeException($this->getName(), "`src` must be an array");
79
        }
80
81
        $this->watchForChanges($output, $this->getFiles($source));
82
    }
83
84
    /**
85
     * @param OutputInterface $output
86
     * @param SplFileInfo[]   $files
87
     *
88
     * @return void
89
     */
90
    private function watchForChanges(OutputInterface $output, array $files)
91
    {
92
        $output->writeln("Watching for changes");
93
94
        $previously = [];
95
        while (true) {
96
            foreach ($files as $file) {
97
                /** @var SplFileInfo $file */
98
                if ($this->checkFile($file->getRealPath(), $previously)) {
99
                    $output->writeln(
100
                        sprintf(
101
                            "<info>>>>></info> <comment>The following file changed:</comment> <info>%s</info>",
102
                            $file->getPathname()
103
                        )
104
                    );
105
106
                    $this->getJobs();
107
                    $this->registry->addJob($this->registry->getNewJob());
0 ignored issues
show
Security Bug introduced by
It seems like $this->registry->getNewJob() targeting Bldr\Registry\JobRegistry::getNewJob() can also be of type false; however, Bldr\Registry\JobRegistry::addJob() does only seem to accept object<Bldr\Definition\JobDefinition>, did you maybe forget to handle an error condition?
Loading history...
108
109
                    return;
110
                }
111
            }
112
            sleep(1);
113
        }
114
115
        return;
116
    }
117
118
    /**
119
     * @param string $name
120
     * @param array  $previously
121
     *
122
     * @return bool
123
     */
124
    private function checkFile($name, array &$previously)
125
    {
126
        $hash              = sha1_file($name);
127
        $changed           = array_key_exists($name, $previously) ? ($previously[$name] !== $hash) : false;
128
        $previously[$name] = $hash;
129
130
        return $changed;
131
    }
132
133
    /**
134
     * Fetches the tasks for either the profile, or the passed task
135
     */
136
    private function getJobs()
137
    {
138
        if ($this->hasParameter('profile')) {
139
            $this->fetchJobs($this->getParameter('profile'));
0 ignored issues
show
Bug introduced by
It seems like $this->getParameter('profile') targeting Bldr\Block\Core\Task\AbstractTask::getParameter() can also be of type array; however, Bldr\Block\Watch\Task\WatchTask::fetchJobs() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
140
141
            return;
142
        }
143
144
        $this->buildJobs([$this->getParameter('job')]);
0 ignored issues
show
Documentation introduced by
array($this->getParameter('job')) is of type array<integer,array|string,{"0":"array|string"}>, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
145
    }
146
147
    /**
148
     * @param string $profileName
149
     */
150
    public function fetchJobs($profileName)
151
    {
152
        $profile = $this->config['profiles'][$profileName];
153
        $this->buildJobs($profile['jobs']);
154
    }
155
156
    /**
157
     * @param string[] $names
158
     *
159
     * @return array
160
     */
161
    public function buildJobs($names)
162
    {
163
        foreach ($names as $name) {
164
            $jobInfo     = $this->config['jobs'][$name];
165
            $description = isset($jobInfo['description']) ? $jobInfo['description'] : "";
166
167
            $job = new JobDefinition($name, $description);
168
            foreach ($jobInfo['tasks'] as $taskInfo) {
169
                $task = new TaskDefinition($taskInfo['type']);
170
                $task->setContinueOnError(isset($taskInfo['continueOnError']) ? $taskInfo['continueOnError'] : false);
171
                unset($taskInfo['type'], $taskInfo['continueOnError']);
172
                $task->setParameters($taskInfo);
173
                $job->addTask($task);
174
            }
175
            $this->registry->addJob($job);
176
        }
177
    }
178
}
179