diff --git a/CHANGELOG b/CHANGELOG index 54178e6b3..c89e0ea79 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ # 3.3.9 (2022-XX-XX) * Fix custom escapers when using multiple Twig environments + * Add support for "constant('class', object)" # 3.3.8 (2022-02-04) diff --git a/doc/functions/constant.rst b/doc/functions/constant.rst index 660bf870c..1201def04 100644 --- a/doc/functions/constant.rst +++ b/doc/functions/constant.rst @@ -14,6 +14,12 @@ You can read constants from object instances as well: {{ constant('RSS', date) }} +Retrieve the fully qualified class name of an object: + +.. code-block:: twig + + {{ constant('class', date) }} + Use the ``defined`` test to check if a constant is defined: .. code-block:: twig diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index 88cd75458..b77985859 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -1359,6 +1359,10 @@ function twig_source(Environment $env, $name, $ignoreMissing = false) function twig_constant($constant, $object = null) { if (null !== $object) { + if ('class' === $constant) { + return \get_class($object); + } + $constant = \get_class($object).'::'.$constant; } @@ -1376,6 +1380,10 @@ function twig_constant($constant, $object = null) function twig_constant_is_defined($constant, $object = null) { if (null !== $object) { + if ('class' === $constant) { + return true; + } + $constant = \get_class($object).'::'.$constant; } diff --git a/tests/Fixtures/functions/constant.test b/tests/Fixtures/functions/constant.test index fd6dd0611..cbad8506e 100644 --- a/tests/Fixtures/functions/constant.test +++ b/tests/Fixtures/functions/constant.test @@ -3,8 +3,10 @@ --TEMPLATE-- {{ constant('DATE_W3C') == expect ? 'true' : 'false' }} {{ constant('ARRAY_AS_PROPS', object) }} +{{ constant('class', object) }} --DATA-- return ['expect' => DATE_W3C, 'object' => new \ArrayObject(['hi'])] --EXPECT-- true 2 +ArrayObject