public function testExecute()
 {
     $application = new Application();
     $command = new ListAdminCommand();
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $admin1 = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $admin1->expects($this->any())->method('getClass')->will($this->returnValue('Acme\\Entity\\Foo'));
     $admin2 = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $admin2->expects($this->any())->method('getClass')->will($this->returnValue('Acme\\Entity\\Bar'));
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($container, $admin1, $admin2) {
         switch ($id) {
             case 'sonata.admin.pool':
                 $pool = new Pool($container, '', '');
                 $pool->setAdminServiceIds(array('acme.admin.foo', 'acme.admin.bar'));
                 return $pool;
                 break;
             case 'acme.admin.foo':
                 return $admin1;
                 break;
             case 'acme.admin.bar':
                 return $admin2;
                 break;
         }
         return null;
     }));
     $command->setContainer($container);
     $application->add($command);
     $command = $application->find('sonata:admin:list');
     $commandTester = new CommandTester($command);
     $commandTester->execute(array('command' => $command->getName()));
     $this->assertRegExp('@Admin services:\\s+acme.admin.foo\\s+Acme\\\\Entity\\\\Foo\\s+acme.admin.bar\\s+Acme\\\\Entity\\\\Bar@', $commandTester->getDisplay());
 }
 /**
  * Retrieves the menu based on the group options.
  *
  * @param string $name
  * @param array  $options
  *
  * @return \Knp\Menu\ItemInterface
  *
  * @throws \InvalidArgumentException if the menu does not exists
  */
 public function get($name, array $options = array())
 {
     $group = $options['group'];
     $menuItem = $this->menuFactory->createItem($options['name'], array('label' => $group['label']));
     foreach ($group['items'] as $item) {
         if (isset($item['admin']) && !empty($item['admin'])) {
             $admin = $this->pool->getInstance($item['admin']);
             // skip menu item if no `list` url is available or user doesn't have the LIST access rights
             if (!$admin->hasRoute('list') || !$admin->isGranted('LIST')) {
                 continue;
             }
             $label = $admin->getLabel();
             $options = $admin->generateMenuUrl('list');
             $options['extras'] = array('translation_domain' => $admin->getTranslationDomain(), 'admin' => $admin);
         } else {
             $label = $item['label'];
             $options = array('route' => $item['route'], 'routeParameters' => $item['route_params'], 'extras' => array('translation_domain' => $group['label_catalogue']));
         }
         $menuItem->addChild($label, $options);
     }
     if (false === $menuItem->hasChildren()) {
         $menuItem->setDisplay(false);
     }
     return $menuItem;
 }
 public function testExecuteWithException2()
 {
     $application = new Application();
     $command = new SetupAclCommand();
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($container, $admin) {
         switch ($id) {
             case 'sonata.admin.pool':
                 $pool = new Pool($container, '', '');
                 $pool->setAdminServiceIds(array('acme.admin.foo'));
                 return $pool;
             case 'sonata.admin.manipulator.acl.admin':
                 return new \stdClass();
             case 'acme.admin.foo':
                 return $admin;
         }
         return;
     }));
     $command->setContainer($container);
     $application->add($command);
     $command = $application->find('sonata:admin:setup-acl');
     $commandTester = new CommandTester($command);
     $commandTester->execute(array('command' => $command->getName()));
     $this->assertRegExp('@Starting ACL AdminBundle configuration\\s+The interface "AdminAclManipulatorInterface" is not implemented for stdClass: ignoring@', $commandTester->getDisplay());
 }
 public function testdashboardActionAjaxLayout()
 {
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $pool = new Pool($container, 'title', 'logo.png');
     $pool->setTemplates(array('ajax' => 'ajax.html'));
     $templating = $this->getMock('Symfony\\Bundle\\FrameworkBundle\\Templating\\EngineInterface');
     $request = new Request();
     $request->headers->set('X-Requested-With', 'XMLHttpRequest');
     $requestStack = null;
     if (Kernel::MINOR_VERSION > 3) {
         $requestStack = new \Symfony\Component\HttpFoundation\RequestStack();
         $requestStack->push($request);
     }
     $values = array('sonata.admin.pool' => $pool, 'templating' => $templating, 'request' => $request, 'request_stack' => $requestStack);
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($values) {
         return $values[$id];
     }));
     $container->expects($this->any())->method('getParameter')->will($this->returnCallback(function ($name) {
         if ($name == 'sonata.admin.configuration.dashboard_blocks') {
             return array();
         }
     }));
     $controller = new CoreController();
     $controller->setContainer($container);
     $response = $controller->dashboardAction();
     $this->isInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response);
 }
 public function setUp()
 {
     if (!interface_exists('JMS\\TranslationBundle\\Translation\\ExtractorInterface')) {
         $this->markTestSkipped('JMS Translator Bundle does not exist');
     }
     $this->fooAdmin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->barAdmin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     // php 5.3 BC
     $fooAdmin = $this->fooAdmin;
     $barAdmin = $this->barAdmin;
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($fooAdmin, $barAdmin) {
         switch ($id) {
             case 'foo_admin':
                 return $fooAdmin;
             case 'bar_admin':
                 return $barAdmin;
         }
         return null;
     }));
     $logger = $this->getMock('Symfony\\Component\\HttpKernel\\Log\\LoggerInterface');
     $this->pool = new Pool($container, '', '');
     $this->pool->setAdminServiceIds(array('foo_admin', 'bar_admin'));
     $this->adminExtractor = new AdminExtractor($this->pool, $logger);
     $this->adminExtractor->setLogger($logger);
 }
 /**
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  * @throws \RuntimeException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request) {
         return;
     }
     if (!$request->hasSession()) {
         return;
     }
     $adminCode = $request->get('_sonata_admin');
     if (!is_null($adminCode)) {
         $this->admin = $this->adminPool->getAdminByAdminCode($adminCode);
         if (!$this->admin) {
             throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
         }
         if (method_exists($this->admin, 'getTrackedActions')) {
             foreach ($this->admin->getTrackedActions() as $trackedAction) {
                 // if an action which is flagged as 'to be tracked' is matching the end of the route: add info to session
                 if (preg_match('#' . $trackedAction . '$#', $request->get('_route'), $matches)) {
                     $this->updateTrackedInfo($request->getSession(), '_networking_initcms_admin_tracker', array('url' => $request->getRequestUri(), 'controller' => $this->admin->getBaseControllerName(), 'action' => $trackedAction));
                 }
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     $user_current = $this->securityContext->getToken()->getUser();
     $info = $this->em->getRepository("ApplicationSonataUserBundle:Matching")->lastMatchingFromUser($user_current);
     // merge settings
     $settings = array_merge($this->getDefaultSettings(), $blockContext->getSettings());
     return $this->renderResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'base_template' => $this->pool->getTemplate('layout'), 'info' => $info, 'settings' => $blockContext->getSettings()), $response);
 }
 protected function setUp()
 {
     $this->application = new Application();
     $command = new ExplainAdminCommand();
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $this->admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->admin->expects($this->any())->method('getCode')->will($this->returnValue('foo'));
     $this->admin->expects($this->any())->method('getClass')->will($this->returnValue('Acme\\Entity\\Foo'));
     $this->admin->expects($this->any())->method('getBaseControllerName')->will($this->returnValue('SonataAdminBundle:CRUD'));
     $routeCollection = new RouteCollection('foo', 'fooBar', 'foo-bar', 'SonataAdminBundle:CRUD');
     $routeCollection->add('list');
     $routeCollection->add('edit');
     $this->admin->expects($this->any())->method('getRoutes')->will($this->returnValue($routeCollection));
     $fieldDescription1 = $this->getMock('Sonata\\AdminBundle\\Admin\\FieldDescriptionInterface');
     $fieldDescription1->expects($this->any())->method('getType')->will($this->returnValue('text'));
     $fieldDescription1->expects($this->any())->method('getTemplate')->will($this->returnValue('SonataAdminBundle:CRUD:foo_text.html.twig'));
     $fieldDescription2 = $this->getMock('Sonata\\AdminBundle\\Admin\\FieldDescriptionInterface');
     $fieldDescription2->expects($this->any())->method('getType')->will($this->returnValue('datetime'));
     $fieldDescription2->expects($this->any())->method('getTemplate')->will($this->returnValue('SonataAdminBundle:CRUD:bar_datetime.html.twig'));
     $this->admin->expects($this->any())->method('getListFieldDescriptions')->will($this->returnValue(array('fooTextField' => $fieldDescription1, 'barDateTimeField' => $fieldDescription2)));
     $this->admin->expects($this->any())->method('getFilterFieldDescriptions')->will($this->returnValue(array('fooTextField' => $fieldDescription1, 'barDateTimeField' => $fieldDescription2)));
     $this->admin->expects($this->any())->method('getFormTheme')->will($this->returnValue(array('FooBundle::bar.html.twig')));
     $this->admin->expects($this->any())->method('getFormFieldDescriptions')->will($this->returnValue(array('fooTextField' => $fieldDescription1, 'barDateTimeField' => $fieldDescription2)));
     $this->admin->expects($this->any())->method('isChild')->will($this->returnValue(true));
     // php 5.3 BC
     $adminParent = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $adminParent->expects($this->any())->method('getCode')->will($this->returnValue('foo_child'));
     $this->admin->expects($this->any())->method('getParent')->will($this->returnCallback(function () use($adminParent) {
         return $adminParent;
     }));
     // Prefer Symfony 2.x interfaces
     if (interface_exists('Symfony\\Component\\Validator\\MetadataFactoryInterface')) {
         $this->validatorFactory = $this->getMock('Symfony\\Component\\Validator\\MetadataFactoryInterface');
         $validator = $this->getMock('Symfony\\Component\\Validator\\ValidatorInterface');
         $validator->expects($this->any())->method('getMetadataFactory')->will($this->returnValue($this->validatorFactory));
     } else {
         $this->validatorFactory = $this->getMock('Symfony\\Component\\Validator\\Mapping\\Factory\\MetadataFactoryInterface');
         $validator = $this->getMock('Symfony\\Component\\Validator\\Validator\\ValidatorInterface');
         $validator->expects($this->any())->method('getMetadataFor')->will($this->returnValue($this->validatorFactory));
     }
     // php 5.3 BC
     $admin = $this->admin;
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($container, $admin, $validator) {
         switch ($id) {
             case 'sonata.admin.pool':
                 $pool = new Pool($container, '', '');
                 $pool->setAdminServiceIds(array('acme.admin.foo', 'acme.admin.bar'));
                 return $pool;
             case 'validator':
                 return $validator;
             case 'acme.admin.foo':
                 return $admin;
         }
         return;
     }));
     $command->setContainer($container);
     $this->application->add($command);
 }
 /**
  * @param ComponentInterface $component
  *
  * @return AdminInterface
  */
 protected function getAdmin(ComponentInterface $component, ActionInterface $action = null)
 {
     if ($action && ($adminComponent = $action->getComponent('admin_code'))) {
         return $this->pool->getAdminByAdminCode($adminComponent);
     }
     try {
         return $this->pool->getAdminByClass($component->getModel());
     } catch (\RuntimeException $e) {
     }
     return false;
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     $user_current = $this->securityContext->getToken()->getUser();
     $info['count_base'] = $this->em->getRepository("ApplicationSonataUserBundle:Base")->countConsumerBases($user_current);
     $info['count_campaign'] = $this->em->getRepository("ApplicationSonataUserBundle:Campaign")->countActiveCampaign();
     $info['count_md5'] = $this->em->getRepository("ApplicationSonataUserBundle:BaseDetail")->countBaseDetailByUser($user_current);
     $info['count_match'] = $this->em->getRepository("ApplicationSonataUserBundle:MatchingDetail")->countMatchingDetailByUser($user_current);
     // merge settings
     $settings = array_merge($this->getDefaultSettings(), $blockContext->getSettings());
     return $this->renderResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'base_template' => $this->pool->getTemplate('layout'), 'info' => $info, 'settings' => $blockContext->getSettings()), $response);
 }
 public function testGenerateLinkDisabledEditAndShow()
 {
     $component = new Component();
     $component->setModel('Acme\\DemoBundle\\Model\\Demo');
     $component->setIdentifier('2');
     $action = new Action();
     $this->admin->expects($this->at(0))->method('hasRoute')->with($this->equalTo('edit'))->will($this->returnValue(false));
     $this->admin->expects($this->at(1))->method('hasRoute')->with($this->equalTo('show'))->will($this->returnValue(false));
     $this->admin->expects($this->once())->method('toString')->with($this->anything())->will($this->returnValue('Text'));
     $this->assertEquals('Text', $this->twigExtension->generateLink($component, $action));
 }
 function testMoveWithAdmin()
 {
     $movedPath = '/cms/to-move';
     $targetPath = '/cms/target/moved';
     $urlSafeId = 'urlSafeId';
     $admin = $this->getMockBuilder('Sonata\\DoctrinePHPCRAdminBundle\\Admin\\Admin')->disableOriginalConstructor()->getMock();
     $admin->expects($this->once())->method('getNormalizedIdentifier')->will($this->returnValue($targetPath));
     $admin->expects($this->once())->method('getUrlsafeIdentifier')->will($this->returnValue($urlSafeId));
     $this->pool->expects($this->once())->method('getAdminByClass')->will($this->returnValue($admin));
     $tree = new PhpcrOdmTree($this->dm, $this->defaultModelManager, $this->pool, $this->translator, $this->assetHelper, array(), array('depth' => 1, 'precise_children' => true));
     $this->assertEquals(array('id' => $targetPath, 'url_safe_id' => $urlSafeId), $tree->move($movedPath, $targetPath));
 }
