BaseMongoEntityModel::find()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 0
crap 2
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\base\models\models;
14
15
use MongoDB\BSON\Binary;
16
use MongoDB\BSON\ObjectID;
17
use rhosocial\base\helpers\Number;
18
use rhosocial\base\helpers\IP;
19
use rhosocial\base\models\queries\BaseMongoEntityQuery;
20
use rhosocial\base\models\traits\EntityTrait;
21
use yii\mongodb\ActiveRecord;
22
23
/**
24
 * Description of BaseMongoEntityModel
25
 *
26
 * @property string $GUID GUID value in readable format (same as $readableGUID).
27
 * @property ObjectID $ID
28
 * @version 1.0
29
 * @author vistart <[email protected]>
30
 */
31
abstract class BaseMongoEntityModel extends ActiveRecord
32
{
33
    use EntityTrait;
34
    
35 73
    public function getGUIDRules()
36
    {
37 73
        $rules = [];
38 73
        if (is_string($this->guidAttribute) || !empty($this->guidAttribute)) {
39
            $rules = [
40 15
                [[$this->guidAttribute], 'required',],
41
            ];
42
        }
43 73
        return $rules;
44
    }
45
    
46 9
    public function getGUID()
47
    {
48 9
        $guidAttribute = $this->guidAttribute;
49 9
        return (!is_string($guidAttribute) || empty($guidAttribute)) ? null : $this->$guidAttribute->getData();
50
    }
51
    
52 74
    public function setGUID($guid)
53
    {
54 74
        $guidAttribute = $this->guidAttribute;
55 74
        if (!is_string($guidAttribute) || empty($guidAttribute)) {
56 58
            return null;
57
        }
58 16
        if (preg_match(Number::GUID_REGEX, $guid)) {
59 3
            $guid = hex2bin(str_replace(['{', '}', '-'], '', $guid));
60
        }
61 16
        return $this->$guidAttribute = new Binary($guid, Binary::TYPE_UUID);
62
    }
63
    
64
    /**
65
     * Check if the $guid existed in current database table.
66
     * @param string|Binary $guid the GUID to be checked.
67
     * @return boolean Whether the $guid exists or not.
68
     */
69 3
    public static function checkGuidExists($guid)
70
    {
71 3
        if (is_string($guid)) {
72 3
            if (strlen($guid) == 16) {
73 3
                $binary = new Binary($guid, Binary::TYPE_UUID);
74 3
            } elseif (preg_match(Number::GUID_REGEX, $guid)) {
75 3
                $binary = new Binary(Number::guid_bin($guid), Binary::TYPE_UUID);
76
            } else {
77 3
                return false;
78
            }
79 3
            return static::findOne($binary) !== null;
80
        }
81 3
        if ($guid instanceof Binary) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\Binary does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
82 3
            return static::findOne($guid) !== null;
83
        }
84 3
        return false;
85
    }
86
    
87
    /**
88
     * Get the rules associated with ip attributes.
89
     * @return array
90
     */
91 73
    public function getIPRules()
92
    {
93 73
        $rules = [];
94 73
        if ($this->enableIP & static::$ipv4) {
95
            $rules = [
96 73
                [[$this->ipAttribute],
97 73
                    'string'
98
                ],
99
            ];
100
        }
101 73
        if ($this->enableIP & static::$ipv6) {
102
            $rules = [
103 73
                [[$this->ipAttribute],
104 73
                    'string'
105
                ],
106
            ];
107
        }
108 73
        if ($this->enableIP & static::$ipAll) {
109 73
            $rules[] = [
110 73
                [$this->ipTypeAttribute], 'in', 'range' => [IP::IPv4, IP::IPv6],
111
            ];
112
        }
113 73
        return $rules;
114
    }
115
    
116
    /**
117
     * Get the IPv4 address.
118
     * @return string
119
     */
120 3
    protected function getIPv4Address()
121
    {
122 3
        return ($this->{$this->ipAttribute});
123
    }
124
    
125
    /**
126
     * Get the IPv6 address.
127
     * @return string
128
     */
129 3
    protected function getIPv6Address()
130
    {
131 3
        return ($this->{$this->ipAttribute});
132
    }
133
    
134 3
    protected function setIPv4Address($ipAddress)
135
    {
136 3
        return $this->{$this->ipAttribute} = ($ipAddress);
137
    }
138
    
139 3
    protected function setIPv6Address($ipAddress)
140
    {
141 3
        return $this->{$this->ipAttribute} = ($ipAddress);
142
    }
143
144
    /**
145
     * Initialize new entity.
146
     */
147 74
    public function init()
148
    {
149 74
        $this->idAttribute = '_id';
150 74
        $this->idAttributeType = static::$idTypeAutoIncrement;
151 74
        if ($this->skipInit) {
152 15
            return;
153
        }
154 74
        $this->initEntityEvents();
155 74
        parent::init();
156 74
    }
157
158
    /**
159
     * @inheritdoc
160
     * @return BaseMongoEntityQuery the newly created [[BaseMongoEntityQuery]] or its sub-class instance.
161
     */
162 61
    public static function find()
163
    {
164 61
        $self = static::buildNoInitModel();
165
        /* @var $self static */
166 61
        if (!is_string($self->queryClass)) {
167 3
            $self->queryClass = BaseMongoEntityQuery::class;
168
        }
169 61
        $queryClass = $self->queryClass;
170 61
        return new $queryClass(get_called_class(), ['noInitModel' => $self]);
171
    }
172
173
    /**
174
     * @inheritdoc
175
     * You can override this method if enabled fields cannot meet you requirements.
176
     * @return array
177
     */
178 16
    public function attributes()
179
    {
180 16
        return $this->enabledFields();
181
    }
182
    
183
    /**
184
     * 
185
     * @param array $models
186
     */
187 7
    public static function compositeGUIDs($models) {
188 7
        if (empty($models)) {
189 1
            return null;
190
        }
191 7
        if (!is_array($models) && $models instanceof static) {
192 1
            return new Binary($models->getGUID(), Binary::TYPE_UUID);
193
        }
194 7
        if (is_string($models) && strlen($models) == 16) {
195 2
            return new Binary($models, Binary::TYPE_UUID);
196
        }
197 5
        $guids = [];
198 5
        foreach ($models as $model) {
0 ignored issues
show
Bug introduced by
The expression $models of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
199 5
            if ($model instanceof static || $model instanceof BaseEntityModel) {
200 1
                $guids[] = new Binary($model->getGUID(), Binary::TYPE_UUID);
201 5
            } elseif (is_string($model) && preg_match(Number::GUID_REGEX, $model)) {
202 1
                $guids[] = new Binary(Number::guid_bin($model), Binary::TYPE_UUID);
203 4
            } elseif (is_string($model) && strlen($model) == 16) {
204 4
                $guids[] = new Binary($model, Binary::TYPE_UUID);
205
            }
206
        }
207 5
        return $guids;
208
    }
209
}
210