Completed
Pull Request — master (#470)
by Claus
01:32
created

AbstractComponent::getNamedChild()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 1
dl 0
loc 20
rs 8.9777
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
namespace TYPO3Fluid\Fluid\Component;
4
5
/*
6
 * This file belongs to the package "TYPO3 Fluid".
7
 * See LICENSE.txt that was shipped with this package.
8
 */
9
10
use TYPO3Fluid\Fluid\Component\Argument\ArgumentCollection;
11
use TYPO3Fluid\Fluid\Component\Argument\ArgumentDefinition;
12
use TYPO3Fluid\Fluid\Component\Error\ChildNotFoundException;
13
use TYPO3Fluid\Fluid\Core\Parser\Exception;
14
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\RootNode;
15
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\TextNode;
16
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
17
use TYPO3Fluid\Fluid\ViewHelpers\ArgumentViewHelper;
18
use TYPO3Fluid\Fluid\ViewHelpers\ParameterViewHelper;
19
20
/**
21
 * Base Component Class
22
 *
23
 * Contains standard implementations for some of the more
24
 * universal methods a Component supports, e.g. handling
25
 * of child components and resolving of named children.
26
 */
27
abstract class AbstractComponent implements ComponentInterface
28
{
29
    /**
30
     * Unnamed children indexed by numeric position in array
31
     *
32
     * @var ComponentInterface[]
33
     */
34
    protected $children = [];
35
36
    /**
37
     * @var string|null
38
     */
39
    protected $name;
40
41
    /**
42
     * Specifies whether the escaping interceptors should be disabled or enabled for the result of renderChildren() calls within this ViewHelper
43
     * @see isChildrenEscapingEnabled()
44
     *
45
     * Note: If this is NULL the value of $this->escapingInterceptorEnabled is considered for backwards compatibility
46
     *
47
     * @var boolean|null
48
     */
49
    protected $escapeChildren = null;
50
51
    /**
52
     * Specifies whether the escaping interceptors should be disabled or enabled for the render-result of this ViewHelper
53
     * @see isOutputEscapingEnabled()
54
     *
55
     * @var boolean|null
56
     */
57
    protected $escapeOutput = null;
58
59
    /**
60
     * @var ArgumentCollection|null
61
     */
62
    protected $arguments = null;
63
64
    private $_lastAddedWasTextNode = false;
65
66
    public function onOpen(RenderingContextInterface $renderingContext): ComponentInterface
67
    {
68
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (TYPO3Fluid\Fluid\Component\AbstractComponent) is incompatible with the return type declared by the interface TYPO3Fluid\Fluid\Compone...ponentInterface::onOpen of type self.

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...
69
    }
70
71
    public function onClose(RenderingContextInterface $renderingContext): ComponentInterface
72
    {
73
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (TYPO3Fluid\Fluid\Component\AbstractComponent) is incompatible with the return type declared by the interface TYPO3Fluid\Fluid\Compone...onentInterface::onClose of type self.

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...
74
    }
75
76
    public function getName(): ?string
77
    {
78
        return $this->name;
79
    }
80
81
    public function setArguments(ArgumentCollection $arguments): ComponentInterface
82
    {
83
        $this->arguments = $arguments;
84
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (TYPO3Fluid\Fluid\Component\AbstractComponent) is incompatible with the return type declared by the interface TYPO3Fluid\Fluid\Compone...Interface::setArguments of type self.

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...
85
    }
86
87
    public function getArguments(): ArgumentCollection
88
    {
89
        return $this->arguments ?? ($this->arguments = new ArgumentCollection());
90
    }
91
92
    public function addChild(ComponentInterface $component): ComponentInterface
93
    {
94
        if ($component instanceof ParameterViewHelper) {
95
            // The child is a parameter declaration. Use the Component's argument values to create and
96
            // add a new ArgumentDefinition to this component.
97
            $arguments = $this->getArguments();
98
            $context = $arguments->getRenderingContext();
99
            $parameters = $component->getArguments()->setRenderingContext($context);
100
            $arguments->addDefinition(
101
                new ArgumentDefinition(
102
                    $parameters['name'],
103
                    $parameters['type'],
104
                    $parameters['description'] ?? 'Argument ' . $parameters['name'],
105
                    $parameters['required'],
106
                    $parameters['default'] ?? null
107
                )
108
            );
109
        } elseif ($component instanceof RootNode) {
110
            // Assimilate child nodes instead of allowing a root node inside a root node.
111
            foreach ($component->getChildren() as $node) {
112
                $this->addChild($node);
113
            }
114
        } elseif ($component instanceof TextNode && $this->_lastAddedWasTextNode) {
115
            end($this->children)->appendText($component->getText());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TYPO3Fluid\Fluid\Component\ComponentInterface as the method appendText() does only exist in the following implementations of said interface: TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\TextNode.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
116
        } else {
117
            $this->children[] = $component;
118
            $this->_lastAddedWasTextNode = $component instanceof TextNode;
119
        }
120
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (TYPO3Fluid\Fluid\Component\AbstractComponent) is incompatible with the return type declared by the interface TYPO3Fluid\Fluid\Compone...nentInterface::addChild of type self.

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...
121
    }
122
123
    public function getNamedChild(string $name): ComponentInterface
124
    {
125
        $parts = explode('.', $name, 2);
126
        foreach (array_reverse($this->children) as $child) {
127
            if ($child->getName() === $parts[0]) {
128
                if (isset($parts[1])) {
129
                    return $child->getNamedChild($parts[1]);
130
                }
131
                return $child;
132
            }
133
            if ($child instanceof TransparentComponentInterface) {
134
                try {
135
                    return $child->getNamedChild($name);
136
                } catch (ChildNotFoundException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
137
138
                }
139
            }
140
        }
141
        throw new ChildNotFoundException(sprintf('Child with name "%s" not found', $name), 1562757835);
142
    }
143
144
    /**
145
     * Gets a new RootNode with children copied from this current
146
     * Component. Scans for children of a specific type (a Component
147
     * class name like a ViewHelper class name) and an optional name
148
     * which if not-null must also be matched (much like getNamedChild,
149
     * except does not error when no children match and is capable of
150
     * returning multiple children if they have the same name).
151
     *
152
     * @param string $typeClassName
153
     * @param string|null $name
154
     * @return ComponentInterface
155
     */
156
    public function getTypedChildren(string $typeClassName, ?string $name = null): ComponentInterface
157
    {
158
        $root = new RootNode();
159
        foreach ($this->children as $child) {
160
            if ($child instanceof $typeClassName) {
161
                if ($name === null || ($parts = explode('.', $name, 2)) && $parts[0] === $child->getName()) {
162
                    // Child will be a Component of the right class; matching name if name is provided. Otherwise ignored.
163
                    if (isset($parts[1])) {
164
                        // If $name is null then $parts won't be set and this condition is not entered. If $parts[1] is set
165
                        // this means the $name had a dot and we must recurse.
166
                        $root->addChild($child->getTypedChildren($typeClassName, $parts[1]));
167
                        continue;
168
                    } else {
169
                        // Otherwise we indiscriminately add the resolved child to our collection, but only if $parts[1]
170
                        // was not set (no more recursion), if $name was null, or if $name matched completely.
171
                        $root->addChild($child);
172
                    }
173
                }
174
            }
175
            if ($child instanceof TransparentComponentInterface) {
176
                $root->addChild($child->getTypedChildren($typeClassName, $name));
177
            }
178
        }
179
        return $root;
180
    }
181
182
    /**
183
     * @return ComponentInterface[]
184
     */
185
    public function getChildren(): iterable
186
    {
187
        return $this->children;
188
    }
189
190
    /**
191
     * Returns one of the following:
192
     *
193
     * - Itself, if there is more than one child node and one or more nodes are not TextNode or NumericNode
194
     * - A plain value if there is a single child node of type TextNode or NumericNode
195
     * - The one child node if there is only a single child node not of type TextNode or NumericNode
196
     * - Null if there are no child nodes at all.
197
     *
198
     * @param bool $extractNode If TRUE, will extract the value of a single node if the node type contains a scalar value
199
     * @return ComponentInterface|string|int|float|null
200
     */
201
    public function flatten(bool $extractNode = false)
202
    {
203
        if (empty($this->children) && $extractNode) {
204
            return null;
205
        }
206
        if (isset($this->children[0]) && !isset($this->children[1])) {
207
            if ($extractNode) {
208
                if ($this->children[0] instanceof TextNode) {
209
                    $text = $this->children[0]->getText();
210
                    return is_numeric($text) ? $text + 0 : $text;
211
                }
212
            }
213
            return $this->children[0];
214
        }
215
        return $this;
216
    }
217
218
    /**
219
     * @param iterable|ComponentInterface[] $children
220
     * @return ComponentInterface
221
     */
222
    public function setChildren(iterable $children): ComponentInterface
223
    {
224
        $this->children = $children;
0 ignored issues
show
Documentation Bug introduced by
It seems like $children can also be of type object<TYPO3Fluid\Fluid\Component\iterable>. However, the property $children is declared as type array<integer,object<TYP...nt\ComponentInterface>>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
225
        $this->_lastAddedWasTextNode = end($children) instanceof TextNode;
226
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (TYPO3Fluid\Fluid\Component\AbstractComponent) is incompatible with the return type declared by the interface TYPO3Fluid\Fluid\Compone...tInterface::setChildren of type self.

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...
227
    }
228
229
    /**
230
     * Returns whether the escaping interceptors should be disabled or enabled for the result of renderChildren() calls within this ViewHelper
231
     *
232
     * Note: This method is no public API, use $this->escapeChildren instead!
233
     *
234
     * @return boolean
235
     */
236
    public function isChildrenEscapingEnabled(): bool
237
    {
238
        if ($this->escapeChildren === null) {
239
            // Disable children escaping automatically, if output escaping is on anyway.
240
            return !$this->isOutputEscapingEnabled();
241
        }
242
        return $this->escapeChildren !== false;
243
    }
244
245
    /**
246
     * Returns whether the escaping interceptors should be disabled or enabled for the render-result of this ViewHelper
247
     *
248
     * Note: This method is no public API, use $this->escapeOutput instead!
249
     *
250
     * @return boolean
251
     */
252
    public function isOutputEscapingEnabled(): bool
253
    {
254
        return $this->escapeOutput !== false;
255
    }
256
257
    public function evaluate(RenderingContextInterface $renderingContext)
258
    {
259
        return $this->evaluateChildren($renderingContext);
260
    }
261
262
    public function allowUndeclaredArgument(string $argumentName): bool
263
    {
264
        return true;
265
    }
266
267
    /**
268
     * Evaluate all child nodes and return the evaluated results.
269
     *
270
     * @param RenderingContextInterface $renderingContext
271
     * @return mixed Normally, an object is returned - in case it is concatenated with a string, a string is returned.
272
     * @throws Exception
273
     */
274
    protected function evaluateChildren(RenderingContextInterface $renderingContext)
275
    {
276
        $evaluatedNodes = [];
277
        foreach ($this->getChildren() as $childNode) {
278
            if ($childNode instanceof EmbeddedComponentInterface) {
279
                continue;
280
            }
281
            $evaluatedNodes[] = $childNode->evaluate($renderingContext);
282
        }
283
        // Make decisions about what to actually return
284
        if (empty($evaluatedNodes)) {
285
            return null;
286
        }
287
        if (count($evaluatedNodes) === 1) {
288
            return $evaluatedNodes[0];
289
        }
290
        $string = '';
291
        foreach ($evaluatedNodes as $evaluatedNode) {
292
            $string .= $this->castToString($evaluatedNode);
293
        }
294
        return $string;
295
    }
296
297
    /**
298
     * @param mixed $value
299
     * @return string
300
     */
301
    protected function castToString($value): string
302
    {
303
        if (is_object($value) && !method_exists($value, '__toString')) {
304
            throw new Exception('Cannot cast object of type "' . get_class($value) . '" to string.', 1273753083);
305
        }
306
        return (string) $value;
307
    }
308
}