Failed Conditions
Push — task/2976_TYPO3.11_compatibili... ( c614ef...950c3e )
by Rafael
42:34
created

AbstractModuleController::injectUriBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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\Component\Exception\InvalidViewObjectNameException;
24
use ApacheSolrForTypo3\Solr\System\Mvc\Backend\Service\ModuleDataStorageService;
25
use Doctrine\DBAL\Driver\Exception as DBALDriverException;
26
use InvalidArgumentException;
27
use Psr\Http\Message\ResponseInterface;
28
use Throwable;
29
use TYPO3\CMS\Backend\Template\Components\Menu\Menu;
30
use TYPO3\CMS\Backend\Template\ModuleTemplate;
31
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
32
use TYPO3\CMS\Backend\Utility\BackendUtility;
33
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
34
use TYPO3\CMS\Core\Http\RedirectResponse;
35
use TYPO3\CMS\Core\Messaging\AbstractMessage;
36
use TYPO3\CMS\Core\Site\SiteFinder;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
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 pagetree 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|null
85
     */
86
    protected ?ConnectionManager $solrConnectionManager = null;
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
     * @param ModuleTemplateFactory $moduleTemplateFactory
117
     */
118
    public function __construct(ModuleTemplateFactory $moduleTemplateFactory) {
119
        $this->moduleTemplateFactory = $moduleTemplateFactory;
120
    }
121 3
122
    /**
123 3
     * Injects UriBuilder object.
124 3
     *
125
     * Purpose: PhpUnit
126
     *
127
     * @param UriBuilder $uriBuilder
128
     * @return void
129
     */
130
    public function injectUriBuilder(UriBuilder $uriBuilder)
131
    {
132
        $this->uriBuilder = $uriBuilder;
133
    }
134
135
    /**
136
     * @param Site $selectedSite
137
     */
138
    public function setSelectedSite(Site $selectedSite)
139
    {
140
        $this->selectedSite = $selectedSite;
141
    }
142
143
    /**
144
     * @param SiteRepository $siteRepository
145
     */
146
    public function injectSiteRepository(SiteRepository $siteRepository)
147
    {
148
        $this->siteRepository = $siteRepository;
149
    }
150
151
    /**
152
     * Initializes the controller and sets needed vars.
153
     * @todo: Make DI for class properties.
154
     */
155
    protected function initializeAction()
156
    {
157
        parent::initializeAction();
158
        $this->indexQueue = GeneralUtility::makeInstance(Queue::class);
159
        $this->solrConnectionManager = GeneralUtility::makeInstance(ConnectionManager::class);
160
        $this->moduleDataStorageService = GeneralUtility::makeInstance(ModuleDataStorageService::class);
161
        $this->siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
162
163
        $this->selectedPageUID = (int)GeneralUtility::_GP('id');
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
     */
188
    protected function autoSelectFirstSiteAndRootPageWhenOnlyOneSiteIsAvailable(): bool
189
    {
190
        $solrConfiguredSites = $this->siteRepository->getAvailableSites();
191
        $availableSites = $this->siteFinder->getAllSites();
192
        if (count($solrConfiguredSites) === 1 && count($availableSites) === 1) {
193
            $this->selectedSite = $this->siteRepository->getFirstAvailableSite();
194
195
            // we only overwrite the selected pageUid when no id was passed
196
            if ($this->selectedPageUID === 0) {
197
                $this->selectedPageUID = $this->selectedSite->getRootPageId();
198
            }
199
            return true;
200
        }
201
202
        return false;
203
    }
204
205
    /**
206
     * Set up the doc header properly here
207
     *
208
     * @param ViewInterface $view
209
     * @return void
210
     * @throws DBALDriverException
211
     * @throws Throwable
212
     */
213
    protected function initializeView($view)
214
    {
215
        $sites = $this->siteRepository->getAvailableSites();
216
217
        $selectOtherPage = count($sites) > 0 || $this->selectedPageUID < 1;
218
        $this->view->assign('showSelectOtherPage', $selectOtherPage);
219
        $this->view->assign('pageUID', $this->selectedPageUID);
220
        if ($this->selectedPageUID < 1) {
221
            return;
222
        }
223
        $this->moduleTemplate = $this->moduleTemplateFactory->create($this->request);
224
        $this->moduleTemplate->addJavaScriptCode('mainJsFunctions', '
225
                top.fsMod.recentIds["searchbackend"] = ' . (int)$this->selectedPageUID . ';'
226
        );
227
        if (null === $this->selectedSite) {
228
            return;
229
        }
230
231
        /* @var BackendUserAuthentication $beUser */
232
        $beUser = $GLOBALS['BE_USER'];
233
        $permissionClause = $beUser->getPagePermsClause(1);
234
        $pageRecord = BackendUtility::readPageAccess($this->selectedSite->getRootPageId(), $permissionClause);
235
236
        if (false === $pageRecord) {
237
            throw new InvalidArgumentException(vsprintf('There is something wrong with permissions for page "%s" for backend user "%s".', [$this->selectedSite->getRootPageId(), $beUser->user['username']]), 1496146317);
238
        }
239
        $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pageRecord);
240
    }
