AddDependencyCallsCompilerPass.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\DependencyInjection\Compiler;
  11. use Doctrine\Common\Inflector\Inflector;
  12. use Sonata\AdminBundle\Datagrid\Pager;
  13. use Symfony\Component\DependencyInjection\ChildDefinition;
  14. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  15. use Symfony\Component\DependencyInjection\ContainerBuilder;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Component\DependencyInjection\Definition;
  18. use Symfony\Component\DependencyInjection\DefinitionDecorator;
  19. use Symfony\Component\DependencyInjection\Reference;
  20. /**
  21. * Add all dependencies to the Admin class, this avoid to write too many lines
  22. * in the configuration files.
  23. *
  24. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  25. */
  26. class AddDependencyCallsCompilerPass implements CompilerPassInterface
  27. {
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function process(ContainerBuilder $container)
  32. {
  33. // check if translator service exist
  34. if (!$container->has('translator')) {
  35. throw new \RuntimeException('The "translator" service is not yet enabled.
  36. It\'s required by SonataAdmin to display all labels properly.
  37. To learn how to enable the translator service please visit:
  38. http://symfony.com/doc/current/translation.html#configuration
  39. ');
  40. }
  41. $parameterBag = $container->getParameterBag();
  42. $groupDefaults = $admins = $classes = array();
  43. $pool = $container->getDefinition('sonata.admin.pool');
  44. foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $tags) {
  45. foreach ($tags as $attributes) {
  46. $definition = $container->getDefinition($id);
  47. $parentDefinition = null;
  48. // NEXT_MAJOR: Remove check for DefinitionDecorator instance when dropping Symfony <3.3 support
  49. if ($definition instanceof ChildDefinition || $definition instanceof DefinitionDecorator) {
  50. $parentDefinition = $container->getDefinition($definition->getParent());
  51. }
  52. $this->replaceDefaultArguments(array(
  53. 0 => $id,
  54. 2 => 'SonataAdminBundle:CRUD',
  55. ), $definition, $parentDefinition);
  56. $this->applyConfigurationFromAttribute($definition, $attributes);
  57. $this->applyDefaults($container, $id, $attributes);
  58. $arguments = $parentDefinition ?
  59. array_merge($parentDefinition->getArguments(), $definition->getArguments()) :
  60. $definition->getArguments();
  61. $admins[] = $id;
  62. if (!isset($classes[$arguments[1]])) {
  63. $classes[$arguments[1]] = array();
  64. }
  65. $classes[$arguments[1]][] = $id;
  66. $showInDashboard = (bool) (isset($attributes['show_in_dashboard']) ? $parameterBag->resolveValue($attributes['show_in_dashboard']) : true);
  67. if (!$showInDashboard) {
  68. continue;
  69. }
  70. $resolvedGroupName = isset($attributes['group']) ? $parameterBag->resolveValue($attributes['group']) : 'default';
  71. $labelCatalogue = isset($attributes['label_catalogue']) ? $attributes['label_catalogue'] : 'SonataAdminBundle';
  72. $icon = isset($attributes['icon']) ? $attributes['icon'] : '<i class="fa fa-folder"></i>';
  73. $onTop = isset($attributes['on_top']) ? $attributes['on_top'] : false;
  74. $keepOpen = isset($attributes['keep_open']) ? $attributes['keep_open'] : false;
  75. if (!isset($groupDefaults[$resolvedGroupName])) {
  76. $groupDefaults[$resolvedGroupName] = array(
  77. 'label' => $resolvedGroupName,
  78. 'label_catalogue' => $labelCatalogue,
  79. 'icon' => $icon,
  80. 'roles' => array(),
  81. 'on_top' => false,
  82. 'keep_open' => false,
  83. );
  84. }
  85. $groupDefaults[$resolvedGroupName]['items'][] = array(
  86. 'admin' => $id,
  87. 'label' => !empty($attributes['label']) ? $attributes['label'] : '',
  88. 'route' => '',
  89. 'route_params' => array(),
  90. 'route_absolute' => false,
  91. );
  92. if (isset($groupDefaults[$resolvedGroupName]['on_top']) && $groupDefaults[$resolvedGroupName]['on_top']
  93. || $onTop && (count($groupDefaults[$resolvedGroupName]['items']) > 1)) {
  94. throw new \RuntimeException('You can\'t use "on_top" option with multiple same name groups.');
  95. }
  96. $groupDefaults[$resolvedGroupName]['on_top'] = $onTop;
  97. $groupDefaults[$resolvedGroupName]['keep_open'] = $keepOpen;
  98. }
  99. }
  100. $dashboardGroupsSettings = $container->getParameter('sonata.admin.configuration.dashboard_groups');
  101. if (!empty($dashboardGroupsSettings)) {
  102. $groups = $dashboardGroupsSettings;
  103. foreach ($dashboardGroupsSettings as $groupName => $group) {
  104. $resolvedGroupName = $parameterBag->resolveValue($groupName);
  105. if (!isset($groupDefaults[$resolvedGroupName])) {
  106. $groupDefaults[$resolvedGroupName] = array(
  107. 'items' => array(),
  108. 'label' => $resolvedGroupName,
  109. 'roles' => array(),
  110. 'on_top' => false,
  111. 'keep_open' => false,
  112. );
  113. }
  114. if (empty($group['items'])) {
  115. $groups[$resolvedGroupName]['items'] = $groupDefaults[$resolvedGroupName]['items'];
  116. }
  117. if (empty($group['label'])) {
  118. $groups[$resolvedGroupName]['label'] = $groupDefaults[$resolvedGroupName]['label'];
  119. }
  120. if (empty($group['label_catalogue'])) {
  121. $groups[$resolvedGroupName]['label_catalogue'] = 'SonataAdminBundle';
  122. }
  123. if (empty($group['icon'])) {
  124. $groups[$resolvedGroupName]['icon'] = $groupDefaults[$resolvedGroupName]['icon'];
  125. }
  126. if (!empty($group['item_adds'])) {
  127. $groups[$resolvedGroupName]['items'] = array_merge($groups[$resolvedGroupName]['items'], $group['item_adds']);
  128. }
  129. if (empty($group['roles'])) {
  130. $groups[$resolvedGroupName]['roles'] = $groupDefaults[$resolvedGroupName]['roles'];
  131. }
  132. if (isset($groups[$resolvedGroupName]['on_top']) && !empty($group['on_top']) && $group['on_top']
  133. && (count($groups[$resolvedGroupName]['items']) > 1)) {
  134. throw new \RuntimeException('You can\'t use "on_top" option with multiple same name groups.');
  135. }
  136. if (empty($group['on_top'])) {
  137. $groups[$resolvedGroupName]['on_top'] = $groupDefaults[$resolvedGroupName]['on_top'];
  138. }
  139. if (empty($group['keep_open'])) {
  140. $groups[$resolvedGroupName]['keep_open'] = $groupDefaults[$resolvedGroupName]['keep_open'];
  141. }
  142. }
  143. } elseif ($container->getParameter('sonata.admin.configuration.sort_admins')) {
  144. $groups = $groupDefaults;
  145. $elementSort = function (&$element) {
  146. usort(
  147. $element['items'],
  148. function ($a, $b) {
  149. $a = !empty($a['label']) ? $a['label'] : $a['admin'];
  150. $b = !empty($b['label']) ? $b['label'] : $b['admin'];
  151. if ($a === $b) {
  152. return 0;
  153. }
  154. return $a < $b ? -1 : 1;
  155. }
  156. );
  157. };
  158. /*
  159. * 1) sort the groups by their index
  160. * 2) sort the elements within each group by label/admin
  161. */
  162. ksort($groups);
  163. array_walk($groups, $elementSort);
  164. } else {
  165. $groups = $groupDefaults;
  166. }
  167. $pool->addMethodCall('setAdminServiceIds', array($admins));
  168. $pool->addMethodCall('setAdminGroups', array($groups));
  169. $pool->addMethodCall('setAdminClasses', array($classes));
  170. $routeLoader = $container->getDefinition('sonata.admin.route_loader');
  171. $routeLoader->replaceArgument(1, $admins);
  172. }
  173. /**
  174. * This method read the attribute keys and configure admin class to use the related dependency.
  175. *
  176. * @param Definition $definition
  177. * @param array $attributes
  178. */
  179. public function applyConfigurationFromAttribute(Definition $definition, array $attributes)
  180. {
  181. $keys = array(
  182. 'model_manager',
  183. 'form_contractor',
  184. 'show_builder',
  185. 'list_builder',
  186. 'datagrid_builder',
  187. 'translator',
  188. 'configuration_pool',
  189. 'router',
  190. 'validator',
  191. 'security_handler',
  192. 'menu_factory',
  193. 'route_builder',
  194. 'label_translator_strategy',
  195. );
  196. foreach ($keys as $key) {
  197. $method = 'set'.Inflector::classify($key);
  198. if (!isset($attributes[$key]) || $definition->hasMethodCall($method)) {
  199. continue;
  200. }
  201. $definition->addMethodCall($method, array(new Reference($attributes[$key])));
  202. }
  203. }
  204. /**
  205. * Apply the default values required by the AdminInterface to the Admin service definition.
  206. *
  207. * @param ContainerBuilder $container
  208. * @param string $serviceId
  209. * @param array $attributes
  210. *
  211. * @return Definition
  212. */
  213. public function applyDefaults(ContainerBuilder $container, $serviceId, array $attributes = array())
  214. {
  215. $definition = $container->getDefinition($serviceId);
  216. $settings = $container->getParameter('sonata.admin.configuration.admin_services');
  217. if (method_exists($definition, 'setShared')) { // Symfony 2.8+
  218. $definition->setShared(false);
  219. } else { // For Symfony <2.8 compatibility
  220. $definition->setScope(ContainerInterface::SCOPE_PROTOTYPE);
  221. }
  222. $manager_type = $attributes['manager_type'];
  223. $overwriteAdminConfiguration = isset($settings[$serviceId]) ? $settings[$serviceId] : array();
  224. $defaultAddServices = array(
  225. 'model_manager' => sprintf('sonata.admin.manager.%s', $manager_type),
  226. 'form_contractor' => sprintf('sonata.admin.builder.%s_form', $manager_type),
  227. 'show_builder' => sprintf('sonata.admin.builder.%s_show', $manager_type),
  228. 'list_builder' => sprintf('sonata.admin.builder.%s_list', $manager_type),
  229. 'datagrid_builder' => sprintf('sonata.admin.builder.%s_datagrid', $manager_type),
  230. 'translator' => 'translator',
  231. 'configuration_pool' => 'sonata.admin.pool',
  232. 'route_generator' => 'sonata.admin.route.default_generator',
  233. 'validator' => 'validator',
  234. 'security_handler' => 'sonata.admin.security.handler',
  235. 'menu_factory' => 'knp_menu.factory',
  236. 'route_builder' => 'sonata.admin.route.path_info'.
  237. (($manager_type == 'doctrine_phpcr') ? '_slashes' : ''),
  238. 'label_translator_strategy' => 'sonata.admin.label.strategy.native',
  239. );
  240. $definition->addMethodCall('setManagerType', array($manager_type));
  241. foreach ($defaultAddServices as $attr => $addServiceId) {
  242. $method = 'set'.Inflector::classify($attr);
  243. if (isset($overwriteAdminConfiguration[$attr]) || !$definition->hasMethodCall($method)) {
  244. $args = array(new Reference(isset($overwriteAdminConfiguration[$attr]) ? $overwriteAdminConfiguration[$attr] : $addServiceId));
  245. if ('translator' === $attr) {
  246. $args[] = false;
  247. }
  248. $definition->addMethodCall($method, $args);
  249. }
  250. }
  251. if (isset($overwriteAdminConfiguration['pager_type'])) {
  252. $pagerType = $overwriteAdminConfiguration['pager_type'];
  253. } elseif (isset($attributes['pager_type'])) {
  254. $pagerType = $attributes['pager_type'];
  255. } else {
  256. $pagerType = Pager::TYPE_DEFAULT;
  257. }
  258. $definition->addMethodCall('setPagerType', array($pagerType));
  259. if (isset($overwriteAdminConfiguration['label'])) {
  260. $label = $overwriteAdminConfiguration['label'];
  261. } elseif (isset($attributes['label'])) {
  262. $label = $attributes['label'];
  263. } else {
  264. $label = '-';
  265. }
  266. $definition->addMethodCall('setLabel', array($label));
  267. if (isset($attributes['persist_filters'])) {
  268. $persistFilters = (bool) $attributes['persist_filters'];
  269. } else {
  270. $persistFilters = (bool) $container->getParameter('sonata.admin.configuration.filters.persist');
  271. }
  272. $definition->addMethodCall('setPersistFilters', array($persistFilters));
  273. if (isset($overwriteAdminConfiguration['show_mosaic_button'])) {
  274. $showMosaicButton = $overwriteAdminConfiguration['show_mosaic_button'];
  275. } elseif (isset($attributes['show_mosaic_button'])) {
  276. $showMosaicButton = $attributes['show_mosaic_button'];
  277. } else {
  278. $showMosaicButton = $container->getParameter('sonata.admin.configuration.show.mosaic.button');
  279. }
  280. $definition->addMethodCall('showMosaicButton', array($showMosaicButton));
  281. $this->fixTemplates($container, $definition, isset($overwriteAdminConfiguration['templates']) ? $overwriteAdminConfiguration['templates'] : array('view' => array()));
  282. if ($container->hasParameter('sonata.admin.configuration.security.information') && !$definition->hasMethodCall('setSecurityInformation')) {
  283. $definition->addMethodCall('setSecurityInformation', array('%sonata.admin.configuration.security.information%'));
  284. }
  285. $definition->addMethodCall('initialize');
  286. return $definition;
  287. }
  288. /**
  289. * @param ContainerBuilder $container
  290. * @param Definition $definition
  291. * @param array $overwrittenTemplates
  292. */
  293. public function fixTemplates(ContainerBuilder $container, Definition $definition, array $overwrittenTemplates = array())
  294. {
  295. $definedTemplates = $container->getParameter('sonata.admin.configuration.templates');
  296. $methods = array();
  297. $pos = 0;
  298. foreach ($definition->getMethodCalls() as $method) {
  299. if ($method[0] == 'setTemplates') {
  300. $definedTemplates = array_merge($definedTemplates, $method[1][0]);
  301. continue;
  302. }
  303. if ($method[0] == 'setTemplate') {
  304. $definedTemplates[$method[1][0]] = $method[1][1];
  305. continue;
  306. }
  307. // set template for simple pager if it is not already overwritten
  308. if ($method[0] === 'setPagerType'
  309. && $method[1][0] === Pager::TYPE_SIMPLE
  310. && (
  311. !isset($definedTemplates['pager_results'])
  312. || $definedTemplates['pager_results'] === 'SonataAdminBundle:Pager:results.html.twig'
  313. )
  314. ) {
  315. $definedTemplates['pager_results'] = 'SonataAdminBundle:Pager:simple_pager_results.html.twig';
  316. }
  317. $methods[$pos] = $method;
  318. ++$pos;
  319. }
  320. $definition->setMethodCalls($methods);
  321. $definedTemplates = $overwrittenTemplates['view'] + $definedTemplates;
  322. if ($container->getParameter('sonata.admin.configuration.templates') !== $definedTemplates) {
  323. $definition->addMethodCall('setTemplates', array($definedTemplates));
  324. } else {
  325. $definition->addMethodCall('setTemplates', array('%sonata.admin.configuration.templates%'));
  326. }
  327. }
  328. /**
  329. * Replace the empty arguments required by the Admin service definition.
  330. *
  331. * @param array $defaultArguments
  332. * @param Definition $definition
  333. * @param Definition|null $parentDefinition
  334. */
  335. private function replaceDefaultArguments(array $defaultArguments, Definition $definition, Definition $parentDefinition = null)
  336. {
  337. $arguments = $definition->getArguments();
  338. $parentArguments = $parentDefinition ? $parentDefinition->getArguments() : array();
  339. foreach ($defaultArguments as $index => $value) {
  340. $declaredInParent = $parentDefinition && array_key_exists($index, $parentArguments);
  341. if (strlen($declaredInParent ? $parentArguments[$index] : $arguments[$index]) == 0) {
  342. $arguments[$declaredInParent ? sprintf('index_%s', $index) : $index] = $value;
  343. }
  344. }
  345. $definition->setArguments($arguments);
  346. }
  347. }