Exemplo n.º 13
0
 public function testGetDashboardGroups()
 {
     $admin_group1 = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $admin_group1->expects($this->once())->method('showIn')->will($this->returnValue(true));
     $admin_group2 = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $admin_group2->expects($this->once())->method('showIn')->will($this->returnValue(false));
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $container->expects($this->any())->method('get')->will($this->onConsecutiveCalls($admin_group1, $admin_group2));
     $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
     $pool->setAdminGroups(array('adminGroup1' => array('items' => array('itemKey' => 'sonata.user.admin.group1')), 'adminGroup2' => array('itmes' => array('itemKey' => 'sonata.user.admin.group1')), 'adminGroup3' => array('items' => array('itemKey' => 'sonata.user.admin.group2'))));
     $groups = $pool->getDashboardGroups();
     $this->assertCount(1, $groups);
 }
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     $admin = $this->pool->getAdminByAdminCode($blockContext->getSetting('code'));
     $datagrid = $admin->getDatagrid();
     $filters = $blockContext->getSetting('filters');
     if (!isset($filters['_per_page'])) {
         $filters['_per_page'] = array('value' => $blockContext->getSetting('limit'));
     }
     foreach ($filters as $name => $data) {
         $datagrid->setValue($name, isset($data['type']) ? $data['type'] : null, $data['value']);
     }
     $datagrid->buildPager();
     return $this->renderPrivateResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'settings' => $blockContext->getSettings(), 'admin_pool' => $this->pool, 'admin' => $admin, 'pager' => $datagrid->getPager(), 'datagrid' => $datagrid), $response);
 }
