|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Image; |
|
4
|
|
|
|
|
5
|
|
|
use ArrayIterator; |
|
6
|
|
|
use IteratorAggregate; |
|
7
|
|
|
|
|
8
|
|
|
class ManipulationSequence implements IteratorAggregate |
|
9
|
|
|
{ |
|
10
|
|
|
/** @var array */ |
|
11
|
|
|
protected $groups = []; |
|
12
|
|
|
|
|
13
|
|
|
/** @var bool */ |
|
14
|
|
|
protected $startNewGroup = true; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param string $operation |
|
18
|
|
|
* @param string $argument |
|
19
|
|
|
* |
|
20
|
|
|
* @return static |
|
21
|
|
|
*/ |
|
22
|
|
|
public function addManipulation(string $operation, string $argument) |
|
23
|
|
|
{ |
|
24
|
|
|
if ($this->startNewGroup) { |
|
25
|
|
|
$this->groups[] = []; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
$lastIndex = count($this->groups) - 1; |
|
29
|
|
|
|
|
30
|
|
|
$this->groups[$lastIndex][$operation] = $argument; |
|
31
|
|
|
|
|
32
|
|
|
$this->startNewGroup = false; |
|
33
|
|
|
|
|
34
|
|
|
return $this; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function merge(ManipulationSequence $manipulationSets) |
|
38
|
|
|
{ |
|
39
|
|
|
foreach($manipulationSets->toArray() as $manipulationSet) { |
|
|
|
|
|
|
40
|
|
|
foreach($manipulationSet as $name => $argument) { |
|
41
|
|
|
$this->addManipulation($name, $argument); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if(next($manipulationSets)) { |
|
45
|
|
|
$this->startNewGroup(); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @return static |
|
52
|
|
|
*/ |
|
53
|
|
|
public function startNewGroup() |
|
54
|
|
|
{ |
|
55
|
|
|
$this->startNewGroup = true; |
|
56
|
|
|
|
|
57
|
|
|
return $this; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function toArray(): array |
|
61
|
|
|
{ |
|
62
|
|
|
return $this->getGroups(); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function getGroups(): array |
|
66
|
|
|
{ |
|
67
|
|
|
return $this->sanitizeManipulationSets($this->groups); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
public function getIterator(): ArrayIterator |
|
71
|
|
|
{ |
|
72
|
|
|
return new ArrayIterator($this->groups); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
public function removeManipulation($manipulationName) |
|
76
|
|
|
{ |
|
77
|
|
|
foreach($this->groups as &$group) { |
|
78
|
|
|
if (array_key_exists($manipulationName, $group)) { |
|
79
|
|
|
unset($group[$manipulationName]); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
return $this; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
protected function sanitizeManipulationSets(array $groups): array |
|
87
|
|
|
{ |
|
88
|
|
|
return array_values(array_filter($groups, function(array $manipulationSet) { |
|
89
|
|
|
return count($manipulationSet); |
|
90
|
|
|
})); |
|
91
|
|
|
} |
|
92
|
|
|
} |
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: