Passed
Push — main ( c49c6c...49fc69 )
by Gaetano
08:47
created

ReferenceSetterTrait::addReference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\AbstractCollection;
6
use Kaliop\eZMigrationBundle\API\Exception\InvalidMatchResultsNumberException;
7
use Kaliop\eZMigrationBundle\API\Exception\InvalidStepDefinitionException;
8
use Kaliop\eZMigrationBundle\API\ReferenceBagInterface;
9
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
10
11
/**
12
 * A trait to be used by Executors which has code useful to set values to references.
13
 * @todo add a method that validates the 'references' key. Atm all we can check is that it is an array (we could as well
14
 * reject empty reference arrays in fact)
15
 */
16
trait ReferenceSetterTrait
17
{
18
    protected function addReference($identifier, $value, $overwrite = false)
19
    {
20
        /** @var ReferenceBagInterface $this->referenceResolver */
21
        return $this->referenceResolver->addReference($identifier, $value, $overwrite);
22
    }
23
24
    /**
25
     * Allows to have refs defined using two syntax variants:
26
     *   - { identifier: xxx, attribute: yyy, overwrite: bool }
27
     * or
28
     *   identifier: attribute
29
     * @param $key
30
     * @param $value
31
     * @return array
32
     * @throws InvalidStepDefinitionException
33
     *
34
     * @todo should we resolve references in ref identifiers, attributes and overwrite? Inception! :-D
35
     */
36
    protected function parseReferenceDefinition($key, $value)
37
    {
38
        if (is_string($key) && is_string($value)) {
39
            return array('identifier' => $key, 'attribute' => $value);
40
        }
41
        if (!is_array($value) || !isset($value['identifier']) || ! isset($value['attribute'])) {
42
            throw new InvalidStepDefinitionException("Invalid reference definition for reference number $key");
43
        }
44
        return $value;
45
    }
46
47
    /**
48
     * Valid reference values are either scalars or nested arrays. No objects, no resources.
49
     * @param mixed $value
50
     * @return bool
51
     */
52
    protected function isValidReferenceValue($value)
53
    {
54
        if (is_scalar($value)) {
55
            return true;
56
        }
57
        if (is_object($value) || is_resource($value)) {
58
            return false;
59
        }
60
        foreach($value as $subValue) {
61
            if (!$this->isValidReferenceValue($subValue)) {
62
                return false;
63
            }
64
        }
65
        return true;
66
    }
67
}
68