Passed
Push — task/2976_TYPO3.11_compatibili... ( 9f9205...0f123d )
by Rafael
27:04
created

AbstractModuleController::initializeView()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 29
ccs 0
cts 19
cp 0
rs 9.3222
cc 5
nc 8
nop 1
crap 30
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\Controller\Backend\Search;
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
use ApacheSolrForTypo3\Solr\ConnectionManager;
19
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
20
use ApacheSolrForTypo3\Solr\Domain\Site\Site;
21
use ApacheSolrForTypo3\Solr\IndexQueue\Queue;
22
use ApacheSolrForTypo3\Solr\System\Solr\SolrConnection as SolrCoreConnection;
23
use ApacheSolrForTypo3\Solr\System\Mvc\Backend\Service\ModuleDataStorageService;
24
use Doctrine\DBAL\Driver\Exception as DBALDriverException;
25
use InvalidArgumentException;
26
use Psr\Http\Message\ResponseInterface;
27
use Throwable;
28
use TYPO3\CMS\Backend\Template\Components\Menu\Menu;
29
use TYPO3\CMS\Backend\Template\ModuleTemplate;
30
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
31
use TYPO3\CMS\Backend\Utility\BackendUtility;
32
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
33
use TYPO3\CMS\Core\Http\RedirectResponse;
34
use TYPO3\CMS\Core\Messaging\AbstractMessage;
35
use TYPO3\CMS\Core\Site\SiteFinder;
36
use TYPO3\CMS\Core\Utility\GeneralUtility;
37
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
38
use TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException;
39
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
40
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
41
use TYPO3Fluid\Fluid\View\ViewInterface;
42
43
/**
44
 * Abstract Module
45
 */
