Test Failed
Branch master (c8a89b)
by Dispositif
04:54 queued 01:58
created

DbAdapter::updateMonitor()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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