MixinCallNode::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 5
1
<?php
2
3
/*
4
 * This file is part of the ILess
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace ILess\Node;
11
12
use ILess\Context;
13
use ILess\DefaultFunc;
14
use ILess\Exception\Exception;
15
use ILess\Exception\CompilerException;
16
use ILess\Exception\ParserException;
17
use ILess\FileInfo;
18
use ILess\Node;
19
use ILess\Visitor\VisitorInterface;
20
21
/**
22
 * Mixin call.
23
 */
24
class MixinCallNode extends Node
25
{
26
    /**
27
     * Node type.
28
     *
29
     * @var string
30
     */
31
    protected $type = 'MixinCall';
32
33
    /**
34
     * The selector.
35
     *
36
     * @var SelectorNode
37
     */
38
    public $selector;
39
40
    /**
41
     * Array of arguments.
42
     *
43
     * @var array
44
     */
45
    public $arguments = [];
46
47
    /**
48
     * Current index.
49
     *
50
     * @var int
51
     */
52
    public $index = 0;
53
54
    /**
55
     * The important flag.
56
     *
57
     * @var bool
58
     */
59
    public $important = false;
60
61
    /**
62
     * Constructor.
63
     *
64
     * @param array $elements The elements
65
     * @param array $arguments The array of arguments
66
     * @param int $index The current index
67
     * @param FileInfo $currentFileInfo
68
     * @param bool $important
69
     */
70
    public function __construct(
71
        array $elements,
72
        array $arguments = [],
73
        $index = 0,
74
        FileInfo $currentFileInfo = null,
75
        $important = false
76
    ) {
77
        $this->selector = new SelectorNode($elements);
78
79
        $this->arguments = $arguments;
80
        $this->index = $index;
81
        $this->currentFileInfo = $currentFileInfo;
82
        $this->important = (boolean) $important;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function accept(VisitorInterface $visitor)
89
    {
90
        if ($this->selector) {
91
            $this->selector = $visitor->visit($this->selector);
92
        }
93
94
        if ($this->arguments) {
95
            $this->arguments = $visitor->visitArray($this->arguments);
0 ignored issues
show
Documentation Bug introduced by
It seems like $visitor->visitArray($this->arguments) of type * is incompatible with the declared type array of property $arguments.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
96
        }
97
    }
98
99
    /**
100
     * Compiles the node.
101
     *
102
     * @param Context $context The context
103
     * @param array|null $arguments Array of arguments
104
     * @param bool|null $important Important flag
105
     *
106
     * @return Node
107
     *
108
     * @throws
109
     */
110
    public function compile(Context $context, $arguments = null, $important = null)
111
    {
112
        $rules = [];
113
        $match = false;
114
        $isOneFound = false;
115
        $candidates = [];
116
        $conditionResult = [];
117
118
        $args = [];
119
        foreach ($this->arguments as $a) {
120
            $aValue = $a['value']->compile($context);
121
            if ($a['expand'] && is_array($aValue->value)) {
122
                $aValue = $aValue->value;
123
                for ($m = 0; $m < count($aValue); ++$m) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
124
                    $args[] = ['value' => $aValue[$m]];
125
                }
126
            } else {
127
                $args[] = [
128
                    'name' => $a['name'],
129
                    'value' => $aValue,
130
                ];
131
            }
132
        }
133
134
        /*
135
         * @param $rule
136
         * @return bool
137
         */
138
        $noArgumentsFilter = function ($rule) use ($context) {
139
            /* @var $rule RulesetNode */
140
            return $rule->matchArgs([], $context);
141
        };
142
143
        // return values for the function
144
        $defFalseEitherCase = -1;
145
        $defNone = 0;
146
        $defTrue = 1;
147
        $defFalse = 2;
148
149
        /*
150
         * Calculate
151
         * @param $mixin
152
         * @param $mixinPath
153
         * @return int
154
         */
155
        $calcDefGroup = function ($mixin, $mixinPath) use (
156
            $context,
157
            $args,
158
            $defTrue,
159
            $defFalse,
160
            $defNone,
161
            $defFalseEitherCase,
162
            &$conditionResult
163
        ) {
164
            $namespace = null;
165
            for ($f = 0; $f < 2; ++$f) {
166
                $conditionResult[$f] = true;
167
                DefaultFunc::value($f);
168
                for ($p = 0; $p < count($mixinPath) && $conditionResult[$f]; ++$p) {
169
                    $namespace = $mixinPath[$p];
170
                    if ($namespace instanceof ConditionMatchableInterface) {
171
                        $conditionResult[$f] = $conditionResult[$f] && $namespace->matchCondition([], $context);
172
                    }
173
                }
174
                if ($mixin instanceof ConditionMatchableInterface) {
175
                    $conditionResult[$f] = $conditionResult[$f] && $mixin->matchCondition($args, $context);
176
                }
177
            }
178
179
            if ($conditionResult[0] || $conditionResult[1]) {
180
                if ($conditionResult[0] != $conditionResult[1]) {
181
                    return $conditionResult[1] ? $defTrue : $defFalse;
182
                }
183
184
                return $defNone;
185
            }
186
187
            return $defFalseEitherCase;
188
        };
189
190
        foreach ($context->frames as $frame) {
191
            /* @var $frame RulesetNode */
192
            $mixins = $frame->find($this->selector, $context, null, $noArgumentsFilter);
193
            if ($mixins) {
194
                $isOneFound = true;
195
                for ($m = 0; $m < count($mixins); ++$m) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
196
                    $mixin = $mixins[$m]['rule'];
197
                    $mixinPath = $mixins[$m]['path'];
198
                    $isRecursive = false;
199
                    foreach ($context->frames as $recurFrame) {
200
                        if ((!($mixin instanceof MixinDefinitionNode)) && ($mixin === $recurFrame->originalRuleset || $mixin === $recurFrame)) {
201
                            $isRecursive = true;
202
                            break;
203
                        }
204
                    }
205
206
                    if ($isRecursive) {
207
                        continue;
208
                    }
209
210
                    if ($mixin->matchArgs($args, $context)) {
211
                        $candidate = [
212
                            'mixin' => $mixin,
213
                            'group' => $calcDefGroup($mixin, $mixinPath),
214
                        ];
215
216
                        if ($candidate['group'] !== $defFalseEitherCase) {
217
                            $candidates[] = $candidate;
218
                        }
219
220
                        $match = true;
221
                    }
222
                }
223
224
                DefaultFunc::reset();
225
226
                $count = [0, 0, 0];
227
                for ($m = 0; $m < count($candidates); ++$m) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
228
                    ++$count[$candidates[$m]['group']];
229
                }
230
231
                if ($count[$defNone] > 0) {
232
                    $defaultResult = $defFalse;
233
                } else {
234
                    $defaultResult = $defTrue;
235
                    if (($count[$defTrue] + $count[$defFalse]) > 1) {
236
                        throw new ParserException(sprintf('Ambiguous use of `default()` found when matching for `%s`',
237
                            $this->formatArgs($args)),
238
                            $this->index,
239
                            $this->currentFileInfo
240
                        );
241
                    }
242
                }
243
244
                for ($m = 0; $m < count($candidates); ++$m) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
245
                    $candidate = $candidates[$m]['group'];
246
                    if (($candidate === $defNone) || ($candidate === $defaultResult)) {
247
                        try {
248
                            $mixin = $candidates[$m]['mixin'];
249
                            if (!($mixin instanceof MixinDefinitionNode)) {
250
                                $originalRuleset = $mixin->originalRuleset ? $mixin->originalRuleset : $mixin;
251
                                $mixin = new MixinDefinitionNode('', [], $mixin->rules, null, false);
252
                                $mixin->originalRuleset = $originalRuleset;
253
                            }
254
                            $compiled = $mixin->compileCall($context, $args, $this->important);
255
                            $rules = array_merge($rules, $compiled->rules);
256
                        } catch (Exception $e) {
257
                            throw new CompilerException($e->getMessage(), $this->index, $this->currentFileInfo,
258
                                $e);
259
                        }
260
                    }
261
                }
262
263
                if ($match) {
264
                    if (!$this->currentFileInfo || !$this->currentFileInfo->reference) {
265
                        foreach ($rules as $rule) {
266
                            if ($rule instanceof MarkableAsReferencedInterface) {
267
                                $rule->markReferenced();
268
                            }
269
                        }
270
                    }
271
272
                    return $rules;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $rules; (array) is incompatible with the return type declared by the interface ILess\Node\CompilableInterface::compile of type ILess\Node.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
273
                }
274
            }
