8000 Added support for deprecating aliases by j92 · Pull Request #24707 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

Added support for deprecating aliases #24707

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

Closed
wants to merge 8 commits into from
Closed
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
59 changes: 59 additions & 0 deletions src/Symfony/Component/DependencyInjection/Alias.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,24 @@

namespace Symfony\Component\DependencyInjection;

use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

class Alias
{
private $id;
private $public;
private $private;
private $deprecated;
private $deprecationTemplate;

private static $defaultDeprecationTemplate = 'The "%service_id%" service alias is deprecated. You should stop using it, as it will soon be removed.';

public function __construct(string $id, bool $public = true)
{
$this->id = $id;
$this->public = $public;
$this->private = 2 > func_num_args();
$this->deprecated = false;
}

/**
Expand Down Expand Up @@ -78,6 +85,58 @@ public function isPrivate()
return $this->private;
}

/**
* Whether this alias is deprecated, that means it should not be called
* anymore.
*
* @param bool $status Defaults to true
* @param string $template Optional template message to use if the alias is deprecated
*
* @return $this
*
* @throws InvalidArgumentException when the message template is invalid
*/
public function setDeprecated($status = true, $template = null)
{
if (null !== $template) {
if (preg_match('#[\r\n]|\*/#', $template)) {
throw new InvalidArgumentException('Invalid characters found in deprecation template.');
}

if (false === strpos($template, '%service_id%')) {
throw new InvalidArgumentException('The deprecation template must contain the "%service_id%" placeholder.');
}

$this->deprecationTemplate = $template;
}

$this->deprecated = (bool) $status;

return $this;
}

/**
* Returns whether this alias is deprecated.
*
* @return bool
*/
public function isDeprecated()
{
return $this->deprecated;
}

/**
* Message to use if this alias is deprecated.
*
* @param string $id Service id relying on this alias
*
* @return string
*/
public function getDeprecationMessage($id)
{
return str_replace('%service_id%', $id, $this->deprecationTemplate ?: self::$defaultDeprecationTemplate);
}

/**
* Returns the Id of this alias.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,12 @@ private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_
}

if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) {
return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices);
$aliasDefinition = $this->aliasDefinitions[$id];
if ($aliasDefinition->isDeprecated()) {
@trigger_error($aliasDefinition->getDeprecationMessage($id), E_USER_DEPRECATED);
}

return $this->doGet((string) $aliasDefinition, $invalidBehavior, $inlineServices);
}

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,10 @@ private function parseDefinition(\DOMElement $service, $file, array $defaults)
$alias->setPublic($defaults['public']);
}

if ($deprecated = $this->getChildren($service, 'deprecated')) {
$alias->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
}

return;
}

Expand Down Expand Up @@ -637,8 +641,12 @@ private function validateAlias(\DOMElement $alias, $file)
}
}

$allowedTags = array('deprecated');
foreach ($alias->childNodes as $child) {
if ($child instanceof \DOMElement && self::NS === $child->namespaceURI) {
if (!$child instanceof \DOMElement && self::NS !== $child->namespaceURI) {
continue;
}
if (!in_array($child->localName, $allowedTags, true)) {
throw new InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $alias->getAttribute('id'), $file));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,13 @@ private function parseDefinition($id, $service, $file, array $defaults)
}

foreach ($service as $key => $value) {
if (!in_array($key, array('alias', 'public'))) {
if (!in_array($key, array('alias', 'public', 'deprecated'))) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias" and "public".', $key, $id, $file));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the message be updated, too? Now it includes hardcoded keys for service aliases are "alias" and "public".

continue;
}

if ('deprecated' === $key) {
$alias->setDeprecated(true, $value);
}
}

Expand Down
110 changes: 110 additions & 0 deletions src/Symfony/Component/DependencyInjection/Tests/AliasTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?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\Component\DependencyInjection\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Alias;

class AliasTest extends TestCase
{
public function testConstructor()
{
$alias = new Alias('foo');

$this->assertEquals('foo', (string) $alias);
$this->assertTrue($alias->isPublic());
}

public function testCanConstructANonPublicAlias()
{
$alias = new Alias('foo', false);

$this->assertEquals('foo', (string) $alias);
$this->assertFalse($alias->isPublic());
}

public function testCanConstructAPrivateAlias()
{
$alias = new Alias('foo', false, false);

$this->assertEquals('foo', (string) $alias);
$this->assertFalse($alias->isPublic());
$this->assertFalse($alias->isPrivate());
}

public function testCanSetPublic()
{
$alias = new Alias('foo', false);
$alias->setPublic(true);

$this->assertTrue($alias->isPublic());
}

public function testCanDeprecateAnAlias()
{
$alias = new Alias('foo', false);
$alias->setDeprecated(true, 'The %service_id% service is deprecated.');

$this->assertTrue($alias->isDeprecated());
}

public function testItHasADefaultDeprecationMessage()
{
$alias = new Alias('foo', false);
$alias->setDeprecated();

$expectedMessage = 'The "foo" service alias is deprecated. You should stop using it, as it will soon be removed.';
$this->assertEquals($expectedMessage, $alias->getDeprecationMessage('foo'));
}

public function testReturnsCorrectDeprecationMessage()
{
$alias = new Alias('foo', false);
$alias->setDeprecated(true, 'The "%service_id%" is deprecated.');

$expectedMessage = 'The "foo" is deprecated.';
$this->assertEquals($expectedMessage, $alias->getDeprecationMessage('foo'));
}

public function testCanOverrideDeprecation()
{
$alias = new Alias('foo', false);
$alias->setDeprecated();

$initial = $alias->isDeprecated();
$alias->setDeprecated(false);
$final = $alias->isDeprecated();

$this->assertTrue($initial);
$this->assertFalse($final);
}

/**
* @dataProvider invalidDeprecationMessageProvider
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testCannotDeprecateWithAnInvalidTemplate($message)
{
$def = new Alias('foo');
$def->setDeprecated(true, $message);
}

public function invalidDeprecationMessageProvider()
{
return array(
"With \rs" => array("invalid \r message %service_id%"),
"With \ns" => array("invalid \n message %service_id%"),
'With */s' => array('invalid */ message %service_id%'),
'message not containing required %service_id% variable' => array('this is deprecated'),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,22 @@ public function testAliases()
}
}