46
abstract class AbstractModuleController extends ActionController
47
{
48
    /**
49
     * In the page-tree selected page UID
50
     *
51
     * @var int
52
     */
53
    protected int $selectedPageUID;
54
55
    /**
56
     * Holds the requested page UID because the selected page uid,
57
     * might be overwritten by the automatic site selection.
58
     *
59
     * @var int
60
     */
61
    protected int $requestedPageUID;
62
63
    /**
64
     * @var ?Site
65
     */
66
    protected ?Site $selectedSite = null;
67
68
    /**
69
     * @var SiteRepository
70
     */
71
    protected SiteRepository $siteRepository;
72
73
    /**
74
     * @var SolrCoreConnection|null
75
     */
76
    protected ?SolrCoreConnection $selectedSolrCoreConnection = null;
77
78
    /**
79
     * @var Menu|null
80
     */
81
    protected ?Menu $coreSelectorMenu = null;
82
83
    /**
84
     * @var ConnectionManager
85
     */
86
    protected ConnectionManager $solrConnectionManager;
87
88
    /**
89
     * @var ModuleDataStorageService|null
90
     */
91
    protected ?ModuleDataStorageService $moduleDataStorageService = null;
92
93
    /**
94
     * @var Queue
95
     */
96
    protected Queue $indexQueue;
97
98
    /**
99
     * @var SiteFinder
100
     */
101
    protected SiteFinder $siteFinder;
102
103
    /**
104
     * @var ModuleTemplateFactory
105
     */
106
    protected ModuleTemplateFactory $moduleTemplateFactory;
107
108
    /**
109
     * @var ModuleTemplate
110
     */
111
    protected ModuleTemplate $moduleTemplate;
112
113
    /**
114
     * Constructor for dependency injection
115
     */
116 5
    public function __construct(
117
        ModuleTemplateFactory $moduleTemplateFactory,
118
        ModuleDataStorageService $moduleDataStorageService,
119
        SiteRepository $siteRepository,
120
        SiteFinder $siteFinder,
121
        ConnectionManager $solrConnectionManager,
122
        Queue $indexQueue,
123
        ?int $selectedPageUID = null
124
    ) {
125 5
        $this->moduleTemplateFactory = $moduleTemplateFactory;
126 5
        $this->moduleDataStorageService = $moduleDataStorageService;
127 5
        $this->siteRepository = $siteRepository;
128 5
        $this->siteFinder = $siteFinder;
129 5
        $this->solrConnectionManager = $solrConnectionManager;
130 5
        $this->indexQueue = $indexQueue;
131 5
        $this->selectedPageUID = $selectedPageUID ?? (int)GeneralUtility::_GP('id');
132 5
    }
133
134
    /**
135
     * Injects UriBuilder object.
136
     *
137
     * Purpose: Is already set in {@link processRequest} but wanted in PhpUnit
138
     *
139
     * @param UriBuilder $uriBuilder
140
     * @return void
141
     */
142 5
    public function injectUriBuilder(UriBuilder $uriBuilder)
143
    {
144 5
        $this->uriBuilder = $uriBuilder;
145 5
    }
146
147
    /**
148
     * @param Site $selectedSite
149
     */
150 5
    public function setSelectedSite(Site $selectedSite)
151
    {
152 5
        $this->selectedSite = $selectedSite;
153 5
    }
154
155
    /**
156
     * Initializes the controller and sets needed vars.
157
     * @throws DBALDriverException
158
     * @throws Throwable
159
     * @throws NoSuchArgumentException
160
     */
161
    protected function initializeAction()
162
    {
163
        parent::initializeAction();
164
        if ($this->request->hasArgument('id')) {
165
            $this->selectedPageUID = (int)$this->request->getArgument('id');
166
        }
167
168
        $this->requestedPageUID = $this->selectedPageUID;
169
170
        if ($this->autoSelectFirstSiteAndRootPageWhenOnlyOneSiteIsAvailable()) {
171
            return;
172
        }
173
174
        if ($this->selectedPageUID < 1) {
175
            return;
176
        }
177
178
        try {
179
            $this->selectedSite = $this->siteRepository->getSiteByPageId($this->selectedPageUID);
180
        } catch (InvalidArgumentException $exception) {
181
            return;
182
        }
183
    }
184
185
    /**
186
     * @return bool
187
     * @throws DBALDriverException
188
     * @throws Throwable
189
     */
190
    protected function autoSelectFirstSiteAndRootPageWhenOnlyOneSiteIsAvailable(): bool
191
    {
192
        $solrConfiguredSites = $this->siteRepository->getAvailableSites();
193
        $availableSites = $this->siteFinder->getAllSites();
194
        if (count($solrConfiguredSites) === 1 && count($availableSites) === 1) {
195
            $this->selectedSite = $this->siteRepository->getFirstAvailableSite();
196
197
            // we only overwrite the selected pageUid when no id was passed
198
            if ($this->selectedPageUID === 0) {
199
                $this->selectedPageUID = $this->selectedSite->getRootPageId();
200
            }
201
            return true;
202
        }
203
204
        return false;
205
    }
206
207
    /**
208
     * Set up the doc header properly here
209
     *
210
     * @param ViewInterface $view
211
     * @return void
212
     * @throws DBALDriverException
213
     * @throws Throwable
214
     */
215
    protected function initializeView($view)
216
    {
217
        $sites = $this->siteRepository->getAvailableSites();
218
219
        $selectOtherPage = count($sites) > 0 || $this->selectedPageUID < 1;
220
        $this->view->assign('showSelectOtherPage', $selectOtherPage);
221
        $this->view->assign('pageUID', $this->selectedPageUID);
222
        if ($this->selectedPageUID < 1) {
223
            return;
224
        }
225
        $this->moduleTemplate = $this->moduleTemplateFactory->create($this->request);
226
        $this->moduleTemplate->addJavaScriptCode(
227
            'mainJsFunctions',
228
            '
229
                top.fsMod.recentIds["searchbackend"] = ' . $this->selectedPageUID . ';'
230
        );
231
        if (null === $this->selectedSite) {
232
            return;
233
        }
234
235
        /* @var BackendUserAuthentication $beUser */
236
        $beUser = $GLOBALS['BE_USER'];
237
        $permissionClause = $beUser->getPagePermsClause(1);
238
        $pageRecord = BackendUtility::readPageAccess($this->selectedSite->getRootPageId(), $permissionClause);
239
240
        if (false === $pageRecord) {
241
            throw new InvalidArgumentException(vsprintf('There is something wrong with permissions for page "%s" for backend user "%s".', [$this->selectedSite->getRootPageId(), $beUser->user['username']]), 1496146317);
242
        }
243
        $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pageRecord);
244
    }
