Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Twig variable dump improvements #12486

Merged
merged 2 commits into from
Dec 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG-WIP.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
- Added the `editable` and `savable` asset query params. ([#12266](https://github.com/craftcms/cms/pull/12266))
- Added the `savable` entry query param. ([#12266](https://github.com/craftcms/cms/pull/12266))
- The `editable` entry query param can now be set to `false` to only show entries that _can’t_ be viewed by the current user. ([#12266](https://github.com/craftcms/cms/pull/12266))
- The `dump()` Twig function now utilizes `Craft::dump()`, and no longer requires Dev Mode to be active. ([#12486](https://github.com/craftcms/cms/pull/12486), [#12479](https://github.com/craftcms/cms/discussions/12479))
- The `{% dd %}` Twig tag can now output the entire `context` array, if no variable is passed to it. ([#12486](https://github.com/craftcms/cms/pull/12486))

### Extensibility
- Console controllers that directly use `craft\console\ControllerTrait` no longer need to call `$this->checkTty()` or `$this->checkRootUser()` themselves; they are now called from `ControllerTrait::init()` and `beforeAction()`.
Expand Down
16 changes: 16 additions & 0 deletions src/helpers/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Twig\Markup;
use Twig\Source;
use Twig\Template as TwigTemplate;
use Twig\TemplateWrapper;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\base\UnknownMethodException;
Expand Down Expand Up @@ -323,4 +324,19 @@ public static function resolveTemplatePathAndLine(string $path, ?int $line)

return [$templatePath, $templateLine];
}

/**
* Filters the template from a context array.
*
* Used by the `dump()` function and `dd` tags.
*
* @param array $context
* @return array
* @since 4.4.0
*/
public static function contextWithoutTemplate(array $context): array
{
// Template check copied from twig_var_dump()
return array_filter($context, fn($value) => !$value instanceof TwigTemplate && !$value instanceof TemplateWrapper);
}
}
5 changes: 0 additions & 5 deletions src/web/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
use Twig\Error\RuntimeError as TwigRuntimeError;
use Twig\Error\SyntaxError as TwigSyntaxError;
use Twig\Extension\CoreExtension;
use Twig\Extension\DebugExtension;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\StringLoaderExtension;
use Twig\Template as TwigTemplate;
Expand Down Expand Up @@ -357,10 +356,6 @@ public function createTwig(): Environment
$twig->addExtension(new GlobalsExtension());
}

if (App::devMode()) {
$twig->addExtension(new DebugExtension());
}

// Add plugin-supplied extensions
foreach ($this->_twigExtensions as $extension) {
$twig->addExtension($extension);
Expand Down
26 changes: 26 additions & 0 deletions src/web/twig/Extension.php
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,7 @@ public function getFunctions(): array
new TwigFunction('create', [Craft::class, 'createObject']),
new TwigFunction('dataUrl', [$this, 'dataUrlFunction']),
new TwigFunction('date', [$this, 'dateFunction'], ['needs_environment' => true]),
new TwigFunction('dump', [$this, 'dumpFunction'], ['is_safe' => ['html'], 'needs_context' => true, 'is_variadic' => true]),
new TwigFunction('expression', [$this, 'expressionFunction']),
new TwigFunction('floor', 'floor'),
new TwigFunction('getenv', [App::class, 'env']),
Expand Down Expand Up @@ -1357,6 +1358,31 @@ public function dateFunction(TwigEnvironment $env, mixed $date = null, mixed $ti
return twig_date_converter($env, $date, $timezone);
}

/**
* Displays a variable(s).
*
* @param array $context
* @param ...$vars
* @return string
* @since 4.4.0
*/
public function dumpFunction(array $context, ...$vars): string
{
if (!$vars) {
$vars = [TemplateHelper::contextWithoutTemplate($context)];
}

$output = '';

foreach ($vars as $var) {
ob_start();
Craft::dump($var);
$output .= str_replace('<code>', '<code style="display:block;">', ob_get_clean());
}

return $output;
}

/**
* @param mixed $expression
* @param array $params
Expand Down
13 changes: 10 additions & 3 deletions src/web/twig/nodes/DdNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
namespace craft\web\twig\nodes;

use Craft;
use craft\helpers\Template;
use Twig\Compiler;
use Twig\Node\Node;

Expand All @@ -27,8 +28,14 @@ public function compile(Compiler $compiler): void
$compiler->addDebugInfo($this);

$compiler
->write(Craft::class . '::dd(')
->subcompile($this->getNode('var'))
->raw(");\n");
->write(Craft::class . '::dd(');

if ($this->hasNode('var')) {
$compiler->subcompile($this->getNode('var'));
} else {
$compiler->raw(sprintf('%s::contextWithoutTemplate($context)', Template::class));
}

$compiler->raw(");\n");
}
}
8 changes: 5 additions & 3 deletions src/web/twig/tokenparsers/DdTokenParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ public function parse(Token $token): DdNode
$parser = $this->parser;
$stream = $parser->getStream();

$nodes = [
'var' => $parser->getExpressionParser()->parseExpression(),
];
$nodes = [];

if (!$stream->test(Token::BLOCK_END_TYPE)) {
$nodes['var'] = $parser->getExpressionParser()->parseExpression();
}

$stream->expect(Token::BLOCK_END_TYPE);

Expand Down