Exemplo n.º 15
0
 /**
  * Builds sidebar menu.
  *
  * @return ItemInterface
  */
 public function createSidebarMenu()
 {
     $menu = $this->factory->createItem('root');
     foreach ($this->pool->getAdminGroups() as $name => $group) {
         $extras = array('icon' => $group['icon'], 'label_catalogue' => $group['label_catalogue'], 'roles' => $group['roles']);
         $menuProvider = isset($group['provider']) ? $group['provider'] : 'sonata_group_menu';
         $subMenu = $this->provider->get($menuProvider, array('name' => $name, 'group' => $group));
         $subMenu = $menu->addChild($subMenu);
         $subMenu->setExtras(array_merge($subMenu->getExtras(), $extras));
     }
     $event = new ConfigureMenuEvent($this->factory, $menu);
     $this->eventDispatcher->dispatch(ConfigureMenuEvent::SIDEBAR, $event);
     return $event->getMenu();
 }
Exemplo n.º 16
0
 /**
  * {@inheritDoc}
  */
 public function load($resource, $type = null)
 {
     $collection = new SymfonyRouteCollection();
     foreach ($this->adminServiceIds as $id) {
         $admin = $this->pool->getInstance($id);
         foreach ($admin->getRoutes()->getElements() as $code => $route) {
             $collection->add($route->getDefault('_sonata_name'), $route);
         }
         $reflection = new \ReflectionObject($admin);
         $collection->addResource(new FileResource($reflection->getFileName()));
     }
     $reflection = new \ReflectionObject($this->container);
     $collection->addResource(new FileResource($reflection->getFileName()));
     return $collection;
 }
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     try {
         $admin = $this->pool->getAdminByAdminCode($blockContext->getSetting('admin_code'));
     } catch (ServiceNotFoundException $e) {
         throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
     }
     if (!$admin instanceof AdminInterface) {
         throw new \RuntimeException('The requested service is not an Admin instance');
     }
     if (!$admin->isGranted('LIST')) {
         throw new AccessDeniedException();
     }
     $pager = $this->searchHandler->search($admin, $blockContext->getSetting('query'), $blockContext->getSetting('page'), $blockContext->getSetting('per_page'));
     return $this->renderPrivateResponse($admin->getTemplate('search_result_block'), array('block' => $blockContext->getBlock(), 'settings' => $blockContext->getSettings(), 'admin_pool' => $this->pool, 'pager' => $pager, 'admin' => $admin), $response);
 }
