Completed
Push — master ( 63ca0f...fd375a )
by Edgar
03:21
created

Transform::skewX()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
namespace nstdio\svg\util;
3
use Doctrine\Instantiator\Exception\InvalidArgumentException;
4
5
/**
6
 * Class Transform
7
 *
8
 * @package nstdio\svg\util
9
 * @author  Edgar Asatryan <[email protected]>
10
 */
11
class Transform implements TransformInterface
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
12
{
13
    private $trans;
14
15
    private $data;
16
17
    private $sequence;
18
19
    private $argDelimiter = TransformInterface::ARG_DELIM_SPACE;
20
21
    const ROTATE_PATTERN = "/rotate\s*\(\s*(?<a>[+-]?\d+(?:\.\d+)?)((?:\s{1,}\,?\s*|\,\s*)(?<x>[+-]?\d+(?:\.\d+)?)(?:\s{1,}\,?\s*|\,\s*)(?<y>[+-]?\d+(?:\.\d+)?))?\s*\)/";
22
23
    const TRANSLATE_PATTERN = "/translate\s*\(\s*(?<x>[+-]?\d+(?:\.\d+)?)((?:\s{1,}\,?\s*|\,\s*)(?<y>[+-]?\d+(?:\.\d+)?))?\)/";
24
25
    const SCALE_PATTERN = "/scale\s*\(\s*(?<x>[+-]?\d+(?:\.\d+)?)((?:\s{1,}\,?\s*|\,\s*)(?<y>[+-]?\d+(?:\.\d+)?))?\)/";
26
27
    const SKEW_PATTERN = "/skew([XY])\s*\(\s*(?<x>[+-]?\d+(?:\.\d+)?)?\)/";
28
29
    const MATRIX_PATTERN = "/matrix\s*\(\s*((([+-]?\d+(?:\.\d+)?)(?:\s+,?\s*|,\s*)){5}([+-]?\d+(?:\.\d+)?)\s*)\)/";
30
31
    private function __construct()
32
    {
33
    }
34
35
    /**
36
     * Use this method to instantiate Transform class.
37
     *
38
     * @param $transformString
39
     *
40
     * @uses matchRotate()
41
     * @uses matchSkewX()
42
     * @uses matchSkewY()
43
     * @uses matchTranslate()
44
     * @uses matchScale()
45
     * @uses matchMatrix()
46
     *
47
     * @return Transform
48
     */
49
    public static function newInstance($transformString = null)
50
    {
51
        $instance = new Transform();
52
        $instance->trans = $transformString;
53
        $instance->sequence = $instance->makeSequence();
54
55
        foreach ($instance->sequence as $value) {
56
            $method = 'match' . ucfirst($value);
57
            $instance->data[$value] = $instance->$method();
58
        }
59
60
        return $instance;
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function result()
67
    {
68
        return $this->trans;
69
    }
70
71
    /**
72
     * @inheritdoc
73
     */
74
    public function setArgumentDelimiter($delim)
75
    {
76
        if ($delim !== TransformInterface::ARG_DELIM_COMMA &&
77
            $delim !== TransformInterface::ARG_DELIM_COMMA_SPACE &&
78
            $delim !== TransformInterface::ARG_DELIM_SPACE
79
        ) {
80
            throw new \InvalidArgumentException("Invalid delimiter. See TransformInterface::setArgumentDelimiter documentation for valid value.");
81
        }
82
83
        $this->argDelimiter = $delim;
84
    }
85
86
    /**
87
     * @inheritdoc
88
     */
89
    public function rotate($angle, $cx = null, $cy = null)
90
    {
91
        if ($cx !== null && $cy === null) {
92
            $cy = $cx;
93
        }
94
        if ($cy !== null && $cx === null) {
95
            $cx = $cy;
96
        }
97
98
        $this->addTransformIfNeeded('rotate');
99
100
        $this->setTransformData('rotate', [$angle, $cx, $cy]);
101
102
        return $this->buildTransformString();
103
    }
104
105
    /**
106
     * @inheritdoc
107
     */
108 View Code Duplication
    public function translate($x, $y = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
109
    {
110
        $this->addTransformIfNeeded('translate');
111
112
        $this->setTransformData('translate', [$x, $y]);
113
114
        return $this->buildTransformString();
115
    }
116
117
    /**
118
     * @inheritdoc
119
     */
120 View Code Duplication
    public function scale($x, $y = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
121
    {
122
        $this->addTransformIfNeeded('scale');
123
124
        $this->setTransformData('scale', [$x, $y]);
125
126
        return $this->buildTransformString();
127
    }
128
129
    /**
130
     * @inheritdoc
131
     */
132
    public function skewX($x)
133
    {
134
        $this->addTransformIfNeeded('skewX');
135
136
        $this->setTransformData('skewX', [$x]);
137
138
        return $this->buildTransformString();
139
    }
140
141
    /**
142
     * @inheritdoc
143
     */
144
    public function skewY($y)
145
    {
146
        $this->addTransformIfNeeded('skewY');
147
148
        $this->setTransformData('skewY', [$y]);
149
150
        return $this->buildTransformString();
151
    }
152
153
    /**
154
     * @inheritdoc
155
     */
156
    public function matrix(array $matrix)
157
    {
158
        if (count($matrix) !== 6) {
159
            throw new InvalidArgumentException("Invalid matrix size. You must provide en array with 6 elements. " . count($matrix) . " elements given.");
160
        }
161
        $this->addTransformIfNeeded('matrix');
162
163
        $this->setTransformData('matrix', $matrix);
164
165
        return $this->buildTransformString();
166
167
    }
168
169
    /**
170
     * @return mixed
171
     */
172 View Code Duplication
    private function matchRotate()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
173
    {
174
        preg_match(self::ROTATE_PATTERN, $this->trans, $matches);
175
176
        $ret = [$matches['a']];
177
        $ret[] = isset($matches['x']) ? $matches['x'] : null;
178
        $ret[] = isset($matches['y']) ? $matches['y'] : null;
179
180
        return $ret;
181
    }
182
183
    private function matchSkewX()
184
    {
185
        return $this->matchSkew();
186
    }
187
188
    private function matchSkewY()
189
    {
190
        return $this->matchSkew();
191
    }
192
193
    private function matchSkew()
194
    {
195
        preg_match(self::SKEW_PATTERN, $this->trans, $matches);
196
197
        $ret[] = isset($matches['x']) ? $matches['x'] : null;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ret was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ret = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
198
199
        return $ret;
200
    }
201
202 View Code Duplication
    private function matchScale()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
203
    {
204
        preg_match(self::SCALE_PATTERN, $this->trans, $matches);
205
        $ret[] = isset($matches['x']) ? $matches['x'] : null;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ret was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ret = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
206
        $ret[] = isset($matches['y']) ? $matches['y'] : null;
207
208
        return $ret;
209
    }
210
211
    private function matchMatrix()
212
    {
213
        preg_match(self::MATRIX_PATTERN, $this->trans, $matches);
214
        $matrix = explode(' ', preg_replace(['/\s+/', '/\,+/'], [' ', ''], $matches[1]), 6);
215
216
        if (count($matrix) !== 6) {
217
            throw new \InvalidArgumentException("Matrix must have exactly 6 arguments " . count($matrix) . " given.");
218
        }
219
220
        return $matrix;
221
    }
222
223 View Code Duplication
    private function matchTranslate()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
224
    {
225
        preg_match(self::TRANSLATE_PATTERN, $this->trans, $matches);
226
        $ret[] = isset($matches['x']) ? $matches['x'] : null;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ret was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ret = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
227
        $ret[] = isset($matches['y']) ? $matches['y'] : null;
228
229
        return $ret;
230
    }
231
232
    /**
233
     * @return array
234
     */
235
    public function getData()
236
    {
237
        return $this->data;
238
    }
239
240
    private function hasTransform($transform)
241
    {
242
        return in_array($transform, $this->sequence);
243
    }
244
245
    private function getTransform($transform)
246
    {
247
        if ($this->hasTransform($transform)) {
248
            return $this->data[$transform];
249
        }
250
251
        return null;
252
    }
253
254
    private function makeSequence()
255
    {
256
        preg_match_all("/\s*(matrix|translate|scale|rotate|skew[XY])/i", $this->trans, $matches);
257
258
        return $matches[1];
259
    }
260
261
    private function addTransformSequence($transform)
262
    {
263
        $this->sequence[] = $transform;
264
    }
265
266
    private function buildTransformString()
267
    {
268
        $ret = '';
269
        foreach ($this->sequence as $transform) {
270
            $ret .= $transform . "(" . rtrim(implode($this->argDelimiter, $this->data[$transform])) . ") ";
271
        }
272
        $this->trans = rtrim($ret);
273
274
        return $this->trans;
275
    }
276
277
    private function setTransformData($transform, $data)
278
    {
279
        if (isset($this->data[$transform]) === true) {
280
            $oldData = $this->data[$transform];
281
            foreach ($data as $key => $item) {
282
                if ($item === null) {
283
                    $data[$key] = $oldData[$key];
284
                }
285
            }
286
        }
287
        $this->data[$transform] = $data;
288
    }
289
290
    private function addTransformIfNeeded($transform)
291
    {
292
        if ($this->getTransform($transform) === null) {
293
            $this->addTransformSequence($transform);
294
        }
295
    }
296
}