BannerController::getBannersAction()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 8.3814
c 0
b 0
f 0
cc 6
nc 4
nop 6

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
namespace DERHANSEN\SfBanners\Controller;
3
4
/*
5
 * This file is part of the Extension "sf_banners" for TYPO3 CMS.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
use DERHANSEN\SfBanners\Domain\Model\BannerDemand;
12
use TYPO3\CMS\Core\Cache\CacheManager;
13
use TYPO3\CMS\Core\Context\Context;
14
use TYPO3\CMS\Core\Http\ImmediateResponseException;
15
use TYPO3\CMS\Core\Page\PageRenderer;
16
use TYPO3\CMS\Core\Utility\GeneralUtility;
17
use TYPO3\CMS\Core\Utility\MathUtility;
18
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
19
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
20
use TYPO3\CMS\Frontend\Controller\ErrorController;
21
22
/**
23
 * Banner Controller
24
 *
25
 * @author Torben Hansen <[email protected]>
26
 */
27
class BannerController extends ActionController
28
{
29
    /**
30
     * Banner Service
31
     *
32
     * @var \DERHANSEN\SfBanners\Service\BannerService
33
     */
34
    protected $bannerService;
35
36
    /**
37
     * bannerRepository
38
     *
39
     * @var \DERHANSEN\SfBanners\Domain\Repository\BannerRepository
40
     */
41
    protected $bannerRepository;
42
43
    /**
44
     * Hash Service
45
     *
46
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
47
     */
48
    protected $hashService;
49
50
    /**
51
     * The Cache
52
     *
53
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
54
     */
55
    protected $cacheInstance;
56
57
    /**
58
     * Initialize cache
59
     */
60
    public function initializeAction()
61
    {
62
        $this->initializeCache();
63
    }
64
65
    /**
66
     * Initialize cache instance to be ready to use
67
     *
68
     * @return void
69
     */
70
    protected function initializeCache()
71
    {
72
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
73
        $this->cacheInstance = $cacheManager->getCache('sfbanners_cache');
74
    }
75
76
    /**
77
     * @param \DERHANSEN\SfBanners\Domain\Repository\BannerRepository $bannerRepository
78
     */
79
    public function injectBannerRepository(\DERHANSEN\SfBanners\Domain\Repository\BannerRepository $bannerRepository)
80
    {
81
        $this->bannerRepository = $bannerRepository;
82
    }
83
84
    /**
85
     * @param \DERHANSEN\SfBanners\Service\BannerService $bannerService
86
     */
87
    public function injectBannerService(\DERHANSEN\SfBanners\Service\BannerService $bannerService)
88
    {
89
        $this->bannerService = $bannerService;
90
    }
91
92
    /**
93
     * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
94
     */
95
    public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
96
    {
97
        $this->hashService = $hashService;
98
    }
99
100
    /**
101
     * Click Action for a banner
102
     *
103
     * @param \DERHANSEN\SfBanners\Domain\Model\Banner $banner
104
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
105
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
106
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
107
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException
108
     */
109
    public function clickAction(\DERHANSEN\SfBanners\Domain\Model\Banner $banner = null)
110
    {
111
        if (is_null($banner)) {
112
            $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
113
                $GLOBALS['TYPO3_REQUEST'],
114
                'Banner not found.'
115
            );
116
            throw new ImmediateResponseException($response, 1549896549);
117
        }
118
        $banner->increaseClicks();
119
        $this->bannerRepository->update($banner);
120
        $this->redirectToURI($banner->getLinkUrl());
121
    }
122
123
    /**
124
     * Show action
125
     *
126
     * @return void
127
     */
128
    public function showAction()
