Failed Conditions
Push — task/2976_TYPO3.11_compatibili... ( ba9fea...772e40 )
by Rafael
42:34
created

initializeSelectedSolrCoreConnection()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 19
ccs 0
cts 10
cp 0
rs 9.2222
c 0
b 0
f 0
cc 6
nc 7
nop 0
crap 42
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
     * @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('mainJsFunctions', '
227
                top.fsMod.recentIds["searchbackend"] = ' . (int)$this->selectedPageUID . ';'
228
        );
229
        if (null === $this->selectedSite) {
230
            return;
231
        }
232
233
        /* @var BackendUserAuthentication $beUser */
234
        $beUser = $GLOBALS['BE_USER'];
235
        $permissionClause = $beUser->getPagePermsClause(1);
236
        $pageRecord = BackendUtility::readPageAccess($this->selectedSite->getRootPageId(), $permissionClause);
237
238
        if (false === $pageRecord) {
239
            throw new InvalidArgumentException(vsprintf('There is something wrong with permissions for page "%s" for backend user "%s".', [$this->selectedSite->getRootPageId(), $beUser->user['username']]), 1496146317);
240
        }
241
        $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pageRecord);
242
    }
243
244
    /**
245
     * Generates selector menu in backends doc header using selected page from page tree.
246
     *
247
     * @param string|null $uriToRedirectTo
248
     * @throws InvalidViewObjectNameException
249
     */
250
    public function generateCoreSelectorMenuUsingPageTree(string $uriToRedirectTo = null)
251
    {
252
        if ($this->selectedPageUID < 1 || null === $this->selectedSite) {
253
            return;
254
        }
255
256
        $this->generateCoreSelectorMenu($this->selectedSite, $uriToRedirectTo);
257
    }
258
259
    /**
260
     * Generates Core selector Menu for given Site.
261
     *
262
     * @param Site $site
263
     * @param string|null $uriToRedirectTo
264
     */
265
    protected function generateCoreSelectorMenu(Site $site, string $uriToRedirectTo = null)
266
    {
267
        $this->coreSelectorMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
268
        $this->coreSelectorMenu->setIdentifier('component_core_selector_menu');
269
270
        if (!isset($uriToRedirectTo)) {
271
            $uriToRedirectTo = $this->uriBuilder->reset()->uriFor();
272
        }
273
274
        $this->initializeSelectedSolrCoreConnection();
275
        $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

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

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

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

309
                [$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...
310
        );
311
312
        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...
313
    }
314
315
    /**
316
     * Switches used core.
317
     *
318
     * Note: Does not check availability of core in site. All this stuff is done in the generation step.
319
     *
320
     * @param string $corePath
321
     * @param string $uriToRedirectTo
322
     * @return ResponseInterface
323
     */
324
    public function switchCoreAction(string $corePath, string $uriToRedirectTo): ResponseInterface
325
    {
326
        $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

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

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