Completed
Push — master ( f6a0b6...8e4f56 )
by Filipe
02:21
created

HasOne::load()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 20
ccs 15
cts 15
cp 1
rs 9.4285
cc 2
eloc 13
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of slick/orm package
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Slick\Orm\Mapper\Relation;
11
12
use Slick\Common\Utils\Text;
13
use Slick\Database\Sql;
14
use Slick\Orm\Entity\EntityCollection;
15
use Slick\Orm\EntityInterface;
16
use Slick\Orm\Event\Delete;
17
use Slick\Orm\Event\Select;
18
use Slick\Orm\Orm;
19
20
/**
21
 * HasOne (one-to-one) relation
22
 * 
23
 * @package Slick\Orm\Mapper\Relation
24
 * @author  Filipe Silva <[email protected]>
25
 */
26
class HasOne extends BelongsTo
27
{
28
29
    /**
30
     * Handles the before select callback
31
     *
32
     * @param Select $event
33
     */
34 4 View Code Duplication
    public function beforeSelect(Select $event)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
    {
36 4
        if ($this->isLazyLoaded()) {
37 2
            return;
38
        }
39
40 2
        $fields = $this->getFieldsPrefixed();
41 2
        $table = $this->entityDescriptor->getTableName();
42 2
        $relateTable = $this->getParentTableName();
43 2
        $pmk = $this->entityDescriptor->getPrimaryKey()->getField();
44
45 2
        $onClause = "{$table}.{$pmk} = ".
46 2
            "{$relateTable}.{$this->getForeignKey()}";
47
48 2
        $query = $event->getQuery();
49 2
        $query->join($relateTable, $onClause, $fields, $relateTable);
50 2
    }
51
52
    /**
53
     * Gets the foreign key field name
54
     *
55
     * @return string
56
     */
57 4 View Code Duplication
    public function getForeignKey()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
    {
59 4
        if (is_null($this->foreignKey)) {
60 4
            $name = $this->getEntityDescriptor()->getTableName();
61 4
            $name = Text::singular(strtolower($name));
62 4
            $this->foreignKey = "{$name}_id";
63 2
        }
64 4
        return $this->foreignKey;
65
    }
66
67
    /**
68
     * Loads the entity or entity collection for this relation
69
     *
70
     * @param EntityInterface $entity
71
     *
72
     * @return null|EntityInterface
73
     */
74 2
    public function load(EntityInterface $entity)
75
    {
76 2
        $adapter = $this->getAdapter();
77 2
        $relTable = $this->getParentTableName();
78 2
        $pmk = $this->getEntityDescriptor()->getPrimaryKey();
79 2
        $fnk = $this->getForeignKey();
80
81 2
        $data = Sql::createSql($adapter)
82 2
            ->select($relTable)
83 2
            ->where([
0 ignored issues
show
Documentation introduced by
array("{$relTable}.{$fnk...$entity->{$pmk->name})) is of type array<string|integer,array<string,?,{":id":"?"}>>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84 2
                "{$relTable}.{$fnk} = :id" => [
85 2
                    ':id' => $entity->{$pmk->name}
86 1
                ]
87 1
            ])
88 2
            ->first();
89
90 2
        $relEntity = $this->getParentEntityMapper()->createFrom($data);
91
92 2
        return null == $relEntity ? null :$this->registerEntity($relEntity);
0 ignored issues
show
Bug introduced by
It seems like $relEntity defined by $this->getParentEntityMapper()->createFrom($data) on line 90 can also be of type array<integer,object<Sli...EntityMapperInterface>>; however, Slick\Orm\Mapper\Relatio...ation::registerEntity() does only seem to accept object<Slick\Orm\EntityI...ntity\EntityCollection>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
93
    }
94
95
    /**
96
     * Deletes the related entity for before deleting current entity
97
     * 
98
     * @param Delete $event
99
     */
100 2
    public function beforeDelete(Delete $event)
101
    {
102 2
        $parent = $event->getEntity()->{$this->propertyName};
103 2
        if ($parent instanceof EntityInterface) {
104 2
            $parent->delete();
105 1
        }
106 2
    }
107
108
    /**
109
     * Registers the listener for before select event
110
     */
111 12
    protected function registerListeners()
112
    {
113 12
        Orm::addListener(
114 12
            $this->entityDescriptor->className(),
115 12
            Select::ACTION_BEFORE_SELECT,
116 12
            [$this, 'beforeSelect']
117 6
        );
118
119 12
        Orm::addListener(
120 12
            $this->entityDescriptor->className(),
121 12
            Select::ACTION_AFTER_SELECT,
122 12
            [$this, 'afterSelect']
123 6
        );
124
125 12
        Orm::addListener(
126 12
            $this->entityDescriptor->className(),
127 12
            Delete::ACTION_BEFORE_DELETE,
128 12
            [$this, 'beforeDelete']
129 6
        );
130 12
    }
131
132
    /**
133
     * Check if entity is already loaded and uses it.
134
     *
135
     * If not loaded the entity will be created and loaded to the repository's
136
     * identity map so that it can be reused next time.
137
     *
138
     * @param array $dataRow
139
     *
140
     * @return null|EntityCollection|EntityInterface|EntityInterface[]
141
     */
142 3
    protected function getFromMap($dataRow)
143
    {
144 2
        $tableName = $this->getParentTableName();
145 2
        $pmk = $this->getParentPrimaryKey();
146 2
        $index = "{$tableName}_{$pmk}";
147 2
        $entity = $this->getParentRepository()
148 2
            ->getIdentityMap()
149 3
            ->get($dataRow[$index], false);
150
151 2
        if (false === $entity) {
152 2
            $entity = $this->map($dataRow);
153 1
        }
154 2
        return $entity;
155
    }
156
    
157
}