Exemplo n.º 18
0
 public function testTemplates()
 {
     $this->assertInternalType('array', $this->pool->getTemplates());
     $this->pool->setTemplates(array('ajax' => 'Foo.html.twig'));
     $this->assertNull($this->pool->getTemplate('bar'));
     $this->assertEquals('Foo.html.twig', $this->pool->getTemplate('ajax'));
 }
Exemplo n.º 19
0
 public function testConfigureWithException2()
 {
     $this->setExpectedException('RuntimeException', 'Unable to find the admin class related to the current controller ' . '(Sonata\\AdminBundle\\Controller\\CRUDController)');
     $this->pool->setAdminServiceIds(array('nonexistent.admin'));
     $this->request->attributes->set('_sonata_admin', 'nonexistent.admin');
     $this->protectedTestedMethods['configure']->invoke($this->controller);
 }
Exemplo n.º 20
0
 /**
  * @param ItemInterface $menu
  * @param AdminMenu[] $tree
  * @param int $level
  */
 protected function generateMenu(&$menu, &$tree, $level = 0)
 {
     while (!empty($tree)) {
         $item = array_shift($tree);
         $type = $item->getType();
         $itemLabel = $item->getTitle();
         $itemLevel = $item->getLevel();
         if ($itemLevel == $level) {
             $options = [];
             if (AdminMenu::TYPE_FOLDER !== $type) {
                 $admin = $this->pool->getInstance($item->getServiceId());
                 if ($admin) {
                     $options = $admin->generateMenuUrl('list');
                     $options['extras'] = ['admin' => $admin];
                 } else {
                     $this->logger->alert('Admin not found for class', [$item->getServiceId()]);
                 }
             }
             $child = $menu->addChild($itemLabel, $options);
         } elseif ($itemLevel > $level) {
             array_unshift($tree, $item);
             $this->generateMenu($child, $tree, $itemLevel);
         } else {
             array_unshift($tree, $item);
             break;
         }
     }
 }
 /**
  * Get KnpMenu
  *
  * @param Request $request
  *
  * @return ItemInterface
  */
 public function getKnpMenu(Request $request = null)
 {
     $menuFactory = new MenuFactory();
     $menu = $menuFactory->createItem('root')->setExtra('request', $request);
     foreach ($this->pool->getAdminGroups() as $name => $group) {
         $menu->addChild($name, array('label' => $group['label']))->setAttributes(array('icon' => $group['icon'], 'label_catalogue' => $group['label_catalogue']))->setExtra('roles', $group['roles']);
         foreach ($group['items'] as $item) {
             if (array_key_exists('admin', $item) && $item['admin'] != null) {
                 $admin = $this->pool->getInstance($item['admin']);
                 // skip menu item if no `list` url is available or user doesn't have the LIST access rights
                 if (!$admin->hasRoute('list') || !$admin->isGranted('LIST')) {
                     continue;
                 }
                 $label = $admin->getLabel();
                 $route = $admin->generateUrl('list');
                 $translationDomain = $admin->getTranslationDomain();
             } else {
                 $label = $item['label'];
                 $route = $this->router->generate($item['route'], $item['route_params']);
                 $translationDomain = $group['label_catalogue'];
                 $admin = null;
             }
             $menu[$name]->addChild($label, array('uri' => $route))->setExtra('translationdomain', $translationDomain)->setExtra('admin', $admin);
         }
     }
     return $menu;
 }
 /**
  * @param array $adminGroupsOnTopOption
  *
  * @dataProvider getAdminGroupsWithOnTopOption
  */
 public function testGetMenuProviderOnTopOptions(array $adminGroupsOnTopOption)
 {
     $this->pool->expects($this->once())->method('getInstance')->with($this->equalTo('sonata_admin_foo_service'))->will($this->returnValue($this->getAdminMock(true, false)));
     $menu = $this->provider->get('providerFoo', array('name' => 'foo', 'group' => $adminGroupsOnTopOption));
     $this->assertInstanceOf('Knp\\Menu\\ItemInterface', $menu);
     $this->assertCount(0, $menu->getChildren());
 }
 /**
  * Get the identifiers as a string that is save to use in an url.
  *
  * @param object         $model
  * @param AdminInterface $admin
  *
  * @return string string representation of the id that is save to use in an url
  */
 public function getUrlsafeIdentifier($model, AdminInterface $admin = null)
 {
     if (is_null($admin)) {
         $admin = $this->pool->getAdminByClass(ClassUtils::getClass($model));
     }
     return $admin->getUrlsafeIdentifier($model);
 }
 /**
  * @return array
  */
 public function getRoles()
 {
     $roles = array();
     $rolesReadOnly = array();
     if (!$this->securityContext->getToken()) {
         return array($roles, $rolesReadOnly);
     }
     // get roles from the Admin classes
     foreach ($this->pool->getAdminServiceIds() as $id) {
         try {
             $admin = $this->pool->getInstance($id);
         } catch (\Exception $e) {
             continue;
         }
         $isMaster = $admin->isGranted('MASTER');
         $securityHandler = $admin->getSecurityHandler();
         // TODO get the base role from the admin or security handler
         $baseRole = $securityHandler->getBaseRole($admin);
         if (strlen($baseRole) == 0) {
             // the security handler related to the admin does not provide a valid string
             continue;
         }
         foreach ($admin->getSecurityInformation() as $role => $permissions) {
             $role = sprintf($baseRole, $role);
             if ($isMaster) {
                 // if the user has the MASTER permission, allow to grant access the admin roles to other users
                 $roles[$role] = $role;
             } elseif ($this->securityContext->isGranted($role)) {
                 // although the user has no MASTER permission, allow the currently logged in user to view the role
                 $rolesReadOnly[$role] = $role;
             }
         }
     }
     $isMaster = $this->securityContext->isGranted('ROLE_SUPER_ADMIN');
     // get roles from the service container
     foreach ($this->rolesHierarchy as $name => $rolesHierarchy) {
         if ($this->securityContext->isGranted($name) || $isMaster) {
             $roles[$name] = $name . ': ' . implode(', ', $rolesHierarchy);
             foreach ($rolesHierarchy as $role) {
                 if (!isset($roles[$role])) {
                     $roles[$role] = $role;
                 }
             }
         }
     }
     return array($roles, $rolesReadOnly);
 }
