MultiProcessRequestForm::getLinkButton()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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