/**
* @group legacy
* @expectedDeprecation The "foobar" service alias is deprecated. You should stop using it, as it will soon be removed.
*/
public function testDeprecatedAlias()
{
$builder = new ContainerBuilder();
$builder->register('foo', 'stdClass');

$alias = new Alias('foo');
$alias->setDeprecated();
$builder->setAlias('foobar', $alias);

$builder->get('foobar');
}

public function testGetAliases()
{
$builder = new ContainerBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@
$s->set('deprecated_service', 'stdClass')
->deprecate();

$s->set('deprecated_service_alias', 'stdClass')
->deprecate('The "%service_id%" service alias is deprecated.');

$s->set('new_factory', 'FactoryClass')
->property('foo', 'bar')
->private();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@
->setDeprecated(true)
->setPublic(true)
;
$container
->register('deprecated_service_alias', 'stdClass')
->setDeprecated(true, 'The "%service_id%" service alias is deprecated.')
->setPublic(true)
;
$container
->register('new_factory', 'FactoryClass')
->setProperty('foo', 'bar')
Expand Down
E377
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ digraph sc {
node_decorator_service [label="decorator_service\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_decorator_service_with_name [label="decorator_service_with_name\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_deprecated_service [label="deprecated_service\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_deprecated_service_alias [label="deprecated_service_alias\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_new_factory [label="new_factory\nFactoryClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_new_factory_service [label="new_factory_service\nFooBarBaz\n", shape=record, fillcolor="#eeeeee", style="filled"];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

return $this->services['deprecated_service'] = new \stdClass();

[Container%s/getDeprecatedServiceAliasService.php] => <?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the public 'deprecated_service_alias' shared service.

@trigger_error('The "deprecated_service_alias" service alias is deprecated.', E_USER_DEPRECATED);

return $this->services['deprecated_service_alias'] = new \stdClass();

[Container%s/getFactoryServiceService.php] => <?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
Expand Down Expand Up @@ -343,6 +354,7 @@ class ProjectServiceContainer extends Container
'decorator_service' => __DIR__.'/getDecoratorServiceService.php',
'decorator_service_with_name' => __DIR__.'/getDecoratorServiceWithNameService.php',
'deprecated_service' => __DIR__.'/getDeprecatedServiceService.php',
'deprecated_service_alias' => __DIR__.'/getDeprecatedServiceAliasService.php',
'factory_service' => __DIR__.'/getFactoryServiceService.php',
'factory_service_simple' => __DIR__.'/getFactoryServiceSimpleService.php',
'foo' => __DIR__.'/getFooService.php',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public function __construct()
'decorator_service' => 'getDecoratorServiceService',
'decorator_service_with_name' => 'getDecoratorServiceWithNameService',
'deprecated_service' => 'getDeprecatedServiceService',
'deprecated_service_alias' => 'getDeprecatedServiceAliasService',
'factory_service' => 'getFactoryServiceService',
'factory_service_simple' => 'getFactoryServiceSimpleService',
'foo' => 'getFooService',
Expand Down Expand Up @@ -224,6 +225,20 @@ protected function getDeprecatedServiceService()
return $this->services['deprecated_service'] = new \stdClass();
}

/**
* Gets the public 'deprecated_service_alias' shared service.
*
* @return \stdClass
*
* @deprecated The "deprecated_service_alias" service alias is deprecated.
*/
protected function getDeprecatedServiceAliasService()
{
@trigger_error('The "deprecated_service_alias" service alias is deprecated.', E_USER_DEPRECATED);

return $this->services['deprecated_service_alias'] = new \stdClass();
}

/**
* Gets the public 'factory_service' shared service.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="foo" class="Foo">
</service>
<service id="alias_for_foo" alias="foo">
<deprecated />
</service>
<service id="alias_for_foobar" alias="foobar">
<deprecated>The "%service_id%" service alias is deprecated.</deprecated>
</service>
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@
<service id="deprecated_service" class="stdClass" public="true">
<deprecated>The "%service_id%" service is deprecated. You should stop using it, as it will soon be removed.</deprecated>
</service>
<service id="deprecated_service_alias" class="stdClass" public="true">
<deprecated>The "%service_id%" service alias is deprecated.</deprecated>
</service>
<service id="new_factory" class="FactoryClass" public="false">
<property name="foo">bar</property>
</service>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
services:
alias_for_foobar:
alias: foobar
deprecated: The "%service_id%" service alias is deprecated.
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ services:
class: stdClass
deprecated: The "%service_id%" service is deprecated. You should stop using it, as it will soon be removed.
public: true
deprecated_service_alias:
class: stdClass
deprecated: The "%service_id%" service alias is deprecated.
public: true
new_factory:
class: FactoryClass
public: false
Expand Down
Loading
0