Passed
Push — master ( 1bd1cf...791909 )
by Timo
46s
created

initializeSelectedSolrCoreConnection()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 13
nc 12
nop 0
1
<?php
2
namespace ApacheSolrForTypo3\Solr\Controller\Backend\Search;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-2017 dkd Internet Service GmbH <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 2 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
28
use ApacheSolrForTypo3\Solr\Site;
29
use ApacheSolrForTypo3\Solr\SolrService as SolrCoreConnection;
30
use ApacheSolrForTypo3\Solr\System\Mvc\Backend\Component\Exception\InvalidViewObjectNameException;
31
use ApacheSolrForTypo3\Solr\Utility\StringUtility;
32
use TYPO3\CMS\Backend\Template\Components\Menu\Menu;
33
use TYPO3\CMS\Backend\Utility\BackendUtility;
34
use TYPO3\CMS\Backend\View\BackendTemplateView;
35
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
36
use TYPO3\CMS\Core\Messaging\AbstractMessage;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
39
use TYPO3\CMS\Extbase\Mvc\View\NotFoundView;
40
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
41
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
42
43
/**
44
 * Abstract Module
45
 *
46
 * @property BackendTemplateView $view
47
 */
48
abstract class AbstractModuleController extends ActionController
49
{
50
    /**
51
     * Backend Template Container
52
     *
53
     * @var string
54
     */
55
    protected $defaultViewObjectName = BackendTemplateView::class;
56
57
    /**
58
     * @var \ApacheSolrForTypo3\Solr\Utility\StringUtility
59
     */
60
    protected $stringUtility;
61
62
    /**
63
     * In the pagetree selected page UID
64
     *
65
     * @var int
66
     */
67
    protected $selectedPageUID;
68
69
    /**
70
     * @var Site
71
     */
72
    protected $selectedSite;
73
74
    /**
75
     * @var SolrCoreConnection
76
     */
77
    protected $selectedSolrCoreConnection;
78
79
    /**
80
     * @var Menu
81
     */
82
    protected $coreSelectorMenu = null;
83
84
    /**
85
     * @var \ApacheSolrForTypo3\Solr\ConnectionManager
86
     * @inject
87
     */
88
    protected $solrConnectionManager = null;
89
90
    /**
91
     * @var \ApacheSolrForTypo3\Solr\System\Mvc\Backend\Service\ModuleDataStorageService
92
     * @inject
93
     */
94
    protected $moduleDataStorageService = null;
95
96
    /**
97
     * Method to pass a StringUtil object.
98
     * Use to overwrite injected object in unit test context.
99
     *
100
     * @param \ApacheSolrForTypo3\Solr\Utility\StringUtility $stringUtility
101
     */
102
    public function injectStringHelper(StringUtility $stringUtility)
103
    {
104
        $this->stringUtility = $stringUtility;
105
    }
106
107
    /**
108
     * Initializes the controller and sets needed vars.
109
     */
110
    protected function initializeAction()
111
    {
112
        parent::initializeAction();
113
        $this->selectedPageUID = (int)GeneralUtility::_GP('id');
114
115
        if ($this->selectedPageUID < 1) {
116
            return;
117
        }
118
        /* @var SiteRepository $siteRepository */
119
        $siteRepository = $this->objectManager->get(SiteRepository::class);
120
        $this->selectedSite = $siteRepository->getSiteByPageId($this->selectedPageUID);
121
    }
122
123
    /**
124
     * Set up the doc header properly here
125
     *
126
     * @param ViewInterface $view
127
     * @return void
128
     */
129
    protected function initializeView(ViewInterface $view)
130
    {
131
        parent::initializeView($view);
132
        if ($view instanceof NotFoundView || $this->selectedPageUID < 1) {
133
            return;
134
        }
135
        /* @var BackendUserAuthentication $beUser */
136
        $beUser = $GLOBALS['BE_USER'];
137
        $permissionClause = $beUser->getPagePermsClause(1);
138
        $pageRecord = BackendUtility::readPageAccess($this->selectedSite->getRootPageId(), $permissionClause);
139
140
        if (false === $pageRecord) {
141
            throw new \InvalidArgumentException(vsprintf('There is something wrong with permissions for page "%s" for backend user "%s".', [$this->selectedSite->getRootPageId(), $beUser->user['username']]), 1496146317);
142
        }
143
        $this->view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation($pageRecord);
144
    }
145
146
    /**
147
     * Generates selector menu in backends doc header using selected page from page tree.
148
     *
149
     * @param string|null $uriToRedirectTo
150
     */
151
    public function generateCoreSelectorMenuUsingPageTree(string $uriToRedirectTo = null)
152
    {
153
        $selectedPageUID = (int)GeneralUtility::_GP('id');
154
        if ($selectedPageUID < 1) {
155
            return;
156
        }
157
        /* @var SiteRepository $siteRepository */
158
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
159
        $this->selectedSite = $siteRepository->getSiteByPageId($selectedPageUID);
160
161
        if ($this->view instanceof NotFoundView) {
162
            $this->initializeSelectedSolrCoreConnection();
163
            return;
164
        }
165
166
        $this->generateCoreSelectorMenu($this->selectedSite, $uriToRedirectTo);
167
    }
168
169
    /**
170
     * Generates Core selector Menu for given Site.
171
     *
172
     * @param Site $site
173
     * @param string|null $uriToRedirectTo
174
     * @throws InvalidViewObjectNameException
175
     */
176
    protected function generateCoreSelectorMenu(Site $site, string $uriToRedirectTo = null)
177
    {
178
        if (!$this->view instanceof BackendTemplateView) {
179
            throw new InvalidViewObjectNameException(vsprintf(
180
                'The controller "%s" must use BackendTemplateView to be able to generate menu for backends docheader. \
181
                Please set `protected $defaultViewObjectName = BackendTemplateView::class;` field in your controller.',
182
                [static::class]), 1493804179);
183
        }
184
        $this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
185
186
        $this->coreSelectorMenu = $this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
187
        $this->coreSelectorMenu->setIdentifier('component_core_selector_menu');
188
189
        if (!isset($uriToRedirectTo)) {
190
            $uriToRedirectTo = $this->uriBuilder->reset()->uriFor();
191
        }
192
193
        $this->initializeSelectedSolrCoreConnection();
194
        $cores = $this->solrConnectionManager->getConnectionsBySite($site);
195
        foreach ($cores as $core) {
196
            $menuItem = $this->coreSelectorMenu->makeMenuItem();
197
            $menuItem->setTitle($core->getPath());
198
            $uri = $this->uriBuilder->reset()->uriFor('switchCore',
199
                [
200
                    'corePath' => $core->getPath(),
201
                    'uriToRedirectTo' => $uriToRedirectTo
202
                ]
203
            );
204
            $menuItem->setHref($uri);
205
206
            if ($core->getPath() == $this->selectedSolrCoreConnection->getPath()) {
207
                $menuItem->setActive(true);
208
            }
209
            $this->coreSelectorMenu->addMenuItem($menuItem);
210
        }
211
212
        $this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->addMenu($this->coreSelectorMenu);
213
    }
214
215
    /**
216
     * Switches used core.
217
     *
218
     * Note: Does not check availability of core in site. All this stuff is done in the generation step.
219
     *
220
     * @param string $corePath
221
     * @param string $uriToRedirectTo
222
     */
223
    public function switchCoreAction(string $corePath, string $uriToRedirectTo)
224
    {
225
        $moduleData = $this->moduleDataStorageService->loadModuleData();
226
        $moduleData->setCore($corePath);
227
228
        $this->moduleDataStorageService->persistModuleData($moduleData);
229
        $message = LocalizationUtility::translate('coreselector_switched_successfully', 'solr', [$corePath]);
230
        $this->addFlashMessage($message);
231
        $this->redirectToUri($uriToRedirectTo);
232
    }
233
234
    /**
235
     * Initializes the solr core connection considerately to the components state.
236
     * Uses and persists default core connection if persisted core in Site does not exist.
237
     *
238
     */
239
    private function initializeSelectedSolrCoreConnection()
240
    {
241
        $moduleData = $this->moduleDataStorageService->loadModuleData();
242
243
        $solrCoreConnections = $this->solrConnectionManager->getConnectionsBySite($this->selectedSite);
244
        $currentSolrCorePath = $moduleData->getCore();
245
        if (empty($currentSolrCorePath)) {
246
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
247
        }
248
        foreach ($solrCoreConnections as $solrCoreConnection) {
249
            if ($solrCoreConnection->getPath() == $currentSolrCorePath) {
250
                $this->selectedSolrCoreConnection = $solrCoreConnection;
251
            }
252
        }
253
        if (!$this->selectedSolrCoreConnection instanceof SolrCoreConnection && count($solrCoreConnections) > 0) {
254
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
255
            $message = LocalizationUtility::translate('coreselector_switched_to_default_core', 'solr', [$currentSolrCorePath, $this->selectedSite->getLabel(), $this->selectedSolrCoreConnection->getPath()]);
256
            $this->addFlashMessage($message, '', AbstractMessage::NOTICE);
257
        }
258
    }
259
260
    /**
261
     * @param SolrCoreConnection[] $solrCoreConnections
262
     */
263
    private function initializeFirstAvailableSolrCoreConnection(array $solrCoreConnections, $moduleData)
264
    {
265
        $this->selectedSolrCoreConnection = $solrCoreConnections[0];
266
        $moduleData->setCore($this->selectedSolrCoreConnection->getPath());
267
        $this->moduleDataStorageService->persistModuleData($moduleData);
268
    }
269
}
270