Instructions::merge()   B
last analyzed

Complexity

Conditions 10
Paths 28

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 7.1587
c 0
b 0
f 0
cc 10
nc 28
nop 1

How to fix   Long Method    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
 * Webino (http://webino.sk)
4
 *
5
 * @link        https://github.com/webino/WebinoDraw for the canonical source repository
6
 * @copyright   Copyright (c) 2012-2017 Webino, s. r. o. (http://webino.sk)
7
 * @author      Peter Bačinský <[email protected]>
8
 * @license     BSD-3-Clause
9
 */
10
11
namespace WebinoDraw\Instructions;
12
13
use ArrayObject;
14
use WebinoDraw\Exception\InvalidInstructionException;
15
16
/**
17
 * Draw instructions utilities
18
 */
19
class Instructions extends ArrayObject implements
20
    InstructionsInterface
21
{
22
    /**
23
     * Stack space before instruction without index
24
     */
25
    const STACK_SPACER = 10;
26
27
    /**
28
     * @param array $array
29
     */
30
    public function __construct(array $array = [])
31
    {
32
        empty($array) or
33
            $this->merge($array);
34
    }
35
36
    /**
37
     * @param array $array
38
     */
39
    public function exchangeArray($array)
40
    {
41
        parent::exchangeArray([]);
42
        $this->merge($array);
43
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WebinoDraw\Instructions\Instructions) is incompatible with the return type of the parent method ArrayObject::exchangeArray of type array.

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...
44
    }
45
46
    /**
47
     * {@inheritDoc}
48
     */
49
    public function getSortedArrayCopy()
50
    {
51
        $instructions = $this->getArrayCopy();
52
        ksort($instructions);
53
        return $instructions;
54
    }
55
56
    /**
57
     * Merge draw instructions
58
     *
59
     * If node with name exists merge else add,
60
     * or if same stackIndex throws exception.
61
     *
62
     * Instructions structure:
63
     * <pre>
64
     * [
65
     *   'node_name' => [
66
     *     'stackIndex' => '50',
67
     *     'customkey'  => 'customvalue',
68
     *     ....
69
     *   ],
70
     * ];
71
     * </pre>
72
     *
73
     * If no stackIndex is defined add as last with
74
     * space before.
75
     *
76
     * @param array $instructions Merge from
77
     * @return self
78
     * @throws InvalidInstructionException
79
     */
80
    public function merge(array $instructions)
81
    {
82
        $mergeWith     = $this->getArrayCopy();
83
        $mergeFrom     = $instructions;
84
        $instructionsN = count($mergeWith) * self::STACK_SPACER;
85
86
        foreach ($mergeWith as &$spec) {
87
            foreach ($mergeFrom as $iKey => $iSpec) {
88
                if (key($spec) != $iKey) {
89
                    continue;
90
                }
91
92
                // merge existing spec
93
                unset($mergeFrom[$iKey]);
94
                $spec = array_replace_recursive($spec, [$iKey => $iSpec]);
95
            }
96
        }
97
98
        unset($spec);
99
100
        foreach ($mergeFrom as $index => $spec) {
101
            if (null === $spec) {
102
                continue;
103
            }
104
105
            if (!is_array($spec)) {
106
                throw new InvalidInstructionException('Instruction node spec expect array');
107
            }
108
109
            if (!isset($spec['stackIndex'])) {
110
                // add without stack index
111
                $stackIndex = $instructionsN + self::STACK_SPACER;
112
113
                if (!isset($mergeWith[$stackIndex])) {
114
                    $instructionsN = $stackIndex;
115
                    $mergeWith[$stackIndex][$index] = $spec;
116
                    continue;
117
                }
118
119
                unset($stackIndex);
120
121
            } elseif (!isset($mergeWith[$spec['stackIndex']])) {
122
                // add with stackindex
123
                $mergeWith[$spec['stackIndex']][$index] = $spec;
124
                continue;
125
            }
126
127
            throw new InvalidInstructionException(sprintf('Stack index already exists `%s`', print_r($spec, true)));
128
        }
129
130
        parent::exchangeArray($mergeWith);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (exchangeArray() instead of merge()). Are you sure this is correct? If so, you might want to change this to $this->exchangeArray().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
131
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WebinoDraw\Instructions\Instructions) is incompatible with the return type declared by the interface WebinoDraw\Instructions\...uctionsInterface::merge of type array.

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...
132
    }
133
}
134