Completed
Branch master (5a127a)
by Martin
02:17
created

AttributesProcessor::processDocument()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 33
Code Lines 18

Duplication

Lines 3
Ratio 9.09 %

Code Coverage

Tests 18
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 3
loc 33
ccs 18
cts 18
cp 1
rs 5.1612
cc 12
eloc 18
nc 12
nop 1
crap 12

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
/*
4
 * This is part of the webuni/commonmark-attributes-extension package.
5
 *
6
 * (c) Martin Hasoň <[email protected]>
7
 * (c) Webuni s.r.o. <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Webuni\CommonMark\AttributesExtension;
14
15
use League\CommonMark\Block\Element\AbstractBlock;
16
use League\CommonMark\Block\Element\Document;
17
use League\CommonMark\Block\Element\ListBlock;
18
use League\CommonMark\Block\Element\ListItem;
19
use League\CommonMark\DocumentProcessorInterface;
20
21
class AttributesProcessor implements DocumentProcessorInterface
22
{
23
    const DIRECTION_PREFIX = 'prefix';
24
    const DIRECTION_SUFFIX = 'suffix';
25
26 5
    public function processDocument(Document $document)
27
    {
28 5
        $walker = $document->walker();
29 5
        while ($event = $walker->next()) {
30 5
            $node = $event->getNode();
31
32 5
            if ($event->isEntering() || !$node instanceof Attributes) {
33 5
                continue;
34
            }
35
36 5
            list($target, $direction) = $this->findTargetAndDirection($node);
37
38 5
            if ($target) {
39 5 View Code Duplication
                if (($parent = $target->parent()) instanceof ListItem && $parent->parent() instanceof ListBlock && $parent->parent()->isTight()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40 1
                    $target = $parent;
41
                }
42
43 5
                if ($direction === self::DIRECTION_SUFFIX) {
44 4
                    $attributes = AttributesUtils::merge($target, $node->getAttributes());
45
                } else {
46 3
                    $attributes = AttributesUtils::merge($node->getAttributes(), $target);
47
                }
48
49 5
                $target->data['attributes'] = $attributes;
0 ignored issues
show
Bug introduced by
The property data does not seem to exist in League\CommonMark\Node\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
50
            }
51
52 5
            if ($node->endsWithBlankLine() && $node->next() && $node->previous()) {
53 3
                $node->previous()->setLastLineBlank(true);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class League\CommonMark\Node\Node as the method setLastLineBlank() does only exist in the following sub-classes of League\CommonMark\Node\Node: League\CommonMark\Block\Element\AbstractBlock, League\CommonMark\Block\Element\BlockQuote, League\CommonMark\Block\Element\Document, League\CommonMark\Block\Element\FencedCode, League\CommonMark\Block\Element\Heading, League\CommonMark\Block\Element\HtmlBlock, League\CommonMark\Block\Element\IndentedCode, League\CommonMark\Block\Element\ListBlock, League\CommonMark\Block\Element\ListItem, League\CommonMark\Block\Element\Paragraph, League\CommonMark\Block\Element\ThematicBreak, Webuni\CommonMark\AttributesExtension\Attributes, Webuni\CommonMark\TableExtension\Table, Webuni\CommonMark\TableExtension\TableCaption, Webuni\CommonMark\TableExtension\TableCell, Webuni\CommonMark\TableExtension\TableRow, Webuni\CommonMark\TableExtension\TableRows. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
54
            }
55
56 5
            $node->detach();
57
        }
58 5
    }
59
60 5
    private function findTargetAndDirection(AbstractBlock $node)
61
    {
62 5
        $target = null;
63 5
        $direction = null;
64 5
        $previous = $next = $node;
65 5
        while (true) {
66 5
            $previous = $this->getPrevious($previous);
67 5
            $next = $this->getNext($next);
68
69 5
            if ($previous === null && $next === null) {
70 1
                $target = $node->parent();
71 1
                $direction = self::DIRECTION_SUFFIX;
72 1
                break;
73
            }
74
75 5 View Code Duplication
            if ($previous !== null && !$previous instanceof Attributes) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76 4
                $target = $previous;
77 4
                $direction = self::DIRECTION_SUFFIX;
78 4
                break;
79
            }
80
81 3 View Code Duplication
            if ($next !== null && !$next instanceof Attributes) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82 3
                $target = $next;
83 3
                $direction = self::DIRECTION_PREFIX;
84 3
                break;
85
            }
86
        }
87
88 5
        return [$target, $direction];
89
    }
90
91 5
    private function getPrevious(AbstractBlock $node = null)
92
    {
93 5
        $previous = $node instanceof AbstractBlock ? $node->previous() : null;
94
95 5
        if ($previous && $previous->endsWithBlankLine()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class League\CommonMark\Node\Node as the method endsWithBlankLine() does only exist in the following sub-classes of League\CommonMark\Node\Node: League\CommonMark\Block\Element\AbstractBlock, League\CommonMark\Block\Element\BlockQuote, League\CommonMark\Block\Element\Document, League\CommonMark\Block\Element\FencedCode, League\CommonMark\Block\Element\Heading, League\CommonMark\Block\Element\HtmlBlock, League\CommonMark\Block\Element\IndentedCode, League\CommonMark\Block\Element\ListBlock, League\CommonMark\Block\Element\ListItem, League\CommonMark\Block\Element\Paragraph, League\CommonMark\Block\Element\ThematicBreak, Webuni\CommonMark\AttributesExtension\Attributes, Webuni\CommonMark\TableExtension\Table, Webuni\CommonMark\TableExtension\TableCaption, Webuni\CommonMark\TableExtension\TableCell, Webuni\CommonMark\TableExtension\TableRow, Webuni\CommonMark\TableExtension\TableRows. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
96 2
            $previous = null;
97
        }
98
99 5
        return $previous;
100
    }
101
102 5
    private function getNext(AbstractBlock $node = null)
103
    {
104 5
        if ($node instanceof AbstractBlock) {
105 5
            return $node->endsWithBlankLine() ? null : $node->next();
106
        }
107
    }
108
}
109