Passed
Push — dev ( b8ced8...f7ea32 )
by Dispositif
07:14
created

DbAdapter::insertTempRawOpti()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 14
rs 10
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\Infrastructure;
11
12
use App\Application\QueueInterface;
13
use App\Infrastructure\entities\DbEditedPage;
1 ignored issue
show
Bug introduced by
The type App\Infrastructure\entities\DbEditedPage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use DateInterval;
15
use DateTime;
16
use Exception;
17
use Simplon\Mysql\Mysql;
18
use Simplon\Mysql\MysqlException;
19
use Simplon\Mysql\PDOConnector;
20
use Throwable;
21
22
/**
23
 * Temporary SQL play. https://github.com/fightbulc/simplon_mysql .
24
 * Class DbAdapter.
25
 */
26
class DbAdapter implements QueueInterface
27
{
28
    protected $db;
29
30
    protected $pdoConn;
31
32
    const OPTI_VALID_DATE = '2019-11-20 14:00:00'; // v.34 sous-titre sans maj
33
34
    public function __construct()
35
    {
36
        $pdo = new PDOConnector(
37
            getenv('MYSQL_HOST'), getenv('MYSQL_USER'), getenv('MYSQL_PASSWORD'), getenv('MYSQL_DATABASE')
38
        );
39
        $this->pdoConn = $pdo->connect('utf8', ['port' => getenv('MYSQL_PORT')]);
40
        $this->db = new Mysql($this->pdoConn);
41
    }
42
43
    /**
44
     * @param $datas
45
     *
46
     * @return array|bool
47
     * @throws Exception
48
     */
49
    public function insertPageOuvrages(array $datas)
50
    {
51
        // check if article already in db
52
        $page = $datas[0]['page'];
53
        $count = $this->db->fetchRowMany(
54
            'SELECT id from page_ouvrages WHERE page=:page',
55
            ['page' => $page]
56
        );
57
        if (null !== $count) {
58
            return false;
59
        }
60
61
        // add the citations
62
        return $this->db->insertMany('page_ouvrages', $datas);
63
    }
64
65
    /**
66
     * Get one new row (page, raw) to complete.
67
     *
68
     * @return array|null
69
     */
70
    public function getNewRaw(): ?array
71
    {
72
        $raw = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $raw is dead and can be removed.
Loading history...
73
74
        try {
75
            $row = $this->db->fetchRow(
76
                'SELECT page,raw FROM page_ouvrages 
77
                WHERE raw <> "" AND (opti = "" OR optidate IS NULL OR optidate < :validDate ) AND (edited IS NULL)
78
                ORDER BY priority DESC,id
79
                LIMIT 1',
80
                [
81
                    'validDate' => self::OPTI_VALID_DATE,
82
                ]
83
            );
84
        } catch (Throwable $e) {
85
            echo "SQL : No more queue to process \n";
86
        }
87
88
        return $row;
89
    }
90
91
    /**
92
     * Update DB with completed data from CompleteProcess.
93
     *
94
     * @param array $finalData
95
     *
96
     * @return bool
97
     */
98
    public function sendCompletedData(array $finalData): bool
99
    {
100
        try {
101
            $result = $this->db->update(
102
                'page_ouvrages',
103
                ['raw' => $finalData['raw']], // condition
104
                $finalData
105
            );
106
        } catch (MysqlException $e) {
107
            dump($e);
108
109
            return false;
110
        }
111
112
        return !empty($result);
113
    }
114
115
    //------------------------------------------------------
116
    //          EDIT QUEUE
117
    //------------------------------------------------------
118
119
    /**
120
     * Get batch of citations(template) for edit process.
121
     *
122
     * @param int|null $limit
123
     *
124
     * @return string|null
125
     */
126
    public function getAllRowsToEdit(?int $limit = 100): ?string
127
    {
128
        $json = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $json is dead and can be removed.
Loading history...
129
130
        try {
131
            $pageInfo = $this->pdoConn->query(
132
                '
133
                SELECT A.page FROM page_ouvrages A
134
                WHERE notcosmetic=1. 
135
                AND NOT EXISTS
136
                    (SELECT B.* FROM page_ouvrages B
137
                    WHERE (
138
                        B.edited IS NOT NULL 
139
                        OR B.optidate < "'.self::OPTI_VALID_DATE.'" 
140
                        OR B.optidate IS NULL 
141
                        OR B.opti="" 
142
                        OR B.skip=1
143
                        OR B.raw=""
144
                        )
145
                    AND A.page = B.page
146
                    )
147
                ORDER BY A.priority,RAND()
148
                LIMIT '.$limit.'
149
                '
150
            );
151
152
            // No page to edit
153
            $rows = $pageInfo->fetchAll();
154
            if (empty($rows)) {
155
                return '[]';
156
            }
157
158
            $page = $rows[0]['page'];
159
160
            // Order by optidate for first version in edit commentary ?
161
            $data = $this->db->fetchRowMany(
162
                'SELECT * FROM page_ouvrages WHERE page=:page ORDER BY optidate DESC',
163
                ['page' => $page]
164
            );
165
            $json = json_encode($data);
166
        } catch (Throwable $e) {
167
            throw new Exception('SQL : No more queue to process');
168
        }
169
170
        return $json;
171
    }
172
173
    public function skipArticle(string $title): bool
174
    {
175
        try {
176
            $result = $this->db->update(
177
                'page_ouvrages',
178
                ['page' => $title], // condition
179
                ['skip' => true]
180
            );
181
        } catch (MysqlException $e) {
182
            dump($e);
183
184
            return false;
185
        }
186
187
        return !empty($result);
188
    }
189
190
    public function skipRow(int $id): bool
191
    {
192
        try {
193
            $result = $this->db->update(
194
                'page_ouvrages',
195
                ['id' => $id], // condition
196
                ['skip' => true]
197
            );
198
        } catch (MysqlException $e) {
199
            dump($e);
200
201
            return false;
202
        }
203
204
        return !empty($result);
205
    }
206
207
    /**
208
     * Update DB after wiki edition.
209
     *
210
     * @param array $data
211
     *
212
     * @return bool
213
     */
214
    public function sendEditedData(array $data): bool
215
    {
216
        try {
217
            $result = $this->db->update(
218
                'page_ouvrages',
219
                ['id' => $data['id']], // condition
220
                ['edited' => date('Y-m-d H:i:s')]
221
            );
222
        } catch (MysqlException $e) {
223
            dump($e);
224
225
            return false;
226
        }
227
228
        return !empty($result);
229
    }
230
231
    //------------------------------------------------------
232
233
    /**
234
     * Dirty naive ORM.
235
     *
236
     * @param object $object
237
     *
238
     * @return array|bool
239
     */
240
    public function saveEntity(object $object)
241
    {
242
        if ($object instanceof DbEditedPage) {
243
            /*
244
             * @var $object DbEditedPage
245
             */
246
            try {
247
                return $this->db->replace('editedpages', $object->getVars());
248
            } catch (MysqlException $e) {
249
                unset($e);
250
            }
251
        }
252
253
        return false;
254
    }
255
256
    /**
257
     * Dirty naive ORM.
258
     *
259
     * @param $table
260
     * @param $primary
261
     *
262
     * @return object|null
263
     */
264
    public function findEntity($table, $primary): ?object
265
    {
266
        if ('editedpages' === $table) {
267
            /*
268
             * @var $object DbEditedPage
269
             */
270
            try {
271
                $res = $this->db->fetchRow('SELECT * FROM editedpages WHERE title = :title', ['title' => $primary]);
272
                $obj = new DbEditedPage($this);
273
                $obj->setTitle($primary);
274
                $obj->setCompleted($res['completed']);
275
                $obj->setEdited($res['edited']);
276
277
                return $obj;
278
            } catch (MysqlException $e) {
279
                unset($e);
280
            }
281
        }
282
283
        return null;
284
    }
285
286
    /**
287
     * Get a row to monitor edits.
288
     */
289
    public function getMonitor(): ?array
290
    {
291
        $data = null;
1 ignored issue
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
292
        // 2 hours ago
293
        $beforeTime = (new DateTime())->sub(new DateInterval('PT3H'));
294
295
        try {
296
            $data = $this->db->fetchRowMany(
297
                'SELECT id,page,raw,opti,optidate,edited,verify,skip FROM page_ouvrages WHERE page = (
298
                    SELECT page FROM page_ouvrages
299
                    WHERE edited IS NOT NULL 
300
                    and edited > :afterDate and edited < :beforeDate
301
                    and (verify is null or verify < :nextVerifyDate )
302
             		ORDER BY verify,edited
303
                    LIMIT 1)',
304
                [
305
                    'afterDate' => '2019-11-26 06:00:00',
306
                    'beforeDate' => $beforeTime->format('Y-m-d H:i:s'),
307
                    'nextVerifyDate' => (new DateTime())->sub(new DateInterval('P2D'))->format('Y-m-d H:i:s'),
308
                ]
309
            );
310
        } catch (Throwable $e) {
311
            echo "SQL : No more queue to process \n";
312
        }
313
314
        return $data;
315
    }
316
317
    public function updateMonitor(array $data): bool
318
    {
319
        if (empty($data['page'])) {
320
            throw new Exception('pas de page');
321
        }
322
323
        try {
324
            $result = $this->db->update(
325
                'page_ouvrages',
326
                ['page' => $data['page']], // condition
327
                $data
328
            );
329
        } catch (MysqlException $e) {
330
            dump($e);
331
332
            return false;
333
        }
334
335
        return !empty($result);
336
    }
337
}
338