241
242
    /**
243
     * Generates selector menu in backends doc header using selected page from page tree.
244
     *
245
     * @param string|null $uriToRedirectTo
246
     * @throws InvalidViewObjectNameException
247
     */
248
    public function generateCoreSelectorMenuUsingPageTree(string $uriToRedirectTo = null)
249
    {
250
        if ($this->selectedPageUID < 1 || null === $this->selectedSite) {
251
            return;
252
        }
253
254
        $this->generateCoreSelectorMenu($this->selectedSite, $uriToRedirectTo);
255
    }
256
257
    /**
258
     * Generates Core selector Menu for given Site.
259
     *
260
     * @param Site $site
261
     * @param string|null $uriToRedirectTo
262
     */
263
    protected function generateCoreSelectorMenu(Site $site, string $uriToRedirectTo = null)
264
    {
265
        $this->coreSelectorMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
266
        $this->coreSelectorMenu->setIdentifier('component_core_selector_menu');
267
268
        if (!isset($uriToRedirectTo)) {
269
            $uriToRedirectTo = $this->uriBuilder->reset()->uriFor();
270
        }
271
272
        $this->initializeSelectedSolrCoreConnection();
273
        $cores = $this->solrConnectionManager->getConnectionsBySite($site);
0 ignored issues
show
Bug introduced by
The method getConnectionsBySite() 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

273
        /** @scrutinizer ignore-call */ 
274
        $cores = $this->solrConnectionManager->getConnectionsBySite($site);

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...
274
        foreach ($cores as $core) {
275
            $coreAdmin = $core->getAdminService();
276
            $menuItem = $this->coreSelectorMenu->makeMenuItem();
277
            $menuItem->setTitle($coreAdmin->getCorePath());
278
            $uri = $this->uriBuilder->reset()->uriFor('switchCore',
279
                [
280
                    'corePath' => $coreAdmin->getCorePath(),
281
                    'uriToRedirectTo' => $uriToRedirectTo
282
                ]
283
            );
284
            $menuItem->setHref($uri);
285
286
            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

286
            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...
287
                $menuItem->setActive(true);
288
            }
289
            $this->coreSelectorMenu->addMenuItem($menuItem);
290
        }
291
292
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($this->coreSelectorMenu);
293
    }
294
295
    /**
296
     * Empties the Index Queue
297
     *
298
     * @return void
299
     *
300
     * @noinspection PhpUnused Used in IndexQueue- and IndexAdministration- controllers
301
     */
302
    public function clearIndexQueueAction(): ResponseInterface
303
    {
304
        $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

304
        $this->indexQueue->deleteItemsBySite(/** @scrutinizer ignore-type */ $this->selectedSite);
Loading history...
305
        $this->addFlashMessage(
306
            LocalizationUtility::translate('solr.backend.index_administration.success.queue_emptied', 'Solr',
307
                [$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

307
                [$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...
308
        );
309
310
        return new RedirectResponse($this->uriBuilder->uriFor('index'), 303);
0 ignored issues
show
Bug Best Practice introduced by
The expression return new TYPO3\CMS\Cor...->uriFor('index'), 303) returns the type TYPO3\CMS\Core\Http\RedirectResponse which is incompatible with the documented return type void.
Loading history...
311
    }
312
313
    /**
314
     * Switches used core.
315
     *
316
     * Note: Does not check availability of core in site. All this stuff is done in the generation step.
317
     *
318
     * @param string $corePath
319
     * @param string $uriToRedirectTo
320
     * @return ResponseInterface
321
     */
322
    public function switchCoreAction(string $corePath, string $uriToRedirectTo): ResponseInterface
323
    {
324
        $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

324
        /** @scrutinizer ignore-call */ 
325
        $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...
325
        $moduleData->setCore($corePath);
326
327
        $this->moduleDataStorageService->persistModuleData($moduleData);
328
        $message = LocalizationUtility::translate('coreselector_switched_successfully', 'solr', [$corePath]);
329
        $this->addFlashMessage($message);
330
        return new RedirectResponse($uriToRedirectTo, 303);
331
    }
332
333
    /**
334
     * Initializes the solr core connection considerately to the components state.
335
     * Uses and persists default core connection if persisted core in Site does not exist.
336
     *
337
     */
338
    private function initializeSelectedSolrCoreConnection()
339
    {
340
        $moduleData = $this->moduleDataStorageService->loadModuleData();
341
342
        $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

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