129
    {
130
        $languageAspect = GeneralUtility::makeInstance(Context::class)->getAspect('language');
131
        $maxResults = $this->settings['maxResults'] !== '' ? (int)$this->settings['maxResults'] : 0;
132
        $uniqueid = strtolower(substr(base64_encode(sha1(microtime())), 0, 9));
133
        $stringToHash = $GLOBALS['TSFE']->id . $this->settings['category'] . $this->settings['startingPoint'] .
134
            $this->settings['displayMode'] . $maxResults;
135
        $hmac = $this->hashService->generateHmac($stringToHash);
136
137
        $arguments = [
138
            'L' => $languageAspect->getId(),
139
            'type' => $this->settings['ajaxPageTypeNum'],
140
            'tx_sfbanners_pi1[action]' => 'getBanners',
141
            'tx_sfbanners_pi1[controller]' => 'Banner',
142
            'tx_sfbanners_pi1[currentPageUid]' => $GLOBALS['TSFE']->id,
143
            'tx_sfbanners_pi1[hmac]' => $hmac,
144
        ];
145
146
        if ($this->settings['startingPoint'] !== '') {
147
            $arguments['tx_sfbanners_pi1[startingPoint]'] = $this->settings['startingPoint'];
148
        }
149
        if ($this->settings['category'] !== '') {
150
            $arguments['tx_sfbanners_pi1[categories]'] = $this->settings['category'];
151
        }
152
        if ($this->settings['displayMode'] !== '') {
153
            $arguments['tx_sfbanners_pi1[displayMode]'] = $this->settings['displayMode'];
154
        }
155
        if ($this->settings['maxResults'] !== '' &&
156
            MathUtility::canBeInterpretedAsInteger($this->settings['maxResults'])
157
        ) {
158
            $arguments['tx_sfbanners_pi1[maxResults]'] = (int)$this->settings['maxResults'];
159
        }
160
161
        $url = $this->controllerContext
162
            ->getUriBuilder()
163
            ->reset()
164
            ->setUseCacheHash(true)
0 ignored issues
show
Unused Code introduced by
The call to UriBuilder::setUseCacheHash() has too many arguments starting with true.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
165
            ->setTargetPageUid($GLOBALS['TSFE']->id)
166
            ->setArguments($arguments)
167
            ->buildFrontendUri();
168
169
        $this->view->assign('url', $url);
170
        $this->view->assign('uniqueid', $uniqueid);
171
172
        /* Find all banners and add additional CSS */
173
        $banners = $this->bannerRepository->findAll();
174
        $cssFile = $this->bannerService->getAdditionalCssFile($banners);
0 ignored issues
show
Bug introduced by
It seems like $banners defined by $this->bannerRepository->findAll() on line 173 can also be of type object<TYPO3\CMS\Extbase...e\QueryResultInterface>; however, DERHANSEN\SfBanners\Serv...:getAdditionalCssFile() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
175
176
        if ($cssFile != '') {
177
            /** @var PageRenderer $pageRenderer */
178
            $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
179
            $pageRenderer->addCssFile($cssFile, 'stylesheet', 'all', '', true);
180
        }
181
    }
182
183
    /**
184
     * Returns banners for the given parameters if given Hmac validation succeeds
185
     *
186
     * @param string $categories
187
     * @param string $startingPoint
188
     * @param string $displayMode
189
     * @param int $currentPageUid
190
     * @param int $maxResults
191
     * @param string $hmac
192
     * @return string
193
     */
194
    public function getBannersAction(
195
        $categories = '',
196
        $startingPoint = '',
197
        $displayMode = 'all',
198
        $currentPageUid = 0,
199
        $maxResults = 0,
200
        $hmac = ''
201
    ) {
202
        $compareString = $currentPageUid . $categories . $startingPoint . $displayMode . $maxResults;
203
204
        if ($this->hashService->validateHmac($compareString, $hmac)) {
205
            /** @var \DERHANSEN\SfBanners\Domain\Model\BannerDemand $demand */
206
            $demand = $this->objectManager->get(BannerDemand::class);
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated with message: since TYPO3 10.4, will be removed in version 12.0

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

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

Loading history...
207
            $demand->setCategories($categories);
208
            $demand->setStartingPoint($startingPoint);
209
            $demand->setDisplayMode($displayMode);
210
            $demand->setCurrentPageUid($currentPageUid);
211
            $demand->setMaxResults($maxResults);
212
213
            /* Get banners */
214
            $banners = $this->bannerRepository->findDemanded($demand);
215
216
            /* If no banners available, return empty string */
217
            if (count($banners) === 0) {
218
                return '';
219
            }
220
221
            /* Update Impressions */
222
            $this->bannerRepository->updateImpressions($banners);
0 ignored issues
show
Bug introduced by
It seems like $banners defined by $this->bannerRepository->findDemanded($demand) on line 214 can also be of type object<TYPO3\CMS\Extbase...e\QueryResultInterface>; however, DERHANSEN\SfBanners\Doma...ry::updateImpressions() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
223
224
            /* Collect identifier based on uids for all banners */
225
            $languageAspect = GeneralUtility::makeInstance(Context::class)->getAspect('language');
226
            $ident = $GLOBALS['TSFE']->id . $languageAspect->getId();
227
            foreach ($banners as $banner) {
228
                $ident .= $banner->getUid();
229
            }
230
231
            $ret = $this->cacheInstance->get(sha1($ident));
232
            if ($ret === false || $ret === null) {
233
                $this->view->assign('banners', $banners);
234
                $this->view->assign('settings', $this->settings);
235
                $ret = $this->view->render();
236
237
                // Save value in cache
238
                $this->cacheInstance->set(sha1($ident), $ret, ['sf_banners'], $this->settings['cacheLifetime']);
239
            }
240
        } else {
241
            $ret = LocalizationUtility::translate('wrong_hmac', 'SfBanners');
242
        }
243
244
        $this->response->setHeader('X-Robots-Tag', 'noindex, nofollow');
245
246
        return $ret;
247
    }
248
}
249