Skip to content

Commit

Permalink
Replace $GLOBALS['objPage'] in the non-legacy code
Browse files Browse the repository at this point in the history
  • Loading branch information
leofeyer committed Mar 12, 2024
1 parent d23230e commit 17c08b1
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 117 deletions.
2 changes: 2 additions & 0 deletions core-bundle/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ services:
class: Contao\CoreBundle\DataCollector\ContaoDataCollector
arguments:
- '@contao.security.token_checker'
- '@contao.routing.page_finder'
tags:
- { name: data_collector, template: '@ContaoCore/Collector/contao.html.twig', id: contao }

Expand Down Expand Up @@ -448,6 +449,7 @@ services:
class: Contao\CoreBundle\InsertTag\Resolver\DateInsertTag
arguments:
- '@contao.framework'
- '@contao.routing.page_finder'

contao.insert_tag.resolver.form:
class: Contao\CoreBundle\InsertTag\Resolver\FormInsertTag
Expand Down
20 changes: 11 additions & 9 deletions core-bundle/src/DataCollector/ContaoDataCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Contao\CoreBundle\ContaoCoreBundle;
use Contao\CoreBundle\Framework\FrameworkAwareInterface;
use Contao\CoreBundle\Framework\FrameworkAwareTrait;
use Contao\CoreBundle\Routing\PageFinder;
use Contao\CoreBundle\Security\Authentication\Token\TokenChecker;
use Contao\LayoutModel;
use Contao\Model\Registry;
Expand All @@ -31,8 +32,10 @@ class ContaoDataCollector extends DataCollector implements FrameworkAwareInterfa
{
use FrameworkAwareTrait;

public function __construct(private readonly TokenChecker $tokenChecker)
{
public function __construct(
private readonly TokenChecker $tokenChecker,
private readonly PageFinder $pageFinder,
) {
}

public function collect(Request $request, Response $response, \Throwable|null $exception = null): void
Expand Down Expand Up @@ -143,11 +146,13 @@ private function addSummaryData(): void
$modelCount = Registry::getInstance()->count();
}

$pageModel = $this->pageFinder->getCurrentPage();

$this->data['summary'] = [
'version' => $this->getContaoVersion(),
'framework' => $framework,
'models' => $modelCount,
'frontend' => isset($GLOBALS['objPage']),
'frontend' => $pageModel instanceof PageModel,
'preview' => $this->tokenChecker->isPreviewMode(),
'layout' => $this->getLayoutName(),
'template' => $this->getTemplateName(),
Expand All @@ -174,17 +179,14 @@ private function getTemplateName(): string

private function getLayout(): LayoutModel|null
{
if (!isset($GLOBALS['objPage'])) {
if (!$pageModel = $this->pageFinder->getCurrentPage()) {
return null;
}

/** @var PageModel $objPage */
$objPage = $GLOBALS['objPage'];

if (!$objPage->layoutId) {
if (!$pageModel->layoutId) {
return null;
}

return $this->framework->getAdapter(LayoutModel::class)->findById($objPage->layoutId);
return $this->framework->getAdapter(LayoutModel::class)->findById($pageModel->layoutId);
}
}
11 changes: 0 additions & 11 deletions core-bundle/src/EventListener/PageAccessListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,6 @@ private function getPageModel(Request $request): PageModel|null

$pageModel = $request->attributes->get('pageModel');

if (
isset($GLOBALS['objPage'])
&& $GLOBALS['objPage'] instanceof PageModel
&& (
($pageModel instanceof PageModel && (int) $pageModel->id === $GLOBALS['objPage']->id)
|| (!$pageModel instanceof PageModel && $GLOBALS['objPage']->id === (int) $pageModel)
)
) {
return $GLOBALS['objPage'];
}

if ($pageModel instanceof PageModel) {
return $pageModel;
}
Expand Down
20 changes: 16 additions & 4 deletions core-bundle/src/InsertTag/InsertTagParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\Environment;
use Contao\InsertTags;
use Contao\PageModel;
use Contao\StringUtil;
use Contao\System;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -447,16 +448,27 @@ private function renderBlockSubscription(InsertTag $tag, ParsedSequence|null $co

private function getFragmentForTag(InsertTag $tag): InsertTagResult
{
$clientCache = 0;
$pageId = null;

$request = $this->requestStack->getCurrentRequest();
$pageModel = $request?->attributes->get('pageModel');

if ($pageModel instanceof PageModel) {
$clientCache = $pageModel->clientCache;
$pageId = $pageModel->id;
}

$attributes = ['insertTag' => $tag->serialize()];

if ($scope = $this->requestStack->getCurrentRequest()?->attributes->get('_scope')) {
if ($scope = $request?->attributes->get('_scope')) {
$attributes['_scope'] = $scope;
}

$query = [
'clientCache' => $GLOBALS['objPage']->clientCache ?? 0,
'pageId' => $GLOBALS['objPage']->id ?? null,
'request' => $this->requestStack->getCurrentRequest()?->getRequestUri(),
'clientCache' => $clientCache,
'pageId' => $pageId,
'request' => $request?->getRequestUri(),
];

$esiTag = $this->fragmentHandler->render(
Expand Down
12 changes: 8 additions & 4 deletions core-bundle/src/InsertTag/Resolver/DateInsertTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Contao\CoreBundle\InsertTag\InsertTagResult;
use Contao\CoreBundle\InsertTag\OutputType;
use Contao\CoreBundle\InsertTag\ResolvedInsertTag;
use Contao\CoreBundle\Routing\PageFinder;
use Contao\Date;

#[AsInsertTag('date', asFragment: true)]
Expand All @@ -28,22 +29,25 @@ class DateInsertTag implements InsertTagResolverNestedResolvedInterface
'Y' => ['Y', 'y'],
];

public function __construct(private readonly ContaoFramework $framework)
{
public function __construct(
private readonly ContaoFramework $framework,
private readonly PageFinder $pageFinder,
) {
}

public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult
{
$this->framework->initialize();

$date = $this->framework->getAdapter(Date::class);
$format = $insertTag->getParameters()->get(0) ?? $GLOBALS['objPage']->dateFormat ?? $GLOBALS['TL_CONFIG']['dateFormat'] ?? '';
$pageModel = $this->pageFinder->getCurrentPage();
$format = $insertTag->getParameters()->get(0) ?? $pageModel->dateFormat ?? $GLOBALS['TL_CONFIG']['dateFormat'] ?? '';
$result = new InsertTagResult($date->parse($format), OutputType::text);

// Add caching headers for supported formats
$result = $result->withExpiresAt($this->getExpireAtFromFormat($format));

if ($result->getExpiresAt() && ($rootId = $GLOBALS['objPage']->rootId ?? null)) {
if ($result->getExpiresAt() && ($rootId = $pageModel->rootId ?? null)) {
$result = $result->withCacheTags(["contao.db.tl_page.$rootId"]);
}

Expand Down
25 changes: 15 additions & 10 deletions core-bundle/src/InsertTag/Resolver/LegacyInsertTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,12 +239,14 @@ public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult
$opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$insertTag->getParameters()->get(0)]['options'] ?? null;
$rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$insertTag->getParameters()->get(0)]['reference'] ?? null;

$pageModel = $this->container->get('contao.routing.page_finder')->getCurrentPage();

if ('date' === $rgxp) {
$result = Date::parse($GLOBALS['objPage']->dateFormat ?? $GLOBALS['TL_CONFIG']['dateFormat'] ?? '', $value);
$result = Date::parse($pageModel->dateFormat ?? $GLOBALS['TL_CONFIG']['dateFormat'] ?? '', $value);
} elseif ('time' === $rgxp) {
$result = Date::parse($GLOBALS['objPage']->timeFormat ?? $GLOBALS['TL_CONFIG']['timeFormat'] ?? '', $value);
$result = Date::parse($pageModel->timeFormat ?? $GLOBALS['TL_CONFIG']['timeFormat'] ?? '', $value);
} elseif ('datim' === $rgxp) {
$result = Date::parse($GLOBALS['objPage']->datimFormat ?? $GLOBALS['TL_CONFIG']['datimFormat'] ?? '', $value);
$result = Date::parse($pageModel->datimFormat ?? $GLOBALS['TL_CONFIG']['datimFormat'] ?? '', $value);
} elseif (\is_array($value)) {
$result = implode(', ', $value);
} elseif (\is_array($opts) && ArrayUtil::isAssoc($opts)) {
Expand Down Expand Up @@ -356,7 +358,8 @@ public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult
$objUpdate = Database::getInstance()->query($strQuery);

if ($objUpdate->numRows) {
$result = Date::parse($insertTag->getParameters()->get(0) ?? ($GLOBALS['objPage']->datimFormat ?? $GLOBALS['TL_CONFIG']['datimFormat'] ?? ''), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
$pageModel = $this->container->get('contao.routing.page_finder')->getCurrentPage();
$result = Date::parse($insertTag->getParameters()->get(0) ?? ($pageModel->datimFormat ?? $GLOBALS['TL_CONFIG']['datimFormat'] ?? ''), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
}
break;

Expand Down Expand Up @@ -425,11 +428,12 @@ public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult
// Page
case 'page':
$property = $insertTag->getParameters()->get(0);
$pageModel = $this->container->get('contao.routing.page_finder')->getCurrentPage();

if ($GLOBALS['objPage']) {
if (!$GLOBALS['objPage']->parentPageTitle && 'parentPageTitle' === $property) {
if ($pageModel) {
if (!$pageModel->parentPageTitle && 'parentPageTitle' === $property) {
$property = 'parentTitle';
} elseif (!$GLOBALS['objPage']->mainPageTitle && 'mainPageTitle' === $property) {
} elseif (!$pageModel->mainPageTitle && 'mainPageTitle' === $property) {
$property = 'mainTitle';
}
}
Expand All @@ -443,13 +447,13 @@ public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult
'pageTitle' => htmlspecialchars($htmlHeadBag->getTitle()),
'description' => htmlspecialchars($htmlHeadBag->getMetaDescription()),
};
} elseif ($GLOBALS['objPage']) {
} elseif ($pageModel) {
// Do not use StringUtil::specialchars() here (see #4687)
if (!\in_array($property, ['title', 'parentTitle', 'mainTitle', 'rootTitle', 'pageTitle', 'parentPageTitle', 'mainPageTitle', 'rootPageTitle'], true)) {
$outputType = OutputType::text;
}

$result = $GLOBALS['objPage']->{$property};
$result = $pageModel->{$property};
}
break;

Expand Down Expand Up @@ -566,7 +570,8 @@ public function __invoke(ResolvedInsertTag $insertTag): InsertTagResult

// Use the alternative text from the image metadata if none is given
if (!$alt && ($objFile = FilesModel::findByPath($strFile))) {
$arrMeta = Frontend::getMetaData($objFile->meta, $GLOBALS['objPage']->language ?? $GLOBALS['TL_LANGUAGE']);
$pageModel = $this->container->get('contao.routing.page_finder')->getCurrentPage();
$arrMeta = Frontend::getMetaData($objFile->meta, $pageModel->language ?? $GLOBALS['TL_LANGUAGE']);

if (isset($arrMeta['alt'])) {
$alt = $arrMeta['alt'];
Expand Down
5 changes: 0 additions & 5 deletions core-bundle/tests/Contao/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,6 @@ public function testFigureFunctionUsesImageTemplateByDefault(): void
*/
public function testCompileReplacesLiteralInsertTags(string $buffer, string $expectedOutput): void
{
$page = new \stdClass();
$page->minifyMarkup = false;

$GLOBALS['objPage'] = $page;

$template = new class($buffer) extends FrontendTemplate {
public function __construct(private readonly string|null $testBuffer)
{
Expand Down
33 changes: 23 additions & 10 deletions core-bundle/tests/DataCollector/ContaoDataCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Contao\ContentText;
use Contao\CoreBundle\ContaoCoreBundle;
use Contao\CoreBundle\DataCollector\ContaoDataCollector;
use Contao\CoreBundle\Routing\PageFinder;
use Contao\CoreBundle\Security\Authentication\Token\TokenChecker;
use Contao\CoreBundle\Tests\TestCase;
use Contao\LayoutModel;
Expand Down Expand Up @@ -44,7 +45,7 @@ public function testCollectsDataInBackEnd(): void
'additional_data' => 'data',
];

$collector = new ContaoDataCollector($this->createMock(TokenChecker::class));
$collector = $this->getContaoDataCollector();
$collector->collect(new Request(), new Response());

$this->assertSame(['ContentText' => ContentText::class], $collector->getClassesAliased());
Expand Down Expand Up @@ -87,9 +88,13 @@ public function testCollectsDataInFrontEnd(): void
$page->id = 2;
$page->layoutId = 2;

$GLOBALS['objPage'] = $page;
$pageFinder = $this->createMock(PageFinder::class);
$pageFinder
->method('getCurrentPage')
->willReturn($page)
;

$collector = new ContaoDataCollector($this->createMock(TokenChecker::class));
$collector = $this->getContaoDataCollector(pageFinder: $pageFinder);
$collector->setFramework($framework);
$collector->collect(new Request(), new Response());

Expand All @@ -109,8 +114,6 @@ public function testCollectsDataInFrontEnd(): void
$collector->reset();

$this->assertSame([], $collector->getSummary());

unset($GLOBALS['objPage']);
}

public function testSetsTheFrontendPreviewFromTokenChecker(): void
Expand All @@ -127,7 +130,11 @@ public function testSetsTheFrontendPreviewFromTokenChecker(): void
$page->id = 2;
$page->layoutId = 2;

$GLOBALS['objPage'] = $page;
$pageFinder = $this->createMock(PageFinder::class);
$pageFinder
->method('getCurrentPage')
->willReturn($page)
;

$tokenChecker = $this->createMock(TokenChecker::class);
$tokenChecker
Expand All @@ -136,7 +143,7 @@ public function testSetsTheFrontendPreviewFromTokenChecker(): void
->willReturn(true)
;

$collector = new ContaoDataCollector($tokenChecker);
$collector = $this->getContaoDataCollector($tokenChecker, $pageFinder);
$collector->setFramework($framework);
$collector->collect(new Request(), new Response());

Expand All @@ -152,15 +159,21 @@ public function testSetsTheFrontendPreviewFromTokenChecker(): void
],
$collector->getSummary(),
);

unset($GLOBALS['objPage']);
}

public function testReturnsAnEmptyArrayIfTheKeyIsUnknown(): void
{
$collector = new ContaoDataCollector($this->createMock(TokenChecker::class));
$collector = $this->getContaoDataCollector();
$method = new \ReflectionMethod($collector, 'getData');

$this->assertSame([], $method->invokeArgs($collector, ['foo']));
}

private function getContaoDataCollector(TokenChecker|null $tokenChecker = null, PageFinder|null $pageFinder = null): ContaoDataCollector
{
return new ContaoDataCollector(
$tokenChecker ?? $this->createMock(TokenChecker::class),
$pageFinder ?? $this->createMock(PageFinder::class),
);
}
}

0 comments on commit 17c08b1

Please sign in to comment.