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

AbstractToken   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 108
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 95.83%

Importance

Changes 6
Bugs 0 Features 4
Metric Value
wmc 22
c 6
b 0
f 4
lcom 1
cbo 5
dl 0
loc 108
ccs 46
cts 48
cp 0.9583
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A getDepth() 0 4 1
A getParent() 0 4 1
A setParent() 0 11 2
A getType() 0 4 1
B isValidType() 0 8 5
D cleanChildTokens() 0 31 10
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