Skip to content

Commit

Permalink
Merge pull request #393 from andersundsehr/phpstan
Browse files Browse the repository at this point in the history
✨ phpstan level 2
  • Loading branch information
lochmueller authored Jul 18, 2023
2 parents df3ff42 + 78e7af4 commit 3844cbc
Show file tree
Hide file tree
Showing 16 changed files with 80 additions and 105 deletions.
2 changes: 1 addition & 1 deletion Classes/Cache/Listener/ForceStaticCacheListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function __invoke(CacheRuleEvent $event): void
}

// render the plugins in the output
$GLOBALS['TSFE']->INTincScript();
$GLOBALS['TSFE']->INTincScript($event->getRequest());
}
}
}
Expand Down
9 changes: 7 additions & 2 deletions Classes/Cache/Rule/LoginDeniedConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

/**
* LoginDeniedConfiguration.
* @deprecated can be removed if TYPO3 11 is not supported anymore.
*/
class LoginDeniedConfiguration extends AbstractRule
{
Expand All @@ -21,9 +22,13 @@ public function checkRule(ServerRequestInterface $request, array &$explanation,
if (!($tsfe instanceof TypoScriptFrontendController)) {
return;
}
// @deprecated method was removed with TYPO3 12
if(!method_exists($tsfe, 'checkIfLoginAllowedInBranch')){
return;
}
$name = 'sendCacheHeaders_onlyWhenLoginDeniedInBranch';
$loginDeniedCfg = (!($tsfe->config['config'][$name] ?? false) || !$tsfe->checkIfLoginAllowedInBranch());
if (!$loginDeniedCfg) {
$configActive = $tsfe->config['config'][$name] ?? false;
if ($configActive && $tsfe->checkIfLoginAllowedInBranch()) {
$explanation[__CLASS__] = 'LoginDeniedCfg is true';
}
}
Expand Down
2 changes: 2 additions & 0 deletions Classes/Cache/UriFrontend.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SFC\Staticfilecache\Cache;

use TYPO3\CMS\Core\Cache\Backend\TaggableBackendInterface;
use TYPO3\CMS\Core\Cache\Backend\TransientBackendInterface;
use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
use TYPO3\CMS\Core\Utility\GeneralUtility;
Expand Down Expand Up @@ -47,6 +48,7 @@ public function getByTag($tag)
if (!$this->isValidTag($tag)) {
throw new \InvalidArgumentException('"'.$tag.'" is not a valid tag for a cache entry.', 1233058312);
}
assert($this->backend instanceof TaggableBackendInterface);
$entries = [];
$identifiers = $this->backend->findIdentifiersByTag($tag);
foreach ($identifiers as $identifier) {
Expand Down
6 changes: 3 additions & 3 deletions Classes/Command/AbstractCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ abstract class AbstractCommand extends Command
*
* @param string $description
*
* @return Command
* @return $this
*/
public function setDescription($description): static
public function setDescription(string $description): static
{
return parent::setDescription('StaticFileCache task: '.$description);
return parent::setDescription('StaticFileCache task: ' . $description);
}
}
10 changes: 5 additions & 5 deletions Classes/Command/BoostQueueCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
protected function cleanupQueue(SymfonyStyle $io): void
{
$rows = $this->queueRepository->findOld();
$io->progressStart(\count($rows));
foreach ($rows as $row) {
$this->queueRepository->delete(['uid' => $row['uid']]);
$uids = $this->queueRepository->findOldUids();
$io->progressStart(\count($uids));
foreach ($uids as $uid) {
$this->queueRepository->delete(['uid' => $uid]);
$io->progressAdvance();
}
$io->progressFinish();

$io->success(\count($rows).' items are removed.');
$io->success(\count($uids).' items are removed.');
}
}
2 changes: 0 additions & 2 deletions Classes/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
use SFC\Staticfilecache\Service\ObjectFactoryService;
use TYPO3\CMS\Core\Cache\Backend\NullBackend;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Imaging\IconRegistry;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\ExtensionUtility;

Expand Down Expand Up @@ -112,7 +111,6 @@ protected function registerBackendModule(): self
*/
protected function registerHooks(): self
{
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'][self::EXTENSION_KEY] = LogoffFrontendUser::class.'->logoff';
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = DatamapHook::class;

return $this;
Expand Down
2 changes: 1 addition & 1 deletion Classes/Controller/BackendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function boostAction(bool $run = false): ResponseInterface
$this->view->assignMultiple([
'enable' => (bool) $configurationService->get('boostMode'),
'open' => \count($queueRepository->findOpen(99999999)),
'old' => \count($queueRepository->findOld()),
'old' => \count($queueRepository->findOldUids()),
]);

$moduleTemplate->setContent($this->view->render());
Expand Down
20 changes: 4 additions & 16 deletions Classes/Domain/Repository/CacheRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,16 @@ class CacheRepository extends AbstractRepository
public function findExpiredIdentifiers(): array
{
$queryBuilder = $this->createQuery();
$rows = $queryBuilder->select('identifier')
$cacheIdentifiers = $queryBuilder->select('identifier')
->from($this->getTableName())
->where($queryBuilder->expr()->lt(
'expires',
$queryBuilder->createNamedParameter((new DateTimeService())->getCurrentTime(), \PDO::PARAM_INT)
))
->groupBy('identifier')
->executeQuery()
->fetchAll()
->fetchFirstColumn()
;

$cacheIdentifiers = [];
foreach ($rows as $row) {
$cacheIdentifiers[] = $row['identifier'];
}

return $cacheIdentifiers;
}

Expand All @@ -44,18 +38,12 @@ public function findExpiredIdentifiers(): array
public function findAllIdentifiers(): array
{
$queryBuilder = $this->createQuery();
$rows = $queryBuilder->select('identifier')
$cacheIdentifiers = $queryBuilder->select('identifier')
->from($this->getTableName())
->groupBy('identifier')
->executeQuery()
->fetchAll()
->fetchFirstColumn()
;

$cacheIdentifiers = [];
foreach ($rows as $row) {
$cacheIdentifiers[] = $row['identifier'];
}

return $cacheIdentifiers;
}

Expand Down
2 changes: 1 addition & 1 deletion Classes/Domain/Repository/PageRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function findForBackend($pageId, $displayMode): array
->from('pages')
->orWhere(...$where)
->executeQuery()
->fetchAll()
->fetchAllAssociative()
;
}

Expand Down
9 changes: 5 additions & 4 deletions Classes/Domain/Repository/QueueRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function findOpen($limit = 999): array
->setMaxResults($limit)
->orderBy('cache_priority', 'desc')
->executeQuery()
->fetchAll()
->fetchAllAssociative()
;
}

Expand All @@ -51,16 +51,17 @@ public function countOpenByIdentifier($identifier): int

/**
* Find old entries.
* @return list<int>
*/
public function findOld(): array
public function findOldUids(): array
{
$queryBuilder = $this->createQuery();

return (array) $queryBuilder->select('uid')
return $queryBuilder->select('uid')
->from($this->getTableName())
->where($queryBuilder->expr()->gt('call_date', 0))
->executeQuery()
->fetchAll()
->fetchFirstColumn()
;
}

Expand Down
47 changes: 0 additions & 47 deletions Classes/Hook/LogoffFrontendUser.php

This file was deleted.

57 changes: 39 additions & 18 deletions Classes/Middleware/FrontendUserMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,60 @@
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SFC\Staticfilecache\Service\CookieService;
use SFC\Staticfilecache\Service\DateTimeService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;

/**
* Init frontend user.
*/
class FrontendUserMiddleware implements MiddlewareInterface
{
public function __construct(private CookieService $cookieService)
{
}

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
/** @var FrontendUserAuthentication $feUser */
$feUser = $request->getAttribute('frontend.user');
assert($feUser instanceof FrontendUserAuthentication);

$response = $handler->handle($request);

if ($feUser->dontSetCookie) {
// do not set any cookie
return $response;
}
$weShouldHaveCookie = $this->weShouldHaveCookie($feUser, $request);
$lifetime = (int)($GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] ?? 0);

$started = $feUser->loginSessionStarted;

$cookieService = GeneralUtility::makeInstance(CookieService::class);
if (($started || $feUser->forceSetCookie) && 0 === $feUser->lifetime) {
// If new session and the cookie is a sessioncookie, we need to set it only once!
// // isSetSessionCookie()
$cookieService->setCookie(0);
} elseif (($started || $cookieService->hasCookie()) && $feUser->lifetime > 0) {
// If it is NOT a session-cookie, we need to refresh it.
// isRefreshTimeBasedCookie()
$cookieService->setCookie((new DateTimeService())->getCurrentTime() + $feUser->lifetime);
if ($weShouldHaveCookie) {
if ($lifetime === CookieService::SESSION_LIFETIME) {
// only set session cookie once:
if (!$this->cookieService->hasCookie()) {
$this->cookieService->setCookie(CookieService::SESSION_LIFETIME);
}
} else {
// update lifetime cookie now:
$this->cookieService->setCookie($lifetime);
}
} elseif ($this->cookieService->hasCookie()) {
// remove cookie:
$this->cookieService->unsetCookie();
}

return $response;
}

protected function weShouldHaveCookie(FrontendUserAuthentication $feUser, ServerRequestInterface $request): bool
{
$setCookieHeader = $feUser->appendCookieToResponse(new HtmlResponse(''))->getHeaderLine('Set-Cookie');

if (strpos($setCookieHeader, 'Max-Age=0')) {
// the new cookie is to delete the old cookie:
return false;
}
if ($setCookieHeader) {
// a new cookie is set:
return true;
}

// there was a cookie:
return isset($request->getCookieParams()[FrontendUserAuthentication::getCookieName()]);
}
}
3 changes: 2 additions & 1 deletion Classes/Service/CacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SFC\Staticfilecache\Service;