Exemplo n.º 25
0
 /**
  * @param string $className
  *
  * @return AdminInterface
  */
 private function getAdminByClass($className)
 {
     if (!isset($this->admins[$className])) {
         // will return null if not defined
         $this->admins[$className] = $this->pool->getAdminByClass($className);
     }
     return $this->admins[$className];
 }
 public function testGetUrlsafeIdentifier()
 {
     $entity = new \stdClass();
     // set admin to pool
     $this->pool->setAdminClasses(array('stdClass' => array('sonata_admin_foo_service')));
     $this->admin->expects($this->once())->method('getUrlsafeIdentifier')->with($this->equalTo($entity))->will($this->returnValue(1234567));
     $this->assertEquals(1234567, $this->twigExtension->getUrlsafeIdentifier($entity));
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  */
 public function supports(PuliResource $resource)
 {
     if (false === $resource instanceof CmfResource) {
         return false;
     }
     $payload = $resource->getPayload();
     // sonata has dependency on ClassUtils so this is fine.
     $class = ClassUtils::getClass($payload);
     return $this->pool->hasAdminByClass($class);
 }
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     // Totals stats
     $tots = array('users' => $this->em->getRepository('ApplicationSonataUserBundle:User')->count(), 'children' => $this->em->getRepository('WCSCantineBundle:Eleve')->count(), 'meals' => $this->em->getRepository('WCSCantineBundle:Lunch')->count(), 'schools' => $this->em->getRepository('WCSCantineBundle:School')->count());
     $options['date_day'] = $this->date_now_service->getDate();
     $repoLunch = $this->em->getRepository('WCSCantineBundle:Lunch');
     // stats lunch : current week
     $options['enable_next_week'] = false;
     $options['without_pork'] = true;
     $currentWeekMealsNoPork = $repoLunch->getWeekMeals($options);
     $options['without_pork'] = false;
     $currentWeekMeals = $repoLunch->getWeekMeals($options);
     // stats lunch : next week
     $options['enable_next_week'] = true;
     $options['without_pork'] = true;
     $nextWeekMealsNoPork = $repoLunch->getWeekMeals($options);
     $options['without_pork'] = false;
     $nextWeekMeals = $repoLunch->getWeekMeals($options);
     return $this->renderResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'base_template' => $this->pool->getTemplate('WCSCantineBundle:Block:stateleves.html.twig'), 'settings' => $blockContext->getSettings(), 'currentWeekMeals' => $currentWeekMeals, 'currentWeekMealsNoPork' => $currentWeekMealsNoPork, 'nextWeekMeals' => $nextWeekMeals, 'nextWeekMealsNoPork' => $nextWeekMealsNoPork, 'tots' => $tots), $response);
 }
 /**
  * {@inheritdoc}
  */
 public function enhance(array $data, Resource $resource)
 {
     $object = $resource->getPayload();
     // sonata has dependency on ClassUtils so this is fine.
     $class = ClassUtils::getClass($object);
     if (false === $this->pool->hasAdminByClass($class)) {
         return $data;
     }
     $admin = $this->pool->getAdminByClass($class);
     $links = array();
     $routeCollection = $admin->getRoutes();
     foreach ($routeCollection->getElements() as $code => $route) {
         $routeName = $route->getDefault('_sonata_name');
         $url = $this->urlGenerator->generate($routeName, array($admin->getIdParameter() => $admin->getUrlsafeIdentifier($object)), true);
         $routeRole = substr($code, strlen($admin->getCode()) + 1);
         $links[$routeRole] = $url;
     }
     $data['label'] = $admin->toString($object);
     $data['sonata_label'] = $admin->getLabel();
     $data['sonata_links'] = $links;
     return $data;
 }
 /**
  * Builds sidebar menu.
  *
  * @return ItemInterface
  */
 public function createSidebarMenu()
 {
     $menu = $this->factory->createItem('root', array('extras' => array('request' => $this->request)));
     foreach ($this->pool->getAdminGroups() as $name => $group) {
         $attributes = array();
         $extras = array('icon' => $group['icon'], 'label_catalogue' => $group['label_catalogue'], 'roles' => $group['roles']);
         // Check if the menu group is built by a menu provider
         if (isset($group['provider'])) {
             $subMenu = $this->provider->get($group['provider']);
             $menu->addChild($subMenu)->setExtras(array_merge($subMenu->getExtras(), $extras))->setAttributes(array_merge($subMenu->getAttributes(), $attributes));
             continue;
         }
         // The menu group is built by config
         $menu->addChild($name, array('label' => $group['label'], 'attributes' => $attributes, 'extras' => $extras));
         foreach ($group['items'] as $item) {
             if (isset($item['admin']) && !empty($item['admin'])) {
                 $admin = $this->pool->getInstance($item['admin']);
                 // skip menu item if no `list` url is available or user doesn't have the LIST access rights
                 if (!$admin->hasRoute('list') || !$admin->isGranted('LIST')) {
                     continue;
                 }
                 $label = $admin->getLabel();
                 $options = $admin->generateMenuUrl('list');
                 $options['extras'] = array('translation_domain' => $admin->getTranslationDomain(), 'admin' => $admin);
             } else {
                 $label = $item['label'];
                 $options = array('route' => $item['route'], 'routeParameters' => $item['route_params'], 'extras' => array('translation_domain' => $group['label_catalogue']));
             }
             $menu[$name]->addChild($label, $options);
         }
         if (0 === count($menu[$name]->getChildren())) {
             $menu->removeChild($name);
         }
     }
     $event = new ConfigureMenuEvent($this->factory, $menu);
     $this->eventDispatcher->dispatch(ConfigureMenuEvent::SIDEBAR, $event);
     return $event->getMenu();
 }