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

AbstractComponent   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 267
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 267
rs 8.5599
c 0
b 0
f 0
wmc 48
lcom 3
cbo 6

17 Methods

Rating   Name   Duplication   Size   Complexity  
A onOpen() 0 4 1
A onClose() 0 4 1
A getName() 0 4 1
A setArguments() 0 5 1
A getArguments() 0 4 1
A addChild() 0 15 5
B getNamedChild() 0 20 6
B getTypedChildren() 0 25 8
A getChildren() 0 4 1
B flatten() 0 16 8
A setChildren() 0 6 1
A isChildrenEscapingEnabled() 0 8 2
A isOutputEscapingEnabled() 0 4 1
A evaluate() 0 4 1
A allowUndeclaredArgument() 0 4 1
B evaluateChildren() 0 22 6
A castToString() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like AbstractComponent often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractComponent, and based on these observations, apply Extract Interface, too.

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\Error\ChildNotFoundException;
12
use TYPO3Fluid\Fluid\Core\Parser\Exception;
13
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\RootNode;
14
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\TextNode;
15
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
16
use TYPO3Fluid\Fluid\ViewHelpers\ArgumentViewHelper;
17
18
/**
19
 * Base Component Class
20
 *
21
 * Contains standard implementations for some of the more
22
 * universal methods a Component supports, e.g. handling
23
 * of child components and resolving of named children.
24
 */