use SFC\Staticfilecache\Cache\UriFrontend;
use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheGroupException;
use SFC\Staticfilecache\Domain\Repository\QueueRepository;
use TYPO3\CMS\Core\Cache\CacheManager;
Expand All @@ -22,7 +23,7 @@ class CacheService extends AbstractService
*
* @throws NoSuchCacheException
*/
public function get(): VariableFrontend
public function get(): UriFrontend
{
return $this->getManager()->getCache('staticfilecache');
}
Expand Down
11 changes: 9 additions & 2 deletions Classes/Service/CookieService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,39 @@

namespace SFC\Staticfilecache\Service;

use SFC\Staticfilecache\Service\DateTimeService;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
* Handle cookie related stuff.
*/
class CookieService extends AbstractService
{
public const SESSION_LIFETIME = 0;

/**
* The name of the cookie.
*/
public const FE_COOKIE_NAME = 'staticfilecache';

public function __construct(private DateTimeService $dateTimeService)
{
}

/**
* Set the Cookie.
*/
public function setCookie(int $lifetime): void
{
setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime, '/', $this->getCookieDomain(), GeneralUtility::getIndpEnv('TYPO3_SSL'));
setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime + $this->dateTimeService->getCurrentTime(), '/', $this->getCookieDomain(), GeneralUtility::getIndpEnv('TYPO3_SSL'));
}

/**
* Unset the Cookie.
*/
public function unsetCookie(): void
{
$this->setCookie(time() - 3600);
$this->setCookie( -3600);
}

public function hasCookie(): bool
Expand Down
1 change: 0 additions & 1 deletion Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,3 @@ services:
- name: event.listener
identifier: 'SfcCacheRuleNoBackendUserListener'
event: SFC\Staticfilecache\Event\CacheRuleEvent

2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ includes:
- .Build/vendor/andersundsehr/phpstan-git-files/extension.php

parameters:
level: 1
level: 2
reportUnmatchedIgnoredErrors: false

0 comments on commit 3844cbc

Please sign in to comment.