Completed
Push — typo3v9 ( aea555...37a7d2 )
by Tomas Norre
06:20
created

ProcessRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AOE\Crawler\Domain\Repository;
6
7
/***************************************************************
8
 *  Copyright notice
9
 *
10
 *  (c) 2019 AOE GmbH <[email protected]>
11
 *
12
 *  All rights reserved
13
 *
14
 *  This script is part of the TYPO3 project. The TYPO3 project is
15
 *  free software; you can redistribute it and/or modify
16
 *  it under the terms of the GNU General Public License as published by
17
 *  the Free Software Foundation; either version 3 of the License, or
18
 *  (at your option) any later version.
19
 *
20
 *  The GNU General Public License can be found at
21
 *  http://www.gnu.org/copyleft/gpl.html.
22
 *
23
 *  This script is distributed in the hope that it will be useful,
24
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26
 *  GNU General Public License for more details.
27
 *
28
 *  This copyright notice MUST APPEAR in all copies of the script!
29
 ***************************************************************/
30
31
use AOE\Crawler\Configuration\ExtensionConfigurationProvider;
32
use AOE\Crawler\Domain\Model\Process;
33
use AOE\Crawler\Domain\Model\ProcessCollection;
34
use TYPO3\CMS\Core\Database\ConnectionPool;
35
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
36
use TYPO3\CMS\Core\Utility\GeneralUtility;
37
38
/**
39
 * Class ProcessRepository
40
 *
41
 * @package AOE\Crawler\Domain\Repository
42
 */
