Augmentation vers version 3.3.0

This commit is contained in:
Gauvain Boiché
2020-03-31 15:31:03 +02:00
parent d926806907
commit a1864c0414
2618 changed files with 406015 additions and 31377 deletions

View File

@@ -12,7 +12,6 @@
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Asset\Packages;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
@@ -24,16 +23,10 @@ use Twig\TwigFunction;
class AssetExtension extends AbstractExtension
{
private $packages;
private $foundationExtension;
/**
* Passing an HttpFoundationExtension instance as a second argument must not be relied on
* as it's only there to maintain BC with older Symfony version. It will be removed in 3.0.
*/
public function __construct(Packages $packages, HttpFoundationExtension $foundationExtension = null)
public function __construct(Packages $packages)
{
$this->packages = $packages;
$this->foundationExtension = $foundationExtension;
}
/**
@@ -41,11 +34,10 @@ class AssetExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('asset', array($this, 'getAssetUrl')),
new TwigFunction('asset_version', array($this, 'getAssetVersion')),
new TwigFunction('assets_version', array($this, 'getAssetsVersion'), array('deprecated' => true, 'alternative' => 'asset_version')),
);
return [
new TwigFunction('asset', [$this, 'getAssetUrl']),
new TwigFunction('asset_version', [$this, 'getAssetVersion']),
];
}
/**
@@ -59,20 +51,8 @@ class AssetExtension extends AbstractExtension
*
* @return string The public path of the asset
*/
public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
public function getAssetUrl($path, $packageName = null)
{
// BC layer to be removed in 3.0
if (2 < $count = \func_num_args()) {
@trigger_error('Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.', E_USER_DEPRECATED);
if (4 === $count) {
@trigger_error('Forcing a version with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
}
$args = \func_get_args();
return $this->getLegacyAssetUrl($path, $packageName, $args[2], isset($args[3]) ? $args[3] : null);
}
return $this->packages->getUrl($path, $packageName);
}
@@ -89,56 +69,6 @@ class AssetExtension extends AbstractExtension
return $this->packages->getVersion($path, $packageName);
}
public function getAssetsVersion($packageName = null)
{
@trigger_error('The Twig assets_version() function was deprecated in 2.7 and will be removed in 3.0. Please use asset_version() instead.', E_USER_DEPRECATED);
return $this->packages->getVersion('/', $packageName);
}
private function getLegacyAssetUrl($path, $packageName = null, $absolute = false, $version = null)
{
if ($version) {
$package = $this->packages->getPackage($packageName);
$v = new \ReflectionProperty('Symfony\Component\Asset\Package', 'versionStrategy');
$v->setAccessible(true);
$currentVersionStrategy = $v->getValue($package);
if (property_exists($currentVersionStrategy, 'format')) {
$f = new \ReflectionProperty($currentVersionStrategy, 'format');
$f->setAccessible(true);
$format = $f->getValue($currentVersionStrategy);
$v->setValue($package, new StaticVersionStrategy($version, $format));
} else {
$v->setValue($package, new StaticVersionStrategy($version));
}
}
try {
$url = $this->packages->getUrl($path, $packageName);
} catch (\Exception $e) {
if ($version) {
$v->setValue($package, $currentVersionStrategy);
}
throw $e;
}
if ($version) {
$v->setValue($package, $currentVersionStrategy);
}
if ($absolute) {
return $this->foundationExtension->generateAbsoluteUrl($url);
}
return $url;
}
/**
* Returns the name of the extension.
*

View File

@@ -11,6 +11,7 @@
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
@@ -26,9 +27,9 @@ class CodeExtension extends AbstractExtension
private $charset;
/**
* @param string $fileLinkFormat The format for links to source files
* @param string $rootDir The project root directory
* @param string $charset The charset
* @param string|FileLinkFormatter $fileLinkFormat The format for links to source files
* @param string $rootDir The project root directory
* @param string $charset The charset
*/
public function __construct($fileLinkFormat, $rootDir, $charset)
{
@@ -42,16 +43,17 @@ class CodeExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('abbr_class', array($this, 'abbrClass'), array('is_safe' => array('html'))),
new TwigFilter('abbr_method', array($this, 'abbrMethod'), array('is_safe' => array('html'))),
new TwigFilter('format_args', array($this, 'formatArgs'), array('is_safe' => array('html'))),
new TwigFilter('format_args_as_text', array($this, 'formatArgsAsText')),
new TwigFilter('file_excerpt', array($this, 'fileExcerpt'), array('is_safe' => array('html'))),
new TwigFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))),
new TwigFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))),
new TwigFilter('file_link', array($this, 'getFileLink')),
);
return [
new TwigFilter('abbr_class', [$this, 'abbrClass'], ['is_safe' => ['html']]),
new TwigFilter('abbr_method', [$this, 'abbrMethod'], ['is_safe' => ['html']]),
new TwigFilter('format_args', [$this, 'formatArgs'], ['is_safe' => ['html']]),
new TwigFilter('format_args_as_text', [$this, 'formatArgsAsText']),
new TwigFilter('file_excerpt', [$this, 'fileExcerpt'], ['is_safe' => ['html']]),
new TwigFilter('format_file', [$this, 'formatFile'], ['is_safe' => ['html']]),
new TwigFilter('format_file_from_text', [$this, 'formatFileFromText'], ['is_safe' => ['html']]),
new TwigFilter('format_log_message', [$this, 'formatLogMessage'], ['is_safe' => ['html']]),
new TwigFilter('file_link', [$this, 'getFileLink']),
];
}
public function abbrClass($class)
@@ -85,7 +87,7 @@ class CodeExtension extends AbstractExtension
*/
public function formatArgs($args)
{
$result = array();
$result = [];
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$parts = explode('\\', $item[1]);
@@ -93,8 +95,6 @@ class CodeExtension extends AbstractExtension
$formattedValue = sprintf('<em>object</em>(<abbr title="%s">%s</abbr>)', $item[1], $short);
} elseif ('array' === $item[0]) {
$formattedValue = sprintf('<em>array</em>(%s)', \is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
} elseif ('string' === $item[0]) {
$formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES, $this->charset));
} elseif ('null' === $item[0]) {
$formattedValue = '<em>null</em>';
} elseif ('boolean' === $item[0]) {
@@ -102,7 +102,7 @@ class CodeExtension extends AbstractExtension
} elseif ('resource' === $item[0]) {
$formattedValue = '<em>resource</em>';
} else {
$formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES, $this->charset), true));
$formattedValue = str_replace("\n", '', htmlspecialchars(var_export($item[1], true), ENT_COMPAT | ENT_SUBSTITUTE, $this->charset));
}
$result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
@@ -126,28 +126,39 @@ class CodeExtension extends AbstractExtension
/**
* Returns an excerpt of a code file around the given line number.
*
* @param string $file A file path
* @param int $line The selected line number
* @param string $file A file path
* @param int $line The selected line number
* @param int $srcContext The number of displayed lines around or -1 for the whole file
*
* @return string An HTML string
*/
public function fileExcerpt($file, $line)
public function fileExcerpt($file, $line, $srcContext = 3)
{
if (is_readable($file)) {
if (is_file($file) && is_readable($file)) {
// highlight_file could throw warnings
// see https://bugs.php.net/bug.php?id=25725
// see https://bugs.php.net/25725
$code = @highlight_file($file, true);
// remove main code/span tags
$code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code);
// split multiline spans
$code = preg_replace_callback('#<span ([^>]++)>((?:[^<]*+<br \/>)++[^<]*+)</span>#', function ($m) {
return "<span $m[1]>".str_replace('<br />', "</span><br /><span $m[1]>", $m[2]).'</span>';
}, $code);
$content = explode('<br />', $code);
$lines = array();
for ($i = max($line - 3, 1), $max = min($line + 3, \count($content)); $i <= $max; ++$i) {
$lines[] = '<li'.($i == $line ? ' class="selected"' : '').'><code>'.self::fixCodeMarkup($content[$i - 1]).'</code></li>';
$lines = [];
if (0 > $srcContext) {
$srcContext = \count($content);
}
return '<ol start="'.max($line - 3, 1).'">'.implode("\n", $lines).'</ol>';
for ($i = max($line - $srcContext, 1), $max = min($line + $srcContext, \count($content)); $i <= $max; ++$i) {
$lines[] = '<li'.($i == $line ? ' class="selected"' : '').'><a class="anchor" name="line'.$i.'"></a><code>'.self::fixCodeMarkup($content[$i - 1]).'</code></li>';
}
return '<ol start="'.max($line - $srcContext, 1).'">'.implode("\n", $lines).'</ol>';
}
return null;
}
/**
@@ -172,16 +183,12 @@ class CodeExtension extends AbstractExtension
}
}
$text = "$text at line $line";
if (0 < $line) {
$text .= ' at line '.$line;
}
if (false !== $link = $this->getFileLink($file, $line)) {
if (\PHP_VERSION_ID >= 50400) {
$flags = ENT_QUOTES | ENT_SUBSTITUTE;
} else {
$flags = ENT_QUOTES;
}
return sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', htmlspecialchars($link, $flags, $this->charset), $text);
return sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', htmlspecialchars($link, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset), $text);
}
return $text;
@@ -197,8 +204,8 @@ class CodeExtension extends AbstractExtension
*/
public function getFileLink($file, $line)
{
if ($this->fileLinkFormat && is_file($file)) {
return strtr($this->fileLinkFormat, array('%f' => $file, '%l' => $line));
if ($fmt = $this->fileLinkFormat) {
return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
}
return false;
@@ -206,13 +213,32 @@ class CodeExtension extends AbstractExtension
public function formatFileFromText($text)
{
$that = $this;
return preg_replace_callback('/in ("|&quot;)?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) use ($that) {
return 'in '.$that->formatFile($match[2], $match[3]);
return preg_replace_callback('/in ("|&quot;)?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) {
return 'in '.$this->formatFile($match[2], $match[3]);
}, $text);
}
/**
* @internal
*/
public function formatLogMessage($message, array $context)
{
if ($context && false !== strpos($message, '{')) {
$replacements = [];
foreach ($context as $key => $val) {
if (is_scalar($val)) {
$replacements['{'.$key.'}'] = $val;
}
}
if ($replacements) {
$message = strtr($message, $replacements);
}
}
return htmlspecialchars($message, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset);
}
/**
* {@inheritdoc}
*/
@@ -237,6 +263,6 @@ class CodeExtension extends AbstractExtension
$line .= '</span>';
}
return $line;
return trim($line);
}
}