245
246
    /**
247
     * Generates selector menu in backends doc header using selected page from page tree.
248
     *
249
     * @param string|null $uriToRedirectTo
250
     */
251
    public function generateCoreSelectorMenuUsingPageTree(string $uriToRedirectTo = null)
252
    {
253
        if ($this->selectedPageUID < 1 || null === $this->selectedSite) {
254
            return;
255
        }
256
257
        $this->generateCoreSelectorMenu($this->selectedSite, $uriToRedirectTo);
258
    }
259
260
    /**
261
     * Generates Core selector Menu for given Site.
262
     *
263
     * @param Site $site
264
     * @param string|null $uriToRedirectTo
265
     */
266
    protected function generateCoreSelectorMenu(Site $site, string $uriToRedirectTo = null)
267
    {
268
        $this->coreSelectorMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
269
        $this->coreSelectorMenu->setIdentifier('component_core_selector_menu');
270
271
        if (!isset($uriToRedirectTo)) {
272
            $uriToRedirectTo = $this->uriBuilder->reset()->uriFor();
273
        }
274
275
        $this->initializeSelectedSolrCoreConnection();
276
        $cores = $this->solrConnectionManager->getConnectionsBySite($site);
277
        foreach ($cores as $core) {
278
            $coreAdmin = $core->getAdminService();
279
            $menuItem = $this->coreSelectorMenu->makeMenuItem();
280
            $menuItem->setTitle($coreAdmin->getCorePath());
281
            $uri = $this->uriBuilder->reset()->uriFor(
282
                'switchCore',
283
                [
284
                    'corePath' => $coreAdmin->getCorePath(),
285
                    'uriToRedirectTo' => $uriToRedirectTo
286
                ]
287
            );
288
            $menuItem->setHref($uri);
289
290
            if ($coreAdmin->getCorePath() == $this->selectedSolrCoreConnection->getAdminService()->getCorePath()) {
0 ignored issues
show
Bug introduced by
The method getAdminService() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

290
            if ($coreAdmin->getCorePath() == $this->selectedSolrCoreConnection->/** @scrutinizer ignore-call */ getAdminService()->getCorePath()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
291
                $menuItem->setActive(true);
292
            }
293
            $this->coreSelectorMenu->addMenuItem($menuItem);
294
        }
295
296
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($this->coreSelectorMenu);
297
    }
298
299
    /**
300
     * Empties the Index Queue
301
     *
302
     * @return ResponseInterface
303
     *
304
     * @noinspection PhpUnused Used in IndexQueue- and IndexAdministration- controllers
305
     */
306
    public function clearIndexQueueAction(): ResponseInterface
307
    {
308
        $this->indexQueue->deleteItemsBySite($this->selectedSite);
0 ignored issues
show
Bug introduced by
It seems like $this->selectedSite can also be of type null; however, parameter $site of ApacheSolrForTypo3\Solr\...ue::deleteItemsBySite() does only seem to accept ApacheSolrForTypo3\Solr\Domain\Site\Site, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

308
        $this->indexQueue->deleteItemsBySite(/** @scrutinizer ignore-type */ $this->selectedSite);
Loading history...
309
        $this->addFlashMessage(
310
            LocalizationUtility::translate(
311
                'solr.backend.index_administration.success.queue_emptied',
312
                'Solr',
313
                [$this->selectedSite->getLabel()]
0 ignored issues
show
Bug introduced by
The method getLabel() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

313
                [$this->selectedSite->/** @scrutinizer ignore-call */ getLabel()]

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
314
            )
315
        );
316
317
        return new RedirectResponse($this->uriBuilder->uriFor('index'), 303);
318
    }
319
320
    /**
321
     * Switches used core.
322
     *
323
     * Note: Does not check availability of core in site. All this stuff is done in the generation step.
324
     *
325
     * @param string $corePath
326
     * @param string $uriToRedirectTo
327
     *
328
     * @return ResponseInterface
329
     *
330
     * @noinspection PhpUnused Used in IndexQueue- and IndexAdministration- controllers
331
     */
332
    public function switchCoreAction(string $corePath, string $uriToRedirectTo): ResponseInterface
333
    {
334
        $moduleData = $this->moduleDataStorageService->loadModuleData();
0 ignored issues
show
Bug introduced by
The method loadModuleData() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

334
        /** @scrutinizer ignore-call */ 
335
        $moduleData = $this->moduleDataStorageService->loadModuleData();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
335
        $moduleData->setCore($corePath);
336
337
        $this->moduleDataStorageService->persistModuleData($moduleData);
338
        $message = LocalizationUtility::translate('coreselector_switched_successfully', 'solr', [$corePath]);
339
        $this->addFlashMessage($message);
340
        return new RedirectResponse($uriToRedirectTo, 303);
341
    }
342
343
    /**
344
     * Initializes the solr core connection considerately to the components state.
345
     * Uses and persists default core connection if persisted core in Site does not exist.
346
     *
347
     */
348
    private function initializeSelectedSolrCoreConnection()
349
    {
350
        $moduleData = $this->moduleDataStorageService->loadModuleData();
351
352
        $solrCoreConnections = $this->solrConnectionManager->getConnectionsBySite($this->selectedSite);
0 ignored issues
show
Bug introduced by
It seems like $this->selectedSite can also be of type null; however, parameter $site of ApacheSolrForTypo3\Solr\...:getConnectionsBySite() does only seem to accept ApacheSolrForTypo3\Solr\Domain\Site\Site, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

352
        $solrCoreConnections = $this->solrConnectionManager->getConnectionsBySite(/** @scrutinizer ignore-type */ $this->selectedSite);
Loading history...
353
        $currentSolrCorePath = $moduleData->getCore();
354
        if (empty($currentSolrCorePath)) {
355
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
356
            return;
357
        }
358
        foreach ($solrCoreConnections as $solrCoreConnection) {
359
            if ($solrCoreConnection->getAdminService()->getCorePath() == $currentSolrCorePath) {
360
                $this->selectedSolrCoreConnection = $solrCoreConnection;
361
            }
362
        }
363
        if (!$this->selectedSolrCoreConnection instanceof SolrCoreConnection && count($solrCoreConnections) > 0) {
364
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
365
            $message = LocalizationUtility::translate('coreselector_switched_to_default_core', 'solr', [$currentSolrCorePath, $this->selectedSite->getLabel(), $this->selectedSolrCoreConnection->getAdminService()->getCorePath()]);
366
            $this->addFlashMessage($message, '', AbstractMessage::NOTICE);
367
        }
368
    }
369
370
    /**
371
     * @param SolrCoreConnection[] $solrCoreConnections
372
     */
373
    private function initializeFirstAvailableSolrCoreConnection(array $solrCoreConnections, $moduleData)
374
    {
375
        if (empty($solrCoreConnections)) {
376
            return;
377
        }
378
        $this->selectedSolrCoreConnection = $solrCoreConnections[0];
379
        $moduleData->setCore($this->selectedSolrCoreConnection->getAdminService()->getCorePath());
380
        $this->moduleDataStorageService->persistModuleData($moduleData);
381
    }
382
}
383