Passed
Push — master ( 0a41a5...99b995 )
by Dispositif
08:05
created

CompleteProcess::onlineIsbnSearch()   F

Complexity

Conditions 21
Paths 7070

Size

Total Lines 65
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 43
nc 7070
nop 2
dl 0
loc 65
rs 0
c 0
b 0
f 0

How to fix   Long Method    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
/**
3
 * This file is part of dispositif/wikibot application
4
 * 2019 © Philippe M. <[email protected]>
5
 * For the full copyright and MIT license information, please view the LICENSE file.
6
 */
7
8
declare(strict_types=1);
9
10
namespace App\Application;
11
12
use App\Domain\Models\Wiki\OuvrageTemplate;
13
use App\Domain\OuvrageComplete;
14
use App\Domain\OuvrageFactory;
15
use App\Domain\OuvrageOptimize;
16
use App\Domain\Publisher\Wikidata2Ouvrage;
17
use App\Domain\Utils\TemplateParser;
18
use Normalizer;
19
use Throwable;
20
21
/**
22
 * Class CompleteProcess
23
 */
24
class CompleteProcess
25
{
26
    /**
27
     * @var bool
28
     */
29
    public $verbose = false;
30
31
    /**
32
     * @var QueueInterface
33
     */
34
    private $queueAdapter;
35
    /**
36
     * @var string
37
     */
38
    private $raw = '';
39
    private $log = [];
40
    private $notCosmetic = false;
41
    private $major = false;
42
    /**
43
     * @var OuvrageTemplate
44
     */
45
    private $ouvrage;
46
47
    public function __construct(QueueInterface $queueAdapter, ?bool $verbose = false)
48
    {
49
        $this->queueAdapter = $queueAdapter;
50
        $this->verbose = (bool)$verbose;
51
    }
52
53
    public function run(?int $limit = 10000)
54
    {
55
        $memory = new Memory();
56
        while ($limit > 0) {
57
            $limit--;
58
            sleep(1);
59
            $this->raw = $this->getNewRaw();
60
61
            echo sprintf(
62
                "-------------------------------\n%s [%s]\n\n%s\n",
63
                date("Y-m-d H:i:s"),
64
                Bot::getGitVersion() ?? '',
65
                $this->raw
66
            );
67
            if ($this->verbose) {
68
                $memory->echoMemory(true);
69
            }
70
71
            // initialise variables
72
            $this->log = [];
73
            $this->ouvrage = null;
74
            $this->notCosmetic = false;
75
            $this->major = false;
76
77
78
            try {
79
                $parse = TemplateParser::parseAllTemplateByName('ouvrage', $this->raw);
80
                $origin = $parse['ouvrage'][0]['model'] ?? null;
81
            } catch (Throwable $e) {
82
                echo sprintf("*** ERREUR impossible de transformer en modèle %s \n", $this->raw);
83
                continue;
84
            }
85
86
            if (!$origin instanceof OuvrageTemplate) {
87
                echo sprintf("*** ERREUR impossible de transformer en modèle %s \n", $this->raw);
88
                continue;
89
            }
90
91
            // Final optimizing (with online predictions)
92
            $optimizer = new OuvrageOptimize($origin, null);
93
            $optimizer->doTasks();
94
            $this->ouvrage = $optimizer->getOuvrage();
95
            $this->log = array_merge($this->log, $optimizer->getLog());
96
            $this->notCosmetic = ($optimizer->notCosmetic || $this->notCosmetic);
97
98
            /**
99
             * RECHERCHE ONLINE
100
             */
101
            $isbn = $origin->getParam('isbn') ?? null; // avant mise en forme EAN>ISBN
102
            $isbn10 = $origin->getParam('isbn2') ?? $origin->getParam('isbn10') ?? null;
103
            if (!empty($isbn)
104
                && empty($origin->getParam('isbn invalide'))
105
                && empty($origin->getParam('isbn erroné'))
106
            ) {
107
                $this->onlineIsbnSearch($isbn, $isbn10);
108
            }
109
110
            $this->sendCompleted();
111
            unset($optimizer);
112
            unset($parse);
113
            unset($origin);
114
        } // END WHILE
115
116
        return true;
117
    }
118
119
    /**
120
     * Get raw string to complete from AMQP queue, SQL Select or file reading.
121
     *
122
     * @return string|null
123
     * @throws \Exception
124
     */
125
    private function getNewRaw(): ?string
126
    {
127
        $raw = $this->queueAdapter->getNewRaw();
128
        if (!$raw) {
129
            echo "STOP: no more queue to process \n";
130
            throw new \Exception('no more queue to process');
131
        }
132
133
        return $raw;
134
    }
135
136
    private function onlineIsbnSearch(string $isbn, ?string $isbn10 = null)
137
    {
138
        online:
139
        if ($this->verbose) {
140
            echo "sleep 10...\n";
141
        }
142
        sleep(10);
143
144
        try {
145
            if ($this->verbose) {
146
                dump('BIBLIO NAT FRANCE...');
147
            }
148
            // BnF sait pas trouver un vieux livre (10) d'après ISBN-13... FACEPALM !
149
            if ($isbn10) {
150
                $bnfOuvrage = OuvrageFactory::BnfFromIsbn($isbn10);
151
                sleep(2);
152
            }
153
            if (!$isbn10 || empty($bnfOuvrage) || empty($bnfOuvrage->getParam('titre'))) {
154
                $bnfOuvrage = OuvrageFactory::BnfFromIsbn($isbn);
155
            }
156
            if (isset($bnfOuvrage) and $bnfOuvrage instanceof OuvrageTemplate) {
157
                $this->completeOuvrage($bnfOuvrage);
158
159
                // Wikidata requests from $infos (ISBN/ISNI)
160
                if (!empty($bnfOuvrage->getInfos())) {
161
                    if ($this->verbose) {
162
                        dump('WIKIDATA...');
163
                    }
164
                    $wdComplete = new Wikidata2Ouvrage(clone $bnfOuvrage);
165
                    $this->completeOuvrage($wdComplete->getOuvrage());
166
                }
167
            }
168
        } catch (Throwable $e) {
169
            echo sprintf(
170
                "*** ERREUR BnF Isbn Search %s %s %s \n",
171
                $e->getMessage(),
172
                $e->getFile(),
173
                $e->getLine()
174
            );
175
        }
176
177
        if (!isset($bnfOuvrage) || !$this->skipGoogle($bnfOuvrage)) {
178
            try {
179
                if ($this->verbose) {
180
                    dump('GOOGLE...');
181
                }
182
                $googleOuvrage = OuvrageFactory::GoogleFromIsbn($isbn);
183
                $this->completeOuvrage($googleOuvrage);
184
            } catch (Throwable $e) {
185
                echo "*** ERREUR GOOGLE Isbn Search ***".$e->getMessage()."\n";
186
                throw $e;
187
            }
188
        }
189
190
        if (!isset($bnfOuvrage) && !isset($googleOuvrage)) {
191
            try {
192
                if ($this->verbose) {
193
                    dump('OpenLibrary...');
194
                }
195
                $openLibraryOuvrage = OuvrageFactory::OpenLibraryFromIsbn($isbn);
196
                if (!empty($openLibraryOuvrage)) {
197
                    $this->completeOuvrage($openLibraryOuvrage);
198
                }
199
            } catch (Throwable $e) {
200
                echo '**** ERREUR OpenLibrary Isbn Search';
201
            }
202
        }
203
    }
204
205
    //    private function onlineQuerySearch(string $query)
206
    //    {
207
    //        echo "sleep 40...";
208
    //        sleep(20);
209
    //        onlineQuerySearch:
210
    //
211
    //        try {
212
    //            dump('GOOGLE SEARCH...');
213
    //            //            $googleOuvrage = OuvrageFactory::GoogleFromIsbn($isbn);
214
    //            $adapter = new GoogleBooksAdapter();
215
    //            $data = $adapter->search('blabla');
216
    //            dump($data);
217
    //            //die;
218
    //            //            return $import->getOuvrage();
219
    //            //            $this->completeOuvrage($googleOuvrage);
220
    //        } catch (Throwable $e) {
221
    //            echo "*** ERREUR GOOGLE QuerySearch *** ".$e->getMessage()."\n";
222
    //            echo "sleep 30min";
223
    //            sleep(60 * 30);
224
    //            echo "Wake up\n";
225
    //            goto onlineQuerySearch;
226
    //        }
227
    //    }
228
229
    private function completeOuvrage(OuvrageTemplate $onlineOuvrage)
230
    {
231
        if ($this->verbose) {
232
            dump($onlineOuvrage->serialize(true));
233
        }
234
        $optimizer = new OuvrageOptimize($onlineOuvrage);
235
        $onlineOptimized = ($optimizer)->doTasks()->getOuvrage();
236
237
        $completer = new OuvrageComplete($this->ouvrage, $onlineOptimized);
238
        $this->ouvrage = $completer->getResult();
239
        if ($this->verbose) {
240
            dump($completer->getLog());
241
        }
242
        if ($completer->major) {
243
            $this->major = true;
244
        }
245
        $this->notCosmetic = ($completer->notCosmetic || $this->notCosmetic);
246
        $this->log = array_merge($this->log, $completer->getLog());
247
        unset($optimizer);
248
        unset($completer);
249
    }
250
251
    private function sendCompleted()
252
    {
253
        $isbn13 = $this->ouvrage->getParam('isbn') ?? null;
254
255
        $finalData = [
256
            //    'page' =>
257
            'raw' => $this->raw,
258
            'opti' => $this->serializeFinalOpti(),
259
            'optidate' => date("Y-m-d H:i:s"),
260
            'modifs' => mb_substr(implode(',', $this->log), 0, 250),
261
            'notcosmetic' => ($this->notCosmetic) ? 1 : 0,
262
            'major' => ($this->major) ? 1 : 0,
263
            'isbn' => substr($isbn13, 0, 20),
264
            'version' => Bot::getGitVersion() ?? null,
265
        ];
266
        if ($this->verbose) {
267
            dump($finalData);
268
        }
269
        // Json ?
270
        $result = $this->queueAdapter->sendCompletedData($finalData);
271
272
        dump($result); // bool
273
    }
274
275
    /**
276
     * Final serialization of the completed OuvrageTemplate.
277
     *
278
     * @return string
279
     */
280
    private function serializeFinalOpti(): string
281
    {
282
        $finalOpti = $this->ouvrage->serialize(true);
283
        $finalOpti = Normalizer::normalize($finalOpti);
284
285
        return $finalOpti;
286
    }
287
288
    private function skipGoogle($bnfOuvrage): bool
289
    {
290
        if ($bnfOuvrage instanceOf OuvrageTemplate
291
            && !empty($bnfOuvrage->getParam('titre'))
292
            && (!empty($this->ouvrage->getParam('lire en ligne'))
293
                || !empty($this->ouvrage->getParam('présentation en ligne')))
294
        ) {
295
            return true;
296
        }
297
298
        return false;
299
    }
300
}
301