View File

@@ -27,22 +27,24 @@ use Twig\TwigFunction;
class DumpExtension extends AbstractExtension
{
private $cloner;
private $dumper;
public function __construct(ClonerInterface $cloner)
public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null)
{
$this->cloner = $cloner;
$this->dumper = $dumper;
}
public function getFunctions()
{
return array(
new TwigFunction('dump', array($this, 'dump'), array('is_safe' => array('html'), 'needs_context' => true, 'needs_environment' => true)),
);
return [
new TwigFunction('dump', [$this, 'dump'], ['is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true]),
];
}
public function getTokenParsers()
{
return array(new DumpTokenParser());
return [new DumpTokenParser()];
}
public function getName()
@@ -53,31 +55,31 @@ class DumpExtension extends AbstractExtension
public function dump(Environment $env, $context)
{
if (!$env->isDebug()) {
return;
return null;
}
if (2 === \func_num_args()) {
$vars = array();
$vars = [];
foreach ($context as $key => $value) {
if (!$value instanceof Template) {
$vars[$key] = $value;
}
}
$vars = array($vars);
$vars = [$vars];
} else {
$vars = \func_get_args();
unset($vars[0], $vars[1]);
}
$dump = fopen('php://memory', 'r+b');
$dumper = new HtmlDumper($dump, $env->getCharset());
$this->dumper = $this->dumper ?: new HtmlDumper();
$this->dumper->setCharset($env->getCharset());
foreach ($vars as $value) {
$dumper->dump($this->cloner->cloneVar($value));
$this->dumper->dump($this->cloner->cloneVar($value), $dump);
}
rewind($dump);
return stream_get_contents($dump);
return stream_get_contents($dump, -1, 0);
}
}

View File

@@ -27,9 +27,9 @@ class ExpressionExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('expression', array($this, 'createExpression')),
);
return [
new TwigFunction('expression', [$this, 'createExpression']),
];
}
public function createExpression($expression)

