Completed
Push — master ( fd1400...ffadf1 )
by Andrii
05:34
created

BaseRepository::findRecordClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * HiAPI Yii2 base project for building API
4
 *
5
 * @link      https://github.com/hiqdev/hiapi
6
 * @package   hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiapi\repositories;
12
13
use hiapi\components\ConnectionInterface;
14
use hiapi\query\Specification;
15
use Yii;
16
17
abstract class BaseRepository extends \yii\base\Component
18
{
19
    /**
20
     * @var ConnectionInterface
21
     */
22
    protected $db;
23
24
    protected $factory;
25
26
    /**
27
     * @var string
28
     */
29
    public $queryClass;
30
31
    public function find(ActiveQuery $query)
32
    {
33
        $query->setRepository($this);
34
35
        return $query;
36
    }
37
38
    public function setRecordClass($value)
39
    {
40
        $this->recordClass = $value;
0 ignored issues
show
Documentation introduced by
The property recordClass does not exist on object<hiapi\repositories\BaseRepository>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
41
    }
42
43
    public function getRecordClass()
44
    {
45
        if ($this->recordClass === null) {
0 ignored issues
show
Documentation introduced by
The property recordClass does not exist on object<hiapi\repositories\BaseRepository>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
46
            $this->recordClass = $this->findRecordClass();
0 ignored issues
show
Documentation introduced by
The property recordClass does not exist on object<hiapi\repositories\BaseRepository>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
47
        }
48
49
        return $this->recordClass;
0 ignored issues
show
Documentation introduced by
The property recordClass does not exist on object<hiapi\repositories\BaseRepository>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
50
    }
51
52
    public function findRecordClass()
53
    {
54
        $parts = explode('\\', get_called_class());
55
56
        return implode('\\', $parts);
57
    }
58
59
    public function findAll(Specification $specification)
60
    {
61
        $rows = $this->queryAll($specification);
62
        $rows = $this->findAllRelations($specification, $rows);
63
64
        return $this->createMultiple($rows);
65
    }
66
67
    public function queryAll(Specification $specification)
68
    {
69
        $query = $this->buildSelectQuery($specification);
70
        $rows = $query->createCommand($this->db)->queryAll();
0 ignored issues
show
Documentation introduced by
$this->db is of type object<hiapi\components\ConnectionInterface>, but the function expects a object<yii\db\Connection>|null.

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...
71
72
        return array_map(function ($row) use ($query) {
73
            return $query->restoreHierarchy($row);
74
        }, $rows);
75
    }
76
77
    public function findOne(Specification $specification)
78
    {
79
        $rows = $this->findAll($specification->limit(1));
80
81
        return reset($rows);
82
    }
83
84
    /// TODO rename
85
    public function findAllRelations(Specification $specification, array $rows)
86
    {
87
        //debug_print_backtrace();
88
        if (is_array($specification->with)) {
89
            foreach ($specification->with as $class) {
90
                /// XXX hardcoded for price
91
                /// TODO generalize
92
                $ids = $this->getIds($rows);
93
                $spec = Yii::createObject(Specification::class)
94
                    //->where(['in', 'plan-id', $ids]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
79% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
95
                    ->where(['plan-id' => reset($ids)]);
96
                $rels = $this->getRepository($class)->queryAll($spec);
97
                foreach ($rels as &$rel) {
98
                    foreach ($rows as &$row) {
99
                        if ($row['id'] === $rel['plan']['id']) {
100
                            $row['prices'][] = $rel;
101
                        }
102
                    }
103
                }
104
            }
105
        }
106
107
        return $rows;
108
    }
109
110
    protected function getIds($rows)
111
    {
112
        $ids = [];
113
        foreach ($rows as $row) {
114
            $ids[$row['id']] = $row['id'];
115
        }
116
117
        return $ids;
118
    }
119
120
    public function old_findOne(Specification $specification)
121
    {
122
        $specification->limit(1);
123
        $query = $this->buildSelectQuery($specification);
124
        $row = $query->createCommand($this->db)->queryOne();
0 ignored issues
show
Documentation introduced by
$this->db is of type object<hiapi\components\ConnectionInterface>, but the function expects a object<yii\db\Connection>|null.

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...
125
        $row = $query->restoreHierarchy($row);
126
127
        return $this->create($row);
128
    }
129
130
    protected function buildSelectQuery(Specification $specification)
131
    {
132
        return $specification->applyTo($this->buildQuery()->initSelect());
133
    }
134
135
    protected function buildQuery()
136
    {
137
        return Yii::createObject($this->getQueryClass());
138
    }
139
140
    protected function getQueryClass()
141
    {
142
        return $this->queryClass;
143
    }
144
145
    protected function createMultiple($rows)
146
    {
147
        $entities = [];
148
        foreach ($rows as $row) {
149
            $entities[] = $this->create($row);
150
        }
151
152
        return $entities;
153
    }
154
155
    protected function create(array $row)
156
    {
157
        return $this->factory->create($this->createDto($row));
158
    }
159
160
    protected function createDto(array $row)
161
    {
162
        $class = $this->getEntityCreationDtoClass();
163
        $dto = new $class();
164
        $props = array_keys(get_object_vars($dto));
165
166
        foreach ($props as $name) {
167
            if (isset($row[$name])) {
168
                $dto->$name = $row[$name];
169
            }
170
        }
171
172
        return $dto;
173
    }
174
175
    protected function getEntityCreationDtoClass()
176
    {
177
        $class = new \ReflectionClass($this->factory);
178
        $method = $class->getMethod('create');
179
        $arg = reset($method->getParameters());
0 ignored issues
show
Bug introduced by
$method->getParameters() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
180
181
        return $arg->getClass()->getName();
182
    }
183
184
    public function createEntity($entityClass, $row)
185
    {
186
        return $this->getRepository($entityClass)->create($row);
187
    }
188
189
    public function getRepository($entityClass)
190
    {
191
        return Yii::$app->entityManager->getRepository($entityClass);
192
    }
193
}
194