Passed
Push — master ( d07642...e03816 )
by Fran
02:05
created

NOSQLModelDto   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 178
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 36
eloc 77
dl 0
loc 178
rs 9.52
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A setLastUpdate() 0 3 2
A validate() 0 17 5
A setName() 0 3 1
A resetPk() 0 3 1
A getLastUpdate() 0 7 2
A getPk() 0 3 1
A getName() 0 3 1
A setPk() 0 6 2
A toArray() 0 11 3
D checkType() 0 50 18
1
<?php
2
namespace NOSQL\Dto\Model;
3
4
use MongoDB\BSON\UTCDateTime;
5
use NOSQL\Exceptions\NOSQLValidationException;
6
use NOSQL\Services\Base\NOSQLBase;
7
use PSFS\base\dto\Dto;
8
use PSFS\base\types\Api;
9
use PSFS\base\types\helpers\InjectorHelper;
10
11
/**
12
 * Class NOSQLModelDto
13
 * @package NOSQL\Dto\Model
14
 */
15
abstract class NOSQLModelDto extends Dto {
16
    /**
17
     * @var string
18
     * @label Model identifier
19
     */
20
    protected $_id;
21
22
    /**
23
     * @var \DateTime
24
     * @label Last update at
25
     */
26
    protected $_last_update;
27
28
29
    /**
30
     * @var string
31
     * @label List name in string
32
     */
33
    protected $__name__;
34
35
    /**
36
     * @return string
37
     */
38
    public function getPk()
39
    {
40
        return $this->_id;
41
    }
42
43
    public function resetPk() {
44
        $this->_id = null;
45
        $this->_last_update = null;
46
    }
47
48
    /**
49
     * @param string $id
50
     * @throws NOSQLValidationException
51
     */
52
    public function setPk(string $id)
53
    {
54
        if(!empty($this->_id)) {
55
            throw new NOSQLValidationException(t('Primary key already defined'), NOSQLValidationException::NOSQL_VALIDATION_ID_ALREADY_DEFINED);
56
        }
57
        $this->_id = $id;
58
    }
59
60
    /**
61
     * @param string $format
62
     * @return \DateTime|string
63
     */
64
    public function getLastUpdate($format = null)
65
    {
66
        $value = $this->_last_update;
67
        if(null !== $format) {
68
69
        }
70
        return $value;
71
    }
72
73
    /**
74
     * @param \DateTime|null $last_update
75
     * @throws \Exception
76
     */
77
    public function setLastUpdate($last_update = null)
78
    {
79
        $this->_last_update = $last_update ?: new UTCDateTime();
0 ignored issues
show
Documentation Bug introduced by
It seems like $last_update ?: new MongoDB\BSON\UTCDateTime() can also be of type MongoDB\BSON\UTCDateTime. However, the property $_last_update is declared as type DateTime. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    public function getName()
86
    {
87
        return $this->__name__;
88
    }
89
90
    /**
91
     * @param string $_name__
92
     */
93
    public function setName($_name__)
94
    {
95
        $this->__name__ = $_name__;
96
    }
97
98
    /**
99
     * @param bool $throwException
100
     * @return array
101
     * @throws NOSQLValidationException
102
     * @throws \ReflectionException
103
     */
104
    public function validate($throwException = false) {
105
        $errors = [];
106
        $reflection = new \ReflectionClass(get_called_class());
107
        foreach($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
108
            $required = InjectorHelper::checkIsRequired($property->getDocComment());
109
            $value = $property->getValue($this);
110
            if($required && empty($value)) {
111
                if($throwException) {
112
                    throw new NOSQLValidationException(t('Empty value for property ') . $property->getName(), NOSQLValidationException::NOSQL_VALIDATION_REQUIRED);
113
                } else {
114
                    $errors[] = $property->getName();
115
                }
116
            } else {
117
                $this->checkType($throwException, $property, $value, $errors);
118
            }
119
        }
120
        return $errors;
121
    }
122
123
    public function toArray()
124
    {
125
        $array = parent::toArray();
126
        if(null !== $this->getPk()) {
0 ignored issues
show
introduced by
The condition null !== $this->getPk() is always true.
Loading history...
127
            $array['_id'] = $this->getPk();
128
        }
129
        if(null !== $this->getName()) {
0 ignored issues
show
introduced by
The condition null !== $this->getName() is always true.
Loading history...
130
            $array[Api::API_LIST_NAME_FIELD] = $this->getName();
131
        }
132
        $array['_last_update'] = $this->getLastUpdate(\DateTime::ATOM);
133
        return $array;
134
    }
135
136
    /**
137
     * @param $throwException
138
     * @param \ReflectionProperty $property
139
     * @param $value
140
     * @param array $errors
141
     * @throws NOSQLValidationException
142
     */
143
    private function checkType($throwException, \ReflectionProperty &$property, $value, array &$errors)
144
    {
145
        $type = InjectorHelper::extractVarType($property->getDocComment());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $type is correct as PSFS\base\types\helpers\...perty->getDocComment()) targeting PSFS\base\types\helpers\...elper::extractVarType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
146
        switch (strtolower($type)) {
147
            case NOSQLBase::NOSQL_TYPE_LONG:
148
            case NOSQLBase::NOSQL_TYPE_INTEGER:
149
            case NOSQLBase::NOSQL_TYPE_DOUBLE:
150
                if (!is_numeric($value)) {
151
                    $errors[] = $property->getName();
152
                } else {
153
                    if(NOSQLBase::NOSQL_TYPE_INTEGER === strtolower($type)) {
154
                        $property->setValue($this, (integer)$value);
155
                    } else {
156
                        $property->setValue($this, (float)$value);
157
                    }
158
                }
159
                break;
160
            case NOSQLBase::NOSQL_TYPE_ENUM:
161
                $values = InjectorHelper::getValues($property->getDocComment());
162
                if (!in_array($value, $values)) {
0 ignored issues
show
Bug introduced by
It seems like $values can also be of type null; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

162
                if (!in_array($value, /** @scrutinizer ignore-type */ $values)) {
Loading history...
163
                    $errors[] = $property->getName();
164
                }
165
                break;
166
            case NOSQLBase::NOSQL_TYPE_OBJECT:
167
                $property->setValue($this, json_decode($value, true));
168
                break;
169
            case NOSQLBase::NOSQL_TYPE_ARRAY:
170
                if (!is_array($value)) {
171
                    $errors[] = $property->getName();
172
                }
173
                break;
174
            case NOSQLBase::NOSQL_TYPE_BOOLEAN:
175
                if (!in_array($value, [true, false, 0, 1])) {
176
                    $errors[] = $property->getName();
177
                }
178
                $property->setValue($this, (bool)$value);
179
                break;
180
            case NOSQLBase::NOSQL_TYPE_DATE:
181
            case NOSQLBase::NOSQL_TYPE_TIMESTAMP:
182
                $dateTime = new \DateTime($value, new \DateTimeZone('UTC'));
183
                if(!$dateTime) {
0 ignored issues
show
introduced by
$dateTime is of type DateTime, thus it always evaluated to true.
Loading history...
184
                    $errors[] = $property->getName();
185
                } else {
186
                    $dateTime->setTimezone(new \DateTimeZone(date_default_timezone_get()));
187
                    $property->setValue($this, new UTCDateTime($dateTime->getTimestamp()*1000));
188
                }
189
                break;
190
        }
191
        if (in_array($property->getName(), $errors) && $throwException) {
192
            throw new NOSQLValidationException(t('Format not valid for property ') . $property->getName(), NOSQLValidationException::NOSQL_VALIDATION_NOT_VALID);
193
        }
194
    }
195
}