Completed
Push — master ( c4ce9d...69540b )
by Dispositif
03:31
created

CompleteProcess::onlineQuerySearch()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 13
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 19
rs 9.8333
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\Examples;
11
12
use App\Application\Bot;
13
use App\Application\Memory;
14
use App\Application\QueueInterface;
15
use App\Domain\Models\Wiki\OuvrageTemplate;
16
use App\Domain\OuvrageComplete;
17
use App\Domain\OuvrageFactory;
18
use App\Domain\OuvrageOptimize;
19
use App\Domain\Utils\TemplateParser;
20
use App\Infrastructure\DbAdapter;
21
use App\Infrastructure\GoogleBooksAdapter;
22
use Throwable;
23
24
include __DIR__.'/../myBootstrap.php';
25
26
$dirty = new CompleteProcess(new DbAdapter());
27
$dirty->run();
28
29
/**
30
 * Class CompleteProcess
31
 */
32
class CompleteProcess
33
{
34
    /**
35
     * @var QueueInterface
36
     */
37
    private $queueAdapter;
38
    /**
39
     * @var string
40
     */
41
    private $raw = '';
42
    private $log = [];
43
    private $notCosmetic = false;
44
    private $major = false;
45
    /**
46
     * @var OuvrageTemplate
47
     */
48
    private $ouvrage;
49
    private $continue = true;
0 ignored issues
show
introduced by
The private property $continue is not used, and could be removed.
Loading history...
50
51
    public function __construct(QueueInterface $queueAdapter)
52
    {
53
        $this->queueAdapter = $queueAdapter;
54
    }
55
56
    public function run(?int $limit = 10000)
57
    {
58
        $memory = new Memory();
59
        while ($limit > 0) {
60
            $limit--;
61
            sleep(1);
62
            $this->raw = $this->getNewRaw();
63
64
            echo sprintf(
65
                "-------------------------------\n%s [%s]\n\n%s\n",
66
                date("Y-m-d H:i:s"),
67
                Bot::getGitVersion() ?? '',
68
                $this->raw
69
            );
70
            $memory->echoMemory(true);
71
72
            // initialise variables
73
            $this->log = [];
74
            $this->ouvrage = null;
75
            $this->notCosmetic = false;
76
            $this->major = false;
77
78
79
            try {
80
                $parse = TemplateParser::parseAllTemplateByName('ouvrage', $this->raw);
81
                $origin = $parse['ouvrage'][0]['model'] ?? null;
82
            } catch (Throwable $e) {
83
                echo sprintf("*** ERREUR impossible de transformer en modèle %s \n", $this->raw);
84
                continue;
85
            }
86
87
            if (!$origin instanceof OuvrageTemplate) {
88
                echo sprintf("*** ERREUR impossible de transformer en modèle %s \n", $this->raw);
89
                continue;
90
            }
91
92
            // Final optimizing (with online predictions)
93
            $optimizer = new OuvrageOptimize($origin, null, true);
94
            $optimizer->doTasks();
95
            $this->ouvrage = $optimizer->getOuvrage();
96
            $this->log = array_merge($this->log, $optimizer->getLog());
97
            $this->notCosmetic = ($optimizer->notCosmetic || $this->notCosmetic);
98
99
            /**
100
             * RECHERCHE ONLINE
101
             */
102
            $isbn = $origin->getParam('isbn') ?? null; // avant mise en forme EAN>ISBN
103
            if (!empty($isbn)) {
104
                $this->onlineIsbnSearch($isbn);
105
            }
106
107
            $this->sendCompleted();
108
            unset($optimizer);
109
            unset($parse);
110
            unset($origin);
111
        } // END WHILE
112
113
        return true;
114
    }
115
116
    /**
117
     * Get raw string to complete from AMQP queue, SQL Select or file reading.
118
     *
119
     * @return string|null
120
     */
121
    private function getNewRaw(): ?string
122
    {
123
        $raw = $this->queueAdapter->getNewRaw();
124
        if (!$raw) {
125
            echo "STOP: no more queue to process \n";
126
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
127
        }
128
129
        return $raw;
130
    }
131
132
    private function onlineIsbnSearch(string $isbn)
133
    {
134
        online:
135
        echo "sleep 40...\n";
136
        sleep(40);
137
138
        try {
139
            dump('BIBLIO NAT FRANCE...');
140
            $bnfOuvrage = OuvrageFactory::BnfFromIsbn($isbn);
141
            $this->completeOuvrage($bnfOuvrage);
142
        } catch (Throwable $e) {
143
            echo "*** ERREUR BnF Isbn Search".$e->getMessage()."\n";
144
            echo "sleep 5min\n";
145
            sleep(60 * 5);
146
            goto online;
147
        }
148
149
        try {
150
            if(!$this->skipGoogle()){
151
                dump('GOOGLE...');
152
                $googleOuvrage = OuvrageFactory::GoogleFromIsbn($isbn);
153
                $this->completeOuvrage($googleOuvrage);
154
            }
155
        } catch (Throwable $e) {
156
            echo "*** ERREUR GOOGLE Isbn Search ***".$e->getMessage()."\n";
157
            if(strpos($e->getMessage(),'Daily Limit Exceeded') !== true ){
158
                echo "sleep 1h\n";
159
                sleep(60 * 60);
160
                echo "Try goto\n";
161
                goto online;
162
            }
163
        }
164
165
166
        try {
167
            dump('OpenLibrary...');
168
            $openLibraryOuvrage = OuvrageFactory::OpenLibraryFromIsbn($isbn);
169
            if (!empty($openLibraryOuvrage)) {
170
                $this->completeOuvrage($openLibraryOuvrage);
171
            }
172
        } catch (Throwable $e) {
173
            echo '**** ERREUR OpenLibrary Isbn Search';
174
        }
175
    }
176
177
    private function onlineQuerySearch(string $query)
0 ignored issues
show
Unused Code introduced by
The method onlineQuerySearch() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
Unused Code introduced by
The parameter $query is not used and could be removed. ( Ignorable by Annotation )

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

177
    private function onlineQuerySearch(/** @scrutinizer ignore-unused */ string $query)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
178
    {
179
        echo "sleep 40...";
180
        sleep(40);
181
        onlineQuerySearch:
182
183
        try {
184
            dump('GOOGLE SEARCH...');
185
            //            $googleOuvrage = OuvrageFactory::GoogleFromIsbn($isbn);
186
            $adapter = new GoogleBooksAdapter();
187
            $data = $adapter->search('blabla');
188
            dump($data);
189
            die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
190
            //            return $import->getOuvrage();
191
            //            $this->completeOuvrage($googleOuvrage);
192
        } catch (Throwable $e) {
193
            echo "*** ERREUR GOOGLE QuerySearch *** ".$e->getMessage()."\n";
194
            sleep(60*30);
195
            goto onlineQuerySearch;
196
        }
197
    }
198
199
    private function completeOuvrage(OuvrageTemplate $onlineOuvrage)
200
    {
201
        dump($onlineOuvrage->serialize(true));
202
        $optimizer = new OuvrageOptimize($onlineOuvrage);
203
        $onlineOptimized = ($optimizer)->doTasks()->getOuvrage();
204
205
        $completer = new OuvrageComplete($this->ouvrage, $onlineOptimized);
206
        $this->ouvrage = $completer->getResult();
207
        dump($completer->getLog());
208
        if ($completer->major) {
209
            $this->major = true;
210
        }
211
        $this->notCosmetic = ($completer->notCosmetic || $this->notCosmetic);
212
        $this->log = array_merge($this->log, $completer->getLog());
213
        unset($optimizer);
214
        unset($completer);
215
    }
216
217
    private function sendCompleted()
218
    {
219
        $isbn13 = $this->ouvrage->getParam('isbn') ?? null;
220
221
        $finalData = [
222
            //    'page' =>
223
            'raw' => $this->raw,
224
            'opti' => $this->ouvrage->serialize(true),
225
            'optidate' => date("Y-m-d H:i:s"),
226
            'modifs' => mb_substr(implode(',', $this->log), 0, 250),
227
            'notcosmetic' => ($this->notCosmetic) ? 1 : 0,
228
            'major' => ($this->major) ? 1 : 0,
229
            'isbn' => substr($isbn13,0,20),
230
            'version' => Bot::getGitVersion() ?? null,
231
        ];
232
        dump($finalData);
233
        // Json ?
234
        $result = $this->queueAdapter->sendCompletedData($finalData);
235
        dump($result); // bool
236
    }
237
238
    private function skipGoogle():bool
239
    {
240
        return false;
241
    }
242
}
243