Completed
Push — master ( e3192d...546b1b )
by Edgar
04:08
created

SVGElement::getXLinkAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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\SVG;
8
use nstdio\svg\traits\ChildTrait;
9
use nstdio\svg\traits\ElementTrait;
10
use nstdio\svg\util\Identifier;
11
use nstdio\svg\util\Inflector;
12
use nstdio\svg\util\KeyValueWriter;
13
use nstdio\svg\util\Transform;
14
use nstdio\svg\util\TransformInterface;
15
16
/**
17
 * Class SVGElement
18
 *
19
 * @property string $id
20
 * @property string $fill The fill color.
21
 * @property float $height The height attribute of element.
22
 * @property float $width The width attribute of element.
23
 *
24
 * @package nstdio\svg
25
 * @author  Edgar Asatryan <[email protected]>
26
 */
27
abstract class SVGElement implements ContainerInterface, ElementFactoryInterface
28
{
29
    use ElementTrait, ChildTrait;
30
31
    private static $notConvertable = ['patternContentUnits', 'patternTransform', 'patternUnits', 'diffuseConstant', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'limitingConeAngle', 'tableValues', 'filterUnits', 'gradientUnits', 'viewBox', 'repeatCount', 'attributeName', 'attributeType', 'stdDeviation'];
32
33
    /**
34
     * @var XMLDocumentInterface | ElementInterface | ElementFactoryInterface | ContainerInterface
35
     */
36
    protected $root;
37
38
    /**
39
     * @var XMLDocumentInterface | ElementInterface | ElementFactoryInterface | ContainerInterface
40
     */
41
    protected $element;
42
43
    public function __construct(ElementInterface $parent)
44
    {
45
        $this->child = new ElementStorage();
46
        $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...
47
        $this->element = $this->createElement($this->getName());
48
        $this->root->append($this);
49
    }
50
51
    public function createElement($name, $value = null, $attributes = [])
52
    {
53
        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...
54
    }
55
56
    abstract public function getName();
57
58
    final public function getRoot()
59
    {
60
        return $this->root;
61
    }
62
63
    final public function getElement()
64
    {
65
        return $this->element;
66
    }
67
68
    public function allAttributes(array $except = [])
69
    {
70
        return $this->element->attributes($except);
71
    }
72
73
    public function __get($name)
74
    {
75
        if ($name === 'filterUrl' || $name === 'fillUrl') {
76
            return $this->getIdFromUrl($name);
77
        }
78
79
        $name = $this->convertAttributeName($name);
80
        $value = $this->element->getAttribute($name);
81
        if ($value === '') {
82
            $value = $this->getXLinkAttribute($name);
83
        }
84
85
        return $value === '' ? null : $value;
86
    }
87
88
    public function __set($name, $value)
89
    {
90
        if ($name === 'id' && $value === null) {
91
            $this->element->setAttribute($name, Identifier::random('__' . $this->getName(), 5));
92
93
            return;
94
        }
95
96
        if ($value === null || $value === false || $value === '') {
97
            return;
98
        }
99
100
        if ($name === 'filterUrl' || $name === 'fillUrl') {
101
            $this->handleUrlPostfixAttribute($name, $value);
102
        }
103
104
        $name = $this->convertAttributeName($name);
105
        $this->element->setAttribute($name, $value);
106
    }
107
108
    public function getXLinkAttribute($name)
109
    {
110
        return $this->element->getAttributeNS('xlink', $name);
111
    }
112
113
    /**
114
     * @param $name
115
     *
116
     * @return string
117
     */
118
    private function convertAttributeName($name)
119
    {
120
        return !in_array($name, self::$notConvertable) ? Inflector::camel2dash($name) : $name;
121
    }
122
123
    /**
124
     * @inheritdoc
125
     */
126
    public function apply(array $assoc)
127
    {
128
        $filtered = [];
129
        foreach ($assoc as $attribute => $value) {
130
            $filtered[$this->convertAttributeName($attribute)] = $value;
131
        }
132
        KeyValueWriter::apply($this->element, $filtered);
133
134
        return $this;
135
    }
136
137
    protected function setAttribute($name, $value, $xLink = false)
138
    {
139
        if ($xLink === true) {
140
            $this->element->setAttributeNS('xlink', $name, $value);
141
        } else {
142
            $this->element->setAttribute($name, $value);
143
        }
144
    }
145
146
    protected function selfRemove()
147
    {
148
        $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...
149
    }
150
151
    protected function getSVG()
152
    {
153
        if ($this->root instanceof SVG) {
154
            return $this->root;
155
        }
156
        $element = $this->root;
157
158
        do {
159
            $element = $element->getRoot();
160
        } while (!($element instanceof SVG));
161
162
        return $element;
163
    }
164
165
    /**
166
     * @inheritdoc
167
     */
168
    public function copy(array $apply = [], array $ignore = [], ContainerInterface $parent = null)
169
    {
170
        /** @var SVGElement $instance */
171
        $instance = (new Instantiator())->instantiate(get_class($this));
172
        $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...
173
        $instance->child = new ElementStorage();
174
        $instance->element = $this->createElement($this->getName());
175
        $instance->id = null;
176
177
        if ($instance instanceof TransformInterface && $this instanceof Transformable) {
178
            $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...
179
        }
180
        $ignore[] = 'id';
181
        $apply = array_merge($this->allAttributes($ignore), $apply);
182
        $instance->apply($apply);
183
        $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...
184
185
        return $instance;
186
    }
187
188
    /**
189
     * @param $attribute
190
     * @param $value
191
     */
192
    private function handleUrlPostfixAttribute(&$attribute, &$value)
193
    {
194
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
195
        if (strpos($value, "url(#") !== 0) {
196
            $value = "url(#" . $value . ")";
197
        }
198
    }
199
200
    private function getIdFromUrl($attribute)
201
    {
202
        $attribute = substr($attribute, 0, strrpos($attribute, 'U'));
203
        return str_replace(['url(#', ')'], '', $this->element->getAttribute($attribute));
204
    }
205
}