Completed
Push — master ( 1409bd...fad66a )
by Edgar
03:44
created

SVGElement::getDefs()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 7
cts 8
cp 0.875
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 3.0175
1
<?php
2
namespace nstdio\svg;
3
4
use Doctrine\Instantiator\Instantiator;
5
use nstdio\svg\attributes\Transformable;
6
use nstdio\svg\container\ContainerInterface;
7
use nstdio\svg\container\Defs;
8
use nstdio\svg\container\SVG;
9
use nstdio\svg\traits\ChildTrait;
10
use nstdio\svg\traits\ElementTrait;
11
use nstdio\svg\util\Identifier;
12
use nstdio\svg\util\Inflector;
13
use nstdio\svg\util\KeyValueWriter;
14
use nstdio\svg\util\Transform;
15
use nstdio\svg\util\TransformInterface;
16
17
/**
18
 * Class SVGElement
19
 *
20
 * @property string $id
21
 * @property string $fill The fill color.
22
 * @property float $height The height attribute of element.
23
 * @property float $width The width attribute of element.
24
 *
25
 * @package nstdio\svg
26
 * @author  Edgar Asatryan <[email protected]>
27
 */
28
abstract class SVGElement implements ContainerInterface, ElementFactoryInterface
29
{
30
    use ElementTrait, ChildTrait;
31
32
    private static $notConvertable = ['patternContentUnits', 'patternTransform', 'patternUnits', 'diffuseConstant', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'limitingConeAngle', 'tableValues', 'filterUnits', 'gradientUnits', 'viewBox', 'repeatCount', 'attributeName', 'attributeType', 'stdDeviation'];
33
34
    /**
35
     * @var XMLDocumentInterface | ElementInterface | ElementFactoryInterface | ContainerInterface
36
     */
37
    protected $root;
38
39
    /**
40
     * @var XMLDocumentInterface | ElementInterface | ElementFactoryInterface | ContainerInterface
41
     */
42
    protected $element;
43
44 127
    public function __construct(ElementInterface $parent)
45
    {
46 127
        $this->child = new ElementStorage();
47 127
        $this->root = $parent;
0 ignored issues
show
Documentation Bug introduced by
It seems like $parent of type object<nstdio\svg\ElementInterface> is incompatible with the declared type object<nstdio\svg\XMLDocumentInterface> of property $root.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
48 127
        $this->element = $this->createElement($this->getName());
49 127
        $this->root->append($this);
50 127
    }
51
52 127
    public function createElement($name, $value = null, $attributes = [])
53
    {
54 127
        return $this->root->createElement($name, $value, $attributes);
0 ignored issues
show
Unused Code introduced by
The call to XMLDocumentInterface::createElement() has too many arguments starting with $attributes.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
55
    }
56
57
    abstract public function getName();
58
59 26
    final public function getRoot()
60
    {
61 26
        return $this->root;
62
    }
63
64 127
    final public function getElement()
65
    {
66 127
        return $this->element;
67
    }
68
69 6
    public function allAttributes(array $except = [])
70
    {
71 6
        return $this->element->attributes($except);
72
    }
73
74 91
    public function __get($name)
75 39
    {
76 91
        if ($name === 'filterUrl' || $name === 'fillUrl') {
77 1
            return $this->getIdFromUrl($name);
78
        }
79
80 91
        $name = $this->convertAttributeName($name);
81 91
        $value = $this->element->getAttribute($name);
82 91
        if ($value === '') {
83 72
            $value = $this->getXLinkAttribute($name);
84 72
        }
85
86 91
        return $value === '' ? null : $value;
87
    }
88
89 98
    public function __set($name, $value)
90
    {
91 98
        if ($name === 'id' && $value === null) {
92 19
            $this->element->setAttribute($name, Identifier::random('__' . $this->getName(), 5));
93
94 19
            return;
95
        }
96
97 96
        if ($value === null || $value === false || $value === '') {
98 6
            return;
99
        }
100
101 96
        if ($name === 'filterUrl' || $name === 'fillUrl') {
102 20
            $this->handleUrlPostfixAttribute($name, $value);
103 20
        }
104
105 96
        $name = $this->convertAttributeName($name);
106 96
        $this->element->setAttribute($name, $value);
107 96
    }
108
109 72
    public function getXLinkAttribute($name)
110
    {
111 72
        return $this->element->getAttributeNS('xlink', $name);
112
    }
113
114
    /**
115
     * @param $name
116
     *
117
     * @return string
118
     */
119 102
    private function convertAttributeName($name)
120
    {
121 102
        return !in_array($name, self::$notConvertable) ? Inflector::camel2dash($name) : $name;
122
    }
123
124
    /**
125
     * @inheritdoc
126
     */
127 37
    public function apply(array $assoc)
128
    {
129 37
        $filtered = [];
130 37
        foreach ($assoc as $attribute => $value) {
131 37
            $filtered[$this->convertAttributeName($attribute)] = $value;
132 37
        }
133 37
        KeyValueWriter::apply($this->element, $filtered);
134
135 37
        return $this;
136
    }
137
138 3
    protected function selfRemove()
139
    {
140 3
        $this->getRoot()->removeChild($this);
0 ignored issues
show
Bug introduced by
The method removeChild() does not seem to exist on object<nstdio\svg\XMLDocumentInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
141 3
    }
142
143 3
    protected function getSVG()
144
    {
145 3
        if ($this->root instanceof SVG) {
146 3
            return $this->root;
147
        }
148
        $element = $this->root;
149
150
        do {
151
            $element = $element->getRoot();
152
        } while (!($element instanceof SVG));
153
154
        return $element;
155
    }
156
157 49
    protected static function getDefs(ElementInterface $container)
158
    {
159 49
        if ($container instanceof Defs) {
160 10
            return $container;
161
        }
162
163 39
        if ($container instanceof SVG) {
164 39
            $defs = $container->getFirstChild();
165 39
        } else {
166
            /** @var SVGElement $container */
167
            $defs = $container->getSVG()->getFirstChild();
168
        }
169
170 39
        return $defs;
171
    }
172
173
    /**
174
     * @inheritdoc
175
     */
176 2
    public function copy(array $apply = [], array $ignore = [], ContainerInterface $parent = null)
177
    {
178
        /** @var SVGElement $instance */
179 2
        $instance = (new Instantiator())->instantiate(get_class($this));
180 2
        $instance->root = $parent === null ? $this->getRoot() : $parent;
0 ignored issues
show
Documentation Bug introduced by
It seems like $parent === null ? $this->getRoot() : $parent can also be of type object<nstdio\svg\container\ContainerInterface>. However, the property $root is declared as type object<nstdio\svg\XMLDocumentInterface>. 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...
181 2
        $instance->child = new ElementStorage();
182 2
        $instance->element = $this->createElement($this->getName());
183 2
        $instance->id = null;
184
185 2
        if ($instance instanceof TransformInterface && $this instanceof Transformable) {
186 2
            $instance->transformImpl = Transform::newInstance($this->getTransformAttribute());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class nstdio\svg\SVGElement as the method getTransformAttribute() does only exist in the following sub-classes of nstdio\svg\SVGElement: nstdio\svg\container\G, nstdio\svg\container\Group, nstdio\svg\container\Pattern, nstdio\svg\shape\Circle, nstdio\svg\shape\Ellipse, nstdio\svg\shape\Line, nstdio\svg\shape\Path, nstdio\svg\shape\Polygon, nstdio\svg\shape\Polyline, nstdio\svg\shape\Rect, nstdio\svg\shape\RoundedShape, nstdio\svg\shape\Shape. 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...
187 2
        }
188 2
        $ignore[] = 'id';
189 2
        $apply = array_merge($this->allAttributes($ignore), $apply);
190 2
        $instance->apply($apply);
191 2
        $parent === null ? $this->root->append($instance) : $parent->append($instance);
0 ignored issues
show
Bug introduced by
The method append() does not exist on nstdio\svg\XMLDocumentInterface. Did you maybe mean appendChild()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
192
193 2
        return $instance;
194
    }
195
196
    /**
197
     * @param $attribute
198
     * @param $value
199
     */
200 20
    private function handleUrlPostfixAttribute(&$attribute, &$value)
201
    {
202 20
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
203 20
        if (strpos($value, "url(#") !== 0) {
204 20
            $value = "url(#" . $value . ")";
205 20
        }
206 20
    }
207
208 1
    private function getIdFromUrl($attribute)
209
    {
210 1
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
211 1
        return str_replace(['url(#', ')'], '', $this->element->getAttribute($attribute));
212
    }
213
}