Completed
Push — master ( 6e9edd...3f79e5 )
by Kevin
02:25
created

AbstractToken::cleanChildTokens()   D

Complexity

Conditions 10
Paths 12

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 10.0658

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 31
ccs 21
cts 23
cp 0.913
rs 4.8196
cc 10
eloc 17
nc 12
nop 3
crap 10.0658

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Groundskeeper\Tokens;
4
5
use Groundskeeper\Configuration;
6
use Groundskeeper\Exceptions\ValidationException;
7
use Groundskeeper\Tokens\Elements\Elements;
8
use Psr\Log\LoggerInterface;
9
10
abstract class AbstractToken implements Token
11
{
12
    /** @var Configuration */
13
    protected $configuration;
14
15
    /** @var int */
16
    private $depth;
17
18
    /** @var null|Token */
19
    private $parent;
20
21
    /** @var string */
22
    private $type;
23
24
    /**
25
     * Constructor
26
     */
27 67
    public function __construct($type, Configuration $configuration, Token $parent = null)
28
    {
29 67
        if (!$this->isValidType($type)) {
30 1
            throw new \InvalidArgumentException('Invalid type: ' . $type);
31
        }
32
33 66
        $this->configuration = $configuration;
34 66
        $this->setParent($parent);
35 66
        $this->type = $type;
36 66
    }
37
38
    /**
39
     * Required by the Token interface.
40
     */
41 38
    public function getDepth()
42
    {
43 38
        return $this->depth;
44
    }
45
46
    /**
47
     * Required by the Token interface.
48
     */
49 19
    public function getParent()
50
    {
51 19
        return $this->parent;
52
    }
53
54
    /**
55
     * Chainable setter for 'parent'.
56
     */
57 66
    public function setParent(Token $parent = null)
58
    {
59 66
        $this->depth = 0;
60 66
        if ($parent instanceof Token) {
61 37
            $this->depth = $parent->getDepth() + 1;
62 37
        }
63
64 66
        $this->parent = $parent;
65
66 66
        return $this;
67
    }
68
69
    /**
70
     * Required by the Token interface.
71
     */
72 31
    public function getType()
73
    {
74 31
        return $this->type;
75
    }
76
77 67
    protected function isValidType($type)
78
    {
79
        return $type === Token::CDATA
80 67
            || $type === Token::COMMENT
81 63
            || $type === Token::DOCTYPE
82 56
            || $type === Token::ELEMENT
83 67
            || $type === Token::TEXT;
84
    }
85
86 48
    public static function cleanChildTokens(Configuration $configuration, array &$children, LoggerInterface $logger = null)
87
    {
88 48
        if ($configuration->get('clean-strategy') == Configuration::CLEAN_STRATEGY_NONE) {
89 1
            return true;
90
        }
91
92 47
        foreach ($children as $key => $child) {
93 39
            if ($child instanceof Cleanable) {
94 33
                $isClean = $child->clean($logger);
95 33
                if (!$isClean) {
96 8
                    $message = 'invalid token. Unable to fix: ' . $child->getType();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Groundskeeper\Tokens\Cleanable as the method getType() does only exist in the following implementations of said interface: Groundskeeper\Tokens\DocType, Groundskeeper\Tokens\Elements\Base, Groundskeeper\Tokens\Elements\Body, Groundskeeper\Tokens\Elements\Br, Groundskeeper\Tokens\Elements\ClosedElement, Groundskeeper\Tokens\Elements\Element, Groundskeeper\Tokens\Elements\Head, Groundskeeper\Tokens\Elements\Hr, Groundskeeper\Tokens\Elements\Html, Groundskeeper\Tokens\Elements\Link, Groundskeeper\Tokens\Elements\Meta, Groundskeeper\Tokens\Elements\OpenElement, Groundskeeper\Tokens\Elements\Style.

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...
97 8
                    if ($child instanceof Element) {
0 ignored issues
show
Bug introduced by
The class Groundskeeper\Tokens\Element does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
98
                        $message = 'invalid element. Unable to fix: ' . $child->getName();
99
                    }
100
101 8
                    if ($configuration->get('error-strategy') == Configuration::ERROR_STRATEGY_THROW) {
102 1
                        throw new ValidationException(ucfirst($message));
103
                    }
104
105 7
                    if ($configuration->get('error-strategy') == Configuration::ERROR_STRATEGY_FIX || $configuration->get('error-strategy') == Configuration::ERROR_STRATEGY_REMOVE) {
106 7
                        unset($children[$key]);
107 7
                        if ($logger !== null) {
108 7
                            $logger->debug('Removing ' . $message);
109 7
                        }
110 7
                    }
111 7
                }
112 32
            }
113 46
        }
114
115 46
        return true;
116
    }
117
}
118