Passed
Push — tests/improvements ( 81b4b0...70a11f )
by Tomas Norre
06:38
created

MultiProcessRequestForm::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AOE\Crawler\Backend\RequestForm;
6
7
/*
8
 * (c) 2020 AOE GmbH <[email protected]>
9
 *
10
 * This file is part of the TYPO3 Crawler Extension.
11
 *
12
 * It is free software; you can redistribute it and/or modify it under
13
 * the terms of the GNU General Public License, either version 2
14
 * of the License, or any later version.
15
 *
16
 * For the full copyright and license information, please read the
17
 * LICENSE.txt file that was distributed with this source code.
18
 *
19
 * The TYPO3 project - inspiring people to share!
20
 */
21
22
use AOE\Crawler\Backend\Helper\UrlBuilder;
23
use AOE\Crawler\Controller\CrawlerController;
24
use AOE\Crawler\Crawler;
25
use AOE\Crawler\Domain\Repository\ProcessRepository;
26
use AOE\Crawler\Domain\Repository\QueueRepository;
27
use AOE\Crawler\Exception\ProcessException;
28
use AOE\Crawler\Service\ProcessService;
29
use AOE\Crawler\Utility\MessageUtility;
30
use Psr\Http\Message\UriInterface;
31
use TYPO3\CMS\Backend\Template\ModuleTemplate;
32
use TYPO3\CMS\Core\Imaging\Icon;
33
use TYPO3\CMS\Core\Imaging\IconFactory;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
use TYPO3\CMS\Core\Utility\MathUtility;
36
use TYPO3\CMS\Fluid\View\StandaloneView;
37
use TYPO3\CMS\Info\Controller\InfoModuleController;
38
39
final class MultiProcessRequestForm extends AbstractRequestForm implements RequestFormInterface
40
{
41
    /**
42
     * @var StandaloneView
43
     */
44
    private $view;
45
46
    /**
47
     * @var ProcessService
48
     */
49
    private $processService;
50
51
    /**
52
     * @var IconFactory
53
     */
54
    private $iconFactory;
55
56
    /**
57
     * @var InfoModuleController
58
     */
59
    private $infoModuleController;
60
61
    /**
62
     * @var int|mixed
63
     */
64
    private $id;
65
66
    /**
67
     * @var Crawler
68
     */
69
    private $crawler;
70
71 2
    public function __construct(StandaloneView $view, InfoModuleController $infoModuleController, array $extensionSettings)
72
    {
73 2
        $this->view = $view;
74 2
        $this->processService = GeneralUtility::makeInstance(ProcessService::class);
75 2
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
76 2
        $this->infoModuleController = $infoModuleController;
77 2
        $this->extensionSettings = $extensionSettings;
78 2
        $this->crawler = GeneralUtility::makeInstance(Crawler::class);
79 2
    }
80
81
    public function render($id, string $elementName, array $menuItems): string
82
    {
83
        return $this->processOverviewAction();
84
    }
85
86
    /**
87
     * This method is used to show an overview about the active an the finished crawling processes
88
     *
89
     * @return string
90
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
91
     */
92
    private function processOverviewAction()
93
    {
94
        $this->view->setTemplate('ProcessOverview');
95
        $this->runRefreshHooks();
96
        $this->makeCrawlerProcessableChecks($this->extensionSettings);
97
98
        try {
99
            $this->handleProcessOverviewActions();
100
        } catch (\Throwable $e) {
101
            $this->isErrorDetected = true;
102
            MessageUtility::addErrorMessage($e->getMessage());
103
        }
104
105
        $processRepository = GeneralUtility::makeInstance(ProcessRepository::class);
106
        $queueRepository = GeneralUtility::makeInstance(QueueRepository::class);
107
108
        $mode = GeneralUtility::_GP('processListMode') ?? $this->infoModuleController->MOD_SETTINGS['processListMode'];
109
        if ($mode === 'simple') {
110
            $allProcesses = $processRepository->findAllActive();
111
        } else {
112
            $allProcesses = $processRepository->findAll();
113
        }
114
        $isCrawlerEnabled = ! $this->crawler->isDisabled() && ! $this->isErrorDetected;
115
        $currentActiveProcesses = $processRepository->findAllActive()->count();
116
        $maxActiveProcesses = MathUtility::forceIntegerInRange($this->extensionSettings['processLimit'], 1, 99, 1);
117
        $this->view->assignMultiple([
118
            'pageId' => (int) $this->id,
119
            'refreshLink' => $this->getRefreshLink(),
120
            'addLink' => $this->getAddLink($currentActiveProcesses, $maxActiveProcesses, $isCrawlerEnabled),
121
            'modeLink' => $this->getModeLink($mode),
122
            'enableDisableToggle' => $this->getEnableDisableLink($isCrawlerEnabled),
123
            'processCollection' => $allProcesses,
124
            'cliPath' => $this->processService->getCrawlerCliPath(),
125
            'isCrawlerEnabled' => $isCrawlerEnabled,
126
            'totalUnprocessedItemCount' => $queueRepository->countAllPendingItems(),
127
            'assignedUnprocessedItemCount' => $queueRepository->countAllAssignedPendingItems(),
128
            'activeProcessCount' => $currentActiveProcesses,
129
            'maxActiveProcessCount' => $maxActiveProcesses,
130
            'mode' => $mode,
131
            'displayActions' => 0,
132
        ]);
133
134
        return $this->view->render();
135
    }
136
137
    private function getLinkButton(string $iconIdentifier, string $title, UriInterface $href): string
138
    {
139
        $moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
140
        $buttonBar = $moduleTemplate->getDocHeaderComponent()->getButtonBar();
141
        return (string) $buttonBar->makeLinkButton()
142
            ->setHref((string) $href)
143
            ->setIcon($this->iconFactory->getIcon($iconIdentifier, Icon::SIZE_SMALL))
144
            ->setTitle($title)
145
            ->setShowLabelText(true);
146
    }
147
148
    /**
149
     * Method to handle incomming actions of the process overview
150
     *
151
     * @throws ProcessException
152
     */
153
    private function handleProcessOverviewActions(): void
154
    {
155
        switch (GeneralUtility::_GP('action')) {
156
            case 'stopCrawling':
157
                //set the cli status to disable (all processes will be terminated)
158
                $this->crawler->setDisabled(true);
159
                break;
160
            case 'addProcess':
161
                if ($this->processService->startProcess() === false) {
0 ignored issues
show
introduced by
The condition $this->processService->startProcess() === false is always false.
Loading history...
162
                    throw new ProcessException($this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.newprocesserror'));
163
                }
164
                MessageUtility::addNoticeMessage($this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.newprocess'));
165
                break;
166
            case 'resumeCrawling':
167
            default:
168
                //set the cli status to end (all processes will be terminated)
169
                $this->crawler->setDisabled(false);
170
                break;
171
        }
172
    }
173
174
    /**
175
     * Returns a tag for the refresh icon
176
     *
177
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
178
     */
179
    private function getRefreshLink(): string
180
    {
181
        return $this->getLinkButton(
182
            'actions-refresh',
183
            $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.refresh'),
184
            UrlBuilder::getInfoModuleUrl(['SET[\'crawleraction\']' => 'crawleraction', 'id' => $this->id])
185
        );
186
    }
187
188
    /**
189
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
190
     */
191
    private function getAddLink(int $currentActiveProcesses, int $maxActiveProcesses, bool $isCrawlerEnabled): string
192
    {
193
        if (! $isCrawlerEnabled) {
194
            return '';
195
        }
196
        if ($currentActiveProcesses >= $maxActiveProcesses) {
197
            return '';
198
        }
199
200
        return $this->getLinkButton(
201
            'actions-add',
202
            $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.process.add'),
203
            UrlBuilder::getInfoModuleUrl(['action' => 'addProcess'])
204
        );
205
    }
206
207
    /**
208
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
209
     */
210
    private function getModeLink(string $mode): string
211
    {
212
        if ($mode === 'detail') {
213
            return $this->getLinkButton(
214
                'actions-document-view',
215
                $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.show.running'),
216
                UrlBuilder::getInfoModuleUrl(['processListMode' => 'simple'])
217
            );
218
        } elseif ($mode === 'simple') {
219
            return $this->getLinkButton(
220
                'actions-document-view',
221
                $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.show.all'),
222
                UrlBuilder::getInfoModuleUrl(['processListMode' => 'detail'])
223
            );
224
        }
225
        return '';
226
    }
227
228
    /**
229
     * Returns a link for the panel to enable or disable the crawler
230
     *
231
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
232
     */
233
    private function getEnableDisableLink(bool $isCrawlerEnabled): string
234
    {
235
        if ($isCrawlerEnabled) {
236
            return $this->getLinkButton(
237
                'tx-crawler-stop',
238
                $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.disablecrawling'),
239
                UrlBuilder::getInfoModuleUrl(['action' => 'stopCrawling'])
240
            );
241
        }
242
        return $this->getLinkButton(
243
            'tx-crawler-start',
244
            $this->getLanguageService()->sL('LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.enablecrawling'),
245
            UrlBuilder::getInfoModuleUrl(['action' => 'resumeCrawling'])
246
        );
247
    }
248
249
    /**
250
     * Activate hooks
251
     */
252
    private function runRefreshHooks(): void
253
    {
254
        $crawlerLib = GeneralUtility::makeInstance(CrawlerController::class);
255
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['refresh_hooks'] ?? [] as $objRef) {
256
            /** @var CrawlerHookInterface $hookObj */
257
            $hookObj = GeneralUtility::makeInstance($objRef);
258
            if (is_object($hookObj)) {
259
                $hookObj->crawler_init($crawlerLib);
260
            }
261
        }
262
    }
263
}
264