Passed
Pull Request — release-11.2.x (#3594)
by Markus
14:43 queued 10:47
created

SearchFormViewHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\ViewHelpers;
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\System\Url\UrlHelper;
19
use ApacheSolrForTypo3\Solr\System\Util\SiteUtility;
20
use ApacheSolrForTypo3\Solr\Util;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
23
24
/**
25
 * Class SearchFormViewHelper
26
 *
27
 * @author Frans Saris <[email protected]>
28
 * @author Timo Hund <[email protected]>
29
 */
30
class SearchFormViewHelper extends AbstractSolrFrontendTagBasedViewHelper
31
{
32
33
    /**
34
     * @var string
35
     */
36
    protected $tagName = 'form';
37
38
    /**
39
     * @var TypoScriptFrontendController
40
     */
41
    protected $frontendController;
42
43
    /**
44
     * @var bool
45
     */
46
    protected $escapeChildren = true;
47
48
    /**
49
     * @var bool
50
     */
51
    protected $escapeOutput = false;
52
53
    /**
54
     * Constructor
55
     */
56 3
    public function __construct()
57
    {
58 3
        parent::__construct();
59 3
        $this->frontendController = $GLOBALS['TSFE'];
60 3
    }
61
62
    /**
63
     * Initialize arguments.
64
     */
65
    public function initializeArguments()
66
    {
67
        parent::initializeArguments();
68
        $this->registerTagAttribute('enctype', 'string', 'MIME type with which the form is submitted');
69
        $this->registerTagAttribute('method', 'string', 'Transfer type (GET or POST)', false, 'get');
70
        $this->registerTagAttribute('name', 'string', 'Name of form');
71
        $this->registerTagAttribute('onreset', 'string', 'JavaScript: On reset of the form');
72
        $this->registerTagAttribute('onsubmit', 'string', 'JavaScript: On submit of the form');
73
        $this->registerUniversalTagAttributes();
74
75
        $this->registerArgument('pageUid', 'integer', 'When not set current page is used', false);
76
        $this->registerArgument('additionalFilters', 'array', 'Additional filters', false);
77
        $this->registerArgument('additionalParams', 'array', 'Query parameters to be attached to the resulting URI', false, []);
78
        $this->registerArgument('pageType', 'integer', 'Type of the target page. See typolink.parameter', false, 0);
79
80
        $this->registerArgument('noCache', 'boolean', 'Set this to disable caching for the target page. You should not need this.', false, false);
81
        $this->registerArgument('noCacheHash', 'boolean', 'Set this to supress the cHash query parameter created by TypoLink. You should not need this.', false, false);
82
        $this->registerArgument('section', 'string', 'The anchor to be added to the action URI (only active if $actionUri is not set)', false, '');
83
        $this->registerArgument('absolute', 'boolean', 'If set, the URI of the rendered link is absolute', false, false);
84
        $this->registerArgument('addQueryString', 'boolean', 'If set, the current query parameters will be kept in the URI', false, false);
85
        $this->registerArgument('argumentsToBeExcludedFromQueryString', 'array', 'arguments to be removed from the URI. Only active if $addQueryString = TRUE', false, []);
86
        $this->registerArgument('addQueryStringMethod', 'string', 'Set which parameters will be kept. Only active if $addQueryString = TRUE', false);
87
        $this->registerArgument('addSuggestUrl', 'boolean', 'Indicates if suggestUrl should be rendered or not', false, true);
88
        $this->registerArgument('suggestHeader', 'string', 'The header for the top results', false, 'Top Results');
89
        $this->registerArgument('suggestPageType', 'integer', 'The page type that should be used for the suggest', false, 7384);
90
    }
91
92
    /**
93
     * Render search form tag
94
     *
95
     * @return string
96
     */
97
    public function render()
98
    {
99
        $pageUid = $this->arguments['pageUid'];
100 3
        if ($pageUid === null && !empty($this->getTypoScriptConfiguration()->getSearchTargetPage())) {
101
            $pageUid = $this->getTypoScriptConfiguration()->getSearchTargetPage();
102 3
        }
103 3
104 1
        $uri = $this->buildUriFromPageUidAndArguments($pageUid);
105
106
        $this->tag->addAttribute('action', trim($uri));
107 3
        if ($this->arguments['addSuggestUrl']) {
108
            $this->tag->addAttribute('data-suggest', $this->getSuggestUrl($this->arguments['additionalFilters'], $pageUid));
109 3
        }
110 3
        $this->tag->addAttribute('data-suggest-header', htmlspecialchars($this->arguments['suggestHeader']));
111
        $this->tag->addAttribute('accept-charset', $this->frontendController->metaCharset);
112
113 3
        // Get search term
114 3
        // @extensionScannerIgnoreLine
115
        $this->getTemplateVariableContainer()->add('q', $this->getQueryString());
116
        // @extensionScannerIgnoreLine
117
        $this->getTemplateVariableContainer()->add('pageUid', $pageUid);
118 3
        // @extensionScannerIgnoreLine
119
        $this->getTemplateVariableContainer()->add('languageUid', Util::getLanguageUid());
120 3
        // @extensionScannerIgnoreLine
121
        $this->getTemplateVariableContainer()->add('existingParameters', $this->getExistingSearchParameters());
122 3
        // @extensionScannerIgnoreLine
123
        $this->getTemplateVariableContainer()->add('addPageAndLanguageId', !$this->getIsSiteManagedSite($pageUid));
124 3
        $formContent = $this->renderChildren();
125
        // @extensionScannerIgnoreLine
126 3
        $this->getTemplateVariableContainer()->remove('addPageAndLanguageId');
127 3
        // @extensionScannerIgnoreLine
128
        $this->getTemplateVariableContainer()->remove('q');
129 3
        // @extensionScannerIgnoreLine
130
        $this->getTemplateVariableContainer()->remove('pageUid');
131 3
        // @extensionScannerIgnoreLine
132
        $this->getTemplateVariableContainer()->remove('languageUid');
133 3
        // @extensionScannerIgnoreLine
134
        $this->getTemplateVariableContainer()->remove('existingParameters');
135 3
136
        $this->tag->setContent($formContent);
137 3
138
        return $this->tag->render();
139 3
    }
140
141 3
    /**
142
     * Get the existing search parameters in an array
143
     * Returns an empty array if search.keepExistingParametersForNewSearches is not set
144
     *
145
     * @return array
146
     */
147
    protected function getExistingSearchParameters()
148
    {
149
        $searchParameters = [];
150 3
        if ($this->getTypoScriptConfiguration()->getSearchKeepExistingParametersForNewSearches()) {
151
            $arguments = GeneralUtility::_GPmerged($this->getTypoScriptConfiguration()->getSearchPluginNamespace());
152 3
            unset($arguments['q'], $arguments['id'], $arguments['L']);
153 3
            $searchParameters = $this->translateSearchParametersToInputTagAttributes($arguments);
154
        }
155
        return $searchParameters;
156
    }
157
158 3
    /**
159
     * Translate the multi-dimensional array of existing arguments into a flat array of name-value pairs for the input tags
160
     *
161
     * @param $arguments
162
     * @param string $nameAttributePrefix
163
     * @return array
164
     */
165
    protected function translateSearchParametersToInputTagAttributes($arguments, $nameAttributePrefix = '')
166
    {
167
        $attributes = [];
168
        foreach ($arguments as $key => $value) {
169
            $name = $nameAttributePrefix . '[' . $key . ']';
170
            if (is_array($value)) {
171
                $attributes = array_merge(
172
                    $attributes,
173
                    $this->translateSearchParametersToInputTagAttributes($value, $name)
174
                );
175
            } else {
176
                $attributes[$name] = $value;
177
            }
178
        }
179
        return $attributes;
180
    }
181
182
    /**
183
     * When a site is managed with site management the language and the id are encoded in the path segment of the url.
184
     * When no speaking urls are active (e.g. with TYPO3 8 and no realurl) this information is passed as query parameter
185
     * and would get lost when it is only part of the query arguments in the action parameter of the form.
186
     *
187
     * @return bool
188
     */
189
    protected function getIsSiteManagedSite($pageId)
190
    {
191
        return SiteUtility::getIsSiteManagedSite($pageId);
192
    }
193
194
    /**
195
     * @return \TYPO3Fluid\Fluid\Core\Variables\VariableProviderInterface
196
     */
197
    protected function getTemplateVariableContainer()
198
    {
199
        return $this->templateVariableContainer;
200
    }
201
202
    /**
203
     * @return string
204
     */
205
    protected function getQueryString()
206
    {
207
        $resultSet = $this->getSearchResultSet();
208 3
        if ($resultSet === null) {
209
            return '';
210 3
        }
211 3
        return trim($this->getSearchResultSet()->getUsedSearchRequest()->getRawUserQuery());
212 3
    }
213
214
    /**
215
     * @param array|null $additionalFilters
216
     * @param int $pageUid
217
     * @return string
218
     */
219
    protected function getSuggestUrl($additionalFilters, $pageUid)
220
    {
221
        $uriBuilder = $this->getControllerContext()->getUriBuilder();
222
        $pluginNamespace = $this->getTypoScriptConfiguration()->getSearchPluginNamespace();
223
        $suggestUrl = $uriBuilder->reset()->setTargetPageUid($pageUid)->setTargetPageType($this->arguments['suggestPageType'])->setUseCacheHash(false)->setArguments([$pluginNamespace => ['additionalFilters' => $additionalFilters]])->build();
0 ignored issues
show
Unused Code introduced by
The call to TYPO3\CMS\Extbase\Mvc\We...lder::setUseCacheHash() has too many arguments starting with false. ( Ignorable by Annotation )

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

223
        $suggestUrl = $uriBuilder->reset()->setTargetPageUid($pageUid)->setTargetPageType($this->arguments['suggestPageType'])->/** @scrutinizer ignore-call */ setUseCacheHash(false)->setArguments([$pluginNamespace => ['additionalFilters' => $additionalFilters]])->build();

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
224
225
        /* @var UrlHelper $urlService */
226
        $urlService = GeneralUtility::makeInstance(UrlHelper::class, $suggestUrl);
227
        $suggestUrl = $urlService->removeQueryParameter('cHash')->getUrl();
0 ignored issues
show
Deprecated Code introduced by
The function ApacheSolrForTypo3\Solr\...:removeQueryParameter() has been deprecated: Will be removed with v12. Use withoutQueryParameter instead. ( Ignorable by Annotation )

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

227
        $suggestUrl = /** @scrutinizer ignore-deprecated */ $urlService->removeQueryParameter('cHash')->getUrl();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
Deprecated Code introduced by
The function ApacheSolrForTypo3\Solr\...Url\UrlHelper::getUrl() has been deprecated: Will be removed with v12. Use __toString() instead. ( Ignorable by Annotation )

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

227
        $suggestUrl = /** @scrutinizer ignore-deprecated */ $urlService->removeQueryParameter('cHash')->getUrl();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
228
229
        return $suggestUrl;
230
    }
231
232
    /**
233
     * @param int|null $pageUid
234
     * @return string
235
     */
236
    protected function buildUriFromPageUidAndArguments($pageUid): string
237
    {
238
        $uriBuilder = $this->getControllerContext()->getUriBuilder();
239 3
        $uri = $uriBuilder
240
            ->reset()
241 3
            ->setTargetPageUid($pageUid)
0 ignored issues
show
Bug introduced by
It seems like $pageUid can also be of type null; however, parameter $targetPageUid of TYPO3\CMS\Extbase\Mvc\We...der::setTargetPageUid() does only seem to accept integer, 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

241
            ->setTargetPageUid(/** @scrutinizer ignore-type */ $pageUid)
Loading history...
242
            ->setTargetPageType($this->arguments['pageType'] ?? 0)
243 3
            ->setNoCache($this->arguments['noCache'] ?? false)
244 3
            ->setUseCacheHash(!$this->arguments['noCacheHash'])
0 ignored issues
show
Unused Code introduced by
The call to TYPO3\CMS\Extbase\Mvc\We...lder::setUseCacheHash() has too many arguments starting with ! $this->arguments['noCacheHash']. ( Ignorable by Annotation )

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

244
            ->/** @scrutinizer ignore-call */ setUseCacheHash(!$this->arguments['noCacheHash'])

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
245 3
            ->setArguments($this->arguments['additionalParams'] ?? [])
246 3
            ->setCreateAbsoluteUri($this->arguments['absolute'] ?? false)
247 3
            ->setAddQueryString($this->arguments['addQueryString'] ?? false)
248 3
            ->setArgumentsToBeExcludedFromQueryString($this->arguments['argumentsToBeExcludedFromQueryString'] ?? [])
249 3
            ->setAddQueryStringMethod($this->arguments['addQueryStringMethod'] ?? '')
250 3
            ->setSection($this->arguments['section'] ?? '')
251 3
            ->build();
252 3
        return $uri;
253 3
    }
254
}
255