Passed
Pull Request — master (#2985)
by
unknown
34:31
created

SiteRepository::buildTypo3ManagedSite()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 75
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 4.0014

Importance

Changes 0
Metric Value
eloc 50
c 0
b 0
f 0
dl 0
loc 75
ccs 43
cts 45
cp 0.9556
rs 9.0909
cc 4
nc 4
nop 1
crap 4.0014

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\Domain\Site;
4
5
/***************************************************************
6
 *  Copyright notice
7
 *
8
 *  (c) 2017 - Thomas Hohn <[email protected]>
9
 *  All rights reserved
10
 *
11
 *  This script is part of the TYPO3 project. The TYPO3 project is
12
 *  free software; you can redistribute it and/or modify
13
 *  it under the terms of the GNU General Public License as published by
14
 *  the Free Software Foundation; either version 3 of the License, or
15
 *  (at your option) any later version.
16
 *
17
 *  The GNU General Public License can be found at
18
 *  http://www.gnu.org/copyleft/gpl.html.
19
 *
20
 *  This script is distributed in the hope that it will be useful,
21
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 *  GNU General Public License for more details.
24
 *
25
 *  This copyright notice MUST APPEAR in all copies of the script!
26
 ***************************************************************/
27
28
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
29
use ApacheSolrForTypo3\Solr\FrontendEnvironment;
30
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
31
use ApacheSolrForTypo3\Solr\System\Configuration\ExtensionConfiguration;
32
use ApacheSolrForTypo3\Solr\System\Records\Pages\PagesRepository;
33
use ApacheSolrForTypo3\Solr\System\Util\SiteUtility;
34
use TYPO3\CMS\Backend\Utility\BackendUtility;
35
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
36
use TYPO3\CMS\Core\Registry;
37
use TYPO3\CMS\Core\Site\SiteFinder;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
39
40
/**
41
 * SiteRepository
42
 *
43
 * Responsible to retrieve instances of Site objects
44
 *
45
 * @author Thomas Hohn <[email protected]>
46
 */
47
class SiteRepository
48
{
49
    /**
50
     * Rootpage resolver
51
     *
52
     * @var RootPageResolver
53
     */
54
    protected $rootPageResolver;
55
56
    /**
57
     * @var TwoLevelCache
58
     */
59
    protected $runtimeCache;
60
61
    /**
62
     * @var Registry
63
     */
64
    protected $registry;
65
66
    /**
67
     * @var SiteFinder
68
     */
69
    protected $siteFinder;
70
71
    /**
72
     * @var ExtensionConfiguration
73
     */
74
    protected $extensionConfiguration;
75
76
    /**
77
     * @var FrontendEnvironment
78
     */
79
    protected $frontendEnvironment = null;
80
81
    /**
82
     * SiteRepository constructor.
83
     *
84
     * @param RootPageResolver|null $rootPageResolver
85
     * @param TwoLevelCache|null $twoLevelCache
86
     * @param Registry|null $registry
87
     * @param SiteFinder|null $siteFinder
88
     * @param ExtensionConfiguration| null
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $ExtensionConfiguration| is correct as it would always require null to be passed?
Loading history...
89
     */
90 163
    public function __construct(
91
        RootPageResolver $rootPageResolver = null,
92
        TwoLevelCache $twoLevelCache = null,
93
        Registry $registry = null,
94
        SiteFinder $siteFinder = null,
95
        ExtensionConfiguration $extensionConfiguration = null,
96
        FrontendEnvironment $frontendEnvironment = null
97
    )
98
    {
99 163
        $this->rootPageResolver = $rootPageResolver ?? GeneralUtility::makeInstance(RootPageResolver::class);
100 163
        $this->runtimeCache = $twoLevelCache ?? GeneralUtility::makeInstance(TwoLevelCache::class, /** @scrutinizer ignore-type */'cache_runtime');
101 163
        $this->registry = $registry ?? GeneralUtility::makeInstance(Registry::class);
102 163
        $this->siteFinder = $siteFinder ?? GeneralUtility::makeInstance(SiteFinder::class);
103 163
        $this->extensionConfiguration = $extensionConfiguration ?? GeneralUtility::makeInstance(ExtensionConfiguration::class);
104 163
        $this->frontendEnvironment = $frontendEnvironment ?? GeneralUtility::makeInstance(FrontendEnvironment::class);
105 163
    }
106
107
    /**
108
     * Gets the Site for a specific page Id.
109
     *
110
     * @param int $pageId The page Id to get a Site object for.
111
     * @param string $mountPointIdentifier
112
     * @return SiteInterface Site for the given page Id.
113
     */
114 69
    public function getSiteByPageId($pageId, $mountPointIdentifier = '')
115
    {
116 69
        $rootPageId = $this->rootPageResolver->getRootPageId($pageId, false, $mountPointIdentifier);
117 69
        return $this->getSiteByRootPageId($rootPageId);
118
    }
119
120
    /**
121
     * Gets the Site for a specific root page Id.
122
     *
123
     * @param int $rootPageId Root page Id to get a Site object for.
124
     * @return SiteInterface Site for the given page Id.
125
     */
126 87
    public function getSiteByRootPageId($rootPageId)
127
    {
128 87
        $cacheId = 'SiteRepository' . '_' . 'getSiteByPageId' . '_' . $rootPageId;
129
130 87
        $methodResult = $this->runtimeCache->get($cacheId);
131 87
        if (!empty($methodResult)) {
132 61
            return $methodResult;
133
        }
134
135 87
        $methodResult = $this->buildSite($rootPageId);
136 80
        $this->runtimeCache->set($cacheId, $methodResult);
137
138 80
        return $methodResult;
139
    }
140
141
    /**
142
     * Returns the first available Site.
143
     *
144
     * @param bool $stopOnInvalidSite
145
     * @throws \Exception
146
     * @return Site
147
     */
148 21
    public function getFirstAvailableSite($stopOnInvalidSite = false)
149
    {
150 21
        $sites = $this->getAvailableSites($stopOnInvalidSite);
151 21
        return array_shift($sites);
152
    }
153
154
    /**
155
     * Gets all available TYPO3 sites with Solr configured.
156
     *
157
     * @param bool $stopOnInvalidSite
158
     * @throws \Exception
159
     * @return Site[] An array of availablesites
160
     */
161 85
    public function getAvailableSites($stopOnInvalidSite = false)
162
    {
163 85
        $cacheId = 'SiteRepository' . '_' . 'getAvailableSites';
164
165 85
        $sites = $this->runtimeCache->get($cacheId);
166 85
        if (!empty($sites)) {
167 15
            return $sites;
168
        }
169
170 85
        $sites = $this->getAvailableTYPO3ManagedSites($stopOnInvalidSite);
171 85
        $this->runtimeCache->set($cacheId, $sites);
172
173 85
        return $sites;
174
    }
175
176
    /**
177
     * @param bool $stopOnInvalidSite
178
     * @return array
179
     * @throws \Exception
180
     */
181 85
    protected function getAvailableTYPO3ManagedSites(bool $stopOnInvalidSite): array
182
    {
183 85
        $typo3ManagedSolrSites = [];
184 85
        $typo3Sites = $this->siteFinder->getAllSites();
185 85
        foreach ($typo3Sites as $typo3Site) {
186
            try {
187 85
                $rootPageId = $typo3Site->getRootPageId();
188 85
                if (isset($typo3ManagedSolrSites[$rootPageId])) {
189
                    //get each site only once
190
                    continue;
191
                }
192 85
                $typo3ManagedSolrSite = $this->buildSite($rootPageId);
193 80
                if ($typo3ManagedSolrSite->isEnabled()) {
194 80
                    $typo3ManagedSolrSites[$rootPageId] = $typo3ManagedSolrSite;
195
                }
196
197 81
            } catch (\Exception $e) {
198 81
                if ($stopOnInvalidSite) {
199
                    throw $e;
200
                }
201
            }
202
        }
203 85
        return $typo3ManagedSolrSites;
204
    }
205
206
     /**
207
     * Creates an instance of the Site object.
208
     *
209
     * @param integer $rootPageId
210
     * @throws \InvalidArgumentException
211
     * @return SiteInterface
212
     */
213 138
    protected function buildSite($rootPageId)
214
    {
215 138
        if (empty($rootPageId)) {
216
            throw new \InvalidArgumentException('Root page id can not be empty');
217
        }
218 138
        $rootPageRecord = (array)BackendUtility::getRecord('pages', $rootPageId);
219
220 138
        $this->validateRootPageRecord($rootPageId, $rootPageRecord);
221
222 127
        return $this->buildTypo3ManagedSite($rootPageRecord);
223
    }
224
225
    /**
226
     * @param string $domain
227
     * @return string
228
     */
229 127
    protected function getSiteHashForDomain($domain)
230
    {
231
        /** @var $siteHashService SiteHashService */
232 127
        $siteHashService = GeneralUtility::makeInstance(SiteHashService::class);
233 127
        $siteHash = $siteHashService->getSiteHashForDomain($domain);
234 127
        return $siteHash;
235
    }
236
237
    /**
238
     * @param int $rootPageId
239
     * @param array $rootPageRecord
240
     * @throws \InvalidArgumentException
241
     */
242 138
    protected function validateRootPageRecord($rootPageId, $rootPageRecord)
243
    {
244 138
        if (empty($rootPageRecord)) {
245 87
            throw new \InvalidArgumentException(
246 87
                'The rootPageRecord for the given rootPageRecord ID \'' . $rootPageId . '\' could not be found in the database and can therefore not be used as site root rootPageRecord.',
247 87
                1487326416
248
            );
249
        }
250
251 128
        if (!Site::isRootPage($rootPageRecord)) {
252 3
            throw new \InvalidArgumentException(
253 3
                'The rootPageRecord for the given rootPageRecord ID \'' . $rootPageId . '\' is not marked as root rootPageRecord and can therefore not be used as site root rootPageRecord.',
254 3
                1309272922
255
            );
256
        }
257 127
    }
258
259
    /**
260
     * @param array $rootPageRecord
261
     * @return Typo3ManagedSite
262
     */
263 127
    protected function buildTypo3ManagedSite(array $rootPageRecord): ?Typo3ManagedSite
264
    {
265 127
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($rootPageRecord['uid']);
266
        /** @var \TYPO3\CMS\Core\Site\Entity\Site $typo3Site */
267
        try {
268 127
            $typo3Site = $this->siteFinder->getSiteByPageId($rootPageRecord['uid']);
269
        } catch (SiteNotFoundException $e) {
270
            return null;
271
        }
272 127
        $domain = $typo3Site->getBase()->getHost();
273
274 127
        $siteHash = $this->getSiteHashForDomain($domain);
275 127
        $defaultLanguage = $typo3Site->getDefaultLanguage()->getLanguageId();
276 127
        $pageRepository = GeneralUtility::makeInstance(PagesRepository::class);
277
        $availableLanguageIds = array_map(function($language) {
278 127
            return $language->getLanguageId();
279 127
        }, $typo3Site->getLanguages());
280
281 127
        $solrConnectionConfigurations = [];
282
283 127
        foreach ($availableLanguageIds as $languageUid) {
284 127
            $solrEnabled = SiteUtility::getConnectionProperty($typo3Site, 'enabled', $languageUid, 'read', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type null|string expected by parameter $defaultValue of ApacheSolrForTypo3\Solr\...getConnectionProperty(). ( Ignorable by Annotation )

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

284
            $solrEnabled = SiteUtility::getConnectionProperty($typo3Site, 'enabled', $languageUid, 'read', /** @scrutinizer ignore-type */ true);
Loading history...
285 127
            if ($solrEnabled) {
286 127
                $solrConnectionConfigurations[$languageUid] = [
287 127
                    'connectionKey' =>  $rootPageRecord['uid'] . '|' . $languageUid,
288 127
                    'rootPageTitle' => $rootPageRecord['title'],
289 127
                    'rootPageUid' => $rootPageRecord['uid'],
290
                    'read' => [
291 127
                        'scheme' => SiteUtility::getConnectionProperty($typo3Site, 'scheme', $languageUid, 'read', 'http'),
292 127
                        'host' => SiteUtility::getConnectionProperty($typo3Site, 'host', $languageUid, 'read', 'localhost'),
293 127
                        'port' => (int)SiteUtility::getConnectionProperty($typo3Site, 'port', $languageUid, 'read', 8983),
294
                        // @todo: transform core to path
295
                        'path' =>
296 127
                            SiteUtility::getConnectionProperty($typo3Site, 'path', $languageUid, 'read', '/solr/') .
297 127
                            SiteUtility::getConnectionProperty($typo3Site, 'core', $languageUid, 'read', 'core_en') . '/' ,
298 127
                        'username' => SiteUtility::getConnectionProperty($typo3Site, 'username', $languageUid, 'read', ''),
299 127
                        'password' => SiteUtility::getConnectionProperty($typo3Site, 'password', $languageUid, 'read', '')
300
                    ],
301
                    'write' => [
302 127
                        'scheme' => SiteUtility::getConnectionProperty($typo3Site, 'scheme', $languageUid, 'write', 'http'),
303 127
                        'host' => SiteUtility::getConnectionProperty($typo3Site, 'host', $languageUid, 'write', 'localhost'),
304 127
                        'port' => (int)SiteUtility::getConnectionProperty($typo3Site, 'port', $languageUid, 'write', 8983),
305
                        // @todo: transform core to path
306
                        'path' =>
307 127
                            SiteUtility::getConnectionProperty($typo3Site, 'path', $languageUid, 'read', '/solr/') .
308 127
                            SiteUtility::getConnectionProperty($typo3Site, 'core', $languageUid, 'read', 'core_en') . '/' ,
309 127
                        'username' => SiteUtility::getConnectionProperty($typo3Site, 'username', $languageUid, 'write', ''),
310 127
                        'password' => SiteUtility::getConnectionProperty($typo3Site, 'password', $languageUid, 'write', '')
311
                    ],
312
313 127
                    'language' => $languageUid
314
                ];
315
            }
316
        }
317
318 127
        return GeneralUtility::makeInstance(
319 127
            Typo3ManagedSite::class,
320
            /** @scrutinizer ignore-type */
321 127
            $solrConfiguration,
322
            /** @scrutinizer ignore-type */
323 127
            $rootPageRecord,
324
            /** @scrutinizer ignore-type */
325 127
            $domain,
326
            /** @scrutinizer ignore-type */
327 127
            $siteHash,
328
            /** @scrutinizer ignore-type */
329 127
            $pageRepository,
330
            /** @scrutinizer ignore-type */
331 127
            $defaultLanguage,
332
            /** @scrutinizer ignore-type */
333 127
            $availableLanguageIds,
334
            /** @scrutinizer ignore-type */
335 127
            $solrConnectionConfigurations,
336
            /** @scrutinizer ignore-type */
337 127
            $typo3Site
338
        );
339
    }
340
341
}
342