275
        }
276
277
        if ($isOneFound) {
278
            throw new CompilerException(
279
                sprintf('No matching definition was found for `%s`', $this->formatArgs($args)),
280
                $this->index, $this->currentFileInfo);
281
        } else {
282
            throw new CompilerException(
283
                sprintf('%s is undefined', trim($this->selector->toCSS($context))), $this->index,
284
                $this->currentFileInfo);
285
        }
286
    }
287
288
    /**
289
     * Format arguments to be used for exception message.
290
     *
291
     * @param array $args
292
     *
293
     * @return string
294
     */
295
    private function formatArgs($args)
296
    {
297
        $context = new Context();
298
        $message = $argsFormatted = [];
299
        $message[] = trim($this->selector->toCSS($context));
300
301
        if ($args) {
302
            $message[] = '(';
303
            foreach ($args as $a) {
304
                $argValue = '';
305
                if (isset($a['name'])) {
306
                    $argValue .= $a['name'] . ':';
307
                }
308
                if ($a['value'] instanceof GenerateCSSInterface) {
309
                    $argValue .= $a['value']->toCSS($context);
310
                } else {
311
                    $argValue .= '???';
312
                }
313
                $argsFormatted[] = $argValue;
314
            }
315
            $message[] = implode(', ', $argsFormatted);
316
            $message[] = ')';
317
        }
318
319
        return implode('', $message);
320
    }
321
}
322