View File

@@ -13,11 +13,11 @@ namespace Symfony\Bridge\Twig\Extension;
use Symfony\Bridge\Twig\Form\TwigRendererInterface;
use Symfony\Bridge\Twig\TokenParser\FormThemeTokenParser;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
use Symfony\Component\Form\FormView;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Extension\InitRuntimeInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
@@ -31,24 +31,32 @@ use Twig\TwigTest;
class FormExtension extends AbstractExtension implements InitRuntimeInterface
{
/**
* This property is public so that it can be accessed directly from compiled
* templates without having to call a getter, which slightly decreases performance.
*
* @var TwigRendererInterface
* @deprecated since version 3.2, to be removed in 4.0 alongside with magic methods below
*/
public $renderer;
private $renderer;
public function __construct(TwigRendererInterface $renderer)
public function __construct($renderer = null)
{
if ($renderer instanceof TwigRendererInterface) {
@trigger_error(sprintf('Passing a Twig Form Renderer to the "%s" constructor is deprecated since Symfony 3.2 and won\'t be possible in 4.0. Pass the Twig\Environment to the TwigRendererEngine constructor instead.', static::class), E_USER_DEPRECATED);
} elseif (null !== $renderer && !(\is_array($renderer) && isset($renderer[0], $renderer[1]) && $renderer[0] instanceof ContainerInterface)) {
throw new \InvalidArgumentException(sprintf('Passing any arguments to the constructor of %s is reserved for internal use.', __CLASS__));
}
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*
* To be removed in 4.0
*/
public function initRuntime(Environment $environment)
{
$this->renderer->setEnvironment($environment);
if ($this->renderer instanceof TwigRendererInterface) {
$this->renderer->setEnvironment($environment);
} elseif (\is_array($this->renderer)) {
$this->renderer[2] = $environment;
}
}
/**
@@ -56,10 +64,10 @@ class FormExtension extends AbstractExtension implements InitRuntimeInterface
*/
public function getTokenParsers()
{
return array(
return [
// {% form_theme form "SomeBundle::widgets.twig" %}
new FormThemeTokenParser(),
);
];
}
/**
@@ -67,18 +75,17 @@ class FormExtension extends AbstractExtension implements InitRuntimeInterface
*/
public function getFunctions()
{
return array(
new TwigFunction('form_enctype', null, array('node_class' => 'Symfony\Bridge\Twig\Node\FormEnctypeNode', 'is_safe' => array('html'), 'deprecated' => true, 'alternative' => 'form_start')),
new TwigFunction('form_widget', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_errors', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_label', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_row', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_rest', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_start', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('form_end', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))),
new TwigFunction('csrf_token', array($this, 'renderCsrfToken')),
);
return [
new TwigFunction('form_widget', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_errors', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_label', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_row', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_rest', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form', null, ['node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_start', null, ['node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('form_end', null, ['node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => ['html']]),
new TwigFunction('csrf_token', ['Symfony\Component\Form\FormRenderer', 'renderCsrfToken']),
];
}
/**
@@ -86,10 +93,10 @@ class FormExtension extends AbstractExtension implements InitRuntimeInterface
*/
public function getFilters()
{
return array(
new TwigFilter('humanize', array($this, 'humanize')),
new TwigFilter('form_encode_currency', array($this, 'encodeCurrency'), array('is_safe' => array('html'), 'needs_environment' => true)),
);
return [
new TwigFilter('humanize', ['Symfony\Component\Form\FormRenderer', 'humanize']),
new TwigFilter('form_encode_currency', ['Symfony\Component\Form\FormRenderer', 'encodeCurrency'], ['is_safe' => ['html'], 'needs_environment' => true]),
];
}
/**
@@ -97,90 +104,66 @@ class FormExtension extends AbstractExtension implements InitRuntimeInterface
*/
public function getTests()
{
return array(
new TwigTest('selectedchoice', array($this, 'isSelectedChoice')),
new TwigTest('rootform', array($this, 'isRootForm')),
);
}
/**
* Renders a CSRF token.
*
* @param string $intention The intention of the protected action
*
* @return string A CSRF token
*/
public function renderCsrfToken($intention)
{
return $this->renderer->renderCsrfToken($intention);
}
/**
* Makes a technical name human readable.
*
* @param string $text The text to humanize
*
* @return string The humanized text
*/
public function humanize($text)
{
return $this->renderer->humanize($text);
}
/**
* Returns whether a choice is selected for a given form value.
*
* Unfortunately Twig does not support an efficient way to execute the
* "is_selected" closure passed to the template by ChoiceType. It is faster
* to implement the logic here (around 65ms for a specific form).
*
* Directly implementing the logic here is also faster than doing so in
* ChoiceView (around 30ms).
*
* The worst option tested so far is to implement the logic in ChoiceView
* and access the ChoiceView method directly in the template. Doing so is
* around 220ms slower than doing the method call here in the filter. Twig
* seems to be much more efficient at executing filters than at executing
* methods of an object.
*
* @param ChoiceView $choice The choice to check
* @param string|array $selectedValue The selected value to compare
*
* @return bool Whether the choice is selected
*
* @see ChoiceView::isSelected()
*/
public function isSelectedChoice(ChoiceView $choice, $selectedValue)
{
if (\is_array($selectedValue)) {
return \in_array($choice->value, $selectedValue, true);
}
return $choice->value === $selectedValue;
return [
new TwigTest('selectedchoice', 'Symfony\Bridge\Twig\Extension\twig_is_selected_choice'),
new TwigTest('rootform', 'Symfony\Bridge\Twig\Extension\twig_is_root_form'),
];
}
/**
* @internal
*/
public function isRootForm(FormView $formView)
public function __get($name)
{
return null === $formView->parent;
if ('renderer' === $name) {
@trigger_error(sprintf('Using the "%s::$renderer" property is deprecated since Symfony 3.2 as it will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
if (\is_array($this->renderer)) {
$renderer = $this->renderer[0]->get($this->renderer[1]);
if (isset($this->renderer[2]) && $renderer instanceof TwigRendererInterface) {
$renderer->setEnvironment($this->renderer[2]);
}
$this->renderer = $renderer;
}
}
return $this->$name;
}
/**
* @internal
*/
public function encodeCurrency(Environment $environment, $text, $widget = '')
public function __set($name, $value)
{
if ('UTF-8' === $charset = $environment->getCharset()) {
$text = htmlspecialchars($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8');
} else {
$text = htmlentities($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8');
$text = iconv('UTF-8', $charset, $text);
$widget = iconv('UTF-8', $charset, $widget);
if ('renderer' === $name) {
@trigger_error(sprintf('Using the "%s::$renderer" property is deprecated since Symfony 3.2 as it will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
}
return str_replace('{{ widget }}', $widget, $text);
$this->$name = $value;
}
/**
* @internal
*/
public function __isset($name)
{
if ('renderer' === $name) {
@trigger_error(sprintf('Using the "%s::$renderer" property is deprecated since Symfony 3.2 as it will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
}
return isset($this->$name);
}
/**
* @internal
*/
public function __unset($name)
{
if ('renderer' === $name) {
@trigger_error(sprintf('Using the "%s::$renderer" property is deprecated since Symfony 3.2 as it will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
}
unset($this->$name);
}
/**
@@ -191,3 +174,31 @@ class FormExtension extends AbstractExtension implements InitRuntimeInterface
return 'form';
}
}
/**
* Returns whether a choice is selected for a given form value.
*
* This is a function and not callable due to performance reasons.
*
* @param string|array $selectedValue The selected value to compare
*
* @return bool Whether the choice is selected
*
* @see ChoiceView::isSelected()
*/
function twig_is_selected_choice(ChoiceView $choice, $selectedValue)
{
if (\is_array($selectedValue)) {
return \in_array($choice->value, $selectedValue, true);
}
return $choice->value === $selectedValue;
}
/**
* @internal
*/
function twig_is_root_form(FormView $formView)
{
return null === $formView->parent;
}

View File

@@ -38,10 +38,10 @@ class HttpFoundationExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('absolute_url', array($this, 'generateAbsoluteUrl')),
new TwigFunction('relative_path', array($this, 'generateRelativePath')),
);
return [
new TwigFunction('absolute_url', [$this, 'generateAbsoluteUrl']),
new TwigFunction('relative_path', [$this, 'generateRelativePath']),
];
}
/**

View File

@@ -12,7 +12,6 @@
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
@@ -23,57 +22,16 @@ use Twig\TwigFunction;
*/
class HttpKernelExtension extends AbstractExtension
{
private $handler;
public function __construct(FragmentHandler $handler)
{
$this->handler = $handler;
}
public function getFunctions()
{
return array(
new TwigFunction('render', array($this, 'renderFragment'), array('is_safe' => array('html'))),
new TwigFunction('render_*', array($this, 'renderFragmentStrategy'), array('is_safe' => array('html'))),
new TwigFunction('controller', array($this, 'controller')),
);
return [
new TwigFunction('render', [HttpKernelRuntime::class, 'renderFragment'], ['is_safe' => ['html']]),
new TwigFunction('render_*', [HttpKernelRuntime::class, 'renderFragmentStrategy'], ['is_safe' => ['html']]),
new TwigFunction('controller', static::class.'::controller'),
];
}
/**
* Renders a fragment.
*
* @param string|ControllerReference $uri A URI as a string or a ControllerReference instance
* @param array $options An array of options
*
* @return string The fragment content
*
* @see FragmentHandler::render()
*/
public function renderFragment($uri, $options = array())
{
$strategy = isset($options['strategy']) ? $options['strategy'] : 'inline';
unset($options['strategy']);
return $this->handler->render($uri, $strategy, $options);
}
/**
* Renders a fragment.
*
* @param string $strategy A strategy name
* @param string|ControllerReference $uri A URI as a string or a ControllerReference instance
* @param array $options An array of options
*
* @return string The fragment content
*
* @see FragmentHandler::render()
*/
public function renderFragmentStrategy($strategy, $uri, $options = array())
{
return $this->handler->render($uri, $strategy, $options);
}
public function controller($controller, $attributes = array(), $query = array())
public static function controller($controller, $attributes = [], $query = [])
{
return new ControllerReference($controller, $attributes, $query);
}

View File

@@ -0,0 +1,64 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
/**
* Provides integration with the HttpKernel component.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HttpKernelRuntime
{
private $handler;
public function __construct(FragmentHandler $handler)
{
$this->handler = $handler;
}
/**
* Renders a fragment.
*
* @param string|ControllerReference $uri A URI as a string or a ControllerReference instance
* @param array $options An array of options
*
* @return string The fragment content
*
* @see FragmentHandler::render()
*/
public function renderFragment($uri, $options = [])
{
$strategy = isset($options['strategy']) ? $options['strategy'] : 'inline';
unset($options['strategy']);
return $this->handler->render($uri, $strategy, $options);
}
/**
* Renders a fragment.
*
* @param string $strategy A strategy name
* @param string|ControllerReference $uri A URI as a string or a ControllerReference instance
* @param array $options An array of options
*
* @return string The fragment content
*
* @see FragmentHandler::render()
*/
public function renderFragmentStrategy($strategy, $uri, $options = [])
{
return $this->handler->render($uri, $strategy, $options);
}
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Twig\Extension\InitRuntimeInterface as TwigInitRuntimeInterface;
/**
* @deprecated to be removed in 4.x
*
* @internal to be removed in 4.x
*/
interface InitRuntimeInterface extends TwigInitRuntimeInterface
{
}

View File

@@ -34,10 +34,10 @@ class LogoutUrlExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('logout_url', array($this, 'getLogoutUrl')),
new TwigFunction('logout_path', array($this, 'getLogoutPath')),
);
return [
new TwigFunction('logout_url', [$this, 'getLogoutUrl']),
new TwigFunction('logout_path', [$this, 'getLogoutPath']),
];
}
/**

View File

@@ -33,16 +33,14 @@ class RoutingExtension extends AbstractExtension
}
/**
* Returns a list of functions to add to the existing list.
*
* @return array An array of functions
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new TwigFunction('url', array($this, 'getUrl'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))),
new TwigFunction('path', array($this, 'getPath'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))),
);
return [
new TwigFunction('url', [$this, 'getUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
new TwigFunction('path', [$this, 'getPath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
];
}
/**
@@ -52,7 +50,7 @@ class RoutingExtension extends AbstractExtension
*
* @return string
*/
public function getPath($name, $parameters = array(), $relative = false)
public function getPath($name, $parameters = [], $relative = false)
{
return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
@@ -64,7 +62,7 @@ class RoutingExtension extends AbstractExtension
*
* @return string
*/
public function getUrl($name, $parameters = array(), $schemeRelative = false)
public function getUrl($name, $parameters = [], $schemeRelative = false)
{
return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
}
@@ -91,7 +89,7 @@ class RoutingExtension extends AbstractExtension
*
* @return array An array with the contexts the URL is safe
*
* To be made @final in 3.4, and the type-hint be changed to "\Twig\Node\Node" in 4.0.
* @final since version 3.4, type-hint to be changed to "\Twig\Node\Node" in 4.0
*/
public function isUrlGenerationSafe(\Twig_Node $argsNode)
{
@@ -103,10 +101,10 @@ class RoutingExtension extends AbstractExtension
if (null === $paramsNode || $paramsNode instanceof ArrayExpression && \count($paramsNode) <= 2 &&
(!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof ConstantExpression)
) {
return array('html');
return ['html'];
}
return array();
return [];
}
/**

View File

@@ -53,9 +53,9 @@ class SecurityExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('is_granted', array($this, 'isGranted')),
);
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
/**

View File

@@ -38,14 +38,14 @@ class StopwatchExtension extends AbstractExtension
public function getTokenParsers()
{
return array(
return [
/*
* {% stopwatch foo %}
* Some stuff which will be recorded on the timeline
* {% endstopwatch %}
*/
new StopwatchTokenParser(null !== $this->stopwatch && $this->enabled),
);
];
}
public function getName()

View File

@@ -32,12 +32,8 @@ class TranslationExtension extends AbstractExtension
private $translator;
private $translationNodeVisitor;
public function __construct(TranslatorInterface $translator, NodeVisitorInterface $translationNodeVisitor = null)
public function __construct(TranslatorInterface $translator = null, NodeVisitorInterface $translationNodeVisitor = null)
{
if (!$translationNodeVisitor) {
$translationNodeVisitor = new TranslationNodeVisitor();
}
$this->translator = $translator;
$this->translationNodeVisitor = $translationNodeVisitor;
}
@@ -52,10 +48,10 @@ class TranslationExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('trans', array($this, 'trans')),
new TwigFilter('transchoice', array($this, 'transchoice')),
);
return [
new TwigFilter('trans', [$this, 'trans']),
new TwigFilter('transchoice', [$this, 'transchoice']),
];
}
/**
@@ -65,7 +61,7 @@ class TranslationExtension extends AbstractExtension
*/
public function getTokenParsers()
{
return array(
return [
// {% trans %}Symfony is great!{% endtrans %}
new TransTokenParser(),
@@ -76,7 +72,7 @@ class TranslationExtension extends AbstractExtension
// {% trans_default_domain "foobar" %}
new TransDefaultDomainTokenParser(),
);
];
}
/**
@@ -84,22 +80,30 @@ class TranslationExtension extends AbstractExtension
*/
public function getNodeVisitors()
{
return array($this->translationNodeVisitor, new TranslationDefaultDomainNodeVisitor());
return [$this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()];
}
public function getTranslationNodeVisitor()
{
return $this->translationNodeVisitor;
return $this->translationNodeVisitor ?: $this->translationNodeVisitor = new TranslationNodeVisitor();
}
public function trans($message, array $arguments = array(), $domain = null, $locale = null)
public function trans($message, array $arguments = [], $domain = null, $locale = null)
{
if (null === $this->translator) {
return strtr($message, $arguments);
}
return $this->translator->trans($message, $arguments, $domain, $locale);
}
public function transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null)
public function transchoice($message, $count, array $arguments = [], $domain = null, $locale = null)
{
return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
if (null === $this->translator) {
return strtr($message, $arguments);
}
return $this->translator->transChoice($message, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale);
}
/**

View File

@@ -0,0 +1,139 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Fig\Link\GenericLinkProvider;
use Fig\Link\Link;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Twig extension for the Symfony WebLink component.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class WebLinkExtension extends AbstractExtension
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new TwigFunction('link', [$this, 'link']),
new TwigFunction('preload', [$this, 'preload']),
new TwigFunction('dns_prefetch', [$this, 'dnsPrefetch']),
new TwigFunction('preconnect', [$this, 'preconnect']),
new TwigFunction('prefetch', [$this, 'prefetch']),
new TwigFunction('prerender', [$this, 'prerender']),
];
}
/**
* Adds a "Link" HTTP header.
*
* @param string $uri The relation URI
* @param string $rel The relation type (e.g. "preload", "prefetch", "prerender" or "dns-prefetch")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The relation URI
*/
public function link($uri, $rel, array $attributes = [])
{
if (!$request = $this->requestStack->getMasterRequest()) {
return $uri;
}
$link = new Link($rel, $uri);
foreach ($attributes as $key => $value) {
$link = $link->withAttribute($key, $value);
}
$linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
$request->attributes->set('_links', $linkProvider->withLink($link));
return $uri;
}
/**
* Preloads a resource.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['crossorigin' => 'use-credentials']")
*
* @return string The path of the asset
*/
public function preload($uri, array $attributes = [])
{
return $this->link($uri, 'preload', $attributes);
}
/**
* Resolves a resource origin as early as possible.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function dnsPrefetch($uri, array $attributes = [])
{
return $this->link($uri, 'dns-prefetch', $attributes);
}
/**
* Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation).
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function preconnect($uri, array $attributes = [])
{
return $this->link($uri, 'preconnect', $attributes);
}
/**
* Indicates to the client that it should prefetch this resource.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function prefetch($uri, array $attributes = [])
{
return $this->link($uri, 'prefetch', $attributes);
}
/**
* Indicates to the client that it should prerender this resource .
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function prerender($uri, array $attributes = [])
{
return $this->link($uri, 'prerender', $attributes);
}
}

View File

@@ -0,0 +1,108 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\Transition;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* WorkflowExtension.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class WorkflowExtension extends AbstractExtension
{
private $workflowRegistry;
public function __construct(Registry $workflowRegistry)
{
$this->workflowRegistry = $workflowRegistry;
}
public function getFunctions()
{
return [
new TwigFunction('workflow_can', [$this, 'canTransition']),
new TwigFunction('workflow_transitions', [$this, 'getEnabledTransitions']),
new TwigFunction('workflow_has_marked_place', [$this, 'hasMarkedPlace']),
new TwigFunction('workflow_marked_places', [$this, 'getMarkedPlaces']),
];
}
/**
* Returns true if the transition is enabled.
*
* @param object $subject A subject
* @param string $transitionName A transition
* @param string $name A workflow name
*
* @return bool true if the transition is enabled
*/
public function canTransition($subject, $transitionName, $name = null)
{
return $this->workflowRegistry->get($subject, $name)->can($subject, $transitionName);
}
/**
* Returns all enabled transitions.
*
* @param object $subject A subject
* @param string $name A workflow name
*
* @return Transition[] All enabled transitions
*/
public function getEnabledTransitions($subject, $name = null)
{
return $this->workflowRegistry->get($subject, $name)->getEnabledTransitions($subject);
}
/**
* Returns true if the place is marked.
*
* @param object $subject A subject
* @param string $placeName A place name
* @param string $name A workflow name
*
* @return bool true if the transition is enabled
*/
public function hasMarkedPlace($subject, $placeName, $name = null)
{
return $this->workflowRegistry->get($subject, $name)->getMarking($subject)->has($placeName);
}
/**
* Returns marked places.
*
* @param object $subject A subject
* @param bool $placesNameOnly If true, returns only places name. If false returns the raw representation
* @param string $name A workflow name
*
* @return string[]|int[]
*/
public function getMarkedPlaces($subject, $placesNameOnly = true, $name = null)
{
$places = $this->workflowRegistry->get($subject, $name)->getMarking($subject)->getPlaces();
if ($placesNameOnly) {
return array_keys($places);
}
return $places;
}
public function getName()
{
return 'workflow';
}
}

View File

@@ -28,13 +28,13 @@ class YamlExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('yaml_encode', array($this, 'encode')),
new TwigFilter('yaml_dump', array($this, 'dump')),
);
return [
new TwigFilter('yaml_encode', [$this, 'encode']),
new TwigFilter('yaml_dump', [$this, 'dump']),
];
}
public function encode($input, $inline = 0, $dumpObjects = false)
public function encode($input, $inline = 0, $dumpObjects = 0)
{
static $dumper;
@@ -43,7 +43,15 @@ class YamlExtension extends AbstractExtension
}
if (\defined('Symfony\Component\Yaml\Yaml::DUMP_OBJECT')) {
return $dumper->dump($input, $inline, 0, \is_bool($dumpObjects) ? Yaml::DUMP_OBJECT : 0);
if (\is_bool($dumpObjects)) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
$flags = $dumpObjects ? Yaml::DUMP_OBJECT : 0;
} else {
$flags = $dumpObjects;
}
return $dumper->dump($input, $inline, 0, $flags);
}
return $dumper->dump($input, $inline, 0, false, $dumpObjects);