RemoveAtAction::execute()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 32
rs 8.439
cc 6
eloc 17
nc 6
nop 0
1
<?php
2
/**
3
 * NextFlow (http://github.com/nextflow)
4
 *
5
 * @link http://github.com/nextflow/nextflow-php for the canonical source repository
6
 * @copyright Copyright (c) 2014-2016 NextFlow (http://github.com/nextflow)
7
 * @license https://raw.github.com/nextflow/nextflow-php/master/LICENSE MIT
8
 */
9
10
namespace NextFlow\Arrays\Action;
11
12
use NextFlow\Core\Action\AbstractAction;
13
14
/**
15
 * Removes the element at a certain position.
16
 */
17
final class RemoveAtAction extends AbstractAction
18
{
19
    /** The output action socket. */
20
    const SOCKET_OUTPUT = 'out';
21
22
    /** The array variable socket. */
23
    const SOCKET_ARRAY = 'array';
24
25
    /** The index variable socket. */
26
    const SOCKET_INDEX = 'index';
27
28
    /** The data variable socket. */
29
    const SOCKET_DATA = 'data';
30
31
    /**
32
     * Initializes a new instance of this class.
33
     */
34
    public function __construct()
35
    {
36
        parent::__construct();
37
38
        $this->createSocket(self::SOCKET_OUTPUT);
39
        $this->createSocket(self::SOCKET_ARRAY);
40
        $this->createSocket(self::SOCKET_INDEX);
41
        $this->createSocket(self::SOCKET_DATA);
42
    }
43
44
    /**
45
     * Executes the node's logic.
46
     */
47
    public function execute()
48
    {
49
        $array = $this->getSocket(self::SOCKET_ARRAY)->getNode(0);
50
        if ($array === null) {
51
            throw new \InvalidArgumentException('No array variable provided.');
52
        }
53
54
        $index = $this->getSocket(self::SOCKET_INDEX)->getNode(0);
55
        if ($index === null || $index->getValue() === null) {
56
            throw new \InvalidArgumentException('No index variable provided.');
57
        }
58
59
        // It could be that the array is an associative array. Therefor we cannot simply remove it by index, we
60
        // have to count up the index and than check the key. That key is used to remove the value.
61
62
        $arrayValue = $array->getValue();
63
64
        for ($i = 0; $i < $index->getValue(); ++$i) {
65
            next($arrayValue);
66
        }
67
68
        $removedValue = current($arrayValue);
69
        unset($arrayValue[key($arrayValue)]);
70
71
        $data = $this->getSocket(self::SOCKET_DATA);
72
        if ($data->hasNodes()) {
73
            $data->getNode(0)->setValue($removedValue);
74
        }
75
76
        $array->setValue($arrayValue);
77
        $this->activate(self::SOCKET_OUTPUT);
78
    }
79
}
80