Completed
Push — master ( fbbc4e...be9123 )
by Edgar
03:17
created

SVGElement::setXLinkAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 1
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 148
    public function __construct(ElementInterface $parent)
45
    {
46 148
        $this->child = new ElementStorage();
47 148
        $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 148
        $this->element = $this->createElement($this->getName());
49 148
        $this->root->append($this);
50 148
    }
51
52 148
    public function createElement($name, $value = null, $attributes = [])
53
    {
54 148
        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 27
    final public function getRoot()
60
    {
61 27
        return $this->root;
62
    }
63
64 148
    final public function getElement()
65
    {
66 148
        return $this->element;
67
    }
68
69 8
    public function allAttributes(array $except = [])
70
    {
71 8
        return $this->element->attributes($except);
72
    }
73
74 108
    public function __get($name)
75 50
    {
76 108
        if ($name === 'filterUrl' || $name === 'fillUrl') {
77 1
            return $this->getIdFromUrl($name);
78
        }
79
80 108
        $name = $this->convertAttributeName($name);
81 108
        $value = $this->element->getAttribute($name);
82 108
        if ($value === '') {
83 80
            $value = $this->getXLinkAttribute($name);
84 80
        }
85
86 108
        return $value === '' ? null : $value;
87
    }
88
89 116
    public function __set($name, $value)
90
    {
91 116
        if ($name === 'id' && $value === null) {
92 36
            $this->element->setAttribute($name, Identifier::random('__' . $this->getName(), 5));
93
94 36
            return;
95
        }
96
97 106
        if ($value === null || $value === false || $value === '') {
98 6
            return;
99
        }
100
101 106
        if ($name === 'filterUrl' || $name === 'fillUrl') {
102 23
            $this->handleUrlPostfixAttribute($name, $value);
103 23
        }
104
105 106
        $name = $this->convertAttributeName($name);
106 106
        $this->element->setAttribute($name, $value);
107 106
    }
108
109 80
    public function getXLinkAttribute($name)
110
    {
111 80
        return $this->element->getAttributeNS('xlink', $name);
112
    }
113
114 1
    public function setXLinkAttribute($name, $value)
115
    {
116 1
        $this->element->setAttributeNS('xlink', "xlink:$name", $value);
117 1
    }
118
119
    /**
120
     * @param $name
121
     *
122
     * @return string
123
     */
124 119
    private function convertAttributeName($name)
125
    {
126 119
        return !in_array($name, self::$notConvertable) ? Inflector::camel2dash($name) : $name;
127
    }
128
129
    /**
130
     * @inheritdoc
131
     */
132 49
    public function apply(array $assoc)
133
    {
134 49
        $filtered = [];
135 49
        foreach ($assoc as $attribute => $value) {
136 48
            $filtered[$this->convertAttributeName($attribute)] = $value;
137 49
        }
138 49
        KeyValueWriter::apply($this->element, $filtered);
139
140 49
        return $this;
141
    }
142
143 3
    protected function selfRemove()
144
    {
145 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...
146 3
    }
147
148 3
    protected function getSVG()
149
    {
150 3
        if ($this->root instanceof SVG) {
151 3
            return $this->root;
152
        }
153
        $element = $this->root;
154
155
        do {
156
            $element = $element->getRoot();
157
        } while (!($element instanceof SVG));
158
159
        return $element;
160
    }
161
162 60
    protected static function getDefs(ElementInterface $container)
163
    {
164 60
        if ($container instanceof Defs) {
165 10
            return $container;
166
        }
167
168 50
        if ($container instanceof SVG) {
169 50
            $defs = $container->getFirstChild();
170 50
        } else {
171
            /** @var SVGElement $container */
172
            $defs = $container->getSVG()->getFirstChild();
173
        }
174
175 50
        return $defs;
176
    }
177
178
    /**
179
     * @inheritdoc
180
     */
181 2
    public function copy(array $apply = [], array $ignore = [], ContainerInterface $parent = null)
182
    {
183
        /** @var SVGElement $instance */
184 2
        $instance = (new Instantiator())->instantiate(get_class($this));
185 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...
186 2
        $instance->child = new ElementStorage();
187 2
        $instance->element = $this->createElement($this->getName());
188 2
        $instance->id = null;
189
190 2
        if ($instance instanceof TransformInterface && $this instanceof Transformable) {
191 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\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...
192 2
        }
193 2
        $ignore[] = 'id';
194 2
        $apply = array_merge($this->allAttributes($ignore), $apply);
195 2
        $instance->apply($apply);
196 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...
197
198 2
        return $instance;
199
    }
200
201
    /**
202
     * @param $attribute
203
     * @param $value
204
     */
205 23
    private function handleUrlPostfixAttribute(&$attribute, &$value)
206
    {
207 23
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
208 23
        if (strpos($value, "url(#") !== 0) {
209 23
            $value = "url(#" . $value . ")";
210 23
        }
211 23
    }
212
213 1
    private function getIdFromUrl($attribute)
214
    {
215 1
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
216 1
        return str_replace(['url(#', ')'], '', $this->element->getAttribute($attribute));
217
    }
218
}