Skip to content

Commit

Permalink
added support for magic constants __LINE__, __FILE__, __DIR__
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 27, 2023
1 parent 45cd10f commit fab3848
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/Latte/Compiler/Nodes/Php/Expression/ConstantFetchNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ public function __construct(

public function print(PrintContext $context): string
{
if ($this->name->kind === NameNode::KindNormal) {
return match ((string) $this->name) {
'__LINE__' => (string) $this->position->line,
'__FILE__' => '(is_file(self::Source) ? self::Source : null)',
'__DIR__' => '(is_file(self::Source) ? dirname(self::Source) : null)',
default => $this->name->print($context),
};
}
return $this->name->print($context);
}

Expand Down
28 changes: 28 additions & 0 deletions tests/phpPrint/magicConstants.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

// Magic constants

declare(strict_types=1);

use Tester\Assert;

require __DIR__ . '/../bootstrap.php';

$test = <<<'XX'
__FILE__,
__DIR__,
__LINE__,
XX;

$node = parseCode($test);
$code = printNode($node);

Assert::same(
loadContent(__FILE__, __COMPILER_HALT_OFFSET__),
$code,
);

__halt_compiler();
(is_file(self::Source) ? self::Source : null),
(is_file(self::Source) ? dirname(self::Source) : null),
3
4 changes: 2 additions & 2 deletions tests/phpPrint/reserved.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use Tester\Assert;
require __DIR__ . '/../bootstrap.php';

$test = <<<'XX'
__FILE__,
__FUNCTION__,
class,
class::$x,
class::interface,
Expand All @@ -27,7 +27,7 @@ Assert::same(
);

__halt_compiler();
namespace\__FILE__,
namespace\__FUNCTION__,
'class',
namespace\class::$x,
namespace\class::interface,
Expand Down

0 comments on commit fab3848

Please sign in to comment.