43
class ProcessRepository extends AbstractRepository
44
{
45
    /**
46
     * @var string
47
     */
48
    protected $tableName = 'tx_crawler_process';
49
50
    /**
51
     * @var QueryBuilder
52
     */
53
    protected $queryBuilder = QueryBuilder::class;
54
55
    /**
56
     * @var array
57
     */
58
    protected $extensionSettings = [];
59
60
    /**
61
     * QueueRepository constructor.
62
     */
63
    public function __construct()
64
    {
65
        $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
66
67
        /** @var ExtensionConfigurationProvider $configurationProvider */
68
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
69
        $this->extensionSettings = $configurationProvider->getExtensionConfiguration();
70
    }
71
72
    /**
73
     * This method is used to find all cli processes within a limit.
74
     *
75
     * @return ProcessCollection
76
     */
77
    public function findAll(): ProcessCollection
78
    {
79
        /** @var ProcessCollection $collection */
80
        $collection = GeneralUtility::makeInstance(ProcessCollection::class);
81
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
82
83
        $statement = $queryBuilder
84
            ->select('*')
85
            ->from($this->tableName)
86
            ->orderBy('ttl', 'DESC')
87
            ->execute();
88
89
        while ($row = $statement->fetch()) {
90
            $process = GeneralUtility::makeInstance(Process::class);
91
            $process->setProcessId($row['process_id']);
92
            $process->setActive($row['active']);
93
            $process->setTtl($row['ttl']);
94
            $process->setAssignedItemsCount($row['assigned_items_count']);
95
            $process->setDeleted($row['deleted']);
96
            $process->setSystemProcessId($row['system_process_id']);
97
            $collection->append($process);
98
        }
99
100
        return $collection;
101
    }
102
103
    /**
104
     * @param string $processId
105
     * @return mixed
106
     */
107
    public function findByProcessId($processId)
108
    {
109
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
110
111
        return $queryBuilder
112
            ->select('*')
113
            ->from($this->tableName)
114
            ->where(
115
                $queryBuilder->expr()->eq('process_id', $queryBuilder->createNamedParameter($processId, \PDO::PARAM_STR))
116
            )->execute()->fetch(0);
117
    }
118
119
    /**
120
     * @return ProcessCollection
121
     */
122
    public function findAllActive(): ProcessCollection
123
    {
124
        /** @var ProcessCollection $collection */
125
        $collection = GeneralUtility::makeInstance(ProcessCollection::class);
126
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
127
128
        $statement = $queryBuilder
129
            ->select('*')
130
            ->from($this->tableName)
131
            ->where(
132
                $queryBuilder->expr()->eq('active', 1),
133
                $queryBuilder->expr()->eq('deleted', 0)
134
            )
135
            ->orderBy('ttl', 'DESC')
136
            ->execute();
137
138
        while ($row = $statement->fetch()) {
139
            $process = new Process();
140
            $process->setProcessId($row['process_id']);
141
            $process->setActive($row['active']);
142
            $process->setTtl($row['ttl']);
143
            $process->setAssignedItemsCount($row['assigned_items_count']);
144
            $process->setDeleted($row['deleted']);
145
            $process->setSystemProcessId($row['system_process_id']);
146
            $collection->append($process);
147
        }
148
149
        return $collection;
150
    }
151
152
    /**
153
     * @param string $processId
154
     *
155
     * @return void
156
     */
157
    public function removeByProcessId($processId): void
158
    {
159
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
160
161
        $queryBuilder
162
            ->delete($this->tableName)
163
            ->where(
164
                $queryBuilder->expr()->eq('process_id', $queryBuilder->createNamedParameter($processId, \PDO::PARAM_STR))
165
            )->execute();
166
    }
167
168
    /**
169
     * Returns the number of active processes.
170
     *
171
     * @return integer
172
     */
173
    public function countActive()
174
    {
175
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
176
177
        return $queryBuilder
178
            ->count('*')
179
            ->from($this->tableName)
180
            ->where(
181
                $queryBuilder->expr()->eq('active', 1),
182
                $queryBuilder->expr()->eq('deleted', 0)
183
            )
184
            ->execute()
185
            ->fetchColumn(0);
186
    }
187
188
    /**
189
     * @return array|null
190
     *
191
     * Function is moved from ProcessCleanUpHook
192
     * TODO: Check why we need both getActiveProcessesOlderThanOneHour and getActiveOrphanProcesses, the get getActiveOrphanProcesses does not really check for Orphan in this implementation.
193
     */
194
    public function getActiveProcessesOlderThanOneHour()
195
    {
196
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
197
        $activeProcesses = [];
198
        $statement = $queryBuilder
199
            ->select('process_id', 'system_process_id')
200
            ->from($this->tableName)
201
            ->where(
202
                $queryBuilder->expr()->lte('ttl', intval(time() - $this->extensionSettings['processMaxRunTime'] - 3600)),
203
                $queryBuilder->expr()->eq('active', 1)
204
            )
205
            ->execute();
206
207
        while ($row = $statement->fetch()) {
208
            $activeProcesses[] = $row;
209
        }
210
211
        return $activeProcesses;
212
    }
213
214
    /**
215
     * Function is moved from ProcessCleanUpHook
216
     *
217
     * @see getActiveProcessesOlderThanOneHour
218
     * @return array
219
     *
220
     */
221
    public function getActiveOrphanProcesses()
222
    {
223
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
224
225
        return $queryBuilder
226
            ->select('process_id', 'system_process_id')
227
            ->from($this->tableName)
228
            ->where(
229
                $queryBuilder->expr()->lte('ttl', intval(time() - $this->extensionSettings['processMaxRunTime'])),
230
                $queryBuilder->expr()->eq('active', 1)
231
            )
232
            ->execute()->fetchAll();
233
    }
234
235
    /**
236
     * Returns the number of processes that live longer than the given timestamp.
237
     *
238
     * @param  integer $ttl
239
     *
240
     * @return integer
241
     */
242
    public function countNotTimeouted($ttl)
243
    {
244
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
245
246
        return $queryBuilder
247
            ->count('*')
248
            ->from($this->tableName)
249
            ->where(
250
                $queryBuilder->expr()->eq('deleted', 0),
251
                $queryBuilder->expr()->gt('ttl', intval($ttl))
252
            )
253
            ->execute()
254
            ->fetchColumn(0);
255
    }
256
257
    /**
258
     * Get limit clause
259
     *
260
     * @param  integer $itemCount
261
     * @param  integer $offset
262
     *
263
     * @return string
264
     */
265 4
    public static function getLimitFromItemCountAndOffset($itemCount, $offset): string
266
    {
267 4
        $itemCount = filter_var($itemCount, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'default' => 20]]);
268 4
        $offset = filter_var($offset, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'default' => 0]]);
269
270 4
        return $offset . ', ' . $itemCount;
271
    }
272
273
    /**
274
     * @return void
275
     */
276
    public function deleteProcessesWithoutItemsAssigned(): void
277
    {
278
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
279
        $queryBuilder
280
            ->delete($this->tableName)
281
            ->where(
282
                $queryBuilder->expr()->eq('assigned_items_count', 0)
283
            )
284
            ->execute();
285
    }
286
287
    public function deleteProcessesMarkedAsDeleted(): void
288
    {
289
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
290
        $queryBuilder
291
            ->delete($this->tableName)
292
            ->where(
293
                $queryBuilder->expr()->eq('deleted', 1)
294
            )
295
            ->execute();
296
    }
297
298
    public function isProcessActive(string $processId): bool
299
    {
300
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
301
        $isActive = $queryBuilder
302
            ->select('active')
303
            ->from($this->tableName)
304
            ->where(
305
                $queryBuilder->expr()->eq('process_id', $queryBuilder->createNamedParameter($processId))
306
            )
307
            ->orderBy('ttl')
308
            ->execute()
309
            ->fetchColumn(0);
310
311
        return (bool)$isActive;
312
    }
313
}
314