Task   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 207
Duplicated Lines 9.66 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 30
c 5
b 0
f 2
lcom 1
cbo 3
dl 20
loc 207
ccs 0
cts 130
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A getName() 0 4 1
A getHelp() 0 4 1
B compile() 0 31 3
F compileBody() 20 77 14
B getArguments() 0 18 6
A getOptions() 0 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @author Gerard van Helden <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
7
namespace Zicht\Tool\Container;
8
9
use Zicht\Tool\Script\Buffer;
10
use Zicht\Tool\Util;
11
12
/**
13
 * Compilable node that represents an executable task
14
 */
15
class Task extends Declaration
16
{
17
    /**
18
     * Construct the task with the provided array as task definition
19
     *
20
     * @param array $path
21
     * @param array $node
22
     */
23
    public function __construct($path, $node)
24
    {
25
        parent::__construct($path);
26
27
        if (strpos(end($this->path), '.') !== false) {
28
            $end = array_pop($this->path);
29
            $this->path = array_merge($this->path, explode('.', $end));
30
        }
31
        $this->taskDef = $node;
0 ignored issues
show
Bug introduced by
The property taskDef does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
32
    }
33
34
35
    /**
36
     * Returns the task name.
37
     *
38
     * @return string
39
     */
40
    public function getName()
41
    {
42
        return join('.', array_slice($this->path, 1));
43
    }
44
45
46
    /**
47
     * Returns the task help
48
     *
49
     * @return mixed
50
     */
51
    public function getHelp()
52
    {
53
        return $this->taskDef['help'];
54
    }
55
56
57
    /**
58
     * Compiles the task initialization code into the buffer.
59
     *
60
     * @param \Zicht\Tool\Script\Buffer $buffer
61
     * @return void
62
     */
63
    public function compile(Buffer $buffer)
64
    {
65
        parent::compile($buffer);
66
        if (substr($this->getName(), 0, 1) !== '_') {
67
            $buffer
68
                ->writeln('try {')
69
                ->indent(1)
70
                    ->writeln('$z->addCommand(')
71
                    ->indent(1)
72
                        ->write('new \Zicht\Tool\Command\TaskCommand(')
73
                        ->asPhp($this->getName())
74
                        ->raw(', ')
75
                        ->asPhp($this->getArguments(true))
76
                        ->raw(', ')
77
                        ->asPhp($this->getOptions())
78
                        ->raw(', ')
79
                        ->asPhp($this->taskDef['flags'])
80
                        ->raw(', ')
81
                        ->asPhp($this->getHelp() ? $this->getHelp() : "(no help available for this task)")
82
                        ->raw(')')->eol()
83
                        ->indent(-1)
84
                    ->writeln(');')
85
                    ->indent(-1)
86
                ->writeln('} catch (\Exception $e) {')
87
                    ->indent(1)
88
                    ->writeln('throw new \Zicht\Tool\Container\ConfigurationException("Error while initializing task \'' . $this->getName() . '\'", 0, $e);')
89
                    ->indent(-1)
90
                ->writeln('}')
91
            ;
92
        }
93
    }
94
95
96
    /**
97
     * Compile the node
98
     *
99
     * @param Buffer $buffer
100
     * @return void
101
     */
102
    public function compileBody(Buffer $buffer)
103
    {
104
        $buffer->writeln('$ret = null;');
105
106
        foreach ($this->taskDef['flags'] as $flag => $value) {
107
            $buffer
108
                ->write('if (null === $z->resolve(')->asPhp($flag)->raw(', false)) {')->eol()
109
                ->indent(1)
110
                ->write('$z->set(')->asPhp($flag)->raw(', ')->asPhp($value)->raw(');')->eol()
111
                ->indent(-1)
112
                ->writeln('}')
113
            ;
114
        }
115
        foreach ($this->taskDef['args'] as $node) {
116
            $node->compile($buffer);
117
        }
118
        foreach ($this->taskDef['opts'] as $node) {
119
            $node->compile($buffer);
120
        }
121
        foreach ($this->taskDef['set'] as $node) {
122
            $node->compile($buffer);
123
        }
124
        $buffer->writeln('$skip = false;');
125
        foreach (array('pre', 'do', 'post') as $scope) {
126
            if ($scope === 'do') {
127 View Code Duplication
                if (!empty($this->taskDef['unless'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
                    $buffer->write('if (!$z->resolve(\'FORCE\') &&');
129
                    $this->taskDef['unless']->compile($buffer);
130
                    $buffer->raw(') {')->eol()->indent(1);
131
                    $echoStr = sprintf('echo "%s skipped", because \'unless\' evaluated to true.', join('.', $this->path));
132
                    $buffer->writeln(sprintf('$z->cmd(%s);', Util::toPhp($echoStr)));
133
                    $buffer->writeln('$skip = true;');
134
                    $buffer->indent(-1);
135
                    $buffer->writeln('}');
136
                }
137 View Code Duplication
                if (!empty($this->taskDef['if'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
                    $buffer->write('if (!$z->resolve(\'FORCE\') && !(');
139
                    $this->taskDef['if']->compile($buffer);
140
                    $buffer->raw(') ) {')->eol()->indent(1);
141
                    $echoStr = sprintf('echo "%s skipped", because \'if\' evaluated to false.', join('.', $this->path));
142
                    $buffer->writeln(sprintf('$z->cmd(%s);', Util::toPhp($echoStr)));
143
                    $buffer->writeln('$skip = true;');
144
                    $buffer->indent(-1);
145
                    $buffer->writeln('}');
146
                }
147
148
                if (!empty($this->taskDef['assert'])) {
149
                    $buffer->write('if (!(');
150
                    $this->taskDef['assert']->compile($buffer);
151
                    $buffer->raw(')) {')->eol()->indent(1);
152
                    $buffer->writeln('throw new \RuntimeException("Assertion failed");');
153
                    $buffer->indent(-1)->writeln('}');
154
                }
155
156
                $buffer->writeln('if (!$skip) {');
157
                $buffer->indent(1);
158
            }
159
            foreach ($this->taskDef[$scope] as $i => $cmd) {
160
                $buffer->write('Debug::enterScope(')->asPhp($scope . '[' . $i . ']')->raw(');')->eol();
161
                if ($cmd) {
162
                    $cmd->compile($buffer);
163
                }
164
                $buffer->write('Debug::exitScope(')->asPhp($scope . '[' . $i . ']')->raw(');')->eol();
165
            }
166
167
            if ($scope === 'post') {
168
                $buffer->indent(-1);
169
                $buffer->writeln('}');
170
            }
171
        }
172
        if (!empty($this->taskDef['yield'])) {
173
            $buffer->writeln('$ret = ');
174
            $this->taskDef['yield']->compile($buffer);
175
            $buffer->write(';');
176
        }
177
        $buffer->writeln('return $ret;');
178
    }
179
180
181
    /**
182
     * Returns all variables that can be injected into the task.
183
     *
184
     * @param bool $onlyPublic
185
     * @return array
186
     */
187
    public function getArguments($onlyPublic = true)
188
    {
189
        $ret = array();
190
        if (isset($this->taskDef['args'])) {
191
            foreach ($this->taskDef['args'] as $name => $expr) {
192
                if ($onlyPublic && $name{0} === '_') {
193
                    // Variables prefixed with an underscore are considered non public
194
                    continue;
195
                }
196
                if ($expr->conditional) {
197
                    // if the part after the question mark is empty, the variable is assumed to be required
198
                    // for execution of the task
199
                    $ret[$name] = ($expr->nodes[0] === null);
200
                }
201
            }
202
        }
203
        return $ret;
204
    }
205
206
    /**
207
     * Returns all variables that can be injected into the task.
208
     *
209
     * @return array
210
     */
211
    public function getOptions()
212
    {
213
        $ret = array();
214
        if (!empty($this->taskDef['opts'])) {
215
            foreach ($this->taskDef['opts'] as $opt) {
216
                $ret[] = $opt->name;
217
            }
218
        }
219
        return $ret;
220
    }
221
}
222