From e584ea3dcbf1419b8f09e9c66ca47dc881cacad5 Mon Sep 17 00:00:00 2001 From: Peter Gribanov Date: Tue, 28 Apr 2020 18:33:02 +0300 Subject: [PATCH] using sprintf() is preferred over string concatenation use multiline throw change position of concatenation character remove duplicates in sprintf() arguments --- .../GetShortObjectDescriptionAction.php | 5 +- src/Action/SetObjectFieldValueAction.php | 15 +- src/Admin/AbstractAdmin.php | 247 ++++++++++-------- src/Admin/Admin.php | 9 +- src/Admin/AdminExtension.php | 10 +- src/Admin/AdminHelper.php | 38 +-- src/Admin/BaseFieldDescription.php | 31 +-- src/Admin/Pool.php | 19 +- src/Command/CreateClassCacheCommand.php | 8 +- src/Command/GenerateObjectAclCommand.php | 39 ++- src/Command/Validators.php | 12 +- src/Controller/CRUDController.php | 175 ++++++------- src/Controller/CoreController.php | 21 +- src/Controller/HelperController.php | 17 +- src/Controller/PolyfillControllerTrait.php | 2 +- src/Datagrid/Datagrid.php | 3 +- src/Datagrid/DatagridMapper.php | 5 +- src/Datagrid/ListMapper.php | 12 +- src/Datagrid/Pager.php | 20 +- .../AddDependencyCallsCompilerPass.php | 3 +- .../Compiler/ExtensionCompilerPass.php | 7 +- .../Compiler/ModelManagerCompilerPass.php | 9 +- src/DependencyInjection/Configuration.php | 19 +- .../AssetsInstallCommandListener.php | 16 +- src/Export/Exporter.php | 10 +- src/Filter/Filter.php | 15 +- src/Filter/FilterFactory.php | 11 +- .../Persister/SessionFilterPersister.php | 2 +- src/Form/ChoiceList/ModelChoiceLoader.php | 11 +- .../ModelToIdPropertyTransformer.php | 30 ++- .../ModelsToArrayTransformer.php | 16 +- src/Form/FormMapper.php | 2 +- src/Form/Type/AdminType.php | 2 +- src/Form/Type/ModelTypeList.php | 10 +- src/Maker/AdminMaker.php | 14 +- src/Mapper/BaseGroupedMapper.php | 24 +- src/Menu/Matcher/Voter/AdminVoter.php | 14 +- src/Menu/Matcher/Voter/ChildrenVoter.php | 5 +- src/Menu/Provider/GroupMenuProvider.php | 17 +- src/Route/DefaultRouteGenerator.php | 4 +- src/Route/PathInfoBuilder.php | 14 +- src/Route/QueryStringBuilder.php | 2 +- src/Route/RouteCollection.php | 6 +- src/Route/RoutesCache.php | 6 +- src/Security/Handler/AclSecurityHandler.php | 2 +- src/Security/Handler/RoleSecurityHandler.php | 7 +- src/Show/ShowMapper.php | 11 +- src/Templating/TemplateRegistry.php | 3 +- src/Twig/Extension/SonataAdminExtension.php | 25 +- .../Extension/TemplateRegistryExtension.php | 2 +- src/Twig/GlobalVariables.php | 18 +- src/Util/AdminObjectAclData.php | 8 +- src/Util/AdminObjectAclManipulator.php | 6 +- tests/Admin/AdminHelperTest.php | 2 +- tests/Admin/AdminTest.php | 16 +- tests/Admin/PoolTest.php | 6 +- tests/App/AppKernel.php | 10 +- tests/Command/CreateClassCacheCommandTest.php | 22 +- tests/Command/ExplainAdminCommandTest.php | 4 +- tests/Controller/CRUDControllerTest.php | 6 +- tests/Datagrid/ListMapperTest.php | 8 +- .../Compiler/ExtensionCompilerPassTest.php | 8 +- tests/Export/ExporterTest.php | 2 +- tests/Fixtures/Entity/FooArrayAccess.php | 4 +- .../ModelToIdPropertyTransformerTest.php | 8 +- tests/Form/Widget/BaseWidgetTest.php | 8 +- tests/Maker/AdminMakerTest.php | 4 +- tests/Mapper/BaseGroupedMapperTest.php | 2 +- tests/Menu/Integration/BaseMenuTest.php | 8 +- tests/Menu/Matcher/Voter/AdminVoterTest.php | 2 +- tests/Menu/Provider/GroupMenuProviderTest.php | 14 +- tests/Resources/XliffTest.php | 2 +- tests/Route/DefaultRouteGeneratorTest.php | 20 +- tests/Route/RouteCollectionTest.php | 2 +- .../Acl/Permission/MaskBuilderTest.php | 10 +- .../Extension/SonataAdminExtensionTest.php | 12 +- 76 files changed, 665 insertions(+), 554 deletions(-) diff --git a/src/Action/GetShortObjectDescriptionAction.php b/src/Action/GetShortObjectDescriptionAction.php index 8825715ca0..21886bbbd1 100644 --- a/src/Action/GetShortObjectDescriptionAction.php +++ b/src/Action/GetShortObjectDescriptionAction.php @@ -51,10 +51,7 @@ public function __invoke(Request $request): Response $admin = $this->pool->getInstance($code); if (!$admin) { - throw new NotFoundHttpException(sprintf( - 'Could not find admin for code "%s"', - $code - )); + throw new NotFoundHttpException(sprintf('Could not find admin for code "%s"', $code)); } $admin->setRequest($request); diff --git a/src/Action/SetObjectFieldValueAction.php b/src/Action/SetObjectFieldValueAction.php index 65d8ef030e..bc9240a3cc 100644 --- a/src/Action/SetObjectFieldValueAction.php +++ b/src/Action/SetObjectFieldValueAction.php @@ -44,10 +44,11 @@ public function __construct(Environment $twig, Pool $pool, $validator) { // NEXT_MAJOR: Move ValidatorInterface check to method signature if (!($validator instanceof ValidatorInterface)) { - throw new \InvalidArgumentException( - 'Argument 3 is an instance of '.\get_class($validator).', expecting an instance of' - .' \Symfony\Component\Validator\Validator\ValidatorInterface' - ); + throw new \InvalidArgumentException(sprintf( + 'Argument 3 is an instance of %s, expecting an instance of %s', + \get_class($validator), + ValidatorInterface::class + )); } $this->pool = $pool; $this->twig = $twig; @@ -74,7 +75,11 @@ public function __invoke(Request $request): JsonResponse } if (Request::METHOD_POST !== $request->getMethod()) { - return new JsonResponse(sprintf('Invalid request method given "%s", %s expected', $request->getMethod(), Request::METHOD_POST), Response::HTTP_METHOD_NOT_ALLOWED); + return new JsonResponse(sprintf( + 'Invalid request method given "%s", %s expected', + $request->getMethod(), + Request::METHOD_POST + ), Response::HTTP_METHOD_NOT_ALLOWED); } $rootObject = $object = $admin->getObject($objectId); diff --git a/src/Admin/AbstractAdmin.php b/src/Admin/AbstractAdmin.php index 9097b966c9..aadd6f2f35 100644 --- a/src/Admin/AbstractAdmin.php +++ b/src/Admin/AbstractAdmin.php @@ -598,21 +598,24 @@ public function __construct($code, $class, $baseControllerName = null) { if (!\is_string($code)) { @trigger_error(sprintf( - 'Passing other type than string as argument 1 for method %s() is deprecated since sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.', + 'Passing other type than string as argument 1 for method %s() is deprecated since' + .' sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } $this->code = $code; if (!\is_string($class)) { @trigger_error(sprintf( - 'Passing other type than string as argument 2 for method %s() is deprecated since sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.', + 'Passing other type than string as argument 2 for method %s() is deprecated since' + .' sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } $this->class = $class; if (null !== $baseControllerName && !\is_string($baseControllerName)) { @trigger_error(sprintf( - 'Passing other type than string or null as argument 3 for method %s() is deprecated since sonata-project/admin-bundle 3.65. It will accept only string and null in version 4.0.', + 'Passing other type than string or null as argument 3 for method %s() is deprecated since' + .' sonata-project/admin-bundle 3.65. It will accept only string and null in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -927,7 +930,7 @@ public function getParentAssociationMapping() } throw new \InvalidArgumentException(sprintf( - "There's no association between %s and %s.", + 'There\'s no association between %s and %s.', $this->getCode(), $this->getParent()->getCode() )); @@ -965,7 +968,10 @@ public function getBaseRoutePattern() preg_match(self::CLASS_REGEX, $this->class, $matches); if (!$matches) { - throw new \RuntimeException(sprintf('Please define a default `baseRoutePattern` value for the admin class `%s`', static::class)); + throw new \RuntimeException(sprintf( + 'Please define a default `baseRoutePattern` value for the admin class `%s`', + static::class + )); } $baseRoutePattern = $this->urlize($matches[5], '-'); } @@ -982,7 +988,10 @@ public function getBaseRoutePattern() preg_match(self::CLASS_REGEX, $this->class, $matches); if (!$matches) { - throw new \RuntimeException(sprintf('Please define a default `baseRoutePattern` value for the admin class `%s`', static::class)); + throw new \RuntimeException(sprintf( + 'Please define a default `baseRoutePattern` value for the admin class `%s`', + static::class + )); } $this->cachedBaseRoutePattern = sprintf( @@ -1015,7 +1024,11 @@ public function getBaseRouteName() preg_match(self::CLASS_REGEX, $this->class, $matches); if (!$matches) { - throw new \RuntimeException(sprintf('Cannot automatically determine base route name, please define a default `baseRouteName` value for the admin class `%s`', static::class)); + throw new \RuntimeException(sprintf( + 'Cannot automatically determine base route name,' + .' please define a default `baseRouteName` value for the admin class `%s`', + static::class + )); } $baseRouteName = $this->urlize($matches[5]); } @@ -1031,7 +1044,11 @@ public function getBaseRouteName() preg_match(self::CLASS_REGEX, $this->class, $matches); if (!$matches) { - throw new \RuntimeException(sprintf('Cannot automatically determine base route name, please define a default `baseRouteName` value for the admin class `%s`', static::class)); + throw new \RuntimeException(sprintf( + 'Cannot automatically determine base route name,' + .' please define a default `baseRouteName` value for the admin class `%s`', + static::class + )); } $this->cachedBaseRouteName = sprintf( @@ -1125,8 +1142,9 @@ public function getActiveSubClass() { if (!$this->hasActiveSubClass()) { @trigger_error(sprintf( - 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52 and will throw an exception in 4.0. '. - 'Use %s::hasActiveSubClass() to know if there is an active subclass.', + 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52' + .' and will throw an exception in 4.0.' + .' Use %s::hasActiveSubClass() to know if there is an active subclass.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1146,8 +1164,9 @@ public function getActiveSubclassCode() { if (!$this->hasActiveSubClass()) { @trigger_error(sprintf( - 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52 and will throw an exception in 4.0. '. - 'Use %s::hasActiveSubClass() to know if there is an active subclass.', + 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52' + .' and will throw an exception in 4.0.' + .' Use %s::hasActiveSubClass() to know if there is an active subclass.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1164,8 +1183,9 @@ public function getActiveSubclassCode() if (!$this->hasSubClass($subClass)) { @trigger_error(sprintf( - 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52 and will throw an exception in 4.0. '. - 'Use %s::hasActiveSubClass() to know if there is an active subclass.', + 'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52' + .' and will throw an exception in 4.0.' + .' Use %s::hasActiveSubClass() to know if there is an active subclass.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1224,7 +1244,7 @@ public function getRoutes() public function getRouterIdParameter() { - return '{'.$this->getIdParameter().'}'; + return sprintf('{%s}', $this->getIdParameter()); } public function getIdParameter() @@ -1232,7 +1252,7 @@ public function getIdParameter() $parameter = 'id'; for ($i = 0; $i < $this->getChildDepth(); ++$i) { - $parameter = 'child'.ucfirst($parameter); + $parameter = sprintf('child%s', ucfirst($parameter)); } return $parameter; @@ -1272,7 +1292,7 @@ public function isCurrentRoute($name, $adminCode = null) return false; } - return ($admin->getBaseRouteName().'_'.$name) === $route; + return sprintf('%s_%s', $admin->getBaseRouteName(), $name) === $route; } public function generateObjectUrl($name, $object, array $parameters = [], $referenceType = RoutingUrlGeneratorInterface::ABSOLUTE_PATH) @@ -1374,8 +1394,8 @@ public function defineFormBuilder(FormBuilderInterface $formBuilder) { if (!$this->hasSubject()) { @trigger_error(sprintf( - 'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.65 and will throw an exception in 4.0. '. - 'Use %s::setSubject() to set the subject.', + 'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.65' + .' and will throw an exception in 4.0. Use %s::setSubject() to set the subject.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1454,10 +1474,10 @@ public function getList() public function createQuery($context = 'list') { if (\func_num_args() > 0) { - @trigger_error( - 'The $context argument of '.__METHOD__.' is deprecated since 3.3, to be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The $context argument of %s is deprecated since 3.3, to be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); } $query = $this->getModelManager()->createQuery($this->getClass()); @@ -1582,10 +1602,10 @@ public function getLabel() */ public function setPersistFilters($persist) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.34 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.34 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); $this->persistFilters = $persist; } @@ -1646,7 +1666,8 @@ public function getFormGroups() { if (!\is_array($this->formGroups) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only array in version 4.0.', + 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.' + .' It will return only array in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -1685,7 +1706,8 @@ public function getFormTabs() { if (!\is_array($this->formTabs) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only array in version 4.0.', + 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.' + .' It will return only array in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -1702,7 +1724,8 @@ public function getShowTabs() { if (!\is_array($this->showTabs) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only array in version 4.0.', + 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.' + .' It will return only array in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -1719,7 +1742,8 @@ public function getShowGroups() { if (!\is_array($this->showGroups) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only array in version 4.0.', + 'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.' + .' It will return only array in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -1749,8 +1773,9 @@ public function getParentFieldDescription() { if (!$this->hasParentFieldDescription()) { @trigger_error(sprintf( - 'Calling %s() when there is no parent field description is deprecated since sonata-project/admin-bundle 3.66 and will throw an exception in 4.0. '. - 'Use %s::hasParentFieldDescription() to know if there is a parent field description.', + 'Calling %s() when there is no parent field description is deprecated since' + .' sonata-project/admin-bundle 3.66 and will throw an exception in 4.0.' + .' Use %s::hasParentFieldDescription() to know if there is a parent field description.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1780,10 +1805,8 @@ public function setSubject($subject) This is deprecated since 3.5 and will no longer be supported in 4.0. EOT; - @trigger_error( - sprintf($message, \get_class($subject), $this->getClass()), - E_USER_DEPRECATED - ); // NEXT_MAJOR : throw an exception instead + // NEXT_MAJOR : throw an exception instead + @trigger_error(sprintf($message, \get_class($subject), $this->getClass()), E_USER_DEPRECATED); } $this->subject = $subject; @@ -1793,8 +1816,8 @@ public function getSubject() { if (!$this->hasSubject()) { @trigger_error(sprintf( - 'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.66 and will throw an exception in 4.0. '. - 'Use %s::hasSubject() to know if there is a subject.', + 'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.66' + .' and will throw an exception in 4.0. Use %s::hasSubject() to know if there is a subject.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1836,8 +1859,9 @@ public function getFormFieldDescription($name) if (!$this->hasFormFieldDescription($name)) { @trigger_error(sprintf( - 'Calling %s() when there is no form field description is deprecated since sonata-project/admin-bundle 3.69 and will throw an exception in 4.0. '. - 'Use %s::hasFormFieldDescription() to know if there is a form field description.', + 'Calling %s() when there is no form field description is deprecated since' + .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.' + .' Use %s::hasFormFieldDescription() to know if there is a form field description.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1908,8 +1932,9 @@ public function getShowFieldDescription($name) if (!$this->hasShowFieldDescription($name)) { @trigger_error(sprintf( - 'Calling %s() when there is no show field description is deprecated since sonata-project/admin-bundle 3.69 and will throw an exception in 4.0. '. - 'Use %s::hasFormFieldDescription() to know if there is a show field description.', + 'Calling %s() when there is no show field description is deprecated since' + .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.' + .' Use %s::hasFormFieldDescription() to know if there is a show field description.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -1956,8 +1981,9 @@ public function getListFieldDescription($name) if (!$this->hasListFieldDescription($name)) { @trigger_error(sprintf( - 'Calling %s() when there is no list field description is deprecated since sonata-project/admin-bundle 3.66 and will throw an exception in 4.0. '. - 'Use %s::hasListFieldDescription(\'%s\') to know if there is a list field description.', + 'Calling %s() when there is no list field description is deprecated since' + .' sonata-project/admin-bundle 3.66 and will throw an exception in 4.0.' + .' Use %s::hasListFieldDescription(\'%s\') to know if there is a list field description.', __METHOD__, __CLASS__, $name @@ -1998,8 +2024,9 @@ public function getFilterFieldDescription($name) if (!$this->hasFilterFieldDescription($name)) { @trigger_error(sprintf( - 'Calling %s() when there is no filter field description is deprecated since sonata-project/admin-bundle 3.69 and will throw an exception in 4.0. '. - 'Use %s::hasFilterFieldDescription() to know if there is a filter field description.', + 'Calling %s() when there is no filter field description is deprecated since' + .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.' + .' Use %s::hasFilterFieldDescription() to know if there is a filter field description.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -2067,8 +2094,7 @@ public function addChild(AdminInterface $child) $child->addParentAssociationMapping($this->getCode(), $args[1]); } else { @trigger_error( - 'Calling "addChild" without second argument is deprecated since' - .' sonata-project/admin-bundle 3.35 and will not be allowed in 4.0.', + 'Calling "addChild" without second argument is deprecated since sonata-project/admin-bundle 3.35 and will not be allowed in 4.0.', E_USER_DEPRECATED ); } @@ -2115,8 +2141,8 @@ public function getParent() { if (!$this->isChild()) { @trigger_error(sprintf( - 'Calling %s() when there is no parent is deprecated since sonata-project/admin-bundle 3.66 and will throw an exception in 4.0. '. - 'Use %s::isChild() to know if there is a parent.', + 'Calling %s() when there is no parent is deprecated since sonata-project/admin-bundle 3.66' + .' and will throw an exception in 4.0. Use %s::isChild() to know if there is a parent.', __METHOD__, __CLASS__ ), E_USER_DEPRECATED); @@ -2194,7 +2220,7 @@ public function setUniqid($uniqid) public function getUniqid() { if (!$this->uniqid) { - $this->uniqid = 's'.uniqid(); + $this->uniqid = sprintf('s%s', uniqid()); } return $this->uniqid; @@ -2218,7 +2244,10 @@ public function getPersistentParameters() $params = $extension->getPersistentParameters($this); if (!\is_array($params)) { - throw new \RuntimeException(sprintf('The %s::getPersistentParameters must return an array', \get_class($extension))); + throw new \RuntimeException(sprintf( + 'The %s::getPersistentParameters must return an array', + \get_class($extension) + )); } $parameters = array_merge($parameters, $params); @@ -2241,11 +2270,12 @@ public function getPersistentParameter($name) public function getBreadcrumbs($action) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'. - ' Use Sonata\AdminBundle\Admin\BreadcrumbsBuilder::getBreadcrumbs instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.2 and will be removed in 4.0.' + .' Use %s::getBreadcrumbs instead.', + __METHOD__, + BreadcrumbsBuilder::class + ), E_USER_DEPRECATED); return $this->getBreadcrumbsBuilder()->getBreadcrumbs($this, $action); } @@ -2261,10 +2291,10 @@ public function getBreadcrumbs($action) */ public function buildBreadcrumbs($action, ?ItemInterface $menu = null) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.2 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); if (isset($this->breadcrumbs[$action])) { return $this->breadcrumbs[$action]; @@ -2281,11 +2311,11 @@ public function buildBreadcrumbs($action, ?ItemInterface $menu = null) */ final public function getBreadcrumbsBuilder() { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'. - ' Use the sonata.admin.breadcrumbs_builder service instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.2 and will be removed in 4.0.' + .' Use the sonata.admin.breadcrumbs_builder service instead.', + __METHOD__ + ), E_USER_DEPRECATED); if (null === $this->breadcrumbsBuilder) { $this->breadcrumbsBuilder = new BreadcrumbsBuilder( $this->getConfigurationPool()->getContainer()->getParameter('sonata.admin.configuration.breadcrumbs') @@ -2302,11 +2332,11 @@ final public function getBreadcrumbsBuilder() */ final public function setBreadcrumbsBuilder(BreadcrumbsBuilderInterface $value) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'. - ' Use the sonata.admin.breadcrumbs_builder service instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.2 and will be removed in 4.0.' + .' Use the sonata.admin.breadcrumbs_builder service instead.', + __METHOD__ + ), E_USER_DEPRECATED); $this->breadcrumbsBuilder = $value; return $this; @@ -2324,14 +2354,12 @@ public function setCurrentChild($currentChild) */ public function getCurrentChild() { - @trigger_error( - sprintf( - 'The %s() method is deprecated since version 3.65 and will be removed in 4.0. Use %s::isCurrentChild() instead.', - __METHOD__, - __CLASS__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s() method is deprecated since version 3.65 and will be removed in 4.0.' + .' Use %s::isCurrentChild() instead.', + __METHOD__, + __CLASS__ + ), E_USER_DEPRECATED); return $this->currentChild; } @@ -2359,10 +2387,10 @@ public function getCurrentChildAdmin() public function trans($id, array $parameters = [], $domain = null, $locale = null) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.9 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.9 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); $domain = $domain ?: $this->getTranslationDomain(); @@ -2385,10 +2413,10 @@ public function trans($id, array $parameters = [], $domain = null, $locale = nul */ public function transChoice($id, $count, array $parameters = [], $domain = null, $locale = null) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.9 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.9 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); $domain = $domain ?: $this->getTranslationDomain(); @@ -2416,10 +2444,10 @@ public function setTranslator(TranslatorInterface $translator) { $args = \func_get_args(); if (isset($args[1]) && $args[1]) { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.9 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.9 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); } $this->translator = $translator; @@ -2434,10 +2462,10 @@ public function setTranslator(TranslatorInterface $translator) */ public function getTranslator() { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since version 3.9 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since version 3.9 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); return $this->translator; } @@ -2557,10 +2585,10 @@ public function getCode() */ public function setBaseCodeRoute($baseCodeRoute) { - @trigger_error( - 'The '.__METHOD__.' is deprecated since 3.24 and will be removed in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s is deprecated since 3.24 and will be removed in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); $this->baseCodeRoute = $baseCodeRoute; } @@ -2569,7 +2597,7 @@ public function getBaseCodeRoute() { // NEXT_MAJOR: Uncomment the following lines. // if ($this->isChild()) { - // return $this->getParent()->getBaseCodeRoute().'|'.$this->getCode(); + // return sprintf('%s|%s', $this->getParent()->getBaseCodeRoute(), $this->getCode()); // } // // return $this->getCode(); @@ -2582,7 +2610,7 @@ public function getBaseCodeRoute() $parentCode = $this->getParent()->getBaseCodeRoute(); } - return $parentCode.'|'.$this->getCode(); + return sprintf('%s|%s', $parentCode, $this->getCode()); } return $this->baseCodeRoute; @@ -2673,7 +2701,7 @@ public function getSecurityHandler() public function isGranted($name, $object = null) { - $objectRef = $object ? '/'.spl_object_hash($object).'#'.$this->id($object) : ''; + $objectRef = $object ? sprintf('/%s#%s', spl_object_hash($object), $this->id($object)) : ''; $key = md5(json_encode($name).$objectRef); if (!\array_key_exists($key, $this->cacheIsGranted)) { @@ -2702,9 +2730,10 @@ public function setValidator($validator) { // NEXT_MAJOR: Move ValidatorInterface check to method signature if (!$validator instanceof ValidatorInterface) { - throw new \InvalidArgumentException( - 'Argument 1 must be an instance of Symfony\Component\Validator\Validator\ValidatorInterface' - ); + throw new \InvalidArgumentException(sprintf( + 'Argument 1 must be an instance of %s', + ValidatorInterface::class + )); } $this->validator = $validator; @@ -3395,11 +3424,7 @@ protected function getSubClass($name) } // NEXT_MAJOR: Throw \LogicException instead. - throw new \RuntimeException(sprintf( - 'Unable to find the subclass `%s` for admin `%s`', - $name, - static::class - )); + throw new \RuntimeException(sprintf('Unable to find the subclass `%s` for admin `%s`', $name, static::class)); } /** diff --git a/src/Admin/Admin.php b/src/Admin/Admin.php index f71e06255c..68b3ef23f1 100644 --- a/src/Admin/Admin.php +++ b/src/Admin/Admin.php @@ -13,11 +13,10 @@ namespace Sonata\AdminBundle\Admin; -@trigger_error( - 'The '.__NAMESPACE__.'\Admin class is deprecated since version 3.1 and will be removed in 4.0.' - .' Use '.__NAMESPACE__.'\AbstractAdmin instead.', - E_USER_DEPRECATED -); +@trigger_error(sprintf( + 'The %1$s\Admin class is deprecated since version 3.1 and will be removed in 4.0. Use %1$s\AbstractAdmin instead.', + __NAMESPACE__ +), E_USER_DEPRECATED); /** * NEXT_MAJOR: remove this class. diff --git a/src/Admin/AdminExtension.php b/src/Admin/AdminExtension.php index 4625a8a875..b2912aeb99 100644 --- a/src/Admin/AdminExtension.php +++ b/src/Admin/AdminExtension.php @@ -13,11 +13,11 @@ namespace Sonata\AdminBundle\Admin; -@trigger_error( - 'The '.__NAMESPACE__.'\AdminExtension class is deprecated since version 3.1 and will be removed in 4.0.' - .' Use '.__NAMESPACE__.'\AbstractAdminExtension instead.', - E_USER_DEPRECATED -); +@trigger_error(sprintf( + 'The %1$s\AdminExtension class is deprecated since version 3.1 and will be removed in 4.0.' + .' Use %1$s\AbstractAdminExtension instead.', + __NAMESPACE__ +), E_USER_DEPRECATED); /** * NEXT_MAJOR: remove this class. diff --git a/src/Admin/AdminHelper.php b/src/Admin/AdminHelper.php index 89d0ac6aae..d711af5f8d 100644 --- a/src/Admin/AdminHelper.php +++ b/src/Admin/AdminHelper.php @@ -15,6 +15,7 @@ use Doctrine\Common\Collections\Collection; use Doctrine\Common\Util\ClassUtils; +use Doctrine\Inflector\Inflector; use Doctrine\Inflector\InflectorFactory; use Doctrine\ODM\MongoDB\PersistentCollection; use Doctrine\ORM\PersistentCollection as DoctrinePersistentCollection; @@ -236,9 +237,11 @@ public function addNewInstance($object, FieldDescriptionInterface $fieldDescript /* * NEXT_MAJOR: Use BadMethodCallException instead */ - throw new \RuntimeException( - sprintf('Method %s::%s() does not exist.', ClassUtils::getClass($object), $method) - ); + throw new \RuntimeException(sprintf( + 'Method %s::%s() does not exist.', + ClassUtils::getClass($object), + $method + )); } $object = $object->$method(); @@ -256,9 +259,11 @@ public function addNewInstance($object, FieldDescriptionInterface $fieldDescript /* * NEXT_MAJOR: Use BadMethodCallException instead */ - throw new \RuntimeException( - sprintf('Method %s::%s() does not exist.', ClassUtils::getClass($object), $method) - ); + throw new \RuntimeException(sprintf( + 'Method %s::%s() does not exist.', + ClassUtils::getClass($object), + $method + )); } } } @@ -283,14 +288,11 @@ public function addNewInstance($object, FieldDescriptionInterface $fieldDescript */ public function camelize($property) { - @trigger_error( - sprintf( - 'The %s method is deprecated since 3.1 and will be removed in 4.0. '. - 'Use \Doctrine\Inflector\Inflector::classify() instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since 3.1 and will be removed in 4.0. Use %s::classify() instead.', + __METHOD__, + Inflector::class + ), E_USER_DEPRECATED); return InflectorFactory::create()->build()->classify($property); } @@ -328,9 +330,11 @@ public function getElementAccessPath($elementId, $model) } if (!empty($currentPath)) { - throw new \Exception( - sprintf('Could not get element id from %s Failing part: %s', $elementId, $currentPath) - ); + throw new \Exception(sprintf( + 'Could not get element id from %s Failing part: %s', + $elementId, + $currentPath + )); } return $totalPath; diff --git a/src/Admin/BaseFieldDescription.php b/src/Admin/BaseFieldDescription.php index 4fe2c2589e..c5eea723b6 100644 --- a/src/Admin/BaseFieldDescription.php +++ b/src/Admin/BaseFieldDescription.php @@ -13,6 +13,7 @@ namespace Sonata\AdminBundle\Admin; +use Doctrine\Inflector\Inflector; use Doctrine\Inflector\InflectorFactory; use Sonata\AdminBundle\Exception\NoValueException; @@ -211,7 +212,8 @@ public function getTemplate() { if (null !== $this->template && !\is_string($this->template) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than string or null in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only those types in version 4.0.', + 'Returning other type than string or null in method %s() is deprecated since' + .' sonata-project/admin-bundle 3.65. It will return only those types in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } @@ -284,8 +286,9 @@ public function getAssociationAdmin() if (!$this->hasAssociationAdmin()) { @trigger_error( sprintf( - 'Calling %s() when there is no association admin is deprecated since sonata-project/admin-bundle 3.69' - .' and will throw an exception in 4.0. Use %s::hasAssociationAdmin() to know if there is an association admin.', + 'Calling %s() when there is no association admin is deprecated since' + .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.' + .' Use %s::hasAssociationAdmin() to know if there is an association admin.', __METHOD__, __CLASS__ ), @@ -328,9 +331,9 @@ public function getFieldValue($object, $fieldName) $camelizedFieldName = InflectorFactory::create()->build()->classify($fieldName); - $getters[] = 'get'.$camelizedFieldName; - $getters[] = 'is'.$camelizedFieldName; - $getters[] = 'has'.$camelizedFieldName; + $getters[] = sprintf('get%s', $camelizedFieldName); + $getters[] = sprintf('is%s', $camelizedFieldName); + $getters[] = sprintf('has%s', $camelizedFieldName); } foreach ($getters as $getter) { @@ -433,14 +436,11 @@ public function getMappingType() */ public static function camelize($property) { - @trigger_error( - sprintf( - 'The %s method is deprecated since 3.1 and will be removed in 4.0. '. - 'Use \Doctrine\Inflector\Inflector::classify() instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since 3.1 and will be removed in 4.0. Use %s::classify() instead.', + __METHOD__, + Inflector::class + ), E_USER_DEPRECATED); return InflectorFactory::create()->build()->classify($property); } @@ -465,7 +465,8 @@ public function getLabel() $label = $this->getOption('label'); if (null !== $label && false !== $label && !\is_string($label) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) { @trigger_error(sprintf( - 'Returning other type than string, false or null in method %s() is deprecated since sonata-project/admin-bundle 3.65. It will return only those types in version 4.0.', + 'Returning other type than string, false or null in method %s() is deprecated since' + .' sonata-project/admin-bundle 3.65. It will return only those types in version 4.0.', __METHOD__ ), E_USER_DEPRECATED); } diff --git a/src/Admin/Pool.php b/src/Admin/Pool.php index 53e258ba35..01cd0c0100 100644 --- a/src/Admin/Pool.php +++ b/src/Admin/Pool.php @@ -256,8 +256,10 @@ public function getAdminByAdminCode($adminCode) { if (!\is_string($adminCode)) { @trigger_error(sprintf( - 'Passing a non string value as argument 1 for %s() is deprecated since sonata-project/admin-bundle 3.51 and will cause a \TypeError in 4.0.', - __METHOD__ + 'Passing a non string value as argument 1 for %s() is deprecated since' + .' sonata-project/admin-bundle 3.51 and will cause a %s in 4.0.', + __METHOD__, + \TypeError::class ), E_USER_DEPRECATED); return false; @@ -269,7 +271,9 @@ public function getAdminByAdminCode($adminCode) $code = trim(array_shift($codes)); if ('' === $code) { - throw new \InvalidArgumentException('Root admin code must contain a valid admin reference, empty string given.'); + throw new \InvalidArgumentException( + 'Root admin code must contain a valid admin reference, empty string given.' + ); } $admin = $this->getInstance($code); @@ -277,7 +281,8 @@ public function getAdminByAdminCode($adminCode) foreach ($codes as $code) { if (!\in_array($code, $this->adminServiceIds, true)) { @trigger_error(sprintf( - 'Passing an invalid admin code as argument 1 for %s() is deprecated since sonata-project/admin-bundle 3.50 and will throw an exception in 4.0.', + 'Passing an invalid admin code as argument 1 for %s() is deprecated since' + .' sonata-project/admin-bundle 3.50 and will throw an exception in 4.0.', __METHOD__ ), E_USER_DEPRECATED); @@ -286,13 +291,15 @@ public function getAdminByAdminCode($adminCode) if (!$admin->hasChild($code)) { @trigger_error(sprintf( - 'Passing an invalid admin hierarchy inside argument 1 for %s() is deprecated since sonata-project/admin-bundle 3.51 and will throw an exception in 4.0.', + 'Passing an invalid admin hierarchy inside argument 1 for %s() is deprecated since' + .' sonata-project/admin-bundle 3.51 and will throw an exception in 4.0.', __METHOD__ ), E_USER_DEPRECATED); // NEXT_MAJOR : remove the previous `trigger_error()` call, uncomment the following exception and declare AdminInterface as return type // throw new \InvalidArgumentException(sprintf( - // 'Argument 1 passed to %s() must contain a valid admin hierarchy, "%s" is not a valid child for "%s"', + // 'Argument 1 passed to %s() must contain a valid admin hierarchy,' + // .' "%s" is not a valid child for "%s"', // __METHOD__, // $code, // $admin->getCode() diff --git a/src/Command/CreateClassCacheCommand.php b/src/Command/CreateClassCacheCommand.php index 18e95a727d..c5cf36f748 100644 --- a/src/Command/CreateClassCacheCommand.php +++ b/src/Command/CreateClassCacheCommand.php @@ -18,10 +18,10 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -@trigger_error( - 'The '.__NAMESPACE__.'\CreateClassCacheCommand class is deprecated since version 3.39.0 and will be removed in 4.0.', - E_USER_DEPRECATED -); +@trigger_error(sprintf( + 'The %s\CreateClassCacheCommand class is deprecated since version 3.39.0 and will be removed in 4.0.', + __NAMESPACE__ +), E_USER_DEPRECATED); /** * NEXT_MAJOR: Remove this class. diff --git a/src/Command/GenerateObjectAclCommand.php b/src/Command/GenerateObjectAclCommand.php index 471bd9b404..8d2b8bb94b 100644 --- a/src/Command/GenerateObjectAclCommand.php +++ b/src/Command/GenerateObjectAclCommand.php @@ -67,7 +67,8 @@ public function __construct(Pool $pool, array $aclObjectManipulators, $registry if (null !== $registry && (!$registry instanceof RegistryInterface && !$registry instanceof ManagerRegistry)) { if (!$registry instanceof ManagerRegistry) { @trigger_error(sprintf( - "Passing an object that doesn't implement %s as argument 3 to %s() is deprecated since sonata-project/admin-bundle 3.56.", + 'Passing an object that doesn\'t implement %s as argument 3 to %s() is deprecated since' + .' sonata-project/admin-bundle 3.56.', ManagerRegistry::class, __METHOD__ ), E_USER_DEPRECATED); @@ -102,18 +103,19 @@ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Welcome to the AdminBundle object ACL generator'); $output->writeln([ - '', - 'This command helps you to generate ACL entities for the objects handled by the AdminBundle.', - '', - 'If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.', - 'You must use the shortcut notation like AcmeDemoBundle:User if you want to set an object owner.', - '', + '', + 'This command helps you to generate ACL entities for the objects handled by the AdminBundle.', + '', + 'If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.', + 'You must use the shortcut notation like AcmeDemoBundle:User if you want to set an object owner.', + '', ]); if (!$this->registry) { - $msg = sprintf('The command "%s" has a dependency on a non-existent service "doctrine".', static::$defaultName); - - throw new ServiceNotFoundException('doctrine', static::class, null, [], $msg); + throw new ServiceNotFoundException('doctrine', static::class, null, [], sprintf( + 'The command "%s" has a dependency on a non-existent service "doctrine".', + static::$defaultName + )); } if ($input->getOption('user_model')) { @@ -224,16 +226,25 @@ protected function getUserEntityClass(InputInterface $input, OutputInterface $ou if ('' === $this->userEntityClass) { if ($input->getOption('user_model')) { - list($userBundle, $userModel) = Validators::validateEntityName($input->getOption('user_model')); + [$userBundle, $userModel] = Validators::validateEntityName($input->getOption('user_model')); } else { - list($userBundle, $userModel) = $this->askAndValidate($input, $output, 'Please enter the User model shortcut name: ', '', 'Sonata\AdminBundle\Command\Validators::validateEntityName'); + [$userBundle, $userModel] = $this->askAndValidate( + $input, + $output, + 'Please enter the User Entity shortcut name: ', + '', + 'Sonata\AdminBundle\Command\Validators::validateEntityName' + ); } + // Entity exists? if ($this->registry instanceof RegistryInterface) { - $this->userEntityClass = $this->registry->getEntityNamespace($userBundle).'\\'.$userModel; + $namespace = $this->registry->getEntityNamespace($userBundle); } else { - $this->userEntityClass = $this->registry->getAliasNamespace($userBundle).'\\'.$userModel; + $namespace = $this->registry->getAliasNamespace($userBundle); } + + $this->userEntityClass = sprintf('%s\%s', $namespace, $userModel); } return $this->userEntityClass; diff --git a/src/Command/Validators.php b/src/Command/Validators.php index f2571ca140..0191b830f8 100644 --- a/src/Command/Validators.php +++ b/src/Command/Validators.php @@ -53,8 +53,8 @@ public static function validateEntityName($shortcut) if (false === $pos = strpos($model, ':')) { throw new \InvalidArgumentException(sprintf( - 'The entity name must contain a ":" (colon sign) ' - .'("%s" given, expecting something like AcmeBlogBundle:Post)', + 'The entity name must contain a ":" (colon sign)' + .' ("%s" given, expecting something like AcmeBlogBundle:Post)', $model )); } @@ -97,8 +97,8 @@ public static function validateAdminClassBasename($adminClassBasename) if (false !== strpos($adminClassBasename, ':')) { throw new \InvalidArgumentException(sprintf( - 'The admin class name must not contain a ":" (colon sign) ' - .'("%s" given, expecting something like PostAdmin")', + 'The admin class name must not contain a ":" (colon sign)' + .' ("%s" given, expecting something like PostAdmin")', $adminClassBasename )); } @@ -121,8 +121,8 @@ public static function validateControllerClassBasename($controllerClassBasename) if (false !== strpos($controllerClassBasename, ':')) { throw new \InvalidArgumentException(sprintf( - 'The controller class name must not contain a ":" (colon sign) ("%s" given, ' - .'expecting something like PostAdminController")', + 'The controller class name must not contain a ":" (colon sign)' + .' ("%s" given, expecting something like PostAdminController")', $controllerClassBasename )); } diff --git a/src/Controller/CRUDController.php b/src/Controller/CRUDController.php index c1eed4bc75..4e03dd1038 100644 --- a/src/Controller/CRUDController.php +++ b/src/Controller/CRUDController.php @@ -16,6 +16,7 @@ use Doctrine\Inflector\InflectorFactory; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; +use Sonata\AdminBundle\Admin\AbstractAdmin; use Sonata\AdminBundle\Admin\AdminInterface; use Sonata\AdminBundle\Admin\FieldDescriptionCollection; use Sonata\AdminBundle\Datagrid\ProxyQueryInterface; @@ -92,10 +93,10 @@ public function setContainer(?ContainerInterface $container = null) */ public function render($view, array $parameters = [], ?Response $response = null) { - @trigger_error( - 'Method '.__CLASS__.'::render has been renamed to '.__CLASS__.'::renderWithExtraParams.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Method %1$s::render has been renamed to %1$s::renderWithExtraParams.', + __CLASS__ + ), E_USER_DEPRECATED); return $this->renderWithExtraParams($view, $parameters, $response); } @@ -281,13 +282,12 @@ public function deleteAction($id) // NEXT_MAJOR: Remove the unused $id parameter public function editAction($deprecatedId = null) // NEXT_MAJOR: Remove the unused $id parameter { if (isset(\func_get_args()[0])) { - @trigger_error( - sprintf( - 'Support for the "id" route param as argument 1 at `%s()` is deprecated since sonata-project/admin-bundle 3.62 and will be removed in 4.0, use `AdminInterface::getIdParameter()` instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Support for the "id" route param as argument 1 at `%s()` is deprecated since' + .' sonata-project/admin-bundle 3.62 and will be removed in 4.0,' + .' use `AdminInterface::getIdParameter()` instead.', + __METHOD__ + ), E_USER_DEPRECATED); } // the key used to lookup the template @@ -351,7 +351,7 @@ public function editAction($deprecatedId = null) // NEXT_MAJOR: Remove the unuse } catch (LockException $e) { $this->addFlash('sonata_flash_error', $this->trans('flash_lock_error', [ '%name%' => $this->escapeHtml($this->admin->toString($existingObject)), - '%link_start%' => '', + '%link_start%' => sprintf('', $this->admin->generateObjectUrl('edit', $existingObject)), '%link_end%' => '', ], 'SonataAdminBundle')); } @@ -408,7 +408,11 @@ public function batchAction() $restMethod = $this->getRestMethod(); if (Request::METHOD_POST !== $restMethod) { - throw $this->createNotFoundException(sprintf('Invalid request method given "%s", %s expected', $restMethod, Request::METHOD_POST)); + throw $this->createNotFoundException(sprintf( + 'Invalid request method given "%s", %s expected', + $restMethod, + Request::METHOD_POST + )); } // check the csrf token @@ -436,13 +440,11 @@ public function batchAction() // NEXT_MAJOR: Remove reflection check. $reflector = new \ReflectionMethod($this->admin, 'getBatchActions'); if ($reflector->getDeclaringClass()->getName() === \get_class($this->admin)) { - @trigger_error( - 'Override Sonata\AdminBundle\Admin\AbstractAdmin::getBatchActions method' - .' is deprecated since version 3.2.' - .' Use Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions instead.' - .' The method will be final in 4.0.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Override %1$s::getBatchActions method is deprecated since version 3.2.' + .' Use %1$s::configureBatchActions instead. The method will be final in 4.0.', + AbstractAdmin::class + ), E_USER_DEPRECATED); } $batchActions = $this->admin->getBatchActions(); if (!\array_key_exists($action, $batchActions)) { @@ -658,13 +660,12 @@ public function createAction() public function showAction($deprecatedId = null) // NEXT_MAJOR: Remove the unused $id parameter { if (isset(\func_get_args()[0])) { - @trigger_error( - sprintf( - 'Support for the "id" route param as argument 1 at `%s()` is deprecated since sonata-project/admin-bundle 3.62 and will be removed in 4.0, use `AdminInterface::getIdParameter()` instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Support for the "id" route param as argument 1 at `%s()` is deprecated since' + .' sonata-project/admin-bundle 3.62 and will be removed in 4.0,' + .' use `AdminInterface::getIdParameter()` instead.', + __METHOD__ + ), E_USER_DEPRECATED); } $request = $this->getRequest(); @@ -713,13 +714,12 @@ public function showAction($deprecatedId = null) // NEXT_MAJOR: Remove the unuse public function historyAction($deprecatedId = null) // NEXT_MAJOR: Remove the unused $id parameter { if (isset(\func_get_args()[0])) { - @trigger_error( - sprintf( - 'Support for the "id" route param as argument 1 at `%s()` is deprecated since sonata-project/admin-bundle 3.62 and will be removed in 4.0, use `AdminInterface::getIdParameter()` instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Support for the "id" route param as argument 1 at `%s()` is deprecated since' + .' sonata-project/admin-bundle 3.62 and will be removed in 4.0,' + .' use `AdminInterface::getIdParameter()` instead.', + __METHOD__ + ), E_USER_DEPRECATED); } $request = $this->getRequest(); @@ -735,12 +735,10 @@ public function historyAction($deprecatedId = null) // NEXT_MAJOR: Remove the un $manager = $this->get('sonata.admin.audit.manager'); if (!$manager->hasReader($this->admin->getClass())) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the audit reader for class : %s', - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the audit reader for class : %s', + $this->admin->getClass() + )); } $reader = $manager->getReader($this->admin->getClass()); @@ -785,12 +783,10 @@ public function historyViewRevisionAction($id = null, $revision = null) // NEXT_ $manager = $this->get('sonata.admin.audit.manager'); if (!$manager->hasReader($this->admin->getClass())) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the audit reader for class : %s', - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the audit reader for class : %s', + $this->admin->getClass() + )); } $reader = $manager->getReader($this->admin->getClass()); @@ -799,14 +795,12 @@ public function historyViewRevisionAction($id = null, $revision = null) // NEXT_ $object = $reader->find($this->admin->getClass(), $id, $revision); if (!$object) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', - $id, - $revision, - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', + $id, + $revision, + $this->admin->getClass() + )); } $this->admin->setSubject($object); @@ -849,12 +843,10 @@ public function historyCompareRevisionsAction($id = null, $base_revision = null, $manager = $this->get('sonata.admin.audit.manager'); if (!$manager->hasReader($this->admin->getClass())) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the audit reader for class : %s', - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the audit reader for class : %s', + $this->admin->getClass() + )); } $reader = $manager->getReader($this->admin->getClass()); @@ -862,27 +854,23 @@ public function historyCompareRevisionsAction($id = null, $base_revision = null, // retrieve the base revision $base_object = $reader->find($this->admin->getClass(), $id, $base_revision); if (!$base_object) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', - $id, - $base_revision, - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', + $id, + $base_revision, + $this->admin->getClass() + )); } // retrieve the compare revision $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision); if (!$compare_object) { - throw $this->createNotFoundException( - sprintf( - 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', - $id, - $compare_revision, - $this->admin->getClass() - ) - ); + throw $this->createNotFoundException(sprintf( + 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', + $id, + $compare_revision, + $this->admin->getClass() + )); } $this->admin->setSubject($base_object); @@ -916,8 +904,7 @@ public function exportAction(Request $request) // NEXT_MAJOR: remove the check if (!$this->has('sonata.admin.admin_exporter')) { @trigger_error( - 'Not registering the exporter bundle is deprecated since version 3.14.' - .' You must register it to be able to use the export action in 4.0.', + 'Not registering the exporter bundle is deprecated since version 3.14. You must register it to be able to use the export action in 4.0.', E_USER_DEPRECATED ); $allowedExportFormats = (array) $this->admin->getExportFormats(); @@ -938,14 +925,12 @@ public function exportAction(Request $request) } if (!\in_array($format, $allowedExportFormats, true)) { - throw new \RuntimeException( - sprintf( - 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', - $format, - $this->admin->getClass(), - implode(', ', $allowedExportFormats) - ) - ); + throw new \RuntimeException(sprintf( + 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', + $format, + $this->admin->getClass(), + implode(', ', $allowedExportFormats) + )); } return $exporter->getResponse( @@ -968,13 +953,12 @@ public function exportAction(Request $request) public function aclAction($deprecatedId = null) // NEXT_MAJOR: Remove the unused $id parameter { if (isset(\func_get_args()[0])) { - @trigger_error( - sprintf( - 'Support for the "id" route param as argument 1 at `%s()` is deprecated since sonata-project/admin-bundle 3.62 and will be removed in 4.0, use `AdminInterface::getIdParameter()` instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Support for the "id" route param as argument 1 at `%s()` is deprecated since' + .' sonata-project/admin-bundle 3.62 and will be removed in 4.0,' + .' use `AdminInterface::getIdParameter()` instead.', + __METHOD__ + ), E_USER_DEPRECATED); } if (!$this->admin->isAclEnabled()) { @@ -1155,7 +1139,7 @@ protected function configure() )); } - $this->templateRegistry = $this->container->get($this->admin->getCode().'.template_registry'); + $this->templateRegistry = $this->container->get(sprintf('%s.template_registry', $this->admin->getCode())); if (!$this->templateRegistry instanceof TemplateRegistryInterface) { throw new \RuntimeException(sprintf( 'Unable to find the template registry related to the current admin (%s)', @@ -1561,8 +1545,7 @@ private function checkParentChildAssociation(Request $request, $object): void if ($parentAdmin->getObject($parentId) !== $propertyAccessor->getValue($object, $propertyPath)) { // NEXT_MAJOR: make this exception @trigger_error( - "Accessing a child that isn't connected to a given parent is" - ." deprecated since sonata-project/admin-bundle 3.34 and won't be allowed in 4.0.", + 'Accessing a child that isn\'t connected to a given parent is deprecated since sonata-project/admin-bundle 3.34 and won\'t be allowed in 4.0.', E_USER_DEPRECATED ); } diff --git a/src/Controller/CoreController.php b/src/Controller/CoreController.php index ab3d55911d..b0e30cc9fe 100644 --- a/src/Controller/CoreController.php +++ b/src/Controller/CoreController.php @@ -15,11 +15,11 @@ // NEXT_MAJOR: remove this file -@trigger_error( - 'The '.__NAMESPACE__.'\CoreController class is deprecated since version 3.36 and will be removed in 4.0.' - .' Use '.__NAMESPACE__.'\SearchAction or '.__NAMESPACE__.'\DashboardAction instead.', - E_USER_DEPRECATED -); +@trigger_error(sprintf( + 'The %1$s\CoreController class is deprecated since version 3.36 and will be removed in 4.0.' + .' Use %1$s\SearchAction or %1$s\DashboardAction instead.', + __NAMESPACE__ +), E_USER_DEPRECATED); use Sonata\AdminBundle\Action\DashboardAction; use Sonata\AdminBundle\Action\SearchAction; @@ -75,11 +75,12 @@ public function searchAction(Request $request) */ public function getRequest() { - @trigger_error( - 'The '.__METHOD__.' method is deprecated since 3.0 and will be removed in 4.0.'. - ' Inject the Symfony\Component\HttpFoundation\Request into the actions instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s method is deprecated since 3.0 and will be removed in 4.0.' + .' Inject the %s into the actions instead.', + __METHOD__, + Request::class + ), E_USER_DEPRECATED); return $this->getCurrentRequest(); } diff --git a/src/Controller/HelperController.php b/src/Controller/HelperController.php index 0ff2695c6d..ef18b130a7 100644 --- a/src/Controller/HelperController.php +++ b/src/Controller/HelperController.php @@ -28,11 +28,11 @@ use Symfony\Component\Validator\Validator\ValidatorInterface; use Twig\Environment; -@trigger_error( - 'The '.__NAMESPACE__.'\HelperController class is deprecated since version 3.38.0 and will be removed in 4.0.' +@trigger_error(sprintf( + 'The %s\HelperController class is deprecated since version 3.38.0 and will be removed in 4.0.' .' Use actions inside Sonata\AdminBundle\Action instead.', - E_USER_DEPRECATED -); + __NAMESPACE__ +), E_USER_DEPRECATED); /** * NEXT_MAJOR: remove this class. @@ -70,10 +70,11 @@ public function __construct(Environment $twig, Pool $pool, AdminHelper $helper, { // NEXT_MAJOR: Move ValidatorInterface check to method signature if (!($validator instanceof ValidatorInterface)) { - throw new \InvalidArgumentException( - 'Argument 4 is an instance of '.\get_class($validator).', expecting an instance of' - .' \Symfony\Component\Validator\Validator\ValidatorInterface' - ); + throw new \InvalidArgumentException(sprintf( + 'Argument 4 is an instance of %s, expecting an instance of %s', + \get_class($validator), + ValidatorInterface::class + )); } $this->twig = $twig; diff --git a/src/Controller/PolyfillControllerTrait.php b/src/Controller/PolyfillControllerTrait.php index 306142054b..58ba26cdf8 100644 --- a/src/Controller/PolyfillControllerTrait.php +++ b/src/Controller/PolyfillControllerTrait.php @@ -43,7 +43,7 @@ public function render($view, array $parameters = [], ?Response $response = null final protected function proxyToControllerClass($methodName, $arguments) { if (!method_exists(Controller::class, $methodName)) { - throw new \LogicException('Call to undefined method '.__CLASS__.'::'.$methodName); + throw new \LogicException(sprintf('Call to undefined method %s::%s', __CLASS__, $methodName)); } $controller = new PolyfillProxyContainer($this->container); diff --git a/src/Datagrid/Datagrid.php b/src/Datagrid/Datagrid.php index 6021cec209..9b8140a03d 100644 --- a/src/Datagrid/Datagrid.php +++ b/src/Datagrid/Datagrid.php @@ -215,7 +215,8 @@ public function getFilter($name) { if (!$this->hasFilter($name)) { @trigger_error(sprintf( - 'Passing a nonexistent filter name as argument 1 to %s() is deprecated since sonata-project/admin-bundle 3.52 and will throw an exception in 4.0.', + 'Passing a nonexistent filter name as argument 1 to %s() is deprecated since' + .' sonata-project/admin-bundle 3.52 and will throw an exception in 4.0.', __METHOD__ ), E_USER_DEPRECATED); diff --git a/src/Datagrid/DatagridMapper.php b/src/Datagrid/DatagridMapper.php index 4468174b94..b8ce50a972 100644 --- a/src/Datagrid/DatagridMapper.php +++ b/src/Datagrid/DatagridMapper.php @@ -77,7 +77,10 @@ public function add( $fieldDescription->mergeOptions($filterOptions); } elseif (\is_string($name)) { if ($this->admin->hasFilterFieldDescription($name)) { - throw new \LogicException(sprintf('Duplicate field name "%s" in datagrid mapper. Names should be unique.', $name)); + throw new \LogicException(sprintf( + 'Duplicate field name "%s" in datagrid mapper. Names should be unique.', + $name + )); } if (!isset($filterOptions['field_name'])) { diff --git a/src/Datagrid/ListMapper.php b/src/Datagrid/ListMapper.php index 2322bb27a4..5c8aae804a 100644 --- a/src/Datagrid/ListMapper.php +++ b/src/Datagrid/ListMapper.php @@ -109,8 +109,7 @@ public function add($name, $type = null, array $fieldDescriptionOptions = []) if ('_action' === $name && self::TYPE_ACTIONS === $type) { if (isset($fieldDescriptionOptions['actions']['view'])) { @trigger_error( - 'Inline action "view" is deprecated since version 2.2.4 and will be removed in 4.0. ' - .'Use inline action "show" instead.', + 'Inline action "view" is deprecated since version 2.2.4 and will be removed in 4.0. Use inline action "show" instead.', E_USER_DEPRECATED ); @@ -128,7 +127,10 @@ public function add($name, $type = null, array $fieldDescriptionOptions = []) $fieldDescriptionOptions['identifier'] = (bool) $fieldDescriptionOptions['identifier']; // NEXT_MAJOR: Remove the previous 6 lines and use commented line below it instead - // throw new \InvalidArgumentException(sprintf('Value for "identifier" option must be boolean, %s given.', gettype($fieldDescriptionOptions['identifier']))); + // throw new \InvalidArgumentException(sprintf( + // 'Value for "identifier" option must be boolean, %s given.', + // gettype($fieldDescriptionOptions['identifier']) + // )); } if ($name instanceof FieldDescriptionInterface) { @@ -149,8 +151,8 @@ public function add($name, $type = null, array $fieldDescriptionOptions = []) ); } else { throw new \TypeError( - 'Unknown field name in list mapper. ' - .'Field name should be either of FieldDescriptionInterface interface or string.' + 'Unknown field name in list mapper.' + .' Field name should be either of FieldDescriptionInterface interface or string.' ); } diff --git a/src/Datagrid/Pager.php b/src/Datagrid/Pager.php index 9a012ee60b..a13f76a786 100644 --- a/src/Datagrid/Pager.php +++ b/src/Datagrid/Pager.php @@ -265,11 +265,11 @@ public function getFirstIndex() */ public function getFirstIndice() { - @trigger_error( - 'Method '.__METHOD__.' is deprecated since version 3.11 and will be removed in 4.0, '. - 'please use getFirstIndex() instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Method %s is deprecated since version 3.11 and will be removed in 4.0,' + .' please use getFirstIndex() instead.', + __METHOD__ + ), E_USER_DEPRECATED); return $this->getFirstIndex(); } @@ -298,11 +298,11 @@ public function getLastIndex() */ public function getLastIndice() { - @trigger_error( - 'Method '.__METHOD__.' is deprecated since version 3.11 and will be removed in 4.0, '. - 'please use getLastIndex() instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Method %s is deprecated since version 3.11 and will be removed in 4.0,' + .' please use getLastIndex() instead.', + __METHOD__ + ), E_USER_DEPRECATED); return $this->getLastIndex(); } diff --git a/src/DependencyInjection/Compiler/AddDependencyCallsCompilerPass.php b/src/DependencyInjection/Compiler/AddDependencyCallsCompilerPass.php index 388dc5ea18..9ee3b71953 100644 --- a/src/DependencyInjection/Compiler/AddDependencyCallsCompilerPass.php +++ b/src/DependencyInjection/Compiler/AddDependencyCallsCompilerPass.php @@ -243,6 +243,7 @@ public function applyConfigurationFromAttribute(Definition $definition, array $a foreach ($keys as $key) { $method = $this->generateSetterMethodName($key); + if (!isset($attributes[$key]) || $definition->hasMethodCall($method)) { continue; } @@ -407,7 +408,7 @@ public function fixTemplates( $definedTemplates = $overwrittenTemplates['view'] + $definedTemplates; - $templateRegistryId = $serviceId.'.template_registry'; + $templateRegistryId = sprintf('%s.template_registry', $serviceId); $templateRegistryDefinition = $container ->register($templateRegistryId, TemplateRegistry::class) ->addTag('sonata.admin.template_registry') diff --git a/src/DependencyInjection/Compiler/ExtensionCompilerPass.php b/src/DependencyInjection/Compiler/ExtensionCompilerPass.php index a803527935..8948f1d799 100644 --- a/src/DependencyInjection/Compiler/ExtensionCompilerPass.php +++ b/src/DependencyInjection/Compiler/ExtensionCompilerPass.php @@ -68,9 +68,10 @@ public function process(ContainerBuilder $container) foreach ($extensions as $extension => $attributes) { if (!$container->has($extension)) { - throw new \InvalidArgumentException( - sprintf('Unable to find extension service for id %s', $extension) - ); + throw new \InvalidArgumentException(sprintf( + 'Unable to find extension service for id %s', + $extension + )); } $this->addExtension($targets, $id, $extension, $attributes); diff --git a/src/DependencyInjection/Compiler/ModelManagerCompilerPass.php b/src/DependencyInjection/Compiler/ModelManagerCompilerPass.php index 20c87414c3..28255547dd 100644 --- a/src/DependencyInjection/Compiler/ModelManagerCompilerPass.php +++ b/src/DependencyInjection/Compiler/ModelManagerCompilerPass.php @@ -42,13 +42,18 @@ public function process(ContainerBuilder $container): void } if (!is_subclass_of($definition->getClass(), ModelManagerInterface::class)) { - throw new LogicException(sprintf('Service "%s" must implement `%s`.', $id, ModelManagerInterface::class)); + throw new LogicException(sprintf( + 'Service "%s" must implement `%s`.', + $id, + ModelManagerInterface::class + )); } // NEXT_MAJOR: Remove this check. if (!$definition->hasTag(self::MANAGER_TAG)) { @trigger_error(sprintf( - 'Not setting the "%s" tag on the "%s" service is deprecated since sonata-project/admin-bundle 3.60.', + 'Not setting the "%s" tag on the "%s" service is deprecated since' + .' sonata-project/admin-bundle 3.60.', self::MANAGER_TAG, $id ), E_USER_DEPRECATED); diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 316ce810e2..05bc2ed395 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -141,15 +141,15 @@ public function getConfigTreeBuilder() ->scalarNode('form_type')->defaultValue('standard')->end() ->scalarNode('default_group') ->defaultValue('default') - ->info("Group used for admin services if one isn't provided.") + ->info('Group used for admin services if one isn\'t provided.') ->end() ->scalarNode('default_label_catalogue') ->defaultValue('SonataAdminBundle') - ->info("Label Catalogue used for admin services if one isn't provided.") + ->info('Label Catalogue used for admin services if one isn\'t provided.') ->end() ->scalarNode('default_icon') ->defaultValue('') - ->info("Icon used for admin services if one isn't provided.") + ->info('Icon used for admin services if one isn\'t provided.') ->end() ->integerNode('dropdown_number_groups_per_colums')->defaultValue(2)->end() ->enumNode('title_mode') @@ -171,8 +171,8 @@ public function getConfigTreeBuilder() ->setDeprecated('The child node "%node%" at path "%path%" is deprecated since sonata-project/admin-bundle 3.70 and will be removed in 4.0.') ->defaultValue(static function (): bool { @trigger_error( - 'Using `true` as value for "sonata_admin.options.legacy_twig_text_extension" option is deprecated since sonata-project/admin-bundle 3.64. '. - 'You should set it to `false`, which will be the default value since version 4.0.' + 'Using `true` as value for "sonata_admin.options.legacy_twig_text_extension" option is deprecated since sonata-project/admin-bundle 3.64. ' + .'You should set it to `false`, which will be the default value since version 4.0.' ); return true; @@ -181,8 +181,8 @@ public function getConfigTreeBuilder() ->ifTrue() ->then(static function (bool $v): bool { @trigger_error( - 'Using `true` as value for "sonata_admin.options.legacy_twig_text_extension" option is deprecated since sonata-project/admin-bundle 3.64 and will be remove in 4.0'. - 'You should set it to `false` before upgrade process.' + 'Using `true` as value for "sonata_admin.options.legacy_twig_text_extension" option is deprecated since sonata-project/admin-bundle 3.64 and will be remove in 4.0' + .'You should set it to `false` before upgrade process.' ); return $v; @@ -206,7 +206,10 @@ public function getConfigTreeBuilder() $disallowedItems = ['items', 'label']; foreach ($disallowedItems as $item) { if (isset($items[$item])) { - throw new \InvalidArgumentException(sprintf('The config value "%s" cannot be used alongside "provider" config value', $item)); + throw new \InvalidArgumentException(sprintf( + 'The config value "%s" cannot be used alongside "provider" config value', + $item + )); } } } diff --git a/src/EventListener/AssetsInstallCommandListener.php b/src/EventListener/AssetsInstallCommandListener.php index 6462353c7a..49ca8b7ab0 100644 --- a/src/EventListener/AssetsInstallCommandListener.php +++ b/src/EventListener/AssetsInstallCommandListener.php @@ -45,7 +45,11 @@ final class AssetsInstallCommandListener public function __construct(Filesystem $filesystem, ?string $projectDir = null) { if (null === $projectDir) { - @trigger_error(sprintf('Not passing the project directory to the constructor of %s is deprecated since Symfony 4.3 and will not be supported in 5.0.', __CLASS__), E_USER_DEPRECATED); + @trigger_error(sprintf( + 'Not passing the project directory to the constructor of %s is deprecated since Symfony 4.3' + .' and will not be supported in 5.0.', + __CLASS__ + ), E_USER_DEPRECATED); } $this->filesystem = $filesystem; @@ -88,7 +92,10 @@ protected function execute(InputInterface $input, OutputInterface $output, Frame $targetArg = $kernel->getProjectDir().'/'.$targetArg; if (!is_dir($targetArg)) { - throw new InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target'))); + throw new InvalidArgumentException(sprintf( + 'The target directory "%s" does not exist.', + $input->getArgument('target') + )); } } @@ -218,7 +225,10 @@ private function symlink(string $originDir, string $targetDir, bool $relative = } $this->filesystem->symlink($originDir, $targetDir); if (!file_exists($targetDir)) { - throw new IOException(sprintf('Symbolic link "%s" was created but appears to be broken.', $targetDir), 0, null, $targetDir); + throw new IOException(sprintf( + 'Symbolic link "%s" was created but appears to be broken.', + $targetDir + ), 0, null, $targetDir); } } diff --git a/src/Export/Exporter.php b/src/Export/Exporter.php index b44e7a4820..39f5c23cd1 100644 --- a/src/Export/Exporter.php +++ b/src/Export/Exporter.php @@ -26,11 +26,11 @@ class Exporter extends CoreExporter { public function __construct() { - @trigger_error( - 'The '.__NAMESPACE__.'\Exporter class is deprecated since version 3.14 and will be removed in 4.0.'. - ' Use \Sonata\Exporter\Exporter instead', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s\Exporter class is deprecated since version 3.14 and will be removed in 4.0.' + .' Use \Sonata\Exporter\Exporter instead', + __NAMESPACE__ + ), E_USER_DEPRECATED); } } } else { diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 323663dc9d..74506977e2 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -116,7 +116,10 @@ public function getFieldName() $fieldName = $this->getOption('field_name'); if (!$fieldName) { - throw new \RuntimeException(sprintf('The option `field_name` must be set for field: `%s`', $this->getName())); + throw new \RuntimeException(sprintf( + 'The option `field_name` must be set for field: `%s`', + $this->getName() + )); } return $fieldName; @@ -132,7 +135,10 @@ public function getFieldMapping() $fieldMapping = $this->getOption('field_mapping'); if (!$fieldMapping) { - throw new \RuntimeException(sprintf('The option `field_mapping` must be set for field: `%s`', $this->getName())); + throw new \RuntimeException(sprintf( + 'The option `field_mapping` must be set for field: `%s`', + $this->getName() + )); } return $fieldMapping; @@ -143,7 +149,10 @@ public function getAssociationMapping() $associationMapping = $this->getOption('association_mapping'); if (!$associationMapping) { - throw new \RuntimeException(sprintf('The option `association_mapping` must be set for field: `%s`', $this->getName())); + throw new \RuntimeException(sprintf( + 'The option `association_mapping` must be set for field: `%s`', + $this->getName() + )); } return $associationMapping; diff --git a/src/Filter/FilterFactory.php b/src/Filter/FilterFactory.php index ed6c1e9498..a9ffcc14d7 100644 --- a/src/Filter/FilterFactory.php +++ b/src/Filter/FilterFactory.php @@ -53,11 +53,12 @@ public function create($name, $type, array $options = []) $filter = $this->container->get($id); if ($filter && !class_exists($type)) { - @trigger_error( - 'Referencing a filter by name ('.$type.') is deprecated since version 3.57 and will be removed in 4.0.' - .' Use the fully-qualified type class name instead ('.\get_class($filter).')', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Referencing a filter by name (%s) is deprecated since version 3.57 and will be removed in 4.0.' + .' Use the fully-qualified type class name instead (%s)', + $type, + \get_class($filter) + ), E_USER_DEPRECATED); } } elseif (class_exists($type)) { $filter = new $type(); diff --git a/src/Filter/Persister/SessionFilterPersister.php b/src/Filter/Persister/SessionFilterPersister.php index baca45d9d7..26ea208f21 100644 --- a/src/Filter/Persister/SessionFilterPersister.php +++ b/src/Filter/Persister/SessionFilterPersister.php @@ -53,6 +53,6 @@ public function reset($adminCode): void */ private function buildStorageKey(string $adminCode): string { - return $adminCode.'.filter.parameters'; + return sprintf('%s.filter.parameters', $adminCode); } } diff --git a/src/Form/ChoiceList/ModelChoiceLoader.php b/src/Form/ChoiceList/ModelChoiceLoader.php index cd5ddd0b8b..f03eb81049 100644 --- a/src/Form/ChoiceList/ModelChoiceLoader.php +++ b/src/Form/ChoiceList/ModelChoiceLoader.php @@ -111,7 +111,11 @@ public function loadChoiceList($value = null) try { $valueObject = (string) $model; } catch (\Exception $e) { - throw new RuntimeException(sprintf('Unable to convert the entity "%s" to string, provide "property" option or implement "__toString()" method in your entity.', ClassUtils::getClass($model)), 0, $e); + throw new RuntimeException(sprintf( + 'Unable to convert the entity "%s" to string, provide "property" option' + .' or implement "__toString()" method in your entity.', + ClassUtils::getClass($model) + ), 0, $e); } } @@ -159,7 +163,10 @@ private function getIdentifierValues($model): array try { return $this->modelManager->getIdentifierValues($model); } catch (\Exception $e) { - throw new \InvalidArgumentException(sprintf('Unable to retrieve the identifier values for entity %s', ClassUtils::getClass($model)), 0, $e); + throw new \InvalidArgumentException(sprintf( + 'Unable to retrieve the identifier values for entity %s', + ClassUtils::getClass($model) + ), 0, $e); } } } diff --git a/src/Form/DataTransformer/ModelToIdPropertyTransformer.php b/src/Form/DataTransformer/ModelToIdPropertyTransformer.php index a63c3b76b7..04efa610b6 100644 --- a/src/Form/DataTransformer/ModelToIdPropertyTransformer.php +++ b/src/Form/DataTransformer/ModelToIdPropertyTransformer.php @@ -113,17 +113,30 @@ public function transform($entityOrCollection) if ($this->multiple) { $isArray = \is_array($entityOrCollection); if (!$isArray && substr(\get_class($entityOrCollection), -1 * \strlen($this->className)) === $this->className) { - throw new \InvalidArgumentException('A multiple selection must be passed a collection not a single value. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); - } elseif ($isArray || ($entityOrCollection instanceof \ArrayAccess)) { + throw new \InvalidArgumentException( + 'A multiple selection must be passed a collection not a single value.' + .' Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true"' + .' is set for many-to-many or one-to-many relations.' + ); + } + if ($isArray || ($entityOrCollection instanceof \ArrayAccess)) { $collection = $entityOrCollection; } else { - throw new \InvalidArgumentException('A multiple selection must be passed a collection not a single value. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); + throw new \InvalidArgumentException( + 'A multiple selection must be passed a collection not a single value.' + .' Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true"' + .' is set for many-to-many or one-to-many relations.' + ); } } else { if (substr(\get_class($entityOrCollection), -1 * \strlen($this->className)) === $this->className) { $collection = [$entityOrCollection]; } elseif ($entityOrCollection instanceof \ArrayAccess) { - throw new \InvalidArgumentException('A single selection must be passed a single value not a collection. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); + throw new \InvalidArgumentException( + 'A single selection must be passed a single value not a collection.' + .' Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true"' + .' is set for many-to-many or one-to-many relations.' + ); } else { $collection = [$entityOrCollection]; } @@ -138,7 +151,9 @@ public function transform($entityOrCollection) if (null !== $this->toStringCallback) { if (!\is_callable($this->toStringCallback)) { - throw new \RuntimeException('Callback in "to_string_callback" option doesn`t contain callable function.'); + throw new \RuntimeException( + 'Callback in "to_string_callback" option doesn`t contain callable function.' + ); } $label = ($this->toStringCallback)($model, $this->property); @@ -146,7 +161,10 @@ public function transform($entityOrCollection) try { $label = (string) $model; } catch (\Exception $e) { - throw new \RuntimeException(sprintf("Unable to convert the entity %s to String, entity must have a '__toString()' method defined", ClassUtils::getClass($model)), 0, $e); + throw new \RuntimeException(sprintf( + 'Unable to convert the entity %s to String, entity must have a \'__toString()\' method defined', + ClassUtils::getClass($model) + ), 0, $e); } } diff --git a/src/Form/DataTransformer/ModelsToArrayTransformer.php b/src/Form/DataTransformer/ModelsToArrayTransformer.php index c4b3a04cbf..c0343789c6 100644 --- a/src/Form/DataTransformer/ModelsToArrayTransformer.php +++ b/src/Form/DataTransformer/ModelsToArrayTransformer.php @@ -159,7 +159,10 @@ public function reverseTransform($keys) } if (\count($notFound) > 0) { - throw new TransformationFailedException(sprintf('The entities with keys "%s" could not be found', implode('", "', $notFound))); + throw new TransformationFailedException(sprintf( + 'The entities with keys "%s" could not be found', + implode('", "', $notFound) + )); } return $collection; @@ -176,8 +179,10 @@ private function legacyConstructor(array $args): void if (!$choiceList instanceof ModelChoiceLoader && !$choiceList instanceof LazyChoiceList) { - throw new RuntimeException('First param passed to ModelsToArrayTransformer should be instance of - ModelChoiceLoader or LazyChoiceList'); + throw new RuntimeException( + 'First param passed to ModelsToArrayTransformer' + .' should be instance of ModelChoiceLoader or LazyChoiceList' + ); } $this->choiceList = $choiceList; @@ -193,7 +198,10 @@ private function getIdentifierValues($model): array try { return $this->modelManager->getIdentifierValues($model); } catch (\Exception $e) { - throw new \InvalidArgumentException(sprintf('Unable to retrieve the identifier values for entity %s', ClassUtils::getClass($model)), 0, $e); + throw new \InvalidArgumentException(sprintf( + 'Unable to retrieve the identifier values for entity %s', + ClassUtils::getClass($model) + ), 0, $e); } } diff --git a/src/Form/FormMapper.php b/src/Form/FormMapper.php index bddf2fecd2..49d3b32be8 100644 --- a/src/Form/FormMapper.php +++ b/src/Form/FormMapper.php @@ -195,7 +195,7 @@ public function removeGroup($group, $tab = 'default', $deleteEmptyTab = false) // When the default tab is used, the tabname is not prepended to the index in the group array if ('default' !== $tab) { - $group = $tab.'.'.$group; + $group = sprintf('%s.%s', $tab, $group); } if (isset($groups[$group])) { diff --git a/src/Form/Type/AdminType.php b/src/Form/Type/AdminType.php index a3a3f59d5d..98109d03a3 100644 --- a/src/Form/Type/AdminType.php +++ b/src/Form/Type/AdminType.php @@ -96,7 +96,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) '', array_map( static function (array $associationMapping): string { - return $associationMapping['fieldName'].'.'; + return sprintf('%s.', $associationMapping['fieldName']); }, $this->getFieldDescription($options)->getParentAssociationMappings() ) diff --git a/src/Form/Type/ModelTypeList.php b/src/Form/Type/ModelTypeList.php index cd52fbf675..a510706c21 100644 --- a/src/Form/Type/ModelTypeList.php +++ b/src/Form/Type/ModelTypeList.php @@ -13,11 +13,11 @@ namespace Sonata\AdminBundle\Form\Type; -@trigger_error( - 'The '.__NAMESPACE__.'\ModelTypeList class is deprecated since version 3.5 and will be removed in 4.0.' - .' Use '.__NAMESPACE__.'\ModelListType instead.', - E_USER_DEPRECATED -); +@trigger_error(sprintf( + 'The %s1$\ModelTypeList class is deprecated since version 3.5 and will be removed in 4.0.' + .' Use %1$s\ModelListType instead.', + __NAMESPACE__ +), E_USER_DEPRECATED); /** * This type is used to render an hidden input text and 3 links diff --git a/src/Maker/AdminMaker.php b/src/Maker/AdminMaker.php index 1aec6e3e07..ee60d304f5 100644 --- a/src/Maker/AdminMaker.php +++ b/src/Maker/AdminMaker.php @@ -74,7 +74,7 @@ public function __construct($projectDirectory, array $modelManagers = []) { $this->projectDirectory = $projectDirectory; $this->availableModelManagers = $modelManagers; - $this->skeletonDirectory = __DIR__.'/../Resources/skeleton'; + $this->skeletonDirectory = sprintf('%s/../Resources/skeleton', __DIR__); } public static function getCommandName(): string @@ -108,7 +108,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma $this->adminClassBasename = $io->ask( 'The admin class basename', - $input->getOption('admin') ?: $this->modelClassBasename.'Admin', + $input->getOption('admin') ?: sprintf('%sAdmin', $this->modelClassBasename), [Validators::class, 'validateAdminClassBasename'] ); if (\count($this->availableModelManagers) > 1) { @@ -120,14 +120,14 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma if ($io->confirm('Do you want to generate a controller?', false)) { $this->controllerClassBasename = $io->ask( 'The controller class basename', - $input->getOption('controller') ?: $this->modelClassBasename.'AdminController', + $input->getOption('controller') ?: sprintf('%sAdminController', $this->modelClassBasename), [Validators::class, 'validateControllerClassBasename'] ); $input->setOption('controller', $this->controllerClassBasename); } $input->setOption('services', false); if ($io->confirm('Do you want to update the services YAML configuration file?', true)) { - $path = $this->projectDirectory.'/config/'; + $path = sprintf('%s/config/', $this->projectDirectory); $servicesFile = $io->ask( 'The services YAML configuration file', is_file($path.'admin.yaml') ? 'admin.yaml' : 'services.yaml', @@ -235,7 +235,7 @@ private function generateController( $controllerClassFullName = $controllerClassNameDetails->getFullName(); $generator->generateClass( $controllerClassFullName, - $this->skeletonDirectory.'/AdminController.tpl.php', + sprintf('%s/AdminController.tpl.php', $this->skeletonDirectory), [] ); $generator->writeChanges(); @@ -265,7 +265,7 @@ private function generateAdmin( $generator->generateClass( $adminClassFullName, - $this->skeletonDirectory.'/Admin.tpl.php', + sprintf('%s/Admin.tpl.php', $this->skeletonDirectory), ['fields' => $fieldString] ); @@ -284,7 +284,7 @@ private function configure(InputInterface $input): void $this->modelClass = Validators::validateClass($input->getArgument('model')); $this->modelClassBasename = (new \ReflectionClass($this->modelClass))->getShortName(); $this->adminClassBasename = Validators::validateAdminClassBasename( - $input->getOption('admin') ?: $this->modelClassBasename.'Admin' + $input->getOption('admin') ?: sprintf('%sAdmin', $this->modelClassBasename) ); if ($this->controllerClassBasename = $input->getOption('controller')) { diff --git a/src/Mapper/BaseGroupedMapper.php b/src/Mapper/BaseGroupedMapper.php index 9f1aac2918..449735c9c8 100644 --- a/src/Mapper/BaseGroupedMapper.php +++ b/src/Mapper/BaseGroupedMapper.php @@ -103,8 +103,14 @@ public function with($name, array $options = []) throw new \LogicException('New tab was added automatically when you have added field or group. You should close current tab before adding new one OR add tabs before adding groups and fields.'); } - throw new \LogicException(sprintf('You should close previous tab "%s" with end() before adding new tab "%s".', $this->currentTab, $name)); - } elseif ($this->currentGroup) { + throw new \LogicException(sprintf( + 'You should close previous tab "%s" with end() before adding new tab "%s".', + $this->currentTab, + $name + )); + } + + if ($this->currentGroup) { throw new \LogicException(sprintf('You should open tab before adding new group "%s".', $name)); } @@ -120,7 +126,11 @@ public function with($name, array $options = []) $this->currentTab = $code; } else { if ($this->currentGroup) { - throw new \LogicException(sprintf('You should close previous group "%s" with end() before adding new tab "%s".', $this->currentGroup, $name)); + throw new \LogicException(sprintf( + 'You should close previous group "%s" with end() before adding new tab "%s".', + $this->currentGroup, + $name + )); } if (!$this->currentTab) { @@ -134,7 +144,8 @@ public function with($name, array $options = []) // if no tab is selected, we go the the main one named '_' .. if ('default' !== $this->currentTab) { - $code = $this->currentTab.'.'.$name; // groups with the same name can be on different tabs, so we prefix them in order to make unique group name + // groups with the same name can be on different tabs, so we prefix them in order to make unique group name + $code = sprintf('%s.%s', $this->currentTab, $name); } $groups = $this->getGroups(); @@ -271,7 +282,10 @@ abstract protected function setTabs(array $tabs); */ protected function getName() { - @trigger_error(__METHOD__.' should be implemented and will be abstract in 4.0.', E_USER_DEPRECATED); + @trigger_error(sprintf( + '%s should be implemented and will be abstract in 4.0.', + __METHOD__ + ), E_USER_DEPRECATED); return 'default'; } diff --git a/src/Menu/Matcher/Voter/AdminVoter.php b/src/Menu/Matcher/Voter/AdminVoter.php index a84ed0f2ee..ce477ac8d2 100644 --- a/src/Menu/Matcher/Voter/AdminVoter.php +++ b/src/Menu/Matcher/Voter/AdminVoter.php @@ -50,15 +50,11 @@ public function __construct(?RequestStack $requestStack = null) */ public function setRequest($request) { - @trigger_error( - sprintf( - 'The %s() method is deprecated since version 3.31. - Pass a Symfony\Component\HttpFoundation\RequestStack - in the constructor instead.', - __METHOD__ - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'The %s() method is deprecated since version 3.31. Pass a %s in the constructor instead.', + __METHOD__, + RequestStack::class + ), E_USER_DEPRECATED); $this->request = $request; diff --git a/src/Menu/Matcher/Voter/ChildrenVoter.php b/src/Menu/Matcher/Voter/ChildrenVoter.php index c6e0ee65d9..4805dd49ac 100644 --- a/src/Menu/Matcher/Voter/ChildrenVoter.php +++ b/src/Menu/Matcher/Voter/ChildrenVoter.php @@ -17,10 +17,7 @@ use Knp\Menu\Matcher\MatcherInterface; use Knp\Menu\Matcher\Voter\VoterInterface; -@trigger_error(sprintf( - '"%s" is deprecated since 3.28, will be removed in 4.0.', - ChildrenVoter::class -)); +@trigger_error(sprintf('"%s" is deprecated since 3.28, will be removed in 4.0.', ChildrenVoter::class)); /** * Children menu voter based on children items. diff --git a/src/Menu/Provider/GroupMenuProvider.php b/src/Menu/Provider/GroupMenuProvider.php index fe07cacd30..6dd1e87577 100644 --- a/src/Menu/Provider/GroupMenuProvider.php +++ b/src/Menu/Provider/GroupMenuProvider.php @@ -59,15 +59,16 @@ public function __construct(FactoryInterface $menuFactory, Pool $pool, $checker * NEXT_MAJOR: Move AuthorizationCheckerInterface check to method signature. */ if (null === $checker) { - @trigger_error( - 'Passing no 3rd argument is deprecated since version 3.10 and will be mandatory in 4.0. - Pass Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface as 3rd argument.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Passing no 3rd argument is deprecated since version 3.10 and will be mandatory in 4.0.' + .' Pass %s as 3rd argument.', + AuthorizationCheckerInterface::class + ), E_USER_DEPRECATED); } elseif (!$checker instanceof AuthorizationCheckerInterface) { - throw new \InvalidArgumentException( - 'Argument 3 must be an instance of \Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface' - ); + throw new \InvalidArgumentException(sprintf( + 'Argument 3 must be an instance of %s', + AuthorizationCheckerInterface::class + )); } $this->checker = $checker; diff --git a/src/Route/DefaultRouteGenerator.php b/src/Route/DefaultRouteGenerator.php index 86b6082ee7..9a8625ee7e 100644 --- a/src/Route/DefaultRouteGenerator.php +++ b/src/Route/DefaultRouteGenerator.php @@ -152,10 +152,10 @@ private function getCode(AdminInterface $admin, string $name): string // someone provide a code, so it is a child if (strpos($name, '.')) { - return $codePrefix.'|'.$name; + return sprintf('%s|%s', $codePrefix, $name); } - return $codePrefix.'.'.$name; + return sprintf('%s.%s', $codePrefix, $name); } private function loadCache(AdminInterface $admin): void diff --git a/src/Route/PathInfoBuilder.php b/src/Route/PathInfoBuilder.php index 58d3cdf3cd..18dd09343a 100644 --- a/src/Route/PathInfoBuilder.php +++ b/src/Route/PathInfoBuilder.php @@ -39,19 +39,19 @@ public function build(AdminInterface $admin, RouteCollection $collection) $collection->add('list'); $collection->add('create'); $collection->add('batch'); - $collection->add('edit', $admin->getRouterIdParameter().'/edit'); - $collection->add('delete', $admin->getRouterIdParameter().'/delete'); - $collection->add('show', $admin->getRouterIdParameter().'/show'); + $collection->add('edit', sprintf('%s/edit', $admin->getRouterIdParameter())); + $collection->add('delete', sprintf('%s/delete', $admin->getRouterIdParameter())); + $collection->add('show', sprintf('%s/show', $admin->getRouterIdParameter())); $collection->add('export'); if ($this->manager->hasReader($admin->getClass())) { - $collection->add('history', $admin->getRouterIdParameter().'/history'); - $collection->add('history_view_revision', $admin->getRouterIdParameter().'/history/{revision}/view'); - $collection->add('history_compare_revisions', $admin->getRouterIdParameter().'/history/{base_revision}/{compare_revision}/compare'); + $collection->add('history', sprintf('%s/history', $admin->getRouterIdParameter())); + $collection->add('history_view_revision', sprintf('%s/history/{revision}/view', $admin->getRouterIdParameter())); + $collection->add('history_compare_revisions', sprintf('%s/history/{base_revision}/{compare_revision}/compare', $admin->getRouterIdParameter())); } if ($admin->isAclEnabled()) { - $collection->add('acl', $admin->getRouterIdParameter().'/acl'); + $collection->add('acl', sprintf('%s/acl', $admin->getRouterIdParameter())); } // add children urls diff --git a/src/Route/QueryStringBuilder.php b/src/Route/QueryStringBuilder.php index 7b3f202b45..3c62b8c9a6 100644 --- a/src/Route/QueryStringBuilder.php +++ b/src/Route/QueryStringBuilder.php @@ -55,7 +55,7 @@ public function build(AdminInterface $admin, RouteCollection $collection) } if ($admin->isAclEnabled()) { - $collection->add('acl', $admin->getRouterIdParameter().'/acl'); + $collection->add('acl', sprintf('%s/acl', $admin->getRouterIdParameter())); } // an admin can have only one level of nested child diff --git a/src/Route/RouteCollection.php b/src/Route/RouteCollection.php index 2e5e017a85..0e3758d991 100644 --- a/src/Route/RouteCollection.php +++ b/src/Route/RouteCollection.php @@ -87,9 +87,9 @@ public function add( array $methods = [], $condition = '' ) { - $pattern = $this->baseRoutePattern.'/'.($pattern ?: $name); + $pattern = sprintf('%s/%s', $this->baseRoutePattern, $pattern ?: $name); $code = $this->getCode($name); - $routeName = $this->baseRouteName.'_'.$name; + $routeName = sprintf('%s_%s', $this->baseRouteName, $name); if (!isset($defaults['_controller'])) { $actionJoiner = false === strpos($this->baseControllerName, '\\') ? ':' : '::'; @@ -125,7 +125,7 @@ public function getCode($name) return $name; } - return $this->baseCodeRoute.'.'.$name; + return sprintf('%s.%s', $this->baseCodeRoute, $name); } /** diff --git a/src/Route/RoutesCache.php b/src/Route/RoutesCache.php index ee77b25a8b..ef3acd730d 100644 --- a/src/Route/RoutesCache.php +++ b/src/Route/RoutesCache.php @@ -51,7 +51,7 @@ public function __construct($cacheFolder, $debug) */ public function load(AdminInterface $admin) { - $filename = $this->cacheFolder.'/route_'.md5($admin->getCode()); + $filename = sprintf('%s/route_%s', $this->cacheFolder, md5($admin->getCode())); $cache = new ConfigCache($filename, $this->debug); if (!$cache->isFresh()) { @@ -64,7 +64,9 @@ public function load(AdminInterface $admin) } if (!$admin->getRoutes()) { - throw new \RuntimeException('Invalid data type, AdminInterface::getRoutes must return a RouteCollection'); + throw new \RuntimeException( + 'Invalid data type, AdminInterface::getRoutes must return a RouteCollection' + ); } foreach ($admin->getRoutes()->getElements() as $code => $route) { diff --git a/src/Security/Handler/AclSecurityHandler.php b/src/Security/Handler/AclSecurityHandler.php index cd32d977f2..8ae5ddc138 100644 --- a/src/Security/Handler/AclSecurityHandler.php +++ b/src/Security/Handler/AclSecurityHandler.php @@ -122,7 +122,7 @@ public function isGranted(AdminInterface $admin, $attributes, $object = null) public function getBaseRole(AdminInterface $admin) { - return 'ROLE_'.str_replace('.', '_', strtoupper($admin->getCode())).'_%s'; + return sprintf('ROLE_%s_%%s', str_replace('.', '_', strtoupper($admin->getCode()))); } public function buildSecurityInformation(AdminInterface $admin) diff --git a/src/Security/Handler/RoleSecurityHandler.php b/src/Security/Handler/RoleSecurityHandler.php index 594dad7f2b..56b1615d9c 100644 --- a/src/Security/Handler/RoleSecurityHandler.php +++ b/src/Security/Handler/RoleSecurityHandler.php @@ -41,7 +41,10 @@ public function __construct($authorizationChecker, array $superAdminRoles) { // NEXT_MAJOR: Move AuthorizationCheckerInterface check to method signature if (!$authorizationChecker instanceof AuthorizationCheckerInterface) { - throw new \InvalidArgumentException('Argument 1 should be an instance of Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface'); + throw new \InvalidArgumentException(sprintf( + 'Argument 1 should be an instance of %s', + AuthorizationCheckerInterface::class + )); } $this->authorizationChecker = $authorizationChecker; @@ -71,7 +74,7 @@ public function isGranted(AdminInterface $admin, $attributes, $object = null) public function getBaseRole(AdminInterface $admin) { - return 'ROLE_'.str_replace('.', '_', strtoupper($admin->getCode())).'_%s'; + return sprintf('ROLE_%s_%%s', str_replace('.', '_', strtoupper($admin->getCode()))); } public function buildSecurityInformation(AdminInterface $admin) diff --git a/src/Show/ShowMapper.php b/src/Show/ShowMapper.php index 60ce4996ef..d8a77eb2b8 100644 --- a/src/Show/ShowMapper.php +++ b/src/Show/ShowMapper.php @@ -73,12 +73,15 @@ public function add($name, $type = null, array $fieldDescriptionOptions = []) $fieldDescriptionOptions ); } else { - throw new \LogicException(sprintf('Duplicate field name "%s" in show mapper. Names should be unique.', $name)); + throw new \LogicException(sprintf( + 'Duplicate field name "%s" in show mapper. Names should be unique.', + $name + )); } } else { throw new \TypeError( - 'Unknown field name in show mapper. ' - .'Field name should be either of FieldDescriptionInterface interface or string.' + 'Unknown field name in show mapper.' + .' Field name should be either of FieldDescriptionInterface interface or string.' ); } @@ -131,7 +134,7 @@ public function removeGroup($group, $tab = 'default', $deleteEmptyTab = false) // When the default tab is used, the tabname is not prepended to the index in the group array if ('default' !== $tab) { - $group = $tab.'.'.$group; + $group = sprintf('%s.%s', $tab, $group); } if (isset($groups[$group])) { diff --git a/src/Templating/TemplateRegistry.php b/src/Templating/TemplateRegistry.php index c29fa5506f..e08ac8127b 100644 --- a/src/Templating/TemplateRegistry.php +++ b/src/Templating/TemplateRegistry.php @@ -108,7 +108,8 @@ public function getTemplate($name): ?string } @trigger_error(sprintf( - 'Passing a nonexistent template name as argument 1 to %s() is deprecated since sonata-project/admin-bundle 3.52 and will throw an exception in 4.0.', + 'Passing a nonexistent template name as argument 1 to %s() is deprecated since' + .' sonata-project/admin-bundle 3.52 and will throw an exception in 4.0.', __METHOD__ ), E_USER_DEPRECATED); diff --git a/src/Twig/Extension/SonataAdminExtension.php b/src/Twig/Extension/SonataAdminExtension.php index ef0ff9aff9..5cf65daf71 100644 --- a/src/Twig/Extension/SonataAdminExtension.php +++ b/src/Twig/Extension/SonataAdminExtension.php @@ -402,8 +402,7 @@ public function renderRelationElement($element, FieldDescriptionInterface $field if ($method) { @trigger_error( - 'Option "associated_tostring" is deprecated since version 2.3 and will be removed in 4.0. ' - .'Use "associated_property" instead.', + 'Option "associated_tostring" is deprecated since version 2.3 and will be removed in 4.0. Use "associated_property" instead.', E_USER_DEPRECATED ); } else { @@ -412,8 +411,8 @@ public function renderRelationElement($element, FieldDescriptionInterface $field if (!method_exists($element, $method)) { throw new \RuntimeException(sprintf( - 'You must define an `associated_property` option or '. - 'create a `%s::__toString` method to the field option %s from service %s is ', + 'You must define an `associated_property` option or create a `%s::__toString` method' + .' to the field option %s from service %s is ', \get_class($element), $fieldDescription->getName(), $fieldDescription->getAdmin()->getCode() @@ -627,21 +626,17 @@ protected function getTemplate( try { $template = $environment->load($templateName); } catch (LoaderError $e) { - @trigger_error( - sprintf( - 'Relying on default template loading on field template loading exception '. - 'is deprecated since 3.1 and will be removed in 4.0. '. - 'A %s exception will be thrown instead', - LoaderError::class - ), - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Relying on default template loading on field template loading exception is deprecated since 3.1' + .' and will be removed in 4.0. A %s exception will be thrown instead', + LoaderError::class + ), E_USER_DEPRECATED); $template = $environment->load($defaultTemplate); if (null !== $this->logger) { $this->logger->warning(sprintf( - 'An error occured trying to load the template "%s" for the field "%s", '. - 'the default template "%s" was used instead.', + 'An error occured trying to load the template "%s" for the field "%s",' + .' the default template "%s" was used instead.', $templateName, $fieldDescription->getFieldName(), $defaultTemplate diff --git a/src/Twig/Extension/TemplateRegistryExtension.php b/src/Twig/Extension/TemplateRegistryExtension.php index 53f01f3b9d..33454dbb6c 100644 --- a/src/Twig/Extension/TemplateRegistryExtension.php +++ b/src/Twig/Extension/TemplateRegistryExtension.php @@ -88,7 +88,7 @@ public function getGlobalTemplate($name): ?string */ private function getTemplateRegistry(string $adminCode): TemplateRegistryInterface { - $serviceId = $adminCode.'.template_registry'; + $serviceId = sprintf('%s.template_registry', $adminCode); $templateRegistry = $this->container->get($serviceId); if ($templateRegistry instanceof TemplateRegistryInterface) { return $templateRegistry; diff --git a/src/Twig/GlobalVariables.php b/src/Twig/GlobalVariables.php index 1636a35f4b..082ec7d1f4 100644 --- a/src/Twig/GlobalVariables.php +++ b/src/Twig/GlobalVariables.php @@ -51,22 +51,22 @@ public function __construct($adminPool, ?string $mosaicBackground = null) // NEXT_MAJOR : remove this block and set adminPool from parameter. if ($adminPool instanceof ContainerInterface) { - @trigger_error( - 'Using an instance of Symfony\Component\DependencyInjection\ContainerInterface is deprecated since - version 3.5 and will be removed in 4.0. Use Sonata\AdminBundle\Admin\Pool instead.', - E_USER_DEPRECATED - ); + @trigger_error(sprintf( + 'Using an instance of %s is deprecated since version 3.5 and will be removed in 4.0. Use %s instead.', + ContainerInterface::class, + Pool::class + ), E_USER_DEPRECATED); $adminPool = $adminPool->get('sonata.admin.pool'); } + if ($adminPool instanceof Pool) { $this->adminPool = $adminPool; return; } - throw new \InvalidArgumentException( - '$adminPool should be an instance of Sonata\AdminBundle\Admin\Pool' - ); + + throw new \InvalidArgumentException(sprintf('$adminPool should be an instance of %s', Pool::class)); } /** @@ -118,7 +118,7 @@ private function getCodeAction(string $code, string $action): array if ($pipe = strpos($code, '|')) { // convert code=sonata.page.admin.page|sonata.page.admin.snapshot, action=list // to => sonata.page.admin.page|sonata.page.admin.snapshot.list - $action = $code.'.'.$action; + $action = sprintf('%s.%s', $code, $action); $code = substr($code, 0, $pipe); } diff --git a/src/Util/AdminObjectAclData.php b/src/Util/AdminObjectAclData.php index ca31db0a8e..ffa1178de2 100644 --- a/src/Util/AdminObjectAclData.php +++ b/src/Util/AdminObjectAclData.php @@ -184,8 +184,7 @@ public function getMasks() public function setForm(Form $form) { @trigger_error( - 'setForm() is deprecated since version 3.0 and will be removed in 4.0. ' - .'Use setAclUsersForm() instead.', + 'setForm() is deprecated since version 3.0 and will be removed in 4.0. Use setAclUsersForm() instead.', E_USER_DEPRECATED ); @@ -204,8 +203,7 @@ public function setForm(Form $form) public function getForm() { @trigger_error( - 'getForm() is deprecated since version 3.0 and will be removed in 4.0. ' - .'Use getAclUsersForm() instead.', + 'getForm() is deprecated since version 3.0 and will be removed in 4.0. Use getAclUsersForm() instead.', E_USER_DEPRECATED ); @@ -334,7 +332,7 @@ protected function updateMasks() $reflectionClass = new \ReflectionClass(new $this->maskBuilderClass()); $this->masks = []; foreach ($permissions as $permission) { - $this->masks[$permission] = $reflectionClass->getConstant('MASK_'.$permission); + $this->masks[$permission] = $reflectionClass->getConstant(sprintf('MASK_%s', $permission)); } } } diff --git a/src/Util/AdminObjectAclManipulator.php b/src/Util/AdminObjectAclManipulator.php index 40687a4f2a..3f93734ffe 100644 --- a/src/Util/AdminObjectAclManipulator.php +++ b/src/Util/AdminObjectAclManipulator.php @@ -77,8 +77,7 @@ public function getMaskBuilderClass() public function createForm(AdminObjectAclData $data) { @trigger_error( - 'createForm() is deprecated since version 3.0 and will be removed in 4.0. ' - .'Use createAclUsersForm() instead.', + 'createForm() is deprecated since version 3.0 and will be removed in 4.0. Use createAclUsersForm() instead.', E_USER_DEPRECATED ); @@ -147,8 +146,7 @@ public function updateAclRoles(AdminObjectAclData $data) public function updateAcl(AdminObjectAclData $data) { @trigger_error( - 'updateAcl() is deprecated since version 3.0 and will be removed in 4.0.' - .'Use updateAclUsers() instead.', + 'updateAcl() is deprecated since version 3.0 and will be removed in 4.0. Use updateAclUsers() instead.', E_USER_DEPRECATED ); diff --git a/tests/Admin/AdminHelperTest.php b/tests/Admin/AdminHelperTest.php index d1227f07ad..de277352da 100644 --- a/tests/Admin/AdminHelperTest.php +++ b/tests/Admin/AdminHelperTest.php @@ -184,7 +184,7 @@ public function testItThrowsExceptionWhenDoesNotFindTheFullPath(): void $subObject->expects($this->atLeastOnce())->method('getMore')->willReturn('Value'); $this->expectException(\Exception::class); - $this->expectExceptionMessage('Could not get element id from '.$path.' Failing part: calls'); + $this->expectExceptionMessage(sprintf('Could not get element id from %s Failing part: calls', $path)); $this->helper->getElementAccessPath($path, $object); } diff --git a/tests/Admin/AdminTest.php b/tests/Admin/AdminTest.php index 8addef408a..ba197cded9 100644 --- a/tests/Admin/AdminTest.php +++ b/tests/Admin/AdminTest.php @@ -91,7 +91,7 @@ class AdminTest extends TestCase protected function setUp(): void { - $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route'; + $this->cacheTempFolder = sprintf('%s/sonata_test_route', sys_get_temp_dir()); $filesystem = new Filesystem(); $filesystem->remove($this->cacheTempFolder); } @@ -403,7 +403,7 @@ public function testGetBaseRoutePatternWithChildAdmin(string $objFqn, string $ex $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController'); $commentAdmin->setParent($postAdmin); - $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern()); + $this->assertSame(sprintf('%s/{id}/comment', $expected), $commentAdmin->getBaseRoutePattern()); } /** @@ -425,7 +425,7 @@ public function testGetBaseRoutePatternWithTwoNestedChildAdmin(string $objFqn, s $commentAdmin->setParent($postAdmin); $commentVoteAdmin->setParent($commentAdmin); - $this->assertSame($expected.'/{id}/comment/{childId}/commentvote', $commentVoteAdmin->getBaseRoutePattern()); + $this->assertSame(sprintf('%s/{id}/comment/{childId}/commentvote', $expected), $commentVoteAdmin->getBaseRoutePattern()); } public function testGetBaseRoutePatternWithSpecifedPattern(): void @@ -583,7 +583,7 @@ public function testGetBaseRouteNameWithChildAdmin(string $objFqn, string $expec 'sonata.post.admin.comment_vote', ]); - $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName()); + $this->assertSame(sprintf('%s_comment', $expected), $commentAdmin->getBaseRouteName()); $this->assertTrue($postAdmin->hasRoute('show')); $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show')); @@ -602,7 +602,7 @@ public function testGetBaseRouteNameWithChildAdmin(string $objFqn, string $expec [], [], [ - '_route' => $postAdmin->getBaseRouteName().'_list', + '_route' => sprintf('%s_list', $postAdmin->getBaseRouteName()), ] ); @@ -1930,7 +1930,7 @@ public function provideGetSubject() ['azerty'], ['4f69bbb5f14a13347f000092'], ['0779ca8d-e2be-11e4-ac58-0242ac11000b'], - ['123'.AdapterInterface::ID_SEPARATOR.'my_type'], // composite keys are supported + [sprintf('123%smy_type', AdapterInterface::ID_SEPARATOR)], // composite keys are supported ]; } @@ -2092,7 +2092,7 @@ public function testGetBatchActions(): void $labelTranslatorStrategy ->method('getLabel') ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string { - return $context.'.'.$type.'_'.$label; + return sprintf('%s.%s_%s', $context, $type, $label); }); $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController'); @@ -2368,7 +2368,7 @@ public function testGetDataSourceIterator(): void $admin ->method('getTranslationLabel') ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string { - return $context.'.'.$type.'_'.$label; + return sprintf('%s.%s_%s', $context, $type, $label); }); $admin ->method('trans') diff --git a/tests/Admin/PoolTest.php b/tests/Admin/PoolTest.php index f332a79ac1..491c5fa0e8 100644 --- a/tests/Admin/PoolTest.php +++ b/tests/Admin/PoolTest.php @@ -193,9 +193,7 @@ public function testGetInstanceWithUndefinedServiceIdAndExistsOther(): void ]); $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Admin service "sonata.news.admin.pos" not found in admin pool. ' - .'Did you mean "sonata.news.admin.post" ' - .'or one of those: [sonata.news.admin.category]?'); + $this->expectExceptionMessage('Admin service "sonata.news.admin.pos" not found in admin pool. Did you mean "sonata.news.admin.post" or one of those: [sonata.news.admin.category]?'); $this->pool->getInstance('sonata.news.admin.pos'); } @@ -255,7 +253,7 @@ public function testGetAdminByAdminCodeWithInvalidCode(): void * * @group legacy * - * @expectedDeprecation Passing a non string value as argument 1 for Sonata\AdminBundle\Admin\Pool::getAdminByAdminCode() is deprecated since sonata-project/admin-bundle 3.51 and will cause a \TypeError in 4.0. + * @expectedDeprecation Passing a non string value as argument 1 for Sonata\AdminBundle\Admin\Pool::getAdminByAdminCode() is deprecated since sonata-project/admin-bundle 3.51 and will cause a TypeError in 4.0. */ public function testGetAdminByAdminCodeWithNonStringCode($adminId): void { diff --git a/tests/App/AppKernel.php b/tests/App/AppKernel.php index 049f1c3e25..50fb4ddadb 100644 --- a/tests/App/AppKernel.php +++ b/tests/App/AppKernel.php @@ -61,12 +61,12 @@ public function registerBundles() public function getCacheDir(): string { - return $this->getBaseDir().'cache'; + return sprintf('%scache', $this->getBaseDir()); } public function getLogDir(): string { - return $this->getBaseDir().'log'; + return sprintf('%slog', $this->getBaseDir()); } public function getProjectDir() @@ -76,7 +76,7 @@ public function getProjectDir() protected function configureRoutes(RouteCollectionBuilder $routes) { - $routes->import($this->getProjectDir().'/config/routes.yml'); + $routes->import(sprintf('%s/config/routes.yml', $this->getProjectDir())); } protected function configureContainer(ContainerBuilder $containerBuilder, LoaderInterface $loader) @@ -100,11 +100,11 @@ protected function configureContainer(ContainerBuilder $containerBuilder, Loader 'exception_controller' => null, ]); - $loader->load($this->getProjectDir().'/config/services.yml'); + $loader->load(sprintf('%s/config/services.yml', $this->getProjectDir())); } private function getBaseDir(): string { - return sys_get_temp_dir().'/sonata-admin-bundle/var/'; + return sprintf('%s/sonata-admin-bundle/var/', sys_get_temp_dir()); } } diff --git a/tests/Command/CreateClassCacheCommandTest.php b/tests/Command/CreateClassCacheCommandTest.php index 93462a3c04..2c24392eda 100644 --- a/tests/Command/CreateClassCacheCommandTest.php +++ b/tests/Command/CreateClassCacheCommandTest.php @@ -46,7 +46,7 @@ protected function setUp(): void if (mkdir($tempFile)) { $this->tempDirectory = $tempFile; - file_put_contents($this->tempDirectory.'/classes.map', 'tempDirectory), 'markTestSkipped(sprintf('Temp directory "%s" creation error.', $tempFile)); } @@ -60,12 +60,12 @@ protected function setUp(): void protected function tearDown(): void { if ($this->tempDirectory) { - if (file_exists($this->tempDirectory.'/classes.map')) { - unlink($this->tempDirectory.'/classes.map'); + if (file_exists(sprintf('%s/classes.map', $this->tempDirectory))) { + unlink(sprintf('%s/classes.map', $this->tempDirectory)); } - if (file_exists($this->tempDirectory.'/classes.php')) { - unlink($this->tempDirectory.'/classes.php'); + if (file_exists(sprintf('%s/classes.php', $this->tempDirectory))) { + unlink(sprintf('%s/classes.php', $this->tempDirectory)); } if (file_exists($this->tempDirectory) && is_dir($this->tempDirectory)) { @@ -77,8 +77,8 @@ protected function tearDown(): void public function testExecute(): void { $this->markTestSkipped(); - $this->assertFileExists($this->tempDirectory.'/classes.map'); - $this->assertFileNotExists($this->tempDirectory.'/classes.php'); + $this->assertFileExists(sprintf('%s/classes.map', $this->tempDirectory)); + $this->assertFileNotExists(sprintf('%s/classes.php', $this->tempDirectory)); $command = $this->application->find('cache:create-cache-class'); $commandTester = new CommandTester($command); @@ -86,14 +86,14 @@ public function testExecute(): void $this->assertRegExp('@Writing cache file ...\s+done!@', $commandTester->getDisplay()); - $this->assertFileExists($this->tempDirectory.'/classes.php'); - $this->assertFileEquals(__DIR__.'/../Fixtures/Command/classes.php', $this->tempDirectory.'/classes.php'); + $this->assertFileExists(sprintf('%s/classes.php', $this->tempDirectory)); + $this->assertFileEquals(sprintf('%s/../Fixtures/Command/classes.php', __DIR__), sprintf('%s/classes.php', $this->tempDirectory)); } public function testExecuteWithException(): void { - $this->assertFileExists($this->tempDirectory.'/classes.map'); - unlink($this->tempDirectory.'/classes.map'); + $this->assertFileExists(sprintf('%s/classes.map', $this->tempDirectory)); + unlink(sprintf('%s/classes.map', $this->tempDirectory)); try { $command = $this->application->find('cache:create-cache-class'); diff --git a/tests/Command/ExplainAdminCommandTest.php b/tests/Command/ExplainAdminCommandTest.php index 5310da052f..e9d6b3393d 100644 --- a/tests/Command/ExplainAdminCommandTest.php +++ b/tests/Command/ExplainAdminCommandTest.php @@ -210,7 +210,7 @@ public function testExecute(): void $commandTester->execute(['command' => $command->getName(), 'admin' => 'acme.admin.foo']); $this->assertSame(sprintf( - str_replace("\n", PHP_EOL, file_get_contents(__DIR__.'/../Fixtures/Command/explain_admin.txt')), + str_replace("\n", PHP_EOL, file_get_contents(sprintf('%s/../Fixtures/Command/explain_admin.txt', __DIR__))), \get_class($this->admin), \get_class($modelManager), \get_class($formBuilder), @@ -263,7 +263,7 @@ public function testExecuteEmptyValidator(): void str_replace( "\n", PHP_EOL, - file_get_contents(__DIR__.'/../Fixtures/Command/explain_admin_empty_validator.txt') + file_get_contents(sprintf('%s/../Fixtures/Command/explain_admin_empty_validator.txt', __DIR__)) ), \get_class($this->admin), \get_class($modelManager), diff --git a/tests/Controller/CRUDControllerTest.php b/tests/Controller/CRUDControllerTest.php index 8ff45eff5e..279d6e3bef 100644 --- a/tests/Controller/CRUDControllerTest.php +++ b/tests/Controller/CRUDControllerTest.php @@ -230,13 +230,13 @@ protected function setUp(): void $this->csrfProvider ->method('getToken') ->willReturnCallback(static function (string $intention): CsrfToken { - return new CsrfToken($intention, 'csrf-token-123_'.$intention); + return new CsrfToken($intention, sprintf('csrf-token-123_%s', $intention)); }); $this->csrfProvider ->method('isTokenValid') ->willReturnCallback(static function (CsrfToken $token): bool { - return $token->getValue() === 'csrf-token-123_'.$token->getId(); + return $token->getValue() === sprintf('csrf-token-123_%s', $token->getId()); }); $this->logger = $this->createMock(LoggerInterface::class); @@ -326,7 +326,7 @@ static function ($name, array $parameters = []) { ->method('generateObjectUrl') ->willReturnCallback( static function (string $name, $object, array $parameters = []): string { - $result = \get_class($object).'_'.$name; + $result = sprintf('%s_%s', \get_class($object), $name); if (!empty($parameters)) { $result .= '?'.http_build_query($parameters); } diff --git a/tests/Datagrid/ListMapperTest.php b/tests/Datagrid/ListMapperTest.php index f61e0dfe29..ac4ee6b6ae 100644 --- a/tests/Datagrid/ListMapperTest.php +++ b/tests/Datagrid/ListMapperTest.php @@ -278,9 +278,7 @@ public function testAddDuplicateNameException(): void public function testAddWrongTypeException(): void { $this->expectException(\TypeError::class); - $this->expectExceptionMessage( - 'Unknown field name in list mapper. Field name should be either of FieldDescriptionInterface interface or string.' - ); + $this->expectExceptionMessage('Unknown field name in list mapper. Field name should be either of FieldDescriptionInterface interface or string.'); $this->listMapper->add(12345); } @@ -288,13 +286,13 @@ public function testAddWrongTypeException(): void public function testAutoAddVirtualOption(): void { foreach (['actions', 'batch', 'select'] as $type) { - $this->listMapper->add('_'.$type, $type); + $this->listMapper->add(sprintf('_%s', $type), $type); } foreach ($this->fieldDescriptionCollection->getElements() as $field) { $this->assertTrue( $field->isVirtual(), - 'Failed asserting that FieldDescription with type "'.$field->getType().'" is tagged with virtual flag.' + sprintf('Failed asserting that FieldDescription with type "%s" is tagged with virtual flag.', $field->getType()) ); } } diff --git a/tests/DependencyInjection/Compiler/ExtensionCompilerPassTest.php b/tests/DependencyInjection/Compiler/ExtensionCompilerPassTest.php index 024f7b6032..e465f34a63 100644 --- a/tests/DependencyInjection/Compiler/ExtensionCompilerPassTest.php +++ b/tests/DependencyInjection/Compiler/ExtensionCompilerPassTest.php @@ -72,8 +72,8 @@ public function testAdminExtensionLoad(): void { $this->extension->load([], $container = $this->getContainer()); - $this->assertTrue($container->hasParameter($this->root.'.extension.map')); - $this->assertIsArray($extensionMap = $container->getParameter($this->root.'.extension.map')); + $this->assertTrue($container->hasParameter(sprintf('%s.extension.map', $this->root))); + $this->assertIsArray($extensionMap = $container->getParameter(sprintf('%s.extension.map', $this->root))); $this->assertArrayHasKey('admins', $extensionMap); $this->assertArrayHasKey('excludes', $extensionMap); @@ -89,7 +89,7 @@ public function testAdminExtensionLoad(): void public function testFlattenEmptyExtensionConfiguration(): void { $this->extension->load([], $container = $this->getContainer()); - $extensionMap = $container->getParameter($this->root.'.extension.map'); + $extensionMap = $container->getParameter(sprintf('%s.extension.map', $this->root)); $method = new \ReflectionMethod( ExtensionCompilerPass::class, @@ -121,7 +121,7 @@ public function testFlattenExtensionConfiguration(): void { $config = $this->getConfig(); $this->extension->load([$config], $container = $this->getContainer()); - $extensionMap = $container->getParameter($this->root.'.extension.map'); + $extensionMap = $container->getParameter(sprintf('%s.extension.map', $this->root)); $method = new \ReflectionMethod( ExtensionCompilerPass::class, diff --git a/tests/Export/ExporterTest.php b/tests/Export/ExporterTest.php index ae21d11831..aaad0f90bf 100644 --- a/tests/Export/ExporterTest.php +++ b/tests/Export/ExporterTest.php @@ -57,7 +57,7 @@ public function testGetResponse(string $format, string $filename, string $conten $this->assertInstanceOf(Response::class, $response); $this->assertSame($contentType, $response->headers->get('Content-Type')); // Quotes does not appear on some sonata versions. - $this->assertRegExp('/attachment; filename="?'.$filename.'"?/', $response->headers->get('Content-Disposition')); + $this->assertRegExp(sprintf('/attachment; filename="?%s"?/', $filename), $response->headers->get('Content-Disposition')); } public function getGetResponseTests() diff --git a/tests/Fixtures/Entity/FooArrayAccess.php b/tests/Fixtures/Entity/FooArrayAccess.php index aad112f688..fba4844ff9 100644 --- a/tests/Fixtures/Entity/FooArrayAccess.php +++ b/tests/Fixtures/Entity/FooArrayAccess.php @@ -45,12 +45,12 @@ public function offsetGet($offset) public function offsetSet($offset, $value): void { - throw new \BadMethodCallException('Array access of class '.\get_class($this).' is read-only!'); + throw new \BadMethodCallException(sprintf('Array access of class %s is read-only!', \get_class($this))); } public function offsetUnset($offset): void { - throw new \BadMethodCallException('Array access of class '.\get_class($this).' is read-only!'); + throw new \BadMethodCallException(sprintf('Array access of class %s is read-only!', \get_class($this))); } public function getBar() diff --git a/tests/Form/DataTransformer/ModelToIdPropertyTransformerTest.php b/tests/Form/DataTransformer/ModelToIdPropertyTransformerTest.php index 961b23f3b8..455569c43e 100644 --- a/tests/Form/DataTransformer/ModelToIdPropertyTransformerTest.php +++ b/tests/Form/DataTransformer/ModelToIdPropertyTransformerTest.php @@ -118,12 +118,8 @@ public function getReverseTransformMultipleTests() */ public function testReverseTransformMultipleInvalidTypeTests(array $expected, $params, string $type): void { - $this->expectException( - \UnexpectedValueException::class - ); - $this->expectExceptionMessage( - sprintf('Value should be array, %s given.', $type) - ); + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage(sprintf('Value should be array, %s given.', $type)); $transformer = new ModelToIdPropertyTransformer($this->modelManager, Foo::class, 'bar', true); diff --git a/tests/Form/Widget/BaseWidgetTest.php b/tests/Form/Widget/BaseWidgetTest.php index 795c1de728..e169fdcf1a 100644 --- a/tests/Form/Widget/BaseWidgetTest.php +++ b/tests/Form/Widget/BaseWidgetTest.php @@ -70,11 +70,13 @@ protected function getEnvironment(): Environment protected function getRenderingEngine(?Environment $environment = null): TwigRendererEngine { if (!\in_array($this->type, ['form', 'filter'], true)) { - throw new \Exception('Please override $this->type in your test class specifying template to use (either form or filter)'); + throw new \Exception( + 'Please override $this->type in your test class specifying template to use (either form or filter)' + ); } return new TwigRendererEngine( - [$this->type.'_admin_fields.html.twig'], + [sprintf('%s_admin_fields.html.twig', $this->type)], $environment ); } @@ -93,7 +95,7 @@ protected function getSonataAdmin() protected function getTemplatePaths(): array { return array_merge(parent::getTemplatePaths(), [ - __DIR__.'/../../../src/Resources/views/Form', + sprintf('%s/../../../src/Resources/views/Form', __DIR__), ]); } } diff --git a/tests/Maker/AdminMakerTest.php b/tests/Maker/AdminMakerTest.php index f39f6e5258..5762f5a9c8 100644 --- a/tests/Maker/AdminMakerTest.php +++ b/tests/Maker/AdminMakerTest.php @@ -79,7 +79,7 @@ protected function setup(): void $this->modelManagers = ['sonata.admin.manager.orm' => $managerOrmProxy->reveal()]; $this->servicesFile = sprintf('%s.yml', lcg_value()); - $this->projectDirectory = sys_get_temp_dir().'/sonata-admin-bundle/'; + $this->projectDirectory = sprintf('%s/sonata-admin-bundle/', sys_get_temp_dir()); $this->filesystem = new Filesystem(); } @@ -121,7 +121,7 @@ public function testExecute(): void $autoloaderUtil ->method('getPathForFutureClass') ->willReturnCallback(function (string $className): string { - return $this->projectDirectory.'/'.str_replace('\\', '/', $className).'.php'; + return sprintf('%s/%s.php', $this->projectDirectory, str_replace('\\', '/', $className)); }); $fileManager = new FileManager( diff --git a/tests/Mapper/BaseGroupedMapperTest.php b/tests/Mapper/BaseGroupedMapperTest.php index 07195c980d..e937601186 100644 --- a/tests/Mapper/BaseGroupedMapperTest.php +++ b/tests/Mapper/BaseGroupedMapperTest.php @@ -47,7 +47,7 @@ protected function setUp(): void $labelStrategy ->method('getLabel') ->willReturnCallback(static function (string $label): string { - return 'label_'.strtolower($label); + return sprintf('label_%s', strtolower($label)); }); $admin diff --git a/tests/Menu/Integration/BaseMenuTest.php b/tests/Menu/Integration/BaseMenuTest.php index 582a2c3306..8541ded90c 100644 --- a/tests/Menu/Integration/BaseMenuTest.php +++ b/tests/Menu/Integration/BaseMenuTest.php @@ -35,9 +35,9 @@ protected function setUp(): void { // Adapt to both bundle and project-wide test strategy $twigPaths = array_filter([ - __DIR__.'/../../../../../../vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views', - __DIR__.'/../../../vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views', - __DIR__.'/../../../src/Resources/views', + sprintf('%s/../../../../../../vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views', __DIR__), + sprintf('%s/../../../vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views', __DIR__), + sprintf('%s/../../../src/Resources/views', __DIR__), ], 'is_dir'); $loader = new StubFilesystemLoader($twigPaths); @@ -69,7 +69,7 @@ protected function renderMenu(ItemInterface $item, array $options = []) protected function cleanHtmlWhitespace(string $html): string { $html = preg_replace_callback('/>([^<]+)'.trim($value[1]).'<'; + return sprintf('>%s<', trim($value[1])); }, $html); return $html; diff --git a/tests/Menu/Matcher/Voter/AdminVoterTest.php b/tests/Menu/Matcher/Voter/AdminVoterTest.php index 6d13cf0245..f16ff95f23 100644 --- a/tests/Menu/Matcher/Voter/AdminVoterTest.php +++ b/tests/Menu/Matcher/Voter/AdminVoterTest.php @@ -146,7 +146,7 @@ private function getChildAdmin( $childAdmin = $this->createMock(AbstractAdmin::class); $childAdmin ->method('getBaseCodeRoute') - ->willReturn($parentCode.'|'.$childCode) + ->willReturn(sprintf('%s|%s', $parentCode, $childCode)) ; $parentAdmin diff --git a/tests/Menu/Provider/GroupMenuProviderTest.php b/tests/Menu/Provider/GroupMenuProviderTest.php index 43e242d242..a7a7b324b1 100644 --- a/tests/Menu/Provider/GroupMenuProviderTest.php +++ b/tests/Menu/Provider/GroupMenuProviderTest.php @@ -62,11 +62,14 @@ protected function setUp(): void $urlGenerator->method('generate')->willReturnCallback(static function (string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string { switch ($referenceType) { case UrlGeneratorInterface::ABSOLUTE_URL: - return 'http://sonata-project/'.$name.($parameters ? '?'.http_build_query($parameters) : ''); + return sprintf('http://sonata-project/%s%s', $name, $parameters ? '?'.http_build_query($parameters) : ''); case UrlGeneratorInterface::ABSOLUTE_PATH: - return '/'.$name.($parameters ? '?'.http_build_query($parameters) : ''); + return sprintf('/%s%s', $name, $parameters ? '?'.http_build_query($parameters) : ''); default: - throw new \InvalidArgumentException(sprintf('Dummy router does not support the reference type "%s".', $referenceType)); + throw new \InvalidArgumentException(sprintf( + 'Dummy router does not support the reference type "%s".', + $referenceType + )); } }); @@ -702,7 +705,10 @@ private function getAdminMock(bool $hasRoute = true, bool $isGranted = true): Ab ->method('generateMenuUrl') ->willReturnCallback(static function (string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): array { if (!\in_array($referenceType, [UrlGeneratorInterface::ABSOLUTE_URL, UrlGeneratorInterface::ABSOLUTE_PATH], true)) { - throw new \InvalidArgumentException(sprintf('Dummy router does not support the reference type "%s".', $referenceType)); + throw new \InvalidArgumentException(sprintf( + 'Dummy router does not support the reference type "%s".', + $referenceType + )); } return [ diff --git a/tests/Resources/XliffTest.php b/tests/Resources/XliffTest.php index 166e46b177..72d5cb9912 100644 --- a/tests/Resources/XliffTest.php +++ b/tests/Resources/XliffTest.php @@ -20,6 +20,6 @@ class XliffTest extends XliffValidatorTestCase */ public function getXliffPaths() { - return [[__DIR__.'/../../src/Resources/translations']]; + return [[sprintf('%s/../../src/Resources/translations', __DIR__)]]; } } diff --git a/tests/Route/DefaultRouteGeneratorTest.php b/tests/Route/DefaultRouteGeneratorTest.php index 0c95ebc754..8bb69fe81c 100644 --- a/tests/Route/DefaultRouteGeneratorTest.php +++ b/tests/Route/DefaultRouteGeneratorTest.php @@ -32,7 +32,7 @@ class DefaultRouteGeneratorTest extends TestCase protected function setUp(): void { - $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route'; + $this->cacheTempFolder = sprintf('%s/sonata_test_route', sys_get_temp_dir()); $filesystem = new Filesystem(); $filesystem->remove($this->cacheTempFolder); @@ -89,9 +89,9 @@ public function testGenerateUrl( switch ($name) { case 'admin_acme_foo': - return $domain.'/foo'.$params; + return sprintf('%s/foo%s', $domain, $params); case 'admin_acme_child_bar': - return $domain.'/foo/bar'.$params; + return sprintf('%s/foo/bar%s', $domain, $params); } }); @@ -109,7 +109,7 @@ public function getGenerateUrlTests(): array ['/foo/bar?abc=a123&efg=e456&default_param=default_val', 'base.Code.Bar.bar', ['default_param' => 'default_val']], ['/foo/bar?abc=a123&efg=e456&default_param=default_val', 'base.Code.Bar.bar', ['default_param' => 'default_val'], RouterInterface::ABSOLUTE_PATH], [ - self::ROUTER_DOMAIN.'/foo/bar?abc=a123&efg=e456&default_param=default_val', + sprintf('%s/foo/bar?abc=a123&efg=e456&default_param=default_val', self::ROUTER_DOMAIN), 'base.Code.Bar.bar', ['default_param' => 'default_val'], RouterInterface::ABSOLUTE_URL, @@ -198,9 +198,9 @@ public function testGenerateUrlChild(string $type, string $expected, string $nam switch ($name) { case 'admin_acme_foo': - return '/foo'.$params; + return sprintf('/foo%s', $params); case 'admin_acme_child_bar': - return '/foo/bar'.$params; + return sprintf('/foo/bar%s', $params); } }); @@ -255,9 +255,9 @@ public function testGenerateUrlParentFieldDescription(string $expected, string $ switch ($name) { case 'admin_acme_foo': - return '/foo'.$params; + return sprintf('/foo%s', $params); case 'admin_acme_child_bar': - return '/foo/bar'.$params; + return sprintf('/foo/bar%s', $params); } }); @@ -359,9 +359,9 @@ public function testGenerateUrlLoadCache(string $expected, string $name, array $ switch ($name) { case 'admin_acme_child_bar': - return '/foo/bar'.$params; + return sprintf('/foo/bar%s', $params); case 'admin_acme_child_standalone_bar': - return '/bar'.$params; + return sprintf('/bar%s', $params); } }); diff --git a/tests/Route/RouteCollectionTest.php b/tests/Route/RouteCollectionTest.php index 0a9db26a29..aba2d0147f 100644 --- a/tests/Route/RouteCollectionTest.php +++ b/tests/Route/RouteCollectionTest.php @@ -171,7 +171,7 @@ public function testRouteWithAllConstructorParameters(): void $route = $routeCollection->get($name); - $combinedPattern = '/'.$baseRoutePattern.'/'.($pattern ?: $name); + $combinedPattern = sprintf('/%s/%s', $baseRoutePattern, $pattern ?: $name); $this->assertSame($combinedPattern, $route->getPath()); $this->assertArrayHasKey('_controller', $route->getDefaults()); diff --git a/tests/Security/Acl/Permission/MaskBuilderTest.php b/tests/Security/Acl/Permission/MaskBuilderTest.php index d1845f7d88..e54512f05b 100644 --- a/tests/Security/Acl/Permission/MaskBuilderTest.php +++ b/tests/Security/Acl/Permission/MaskBuilderTest.php @@ -24,18 +24,18 @@ public function testGetPattern(): void $this->assertSame(MaskBuilder::ALL_OFF, $builder->getPattern()); $builder->add('view'); - $this->assertSame(str_repeat('.', 31).'V', $builder->getPattern()); + $this->assertSame(sprintf('%sV', str_repeat('.', 31)), $builder->getPattern()); $builder->add('owner'); - $this->assertSame(str_repeat('.', 24).'N......V', $builder->getPattern()); + $this->assertSame(sprintf('%sN......V', str_repeat('.', 24)), $builder->getPattern()); $builder->add('list'); - $this->assertSame(str_repeat('.', 19).'L....N......V', $builder->getPattern()); + $this->assertSame(sprintf('%sL....N......V', str_repeat('.', 19)), $builder->getPattern()); $builder->add('export'); - $this->assertSame(str_repeat('.', 18).'EL....N......V', $builder->getPattern()); + $this->assertSame(sprintf('%sEL....N......V', str_repeat('.', 18)), $builder->getPattern()); $builder->add(1 << 10); - $this->assertSame(str_repeat('.', 18).'EL.'.MaskBuilder::ON.'..N......V', $builder->getPattern()); + $this->assertSame(sprintf('%sEL.%s..N......V', str_repeat('.', 18), MaskBuilder::ON), $builder->getPattern()); } } diff --git a/tests/Twig/Extension/SonataAdminExtensionTest.php b/tests/Twig/Extension/SonataAdminExtensionTest.php index 73da831c01..89ab2f20b1 100644 --- a/tests/Twig/Extension/SonataAdminExtensionTest.php +++ b/tests/Twig/Extension/SonataAdminExtensionTest.php @@ -148,7 +148,7 @@ protected function setUp(): void $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource( 'xlf', - __DIR__.'/../../../src/Resources/translations/SonataAdminBundle.en.xliff', + sprintf('%s/../../../src/Resources/translations/SonataAdminBundle.en.xliff', __DIR__), 'en', 'SonataAdminBundle' ); @@ -193,10 +193,10 @@ protected function setUp(): void $this->environment->addExtension(new FakeTemplateRegistryExtension()); // routing extension - $xmlFileLoader = new XmlFileLoader(new FileLocator([__DIR__.'/../../../src/Resources/config/routing'])); + $xmlFileLoader = new XmlFileLoader(new FileLocator([sprintf('%s/../../../src/Resources/config/routing', __DIR__)])); $routeCollection = $xmlFileLoader->load('sonata_admin.xml'); - $xmlFileLoader = new XmlFileLoader(new FileLocator([__DIR__.'/../../Fixtures/Resources/config/routing'])); + $xmlFileLoader = new XmlFileLoader(new FileLocator([sprintf('%s/../../Fixtures/Resources/config/routing', __DIR__)])); $testRouteCollection = $xmlFileLoader->load('routing.xml'); $routeCollection->addCollection($testRouteCollection); @@ -2190,9 +2190,9 @@ public function getRenderViewElementWithNoValueTests(): iterable public function testDeprecatedTextExtension(string $expected, string $type, $value, array $options): void { $loader = new StubFilesystemLoader([ - __DIR__.'/../../../src/Resources/views/CRUD', + sprintf('%s/../../../src/Resources/views/CRUD', __DIR__), ]); - $loader->addPath(__DIR__.'/../../../src/Resources/views/', 'SonataAdmin'); + $loader->addPath(sprintf('%s/../../../src/Resources/views/', __DIR__), 'SonataAdmin'); $environment = new Environment($loader, [ 'strict_variables' => true, 'cache' => false, @@ -2543,7 +2543,7 @@ public function testRenderRelationElementWithClosure(): void ->willReturnCallback(static function ($value, $default = null) { if ('associated_property' === $value) { return static function ($element): string { - return 'closure '.$element->foo; + return sprintf('closure %s', $element->foo); }; } });