Completed
Push — master ( ed783e...f43f89 )
by Dmitry
12:30
created

BulkCommand::offsetUnset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace hiapi\commands;
4
5
use ArrayAccess;
6
use Countable;
7
use Doctrine\Common\Collections\ArrayCollection;
8
use IteratorAggregate;
9
use yii\base\Model;
10
11
/**
12
 * Class BulkCommand
13
 *
14
 * @author Dmytro Naumenko <[email protected]>
15
 */
16
final class BulkCommand extends BaseCommand implements Countable, IteratorAggregate, ArrayAccess
17
{
18
    /**
19
     * @var ArrayCollection
20
     */
21
    private $collection;
22
    /**
23
     * @var string
24
     */
25
    private $commandClassName;
26
27
    public static function of(string $className): self
28
    {
29
        $self = new self();
30
        $self->commandClassName = $className;
31
32
        return $self;
33
    }
34
35
    public function init(): void
36
    {
37
        parent::init();
38
39
        $this->collection = new ArrayCollection();
40
    }
41
42
    public function load($data, $formName = null): bool
43
    {
44
        $data = array_filter($data, 'is_array');
45
46
        for ($i = 0, $iMax = count($data); $i < $iMax; $i++) {
47
            $this->collection->add(new $this->commandClassName);
48
        }
49
50
        return self::loadMultiple($this->collection, $data, $formName);
51
    }
52
53
    public function validate($attributeNames = null, $clearErrors = true)
54
    {
55
        return array_reduce($this->collection->toArray(), static function (bool $isValid, BaseCommand $command): bool {
56
            return $command->validate() && $isValid;
57
        }, true);
58
    }
59
60
    public function add($command): self
61
    {
62
        $this->collection->add($command);
63
64
        return $this;
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70
    public function count()
71
    {
72
        return $this->collection->count();
73
    }
74
75
    /**
76
     * @inheritDoc
77
     */
78
    public function getIterator()
79
    {
80
        return $this->collection->getIterator();
81
    }
82
83
    /**
84
     * @inheritDoc
85
     */
86
    public function offsetExists($offset)
87
    {
88
        return $this->collection->offsetExists($offset);
89
    }
90
91
    /**
92
     * @inheritDoc
93
     */
94
    public function offsetGet($offset)
95
    {
96
        return $this->collection->offsetGet($offset);
97
    }
98
99
    /**
100
     * @inheritDoc
101
     */
102
    public function offsetSet($offset, $value)
103
    {
104
        return $this->collection->offsetSet($offset, $value);
105
    }
106
107
    /**
108
     * @inheritDoc
109
     */
110
    public function offsetUnset($offset)
111
    {
112
        return $this->collection->offsetUnset($offset);
113
    }
114
}
115