Passed
Pull Request — release-11.2.x (#3050)
by Markus
05:22
created

Tsfe::initializeTsfe()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 85
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 4.0001

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 49
c 4
b 0
f 0
dl 0
loc 85
ccs 47
cts 48
cp 0.9792
rs 9.1127
cc 4
nc 6
nop 2
crap 4.0001

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\FrontendEnvironment;
4
5
use TYPO3\CMS\Backend\Utility\BackendUtility;
6
use TYPO3\CMS\Core\Context\Context;
7
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
8
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
9
use TYPO3\CMS\Core\Context\TypoScriptAspect;
10
use TYPO3\CMS\Core\Context\UserAspect;
11
use TYPO3\CMS\Core\Context\VisibilityAspect;
12
use TYPO3\CMS\Core\Core\SystemEnvironmentBuilder;
13
use TYPO3\CMS\Core\Error\Http\InternalServerErrorException;
14
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
15
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
16
use TYPO3\CMS\Core\Http\ImmediateResponseException;
17
use TYPO3\CMS\Core\Http\ServerRequest;
18
use TYPO3\CMS\Core\Localization\Locales;
19
use TYPO3\CMS\Core\SingletonInterface;
20
use TYPO3\CMS\Core\Site\SiteFinder;
21
use TYPO3\CMS\Core\TypoScript\TemplateService;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
24
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
25
use TYPO3\CMS\Frontend\Page\PageRepository;
26
27
class Tsfe implements SingletonInterface
28
{
29
    private $tsfeCache = [];
30
31
    private $requestCache = [];
32
33
    /**
34
     * @param int $pageId
35
     * @param int $language
36
     * @throws AspectNotFoundException
37
     */
38 168
    public function changeLanguageContext(int $pageId, int $language): void
39
    {
40
        /* @var Context $context */
41 168
        $context = GeneralUtility::makeInstance(Context::class);
42 168
        if ($context->hasAspect('language')) {
43 168
            $hasRightLanguageId = $context->getPropertyFromAspect('language', 'id') === $language;
44 168
            $hasRightContentLanguageId = $context->getPropertyFromAspect('language', 'contentId')  === $language;
45 168
            if ($hasRightLanguageId && $hasRightContentLanguageId) {
46 168
                return;
47
            }
48
        }
49
50
        /* @var $siteFinder SiteFinder */
51 18
        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
52
        try {
53 18
            $site = $siteFinder->getSiteByPageId($pageId);
54 18
            $languageAspect = LanguageAspectFactory::createFromSiteLanguage($site->getLanguageById($language));
55 18
            $context->setAspect('language', $languageAspect);
56
        } catch (SiteNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
57
        }
58 18
    }
59
60
    /**
61
     * Initializes the TSFE for a given page ID and language.
62
     *
63
     * @param $pageId
64
     * @param int $language
65
     * @throws AspectNotFoundException
66
     * @throws ImmediateResponseException
67
     * @throws InternalServerErrorException
68
     * @throws ServiceUnavailableException
69
     * @throws SiteNotFoundException
70
     */
71 23
    public function initializeTsfe($pageId, $language = 0)
72
    {
73
74
        // resetting, a TSFE instance with data from a different page Id could be set already
75 23
        unset($GLOBALS['TSFE']);
76
77 23
        $cacheId = $pageId . '|' . $language;
78
79
        /** @var Context $context */
80 23
        $context = GeneralUtility::makeInstance(Context::class);
81 23
        $this->changeLanguageContext((int)$pageId, (int)$language);
82
83
        /* @var SiteFinder $siteFinder */
84 23
        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
85 23
        $site = $siteFinder->getSiteByPageId($pageId);
86 23
        $siteLanguage = $site->getLanguageById($language);
87
88 23
        if (!isset($this->requestCache[$cacheId])) {
89
            /* @var ServerRequest $request */
90 23
            $request = GeneralUtility::makeInstance(ServerRequest::class);
91 23
            $this->requestCache[$cacheId] = $request
92 23
                ->withAttribute('site', $site)
93 23
                ->withAttribute('language', $siteLanguage)
94 23
                ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE)
95 23
                ->withUri($site->getBase());
96
        }
97 23
        $GLOBALS['TYPO3_REQUEST'] = $this->requestCache[$cacheId];
98
99 23
        if (!isset($this->tsfeCache[$cacheId])) {
100
            // TYPO3 by default enables a preview mode if a backend user is logged in,
101
            // the VisibilityAspect is configured to show hidden elements.
102
            // Due to this setting hidden relations/translations might be indexed
103
            // when running the Solr indexer via the TYPO3 backend.
104
            // To avoid this, the VisibilityAspect is adapted for indexing.
105 23
            $context->setAspect(
106 23
                'visibility',
107 23
                GeneralUtility::makeInstance(
108
                    VisibilityAspect::class,
109
                    false,
110 23
                    false
111
                )
112
            );
113
114 23
            $feUser = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
115
116
            /* @var TypoScriptFrontendController $globalsTSFE */
117 23
            $globalsTSFE = GeneralUtility::makeInstance(TypoScriptFrontendController::class, $context, $site, $siteLanguage, null, $feUser);
118 23
            $GLOBALS['TSFE'] = $globalsTSFE;
119 23
            $GLOBALS['TSFE']->id = $pageId;
120 23
            $GLOBALS['TSFE']->type = 0;
121
122
            // for certain situations we need to trick TSFE into granting us
123
            // access to the page in any case to make getPageAndRootline() work
124
            // see http://forge.typo3.org/issues/42122
125 23
            $pageRecord = BackendUtility::getRecord('pages', $pageId, 'fe_group');
126
127 23
            $userGroups = [0, -1];
128 23
            if (!empty($pageRecord['fe_group'])) {
129
                $userGroups = array_unique(array_merge($userGroups, explode(',', $pageRecord['fe_group'])));
130
            }
131 23
            $context->setAspect('frontend.user', GeneralUtility::makeInstance(UserAspect::class, $feUser, $userGroups));
132
133
            // @extensionScannerIgnoreLine
134 23
            $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class);
135 23
            $GLOBALS['TSFE']->getPageAndRootlineWithDomain($pageId, $GLOBALS['TYPO3_REQUEST']);
136
137 23
            $template = GeneralUtility::makeInstance(TemplateService::class, $context);
138 23
            $GLOBALS['TSFE']->tmpl = $template;
139 23
            $context->setAspect('typoscript', GeneralUtility::makeInstance(TypoScriptAspect::class, true));
140 23
            $GLOBALS['TSFE']->no_cache = true;
141 23
            $GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
142 23
            $GLOBALS['TSFE']->no_cache = false;
143 23
            $GLOBALS['TSFE']->getConfigArray();
144 23
            $GLOBALS['TSFE']->settingLanguage();
145
146 22
            $GLOBALS['TSFE']->newCObj();
147 22
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
0 ignored issues
show
Bug Best Practice introduced by
The method ApacheSolrForTypo3\Solr\...tAbsRefPrefixFromTSFE() is not static, but was called statically. ( Ignorable by Annotation )

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

147
            /** @scrutinizer ignore-call */ 
148
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
Loading history...
148 22
            $GLOBALS['TSFE']->calculateLinkVars([]);
149
150 22
            $this->tsfeCache[$cacheId] = $GLOBALS['TSFE'];
151
        }
152
153 22
        $GLOBALS['TSFE'] = $this->tsfeCache[$cacheId];
154 22
        Locales::setSystemLocaleFromSiteLanguage($siteLanguage);
155 22
        $this->changeLanguageContext((int)$pageId, (int)$language);
156 22
    }
157
158
    /**
159
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
160
     * is set to "auto".
161
     */
162 22
    private function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE): string
163
    {
164 22
        $absRefPrefix = '';
165 22
        if (empty($TSFE->config['config']['absRefPrefix'])) {
166
            return $absRefPrefix;
167
        }
168
169 22
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
170 22
        if ($absRefPrefix === 'auto') {
171 22
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
172
        }
173
174 22
        return $absRefPrefix;
175
    }
176
}
177