Passed
Push — refactor/backendModule-ValueOb... ( ba8b37...91b878 )
by Tomas Norre
07:37
created

  A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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