Completed
Push — master ( 6051f2...6377da )
by Dispositif
02:48
created

DbAdapter::findEntity()   A

Complexity

Conditions 3
Paths 7

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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