/**
  * @throws InvalidConfigurationException
  */
 public function configureTabMenu(AdminInterface $admin, MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
 {
     if (!($subject = $admin->getSubject())) {
         return;
     }
     if (!$subject instanceof RouteReferrersReadInterface && !$subject instanceof Route) {
         throw new InvalidConfigurationException(sprintf('%s can only be used on subjects which implement Symfony\\Cmf\\Component\\Routing\\RouteReferrersReadInterface or Symfony\\Component\\Routing\\Route.', __CLASS__));
     }
     if ($subject instanceof PrefixInterface && !is_string($subject->getId())) {
         // we have an unpersisted dynamic route
         return;
     }
     $defaults = array();
     if ($subject instanceof TranslatableInterface) {
         if ($locale = $subject->getLocale()) {
             $defaults['_locale'] = $locale;
         }
     }
     try {
         $uri = $this->router->generate($subject, $defaults);
     } catch (RoutingExceptionInterface $e) {
         // we have no valid route
         return;
     }
     $menu->addChild($this->translator->trans('admin.menu_frontend_link_caption', array(), 'CmfRoutingBundle'), array('uri' => $uri, 'attributes' => array('class' => 'sonata-admin-menu-item', 'role' => 'menuitem'), 'linkAttributes' => array('class' => 'sonata-admin-frontend-link', 'role' => 'button', 'target' => '_blank', 'title' => $this->translator->trans('admin.menu_frontend_link_title', array(), 'CmfRoutingBundle'))));
 }
 public function setUp()
 {
     $this->admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface', array('hasRoute', 'isGranted', 'generateObjectUrl', 'generateUrl', 'toString'));
     $this->pool = $this->getMock('Sonata\\AdminBundle\\Admin\\Pool', array('getAdminByClass'));
     $this->pool->expects($this->any())->method('getAdminByClass')->with($this->equalTo('Acme\\DemoBundle\\Model\\Demo'))->will($this->returnValue($this->admin));
     $this->twigExtension = new SonataTimelineExtension($this->pool);
 }
 /**
  * Configure the object ACL for the passed object identities
  *
  * @param OutputInterface      $output
  * @param AdminInterface       $admin
  * @param array                $oids an array of ObjectIdentityInterface implementations
  * @param UserSecurityIdentity $securityIdentity
  *
  * @throws \Exception
  *
  * @return array [countAdded, countUpdated]
  */
 public function configureAcls(OutputInterface $output, AdminInterface $admin, array $oids, UserSecurityIdentity $securityIdentity = null)
 {
     $countAdded = 0;
     $countUpdated = 0;
     $securityHandler = $admin->getSecurityHandler();
     if (!$securityHandler instanceof AclSecurityHandlerInterface) {
         $output->writeln(sprintf('Admin `%s` is not configured to use ACL : <info>ignoring</info>', $admin->getCode()));
         return array(0, 0);
     }
     $acls = $securityHandler->findObjectAcls($oids);
     foreach ($oids as $oid) {
         if ($acls->contains($oid)) {
             $acl = $acls->offsetGet($oid);
             $countUpdated++;
         } else {
             $acl = $securityHandler->createAcl($oid);
             $countAdded++;
         }
         if (!is_null($securityIdentity)) {
             // add object owner
             $securityHandler->addObjectOwner($acl, $securityIdentity);
         }
         $securityHandler->addObjectClassAces($acl, $securityHandler->buildSecurityInformation($admin));
         try {
             $securityHandler->updateAcl($acl);
         } catch (\Exception $e) {
             $output->writeln(sprintf('Error saving ObjectIdentity (%s, %s) ACL : %s <info>ignoring</info>', $oid->getIdentifier(), $oid->getType(), $e->getMessage()));
         }
     }
     return array($countAdded, $countUpdated);
 }
 /**
  * @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));
                 }
             }
         }
     }
 }
 /**
  * return the base template name
  *
  * @return string the template name
  */
 protected function getBaseTemplate()
 {
     if ($this->isXmlHttpRequest()) {
         return $this->admin->getTemplate('ajax');
     }
     return $this->admin->getTemplate('layout');
 }
 /**
  * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
  * @param array $values
  * @return \Sonata\AdminBundle\Datagrid\DatagridInterface
  */
 public function getBaseDatagrid(AdminInterface $admin, array $values = array())
 {
     $pager = new Pager();
     $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass()));
     $formBuilder = $this->formFactory->createNamedBuilder('form', 'filter', array(), array('csrf_protection' => false));
     return new Datagrid($admin->createQuery(), $admin->getList(), $pager, $formBuilder, $values);
 }
 /**
  * {@inheritdoc}
  */
 public function alterNewInstance(AdminInterface $admin, $object)
 {
     if ($object->getParent() == null) {
         $reflectionClass = $admin->getClass();
         $parent = $this->container->get('doctrine')->getRepository($reflectionClass)->findOneById($this->getRequest()->query->get('parent'));
         $object->setParent($parent);
     }
 }
 /**
  * {@inheritDoc}
  */
 public function buildSecurityInformation(AdminInterface $admin)
 {
     $baseRole = 'ROLE_' . str_replace('.', '_', strtoupper($admin->getCode())) . '_%s';
     $results = array();
     foreach ($admin->getSecurityInformation() as $name => $permissions) {
         $results[sprintf($baseRole, $name)] = $permissions;
     }
     return $results;
 }
 /**
  * {@inheritdoc}
  */
 public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
 {
     $fieldDescription->setTemplate('YnloAdminBundle::CRUD/list_enum.html.twig');
     /** @var ModelManager $modelManager */
     $modelManager = $admin->getModelManager();
     if (null === $fieldDescription->getOption('enum_type') && $modelManager->hasMetadata($admin->getClass())) {
         $mapping = $modelManager->getMetadata($admin->getClass())->getFieldMapping($fieldDescription->getName());
         $fieldDescription->setOption('enum_type', $mapping['type']);
     }
 }
 public function testWithFieldsCascadeTranslationDomain()
 {
     $this->admin->setModelManager($this->modelManager);
     $this->modelManager->expects($this->once())->method('getNewFieldDescriptionInstance')->with('class', 'foo', array('translation_domain' => 'Foobar', 'type' => 'bar'))->will($this->returnValue($this->fieldDescription));
     $this->contractor->expects($this->once())->method('getDefaultOptions')->will($this->returnValue(array()));
     $this->admin->setLabelTranslatorStrategy($this->labelTranslatorStrategy);
     $this->formMapper->with('foobar', array('translation_domain' => 'Foobar'))->add('foo', 'bar')->end();
     $this->assertSame(array('default' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'name' => 'default', 'auto_created' => true, 'groups' => array('foobar'), 'tab' => true)), $this->admin->getFormTabs());
     $this->assertSame(array('foobar' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'name' => 'foobar', 'fields' => array('foo' => 'foo'))), $this->admin->getFormGroups());
 }
 /**
  * @param FormMapper     $formMapper
  * @param AdminInterface $admin
  * @param string         $formField
  * @param string         $field
  * @param array          $fieldOptions
  * @param array          $adminOptions
  *
  * @return FormBuilder
  */
 protected final function getFormAdminType(FormMapper $formMapper, AdminInterface $admin, $formField, $field, $fieldOptions = array(), $adminOptions = array())
 {
     $adminOptions = array_merge(array('edit' => 'list', 'translation_domain' => 'SonataClassificationBundle'), $adminOptions);
     $fieldDescription = $admin->getModelManager()->getNewFieldDescriptionInstance($admin->getClass(), $field, $adminOptions);
     $fieldDescription->setAssociationAdmin($admin);
     $fieldDescription->setAdmin($formMapper->getAdmin());
     $fieldDescription->setAssociationMapping(array('fieldName' => $field, 'type' => ClassMetadataInfo::MANY_TO_ONE));
     $fieldOptions = array_merge(array('sonata_field_description' => $fieldDescription, 'class' => $admin->getClass(), 'model_manager' => $admin->getModelManager(), 'required' => false), $fieldOptions);
     return $formMapper->create($formField, 'sonata_type_model_list', $fieldOptions);
 }
 public function testIsGrantedWithException()
 {
     $this->setExpectedException('RuntimeException', 'Something is wrong');
     $this->admin->expects($this->any())->method('getCode')->will($this->returnValue('foo.bar'));
     $this->securityContext->expects($this->any())->method('isGranted')->will($this->returnCallback(function (array $attributes, $object) {
         throw new \RuntimeException('Something is wrong');
     }));
     $handler = $this->getRoleSecurityHandler(array('ROLE_BATMAN'));
     $handler->isGranted($this->admin, 'BAZ');
 }
 /**
  * {@inheritdoc}
  */
 public function buildField($type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
 {
     if ($type == null) {
         $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
         $fieldDescription->setType($guessType->getType());
     } else {
         $fieldDescription->setType($type);
     }
     $this->fixFieldDescription($admin, $fieldDescription);
 }
 /**
  * Sanity check and default locale to request locale.
  *
  * {@inheritdoc}
  */
 public function alterNewInstance(AdminInterface $admin, $object)
 {
     if (!$object instanceof TranslatableInterface) {
         throw new \InvalidArgumentException('Expected TranslatableInterface, got ' . get_class($object));
     }
     if ($admin->hasRequest()) {
         $currentLocale = $admin->getRequest()->getLocale();
         if (in_array($currentLocale, $this->locales)) {
             $object->setLocale($currentLocale);
         }
     }
 }
 /**
  * Return current translatable locale
  * ie: the locale used to load object translations != current request locale.
  *
  * @return string
  */
 public function getTranslatableLocale(AdminInterface $admin)
 {
     if ($this->translatableLocale == null) {
         if ($admin->getRequest()) {
             $this->translatableLocale = $admin->getRequest()->get(self::TRANSLATABLE_LOCALE_PARAMETER);
         }
         if ($this->translatableLocale == null) {
             $this->translatableLocale = $this->getDefaultTranslationLocale($admin);
         }
     }
     return $this->translatableLocale;
 }
 /**
  * Adds a field to the Field description collection and sets its type.
  * If not type provided, will try to guess it.
  *
  * @param \Sonata\AdminBundle\Admin\FieldDescriptionCollection $list
  * @param string|null $type
  * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
  * @return FieldDescriptionCollection
  */
 public function addField(FieldDescriptionCollection $list, $type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
 {
     if ($type == null) {
         $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName());
         $fieldDescription->setType($guessType->getType());
     } else {
         $fieldDescription->setType($type);
     }
     $this->fixFieldDescription($admin, $fieldDescription);
     $admin->addListFieldDescription($fieldDescription->getName(), $fieldDescription);
     return $list->add($fieldDescription);
 }
 public function testWithFieldsCascadeTranslationDomain()
 {
     $this->contractor->expects($this->once())->method('getDefaultOptions')->will($this->returnValue(array()));
     $this->formMapper->with('foobar', array('translation_domain' => 'Foobar'))->add('foo', 'bar')->end();
     $fieldDescription = $this->admin->getFormFieldDescription('foo');
     $this->assertEquals('foo', $fieldDescription->getName());
     $this->assertEquals('bar', $fieldDescription->getType());
     $this->assertEquals('Foobar', $fieldDescription->getTranslationDomain());
     $this->assertTrue($this->formMapper->has('foo'));
     $this->assertEquals(array('default' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'auto_created' => true, 'groups' => array('foobar'), 'tab' => true, 'name' => 'default', 'box_class' => 'box box-primary')), $this->admin->getFormTabs());
     $this->assertEquals(array('foobar' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'fields' => array('foo' => 'foo'), 'name' => 'foobar', 'box_class' => 'box box-primary')), $this->admin->getFormGroups());
 }
 /**
  * RouteBuilder that allowes slashes in the ids.
  *
  * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
  * @param \Sonata\AdminBundle\Route\RouteCollection $collection
  */
 function build(AdminInterface $admin, RouteCollection $collection)
 {
     $collection->add('list');
     $collection->add('create');
     $collection->add('batch');
     $collection->add('edit', $admin->getRouterIdParameter() . '/edit', array(), array('id' => '.+'));
     $collection->add('delete', $admin->getRouterIdParameter() . '/delete', array(), array('id' => '.+'));
     $collection->add('show', $admin->getRouterIdParameter(), array(), array('id' => '.+', '_method' => 'GET'));
     // add children urls
     foreach ($admin->getChildren() as $children) {
         $collection->addCollection($children->getRoutes());
     }
 }
 /**
  * {@inheritdoc}
  */
 public function preUpdate(AdminInterface $admin, $object)
 {
     if (!$admin->hasRequest() || !($data = $admin->getRequest()->get($admin->getUniqid()))) {
         return;
     }
     if (!isset($data[$this->fieldName])) {
         return;
     }
     $modelManager = $admin->getModelManager();
     if (!$modelManager instanceof LockInterface) {
         return;
     }
     $modelManager->lock($object, $data[$this->fieldName]);
 }
    /**
     * return the Response object associated to the view action
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction($id)
    {
        if (false === $this->admin->isGranted('SHOW')) {
            throw new AccessDeniedException();
        }

        $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        $this->admin->setSubject($object);

        // build the show list
        $elements = $this->admin->getShow();

        return $this->render($this->admin->getShowTemplate(), array(
            'action'         => 'show',
            'object'         => $object,
            'elements'       => $this->admin->getShow(),
            'admin'          => $this->admin,
            'base_template'  => $this->getBaseTemplate(),
        ));
    }
 /**
  * Returns the Response object associated to the acl action.
  *
  * @param int|string|null $id
  *
  * @return Response|RedirectResponse
  *
  * @throws AccessDeniedException If access is not granted.
  * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  */
 public function aclAction($id = null)
 {
     if (!$this->admin->isAclEnabled()) {
         throw new NotFoundHttpException('ACL are not enabled for this admin');
     }
     $id = $this->get('request')->get($this->admin->getIdParameter());
     $object = $this->admin->getObject($id);
     if (!$object) {
         throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
     }
     if (false === $this->admin->isGranted('MASTER', $object)) {
         throw new AccessDeniedException();
     }
     $this->admin->setSubject($object);
     $aclUsers = $this->getAclUsers();
     $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
     $adminObjectAclData = new AdminObjectAclData($this->admin, $object, $aclUsers, $adminObjectAclManipulator->getMaskBuilderClass());
     $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
     $request = $this->getRequest();
     if ($request->getMethod() === 'POST') {
         $form->submit($request);
         if ($form->isValid()) {
             $adminObjectAclManipulator->updateAcl($adminObjectAclData);
             $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
             return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
         }
     }
     return $this->render($this->admin->getTemplate('acl'), array('action' => 'acl', 'permissions' => $adminObjectAclData->getUserPermissions(), 'object' => $object, 'users' => $aclUsers, 'form' => $form->createView()));
 }
 public function testGroupRemovingWithTabAndWithTabRemoving()
 {
     $this->formMapper->tab('mytab')->with('foobar');
     $this->formMapper->removeGroup('foobar', 'mytab', true);
     $this->assertSame(array(), $this->admin->getFormGroups());
     $this->assertSame(array(), $this->admin->getFormTabs());
 }
 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));
 }
 public function testExtractWithException()
 {
     $this->setExpectedException('RuntimeException', 'Foo throws exception');
     $this->fooAdmin->expects($this->any())->method('getShow')->will($this->returnCallback(function () {
         throw new \RuntimeException('Foo throws exception');
     }));
     $catalogue = $this->adminExtractor->extract();
 }
 /**
  * {@inheritDoc}
  */
 public function addField(FieldDescriptionCollection $list, $type = null, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
 {
     if ($type == null) {
         $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
         $fieldDescription->setType($guessType->getType());
     } else {
         $fieldDescription->setType($type);
     }
     $this->fixFieldDescription($admin, $fieldDescription);
     $admin->addShowFieldDescription($fieldDescription->getName(), $fieldDescription);
     switch ($fieldDescription->getMappingType()) {
         case ClassMetadata::MANY_TO_ONE:
         case ClassMetadata::MANY_TO_MANY:
             return;
         default:
             $list->add($fieldDescription);
     }
 }
 /**
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function exportAction(Request $request)
 {
     if (false === $this->admin->isGranted('EXPORT')) {
         throw new AccessDeniedException();
     }
     $format = $request->get('format');
     $filename = sprintf('export_%s_%s.%s', strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)), date('Y_m_d_H_i_s', strtotime('now')), $format);
     return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
 }
    /**
     * Note:
     *   This code is ugly, but there is no better way of doing it.
     *   For now the append form element action used to add a new row works
     *   only for direct FieldDescription (not nested one)
     *
     * @throws \RuntimeException
     * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
     * @param  $elementId
     * @return void
     */
    public function appendFormFieldElement(AdminInterface $admin, $elementId)
    {
        // retrieve the subject
        $formBuilder = $admin->getFormBuilder();

        $form  = $formBuilder->getForm();
        $form->bindRequest($admin->getRequest());

        // get the field element
        $childFormBuilder = $this->getChildFormBuilder($formBuilder, $elementId);

        // retrieve the FieldDescription
        $fieldDescription = $admin->getFormFieldDescription($childFormBuilder->getName());

        try {
            $value = $fieldDescription->getValue($form->getData());
        } catch (NoValueException $e) {
            $value = null;
        }

        // retrieve the posted data
        $data = $admin->getRequest()->get($formBuilder->getName());

        if (!isset($data[$childFormBuilder->getName()])) {
            $data[$childFormBuilder->getName()] = array();
        }

        $objectCount   = count($value);
        $postCount     = count($data[$childFormBuilder->getName()]);

        $fields = array_keys($fieldDescription->getAssociationAdmin()->getFormFieldDescriptions());

        // for now, not sure how to do that
        $value = array();
        foreach ($fields as $name) {
            $value[$name] = '';
        }

        // add new elements to the subject
        while($objectCount < $postCount) {
            // append a new instance into the object
            $this->addNewInstance($form->getData(), $fieldDescription);
            $objectCount++;
        }

        $this->addNewInstance($form->getData(), $fieldDescription);
        $data[$childFormBuilder->getName()][] = $value;

        $form = $admin->getFormBuilder($form->getData())->getForm();

        // bind the data
        $form->bind($data);

        return array($fieldDescription, $form);
    }
 /**
  * Set a default parent if defined in the request
  *
  * {@inheritDoc}
  */
 public function alterNewInstance(AdminInterface $admin, $object)
 {
     if (!$admin->hasRequest() || !($parentId = $admin->getRequest()->get('parent'))) {
         return;
     }
     $parent = $admin->getModelManager()->find(null, $parentId);
     if (!$parent) {
         return;
     }
     switch ($object) {
         case $object instanceof HierarchyInterface:
             $object->setParentDocument($parent);
             break;
         case $object instanceof ChildInterface:
             $object->setParentObject($parent);
             break;
         default:
             throw new \InvalidArgumentException(sprintf('Class %s is not supported', get_class($object)));
     }
 }
Exemple #29
0
 /**
  * @param AdminInterface $admin
  * @param string         $term
  * @param int            $page
  * @param int            $offset
  *
  * @return \Sonata\AdminBundle\Datagrid\PagerInterface
  *
  * @throws \RuntimeException
  */
 public function search(AdminInterface $admin, $term, $page = 0, $offset = 20)
 {
     $datagrid = $admin->getDatagrid();
     $found = false;
     foreach ($datagrid->getFilters() as $name => $filter) {
         /** @var $filter FilterInterface */
         if ($filter->getOption('global_search', false)) {
             $filter->setCondition(FilterInterface::CONDITION_OR);
             $datagrid->setValue($name, null, $term);
             $found = true;
         }
     }
     if (!$found) {
         return false;
     }
     $datagrid->buildPager();
     $pager = $datagrid->getPager();
     $pager->setPage($page);
     $pager->setMaxPerPage($offset);
     return $pager;
 }
 public function testGetKnpMenuWithNotGrantedList()
 {
     $request = $this->getMock('Symfony\\Component\\HttpFoundation\\Request');
     $adminGroups = array('bar' => array('label' => 'foo', 'icon' => '<i class="fa fa-edit"></i>', 'label_catalogue' => 'SonataAdminBundle', 'items' => array(array('admin' => 'sonata_admin_foo_service', 'label' => 'fooLabel')), 'item_adds' => array(), 'roles' => array()));
     $this->pool->setAdminGroups($adminGroups);
     $this->admin->expects($this->once())->method('hasRoute')->with($this->equalTo('list'))->will($this->returnValue(true));
     $this->admin->expects($this->any())->method('isGranted')->with($this->equalTo('LIST'))->will($this->returnValue(false));
     $menu = $this->twigExtension->getKnpMenu($request);
     $this->assertInstanceOf('Knp\\Menu\\ItemInterface', $menu);
     $this->assertArrayNotHasKey('bar', $menu->getChildren());
     $this->assertCount(0, $menu->getChildren());
 }