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

AbstractComponent::allowUndeclaredArgument()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
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 RootNode) {
95
            // Assimilate child nodes instead of allowing a root node inside a root node.
96
            foreach ($component->getChildren() as $node) {
97
                $this->addChild($node);
98
            }
99
        } elseif ($component instanceof TextNode && $this->_lastAddedWasTextNode) {
100
            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...
101
        } else {
102
            $this->children[] = $component;
103
            $this->_lastAddedWasTextNode = $component instanceof TextNode;
104
        }
105
        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...
106
    }
107
108
    public function getNamedChild(string $name): ComponentInterface
109
    {
110
        $parts = explode('.', $name, 2);
111
        foreach (array_reverse($this->children) as $child) {
112
            if ($child->getName() === $parts[0]) {
113
                if (isset($parts[1])) {
114
                    return $child->getNamedChild($parts[1]);
115
                }
116
                return $child;
117
            }
118
            if ($child instanceof TransparentComponentInterface) {
119
                try {
120
                    return $child->getNamedChild($name);
121
                } catch (ChildNotFoundException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
122
123
                }
124
            }
125
        }
126
        throw new ChildNotFoundException(sprintf('Child with name "%s" not found', $name), 1562757835);
127
    }
128
129
    /**
130
     * Gets a new RootNode with children copied from this current
131
     * Component. Scans for children of a specific type (a Component
132
     * class name like a ViewHelper class name) and an optional name
133
     * which if not-null must also be matched (much like getNamedChild,
134
     * except does not error when no children match and is capable of
135
     * returning multiple children if they have the same name).
136
     *
137
     * @param string $typeClassName
138
     * @param string|null $name
139
     * @return ComponentInterface
140
     */
141
    public function getTypedChildren(string $typeClassName, ?string $name = null): ComponentInterface
142
    {
143
        $root = new RootNode();
144
        foreach ($this->children as $child) {
145
            if ($child instanceof $typeClassName) {
146
                if ($name === null || ($parts = explode('.', $name, 2)) && $parts[0] === $child->getName()) {
147
                    // Child will be a Component of the right class; matching name if name is provided. Otherwise ignored.
148
                    if (isset($parts[1])) {
149
                        // If $name is null then $parts won't be set and this condition is not entered. If $parts[1] is set
150
                        // this means the $name had a dot and we must recurse.
151
                        $root->addChild($child->getTypedChildren($typeClassName, $parts[1]));
152
                        continue;
153
                    } else {
154
                        // Otherwise we indiscriminately add the resolved child to our collection, but only if $parts[1]
155
                        // was not set (no more recursion), if $name was null, or if $name matched completely.
156
                        $root->addChild($child);
157
                    }
158
                }
159
            }
160
            if ($child instanceof TransparentComponentInterface) {
161
                $root->addChild($child->getTypedChildren($typeClassName, $name));
162
            }
163
        }
164
        return $root;
165
    }
166
167
    /**
168
     * @return ComponentInterface[]
169
     */
170
    public function getChildren(): iterable
171
    {
172
        return $this->children;
173
    }
174
175
    /**
176
     * Returns one of the following:
177
     *
178
     * - Itself, if there is more than one child node and one or more nodes are not TextNode or NumericNode
179
     * - A plain value if there is a single child node of type TextNode or NumericNode
180
     * - The one child node if there is only a single child node not of type TextNode or NumericNode
181
     * - Null if there are no child nodes at all.
182
     *
183
     * @param bool $extractNode If TRUE, will extract the value of a single node if the node type contains a scalar value
184
     * @return ComponentInterface|string|int|float|null
185
     */
186
    public function flatten(bool $extractNode = false)
187
    {
188
        if (empty($this->children) && $extractNode) {
189
            return null;
190
        }
191
        if (isset($this->children[0]) && !isset($this->children[1])) {
192
            if ($extractNode) {
193
                if ($this->children[0] instanceof TextNode) {
194
                    $text = $this->children[0]->getText();
195
                    return is_numeric($text) ? $text + 0 : $text;
196
                }
197
            }
198
            return $this->children[0];
199
        }
200
        return $this;
201
    }
202
203
    /**
204
     * @param iterable|ComponentInterface[] $children
205
     * @return ComponentInterface
206
     */
207
    public function setChildren(iterable $children): ComponentInterface
208
    {
209
        $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...
210
        $this->_lastAddedWasTextNode = end($children) instanceof TextNode;
211
        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...
212
    }
213
214
    /**
215
     * Returns whether the escaping interceptors should be disabled or enabled for the result of renderChildren() calls within this ViewHelper
216
     *
217
     * Note: This method is no public API, use $this->escapeChildren instead!
218
     *
219
     * @return boolean
220
     */
221
    public function isChildrenEscapingEnabled(): bool
222
    {
223
        if ($this->escapeChildren === null) {
224
            // Disable children escaping automatically, if output escaping is on anyway.
225
            return !$this->isOutputEscapingEnabled();
226
        }
227
        return $this->escapeChildren !== false;
228
    }
229
230
    /**
231
     * Returns whether the escaping interceptors should be disabled or enabled for the render-result of this ViewHelper
232
     *
233
     * Note: This method is no public API, use $this->escapeOutput instead!
234
     *
235
     * @return boolean
236
     */
237
    public function isOutputEscapingEnabled(): bool
238
    {
239
        return $this->escapeOutput !== false;
240
    }
241
242
    public function evaluate(RenderingContextInterface $renderingContext)
243
    {
244
        return $this->evaluateChildren($renderingContext);
245
    }
246
247
    public function allowUndeclaredArgument(string $argumentName): bool
248
    {
249
        return true;
250
    }
251
252
    /**
253
     * Evaluate all child nodes and return the evaluated results.
254
     *
255
     * @param RenderingContextInterface $renderingContext
256
     * @return mixed Normally, an object is returned - in case it is concatenated with a string, a string is returned.
257
     * @throws Exception
258
     */
259
    protected function evaluateChildren(RenderingContextInterface $renderingContext)
260
    {
261
        $evaluatedNodes = [];
262
        foreach ($this->getChildren() as $childNode) {
263
            if ($childNode instanceof EmbeddedComponentInterface) {
264
                continue;
265
            }
266
            $evaluatedNodes[] = $childNode->evaluate($renderingContext);
267
        }
268
        // Make decisions about what to actually return
269
        if (empty($evaluatedNodes)) {
270
            return null;
271
        }
272
        if (count($evaluatedNodes) === 1) {
273
            return $evaluatedNodes[0];
274
        }
275
        $string = '';
276
        foreach ($evaluatedNodes as $evaluatedNode) {
277
            $string .= $this->castToString($evaluatedNode);
278
        }
279
        return $string;
280
    }
281
282
    /**
283
     * @param mixed $value
284
     * @return string
285
     */
286
    protected function castToString($value): string
287
    {
288
        if (is_object($value) && !method_exists($value, '__toString')) {
289
            throw new Exception('Cannot cast object of type "' . get_class($value) . '" to string.', 1273753083);
290
        }
291
        return (string) $value;
292
    }
293
}