GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#3)
by Evgeny
02:16
created

Parser::fillMetaData()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 30
Code Lines 21

Duplication

Lines 14
Ratio 46.67 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 14
loc 30
rs 6.7272
cc 7
eloc 21
nc 7
nop 3
1
<?php
2
3
namespace SimaLand\API\Parser;
4
5
use SimaLand\API\AbstractList;
6
use SimaLand\API\Object;
7
use SimaLand\API\Record;
8
9
/**
10
 * Загрузка и сохранение всех записей сущностей.
11
 *
12
 * ```php
13
 *
14
 * $client = new \SimaLand\API\Rest\Client([
15
 *     'login' => 'login',
16
 *     'password' => 'password'
17
 * ]);
18
 * $itemList = new \SimaLand\API\Entities\ItemList($client);
19
 * $itemStorage = new Csv(['filename' => 'path/to/item.csv']);
20
 * $categoryList = new \SimaLand\API\Entities\CategoryList($client);
21
 * $categoryStorage = new Csv(['filename' => 'path/to/category.csv']);
22
 * $parser = new Parser(['metaFilename' => 'path/to/file']);
23
 * $parser->addEntity($itemList, $itemStorage);
24
 * $parser->addEntity($categoryList, $categoryStorage);
25
 * $parser->run();
26
 *
27
 * ```
28
 */
29
class Parser extends Object
30
{
31
    public $countRecordsSave = 1000;
32
33
    /**
34
     * @var array
35
     */
36
    private $list = [];
37
38
    /**
39
     * Путь до файла с мета данными.
40
     *
41
     * @var string
42
     */
43
    private $metaFilename;
44
45
    /**
46
     * Мета данные.
47
     *
48
     * @var array
49
     */
50
    private $metaData = [];
51
52
    /**
53
     * @inheritdoc
54
     */
55
    public function __construct(array $options = [])
56
    {
57
        if (!isset($options['metaFilename'])) {
58
            throw new \Exception('Param "metaFilename" can`t be empty');
59
        }
60
        $this->metaFilename = $options['metaFilename'];
61
        unset($options['metaFilename']);
62
        parent::__construct($options);
63
    }
64
65
    /**
66
     * @param AbstractList $entity
67
     * @param StorageInterface $storage
68
     * @return Parser
69
     */
70
    public function addEntity(AbstractList $entity, StorageInterface $storage)
71
    {
72
        $this->list[] = [
73
            'entity' => $entity,
74
            'storage' => $storage
75
        ];
76
        return $this;
77
    }
78
79
    /**
80
     * Сбросить мета данные.
81
     *
82
     * @return Parser
83
     */
84
    public function reset()
85
    {
86
        if (file_exists($this->metaFilename)) {
87
            unlink($this->metaFilename);
88
        }
89
        return $this;
90
    }
91
92
    /**
93
     * Запустить парсер.
94
     *
95
     * @param bool|false $continue Продолжить парсить с место обрыва.
96
     */
97
    public function run($continue = true)
98
    {
99
        $this->loadMetaData();
100
        foreach ($this->list as $el) {
101
            /** @var AbstractList $entity */
102
            $entity = $el['entity'];
103
            $entityName = $entity->getEntity();
104
            if ($continue && isset($this->metaData[$entityName])) {
105
                if (isset($this->metaData[$entityName]['finish']) && $this->metaData[$entityName]['finish']) {
106
                    continue;
107
                }
108
                $entity->addGetParams($this->metaData[$entityName]);
109
            }
110
            /** @var StorageInterface  $storage */
111
            $storage = $el['storage'];
112
            foreach ($entity as $key => $record) {
113
                if ($continue) {
114
                    $this->fillMetaData($entity, $record, $key);
115
                    $this->saveMetaData();
116
                }
117
                $storage->save($record);
118
            }
119
            if ($continue) {
120
                $this->finishParseEntity($entity);
121
                $this->saveMetaData();
122
            }
123
        }
124
    }
125
126
    /**
127
     * Загрузить мета данные.
128
     */
129
    private function loadMetaData()
130
    {
131
        if (!file_exists($this->metaFilename)) {
132
            return;
133
        }
134
        $data = file_get_contents($this->metaFilename);
135
        $this->metaData = json_decode($data, true);
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode($data, true) of type * is incompatible with the declared type array of property $metaData.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
136
    }
137
138
    /**
139
     * Заполнить мета данные.
140
     *
141
     * @param AbstractList $entity
142
     * @param Record $record
143
     * @param int $i
144
     */
145
    private function fillMetaData(AbstractList $entity, Record $record, $i)
146
    {
147
        $entityName = $entity->getEntity();
148
        if ($record->meta) {
149 View Code Duplication
            if (!isset($this->metaData[$entityName])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
150
                $this->metaData[$entityName] = [
151
                    $entity->keyThreads => $record->meta['currentPage'],
152
                    'perPage' => $record->meta['perPage'],
153
                ];
154
                return;
155
            }
156
            if ($this->metaData[$entityName][$entity->keyThreads] == $record->meta['currentPage']) {
157
                return;
158
            }
159
            $this->metaData[$entityName][$entity->keyThreads] = $record->meta['currentPage'];
160
        } else {
161
            $id = $record->data['id'];
162 View Code Duplication
            if (!isset($this->metaData[$entityName])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
163
                $this->metaData[$entityName] = [
164
                    $entity->keyAlternativePagination => $id,
165
                    'perPage' => isset($entity->getParams['perPage']) ? $entity->getParams['perPage'] : null,
166
                ];
167
                return;
168
            }
169
            if ($i % $this->countRecordsSave != 0) {
170
                return;
171
            }
172
            $this->metaData[$entityName][$entity->keyAlternativePagination] = $id;
173
        }
174
    }
175
176
    /**
177
     * Записать в мета данные об успешном сохранение сущности.
178
     *
179
     * @param AbstractList $entity
180
     */
181
    private function finishParseEntity(AbstractList $entity)
182
    {
183
        $entityName = $entity->getEntity();
184
        if (!isset($this->metaData[$entityName])) {
185
            $this->metaData[$entityName] = [];
186
        }
187
        $this->metaData[$entityName]['finish'] = true;
188
    }
189
190
    /**
191
     * Сохранить мета данные.
192
     */
193
    private function saveMetaData()
194
    {
195
        $data = json_encode($this->metaData);
196
        file_put_contents($this->metaFilename, $data);
197
    }
198
}
199