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

[5.5] Blade: Make @json directive safe for use in HTML #21574

Merged
merged 3 commits into from
Oct 7, 2017
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
15 changes: 12 additions & 3 deletions src/Illuminate/View/Compilers/Concerns/CompilesJson.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@

trait CompilesJson
{
/**
* Default encoding options.
*
* To make JSON safe for embedding into HTML, <, >, ', &, and " characters
* should be escaped.
*
* @var int
*/
private $safeEncodingOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;

/**
* Compile the JSON statement into valid PHP.
*
Expand All @@ -14,9 +24,8 @@ protected function compileJson($expression)
{
$parts = explode(',', $this->stripParentheses($expression));

$options = $parts[1] ?? 0;

$depth = $parts[2] ?? 512;
$options = trim($parts[1] ?? $this->safeEncodingOptions);
$depth = trim($parts[2] ?? 512);

return "<?php echo json_encode($parts[0], $options, $depth) ?>";
}
Expand Down
22 changes: 22 additions & 0 deletions tests/View/Blade/BladeJsonTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Illuminate\Tests\View\Blade;

class BladeJsonTest extends AbstractBladeTestCase
{
public function testStatementIsCompiledWithSafeDefaultEncodingOptions()
{
$string = 'var foo = @json($var);';
$expected = 'var foo = <?php echo json_encode($var, 15, 512) ?>;';

$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testEncodingOptionsCanBeOverwritten()
{
$string = 'var foo = @json($var, JSON_HEX_TAG);';
$expected = 'var foo = <?php echo json_encode($var, JSON_HEX_TAG, 512) ?>;';

$this->assertEquals($expected, $this->compiler->compileString($string));
}
}