getValueFromReferencedEntity()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
/*
4
* This file is part of the moss-storage package
5
*
6
* (c) Michal Wachowski <[email protected]>
7
*
8
* For the full copyright and license information, please view the LICENSE
9
* file that was distributed with this source code.
10
*/
11
12
namespace Moss\Storage\Query;
13
14
use Moss\Storage\Model\Definition\FieldInterface;
15
16
/**
17
 * Abstract Entity Values Query
18
 * Provides functionality for changing entity values
19
 *
20
 * @package Moss\Storage\Query\OperationTraits
21
 */
22
abstract class AbstractEntityValueQuery extends AbstractEntityQuery
23
{
24
    /**
25
     * Sets field names which values will be written
26
     *
27
     * @param array $fields
28
     *
29
     * @return $this
30
     */
31
    public function values($fields = [])
32
    {
33
        $parts = $this->builder()->getQueryParts();
34
        foreach (['set', 'value'] as $part) {
35
            if (isset($parts[$part])) {
36
                $this->builder()->resetQueryPart($part);
37
            }
38
        }
39
40
        $this->resetBinds('value');
41
42
        if (empty($fields)) {
43
            foreach ($this->model()->fields() as $field) {
44
                $this->assignValue($field);
45
            }
46
47
            return $this;
48
        }
49
50
        foreach ($fields as $field) {
51
            $this->assignValue($this->model()->field($field));
52
        }
53
54
        return $this;
55
    }
56
57
    /**
58
     * Adds field which value will be written
59
     *
60
     * @param string $field
61
     *
62
     * @return $this
63
     */
64
    public function value($field)
65
    {
66
        $this->assignValue($this->model()->field($field));
67
68
        return $this;
69
    }
70
71
    /**
72
     * Assigns value to query
73
     *
74
     * @param FieldInterface $field
75
     */
76
    abstract protected function assignValue(FieldInterface $field);
77
78
    /**
79
     * Gets value from first referenced entity that has it
80
     *
81
     * @param FieldInterface $field
82
     */
83
    protected function getValueFromReferencedEntity(FieldInterface $field)
84
    {
85
        $references = $this->model->referredIn($field->name());
86
        foreach ($references as $foreign => $reference) {
87
            $entity = $this->accessor->getPropertyValue($this->instance, $reference->container());
88
89
            if ($entity === null) {
90
                continue;
91
            }
92
93
            $value = $this->accessor->getPropertyValue($entity, $foreign);
94
            $this->accessor->setPropertyValue($this->instance, $field->name(), $value);
95
            break;
96
        }
97
    }
98
}
99