YmlCatalog::getNewModel()   B
last analyzed

Complexity

Conditions 11
Paths 12

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 18.744

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 9
cts 15
cp 0.6
rs 7.1162
cc 11
eloc 15
nc 12
nop 1
crap 18.744

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace pastuhov\ymlcatalog;
3
4
use pastuhov\ymlcatalog\models\BaseModel;
5
use pastuhov\ymlcatalog\models\Category;
6
use pastuhov\ymlcatalog\models\Currency;
7
use pastuhov\ymlcatalog\models\LocalDeliveryCost;
8
use pastuhov\ymlcatalog\models\Shop;
9
use pastuhov\ymlcatalog\models\SimpleOffer;
10
use pastuhov\ymlcatalog\models\DeliveryOption;
11
use Yii;
12
use pastuhov\FileStream\BaseFileStream;
13
use yii\base\Exception;
14
use yii\data\ActiveDataProvider;
15
use yii\db\ActiveQuery;
16
17
/**
18
 * Yml генератор каталога.
19
 *
20
 * @package pastuhov\ymlcatalog
21
 */
22
class YmlCatalog
23
{
24
    /**
25
     * @var BaseFileStream
26
     */
27
    protected $handle;
28
    /**
29
     * @var string
30
     */
31
    protected $shopClass;
32
    /**
33
     * @var string
34
     */
35
    protected $currencyClass;
36
    /**
37
     * @var string
38
     */
39
    protected $categoryClass;
40
    /**
41
     * @var null|string
42
     */
43
    protected $localDeliveryCostClass;
44
    /**
45
     * @var string
46
     */
47
    protected $offerClass;
48
    /**
49
     * @var null|string
50
     */
51
    protected $date;
52
53
    /**
54
     * @var null|callable
55
     */
56
    protected $onValidationError;
57
58
    /**
59
     * @var null|string
60
     */
61
    protected $customOfferClass;
62
63
    /**
64
     * @var null|string
65
     */
66
    protected $customCategoryClass;
67
68
    /**
69
     * @var null|string
70
     */
71
    protected $deliveryOptionClass;
72
73
    /**
74
     * @param BaseFileStream $handle
75
     * @param string $shopClass class name
76
     * @param string $currencyClass class name
77
     * @param string $categoryClass class name
78
     * @param string $localDeliveryCostClass class name
79 5
     * @param string[] $offerClasses
80
     * @param null|string $date
81
     * @param null|callable $onValidationError
82
     * @param null|string $customOfferClass
83
     * @param null|string $customCategoryClass
84
     * @param string $deliveryOptionClass
85
     */
86
    public function __construct(
87
        BaseFileStream $handle,
88
        $shopClass,
89
        $currencyClass,
90
        $categoryClass,
91 5
        $localDeliveryCostClass = null,
92 5
        Array $offerClasses,
93 5
        $date = null,
94 5
        $onValidationError = null,
95 5
        $customOfferClass = null,
96 5
        $deliveryOptionClass = null,
97 5
        $customCategoryClass = null
98 5
    ) {
99 5
        $this->handle = $handle;
100 5
        $this->shopClass = $shopClass;
101 5
        $this->currencyClass = $currencyClass;
102
        $this->categoryClass = $categoryClass;
103
        $this->localDeliveryCostClass = $localDeliveryCostClass;
104
        $this->offerClasses = $offerClasses;
0 ignored issues
show
Bug introduced by
The property offerClasses does not seem to exist. Did you mean offerClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
105
        $this->date = $date;
106 5
        $this->onValidationError = $onValidationError;
107
        $this->customOfferClass = $customOfferClass;
108 5
        $this->deliveryOptionClass = $deliveryOptionClass;
109
        $this->customCategoryClass = $customCategoryClass;
110 5
    }
111 5
112 5
    /**
113 5
     * @throws Exception
114 5
     */
115
    public function generate()
116 5
    {
117 5
        $date = $this->getDate();
118 5
119 5
        $this->write(
120 5
            '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL .
121 5
            '<!DOCTYPE yml_catalog SYSTEM "shops.dtd">' . PHP_EOL .
122 5
            '<yml_catalog date="' . $date . '">' . PHP_EOL
123 5
        );
124 5
125 4
        $this->writeTag('shop');
126 4
        $this->writeModel(new Shop(), new $this->shopClass());
127 4
        $this->writeTag('currencies');
128 4
        $this->writeEachModel($this->currencyClass);
129 5
        $this->writeTag('/currencies');
130 1
        $this->writeTag('categories');
131 1
        $this->writeEachModel($this->categoryClass);
132 5
        $this->writeTag('/categories');
133 5
        if($this->deliveryOptionClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->deliveryOptionClass of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
134 5
            $this->writeTag('delivery-options');
135 4
            $this->writeModel(new DeliveryOption(), \Yii::createObject($this->deliveryOptionClass));
136 4
            $this->writeTag('/delivery-options');
137 4
        }
138
        if($this->localDeliveryCostClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->localDeliveryCostClass of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
139 4
            $this->writeModel(new LocalDeliveryCost(), \Yii::createObject($this->localDeliveryCostClass));
0 ignored issues
show
Deprecated Code introduced by
The class pastuhov\ymlcatalog\models\LocalDeliveryCost has been deprecated.

This class, trait or interface has been deprecated.

Loading history...
140 4
        }
141
        $this->writeTag('offers');
142
        foreach ($this->offerClasses as $offerClass) {
0 ignored issues
show
Bug introduced by
The property offerClasses does not seem to exist. Did you mean offerClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
143
            $this->writeEachModel($offerClass);
144
        }
145 5
        $this->writeTag('/offers');
146
        $this->writeTag('/shop');
147 5
148
        $this->write('</yml_catalog>');
149 5
    }
150 1
151 1
    /**
152
     * @return null|string
153 5
     */
154
    protected function getDate()
155
    {
156
        $date = $this->date;
157
158
        if ($date === null) {
159
            $date = Yii::$app->formatter->asDatetime(new \DateTime(), 'php:Y-m-d H:i');
160 5
        }
161
162 5
        return $date;
163 5
    }
164
165
    /**
166
     * @param string $string
167
     * @throws \Exception
168 5
     */
169
    protected function write($string)
170 5
    {
171 5
        $this->handle->write($string);
172
    }
173
174
    /**
175
     * @param string $string tag name
176
     */
177
    protected function writeTag($string)
178 5
    {
179
        $this->write('<' . $string . '>' . PHP_EOL);
180 5
    }
181 5
182 5
    /**
183 5
     * @param BaseModel $model
184 5
     * @param $valuesModel
185 5
     * @throws Exception
186 5
     */
187 5
    protected function writeModel(BaseModel $model, $valuesModel)
188 5
    {
189
        if (method_exists($valuesModel, 'getParams')) {
190 5
            $model->setParams($valuesModel->getParams());
191 5
        }
192 5
        if (method_exists($valuesModel, 'getPictures')) {
193 5
            $model->setPictures($valuesModel->getPictures());
194 5
        }
195
        if(method_exists($valuesModel, 'getDeliveryOptions')) {
196
            $model->setDeliveryOptions($valuesModel->getDeliveryOptions());
197
        }
198
199
        if($model->loadModel($valuesModel, $this->onValidationError)) {
0 ignored issues
show
Bug introduced by
It seems like $this->onValidationError can also be of type callable; however, pastuhov\ymlcatalog\models\BaseModel::loadModel() does only seem to accept null, 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...
200
            $string = $model->getYml();
201
            $this->write($string);
202 5
        }
203
    }
204
205
    /**
206
     * @param string|array $modelClass class name or yii configuration array. You can also set params:
207 5
     *      `findParams`:   array of additional find params;
208
     *      `query`:        ActiveQuery object to generate yml use already created object;
209
     *      `dataProvider`: ActiveDataProvider or true to generate yml with pagination;
210
     */
211
    protected function writeEachModel($modelClass)
212 5
    {
213
        /**
214
         * @var mixed
215
         */
216
        $findParams = [];
217 5
218
        /**
219 5
         * @var ActiveQuery
220 4
         */
221 4
        $query = null;
222 4
223 4
        /**
224 4
         * @var ActiveDataProvider
225 4
         */
226 4
        $dataProvider = null;
227
228
        if (is_array($modelClass)) {
229
            foreach (['findParams', 'query', 'dataProvider'] as $name) {
230
                if (array_key_exists($name, $modelClass)) {
231 5
                    $$name = $modelClass[$name];
232
                    unset($modelClass[$name]);
233
                }
234
            }
235
        }
236 5
237 5
        /**
238 5
         * @var BaseFindYmlInterface $class
239 5
         */
240
        $class = \Yii::createObject($modelClass);
241 5
242
        /**
243 5
         * @var ReaderInterface
244
         */
245 5
        $reader = ReaderFactory::build(
246 5
            $class,
247 5
            $dataProvider,
248 5
            $query,
249 5
            $findParams
250 5
        );
251 5
252
        $newModel = $this->getNewModel($class);
253
254
        foreach ($reader as $models) {
255
            foreach ($models as $model) {
256
                $this->writeModel($newModel, $model);
257
            }
258 5
            $this->gc();
259
        }
260 5
    }
261
262 5
    /**
263 5
     * @param BaseFindYmlInterface $modelClass
264 5
     * @return Category|Currency|SimpleOffer
265 5
     * @throws Exception
266 5
     */
267 1
    protected function getNewModel($modelClass)
268 5
    {
269 4
        $obj = is_object($modelClass) ? $modelClass : \Yii::createObject($modelClass);
270 4
271
        if ($obj instanceof CurrencyInterface) {
272
            $model = new Currency();
273
        } elseif ($obj instanceof CustomCategoryInterface && !empty($this->customCategoryClass) && class_exists($this->customCategoryClass)) {
274 5
            $model = \Yii::createObject($this->customCategoryClass);
275
        } elseif ($obj instanceof CategoryInterface) {
276
            $model = new Category();
277
        } elseif ($obj instanceof CustomOfferInterface && $this->customOfferClass !== null && class_exists($this->customOfferClass)) {
278
            $model = \Yii::createObject($this->customOfferClass);
279
        } elseif ($obj instanceof SimpleOfferInterface) {
280 5
            $model = new SimpleOffer();
281
        } else {
282 5
            throw new Exception('Model ' . get_class($obj) . ' has unknown interface');
283
        }
284
285 5
        return $model;
286 5
    }
287
288
    /**
289
     * Performs PHP memory garbage collection.
290
     */
291
    protected function gc()
292
    {
293
        if (!gc_enabled()) {
294
            gc_enable();
295
        }
296
        gc_collect_cycles();
297
    }
298
}
299