25
abstract class AbstractComponent implements ComponentInterface
26
{
27
    /**
28
     * Unnamed children indexed by numeric position in array
29
     *
30
     * @var ComponentInterface[]
31
     */
32
    protected $children = [];
33
34
    /**
35
     * @var string|null
36
     */
37
    protected $name;
38
39
    /**
40
     * Specifies whether the escaping interceptors should be disabled or enabled for the result of renderChildren() calls within this ViewHelper
41
     * @see isChildrenEscapingEnabled()
42
     *
43
     * Note: If this is NULL the value of $this->escapingInterceptorEnabled is considered for backwards compatibility
44
     *
45
     * @var boolean|null
46
     */
47
    protected $escapeChildren = null;
48
49
    /**
50
     * Specifies whether the escaping interceptors should be disabled or enabled for the render-result of this ViewHelper
51
     * @see isOutputEscapingEnabled()
52
     *
53
     * @var boolean|null
54
     */
55
    protected $escapeOutput = null;
56
57
    /**
58
     * @var ArgumentCollection|null
59
     */
60
    protected $arguments = null;
61
62
    private $_lastAddedWasTextNode = false;
63
64
    public function onOpen(RenderingContextInterface $renderingContext): ComponentInterface
65
    {
66
        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...
67
    }
68
69
    public function onClose(RenderingContextInterface $renderingContext): ComponentInterface
70
    {
71
        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...
72
    }
73
74
    public function getName(): ?string
75
    {
76
        return $this->name;
77
    }
78
79
    public function setArguments(ArgumentCollection $arguments): ComponentInterface
80
    {
81
        $this->arguments = $arguments;
82
        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...
83
    }
84
85
    public function getArguments(): ArgumentCollection
86
    {
87
        return $this->arguments ?? ($this->arguments = new ArgumentCollection());
88
    }
89
90
    public function addChild(ComponentInterface $component): ComponentInterface
91
    {
92
        if ($component instanceof RootNode) {
93
            // Assimilate child nodes instead of allowing a root node inside a root node.
94
            foreach ($component->getChildren() as $node) {
95
                $this->addChild($node);
96
            }
97
        } elseif ($component instanceof TextNode && $this->_lastAddedWasTextNode) {
98
            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...
99
        } else {
100
            $this->children[] = $component;
101
            $this->_lastAddedWasTextNode = $component instanceof TextNode;
102
        }
103
        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...
104
    }
105
106
    public function getNamedChild(string $name): ComponentInterface
107
    {
108
        $parts = explode('.', $name, 2);
109
        foreach (array_reverse($this->children) as $child) {
110
            if ($child->getName() === $parts[0]) {
111
                if (isset($parts[1])) {
112
                    return $child->getNamedChild($parts[1]);
113
                }
114
                return $child;
115
            }
116
            if ($child instanceof TransparentComponentInterface) {
117
                try {
118
                    return $child->getNamedChild($name);
119
                } catch (ChildNotFoundException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
120
121
                }
122
            }
123
        }
124
        throw new ChildNotFoundException(sprintf('Child with name "%s" not found', $name), 1562757835);
125
    }
126
127
    /**
128
     * Gets a new RootNode with children copied from this current
129
     * Component. Scans for children of a specific type (a Component
130
     * class name like a ViewHelper class name) and an optional name
131
     * which if not-null must also be matched (much like getNamedChild,
132
     * except does not error when no children match and is capable of
133
     * returning multiple children if they have the same name).
134
     *
135
     * @param string $typeClassName
136
     * @param string|null $name
137
     * @return ComponentInterface
138
     */
139
    public function getTypedChildren(string $typeClassName, ?string $name = null): ComponentInterface
140
    {
141
        $root = new RootNode();
142
        foreach ($this->children as $child) {
143
            if ($child instanceof $typeClassName) {
144
                if ($name === null || ($parts = explode('.', $name, 2)) && $parts[0] === $child->getName()) {
145
                    // Child will be a Component of the right class; matching name if name is provided. Otherwise ignored.
146
                    if (isset($parts[1])) {
147
                        // If $name is null then $parts won't be set and this condition is not entered. If $parts[1] is set
148
                        // this means the $name had a dot and we must recurse.
149
                        $root->addChild($child->getTypedChildren($typeClassName, $parts[1]));
150
                        continue;
151
                    } else {
152
                        // Otherwise we indiscriminately add the resolved child to our collection, but only if $parts[1]
153
                        // was not set (no more recursion), if $name was null, or if $name matched completely.
154
                        $root->addChild($child);
155
                    }
156
                }
157
            }
158
            if ($child instanceof TransparentComponentInterface) {
159
                $root->addChild($child->getTypedChildren($typeClassName, $name));
160
            }
161
        }
162
        return $root;
163
    }
164
165
    /**
166
     * @return ComponentInterface[]
167
     */
168
    public function getChildren(): iterable
169
    {
170
        return $this->children;
171
    }
172
173
    /**
174
     * Returns one of the following:
175
     *
176
     * - Itself, if there is more than one child node and one or more nodes are not TextNode or NumericNode
177
     * - A plain value if there is a single child node of type TextNode or NumericNode
178
     * - The one child node if there is only a single child node not of type TextNode or NumericNode
179
     * - Null if there are no child nodes at all.
180
     *
181
     * @param bool $extractNode If TRUE, will extract the value of a single node if the node type contains a scalar value
182
     * @return ComponentInterface|string|int|float|null
183
     */
184
    public function flatten(bool $extractNode = false)
185
    {
186
        if (empty($this->children) && $extractNode) {
187
            return null;
188
        }
189
        if (isset($this->children[0]) && !isset($this->children[1])) {
190
            if ($extractNode) {
191
                if ($this->children[0] instanceof TextNode) {
192
                    $text = $this->children[0]->getText();
193
                    return is_numeric($text) ? $text + 0 : $text;
194
                }
195
            }
196
            return $this->children[0];
197
        }
198
        return $this;
199
    }
200
201
    /**
202
     * @param iterable|ComponentInterface[] $children
203
     * @return ComponentInterface
204
     */
205
    public function setChildren(iterable $children): ComponentInterface
206
    {
207
        $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...
208
        $this->_lastAddedWasTextNode = end($children) instanceof TextNode;
209
        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...
210
    }
211
212
    /**
213
     * Returns whether the escaping interceptors should be disabled or enabled for the result of renderChildren() calls within this ViewHelper
214
     *
215
     * Note: This method is no public API, use $this->escapeChildren instead!
216
     *
217
     * @return boolean
218
     */
219
    public function isChildrenEscapingEnabled(): bool
220
    {
221
        if ($this->escapeChildren === null) {
222
            // Disable children escaping automatically, if output escaping is on anyway.
223
            return !$this->isOutputEscapingEnabled();
224
        }
225
        return $this->escapeChildren !== false;
226
    }
227
228
    /**
229
     * Returns whether the escaping interceptors should be disabled or enabled for the render-result of this ViewHelper
230
     *
231
     * Note: This method is no public API, use $this->escapeOutput instead!
232
     *
233
     * @return boolean
234
     */
235
    public function isOutputEscapingEnabled(): bool
236
    {
237
        return $this->escapeOutput !== false;
238
    }
239
240
    public function evaluate(RenderingContextInterface $renderingContext)
241
    {
242
        return $this->evaluateChildren($renderingContext);
243
    }
244
245
    public function allowUndeclaredArgument(string $argumentName): bool
246
    {
247
        return true;
248
    }
249
250
    /**
251
     * Evaluate all child nodes and return the evaluated results.
252
     *
253
     * @param RenderingContextInterface $renderingContext
254
     * @return mixed Normally, an object is returned - in case it is concatenated with a string, a string is returned.
255
     * @throws Exception
256
     */
257
    protected function evaluateChildren(RenderingContextInterface $renderingContext)
258
    {
259
        $evaluatedNodes = [];
260
        foreach ($this->getChildren() as $childNode) {
261
            if ($childNode instanceof EmbeddedComponentInterface) {
262
                continue;
263
            }
264
            $evaluatedNodes[] = $childNode->evaluate($renderingContext);
265
        }
266
        // Make decisions about what to actually return
267
        if (empty($evaluatedNodes)) {
268
            return null;
269
        }
270
        if (count($evaluatedNodes) === 1) {
271
            return $evaluatedNodes[0];
272
        }
273
        $string = '';
274
        foreach ($evaluatedNodes as $evaluatedNode) {
275
            $string .= $this->castToString($evaluatedNode);
276
        }
277
        return $string;
278
    }
279
280
    /**
281
     * @param mixed $value
282
     * @return string
283
     */
284
    protected function castToString($value): string
285
    {
286
        if (is_object($value) && !method_exists($value, '__toString')) {
287
            throw new Exception('Cannot cast object of type "' . get_class($value) . '" to string.', 1273753083);
288
        }
289
        return (string) $value;
290
    }
291
}