<commit_before><?php

/*
 * This file is part of the EasyAdminBundle.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Some parts of this file are copied and/or inspired by the
 * DoctrineCRUDGenerator included in the SensioGeneratorBundle.
 *   License: MIT License
 *   Copyright: (c) <NAME> <<EMAIL>>
 *   Source: https://github.com/sensiolabs/SensioGeneratorBundle
 */

namespace JavierEguiluz\Bundle\EasyAdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;

class AdminController extends Controller
{
    protected $allowedActions = array('list', 'edit', 'new', 'show', 'search', 'delete');
    protected $config;
    protected $entity;
    protected $request;

    /**
     * @Route("/", name="admin")
     */
    public function indexAction(Request $request)
    {
        $result = $this->initialize($request);

        // initialize() returns a Response object when an error occurs.
        // This allows to display a detailed error message.
        if ($result instanceof Response) {
            return $result;
        }

        $action = $request->get('action', 'list');

        // for now, the homepage redirects to the 'list' action of the first entity
        if (null === $request->get('entity')) {
            return $this->redirect($this->generateUrl('admin', array('action' => $action, 'entity' => $this->getNameOfTheFirstConfiguredEntity())));
        }

        return $this->{$action.'Action'}($request);
    }

    protected function initialize(Request $request)
    {
        $this->config = $this->container->getParameter('easy_admin.config');

        if (0 === count($this->config['entities'])) {
            return $this->render('@EasyAdmin/error/no_entities.html.twig', array(), new Response('', 404));
        }

        if (!in_array($action = $request->get('action', 'list'), $this->allowedActions)) {
            return $this->render('@EasyAdmin/error/forbidden_action.html.twig', array(
                'action' => $action,
                'allowed_actions' => $this->allowedActions,
            ), new Response('', 404));
        }

        if (null !== $entityName = $request->get('entity')) {
            $this->entity['name'] = $entityName;
            $this->entity['class'] = $this->config['entities'][$entityName]['class'];
            $this->entity['metadata'] = $this->getEntityMetadata($this->entity['class']);
        }

        if (!$request->query->has('sortField')) {
            $request->query->set('sortField', 'id');
        }
        if (!$request->query->has('sortDirection') || !in_array(strtoupper($request->query->has('sortDirection')), array('ASC', 'DESC'))) {
            $request->query->set('sortDirection', 'DESC');
        }

        $this->em = $this->getDoctrine()->getManager();
    }

    public function listAction(Request $request)
    {
        $fields = $this->getFieldsForList($this->entity['metadata']->fieldMappings);
        $paginator = $this->findAll($this->entity['class'], $request->get('page', 1), $this->config['list_max_results'], $request->get('sortField'), $request->get('sortDirection'));

        return $this->render('@EasyAdmin/list.html.twig', array(
            'config'    => $this->config,
            'entity'    => $this->entity,
            'paginator' => $paginator,
            'fields'    => $fields,
        ));
    }

    public function editAction(Request $request)
    {
        if (!$item = $this->em->getRepository($this->entity['class'])->find($request->get('id'))) {
            throw $this->createNotFoundException(sprintf('Unable to find entity (%s #%d).', $this->entity['name'], $request->get('id')));
        }

        $fields = $this->getFieldsForEdit($this->entity['metadata']->fieldMappings);
        $editForm = $this->createEditForm($item, $fields);
        $deleteForm = $this->createDeleteForm($this->entity['name'], $request->get('id'));

        $editForm->handleRequest($request);
        if ($editForm->isValid()) {
            $item = $this->prepareEditEntityForPersist($item);
            $this->getDoctrine()->getEntityManager()->flush();

            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        return $this->render('@EasyAdmin/edit.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'form'   => $editForm->createView(),
            'item'   => $item,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function showAction(Request $request)
    {
        if (!$item = $this->em->getRepository($this->entity['class'])->find($request->get('id'))) {
            throw $this->createNotFoundException(sprintf('Unable to find entity (%s #%d).', $this->entity['name'], $request->get('id')));
        }

        $fields = $this->getFieldsForShow($this->entity['metadata']->fieldMappings);
        $deleteForm = $this->createDeleteForm($this->entity['name'], $request->get('id'));

        return $this->render('@EasyAdmin/show.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'item'   => $item,
            'fields' => $fields,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function newAction(Request $request)
    {
        $entityFullyQualifiedClassName = $this->entity['class'];
        $item = new $entityFullyQualifiedClassName();

        $fields = $this->getFieldsForNew($this->entity['metadata']->fieldMappings);
        $newForm = $this->createNewForm($item, $fields);

        $newForm->handleRequest($request);
        if ($newForm->isValid()) {
            $item = $this->prepareNewEntityForPersist($item);
            $this->em->persist($item);
            $this->em->flush();

            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        return $this->render('@EasyAdmin/new.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'form'   => $newForm->createView(),
            'item'   => $item,
        ));
    }

    public function deleteAction(Request $request)
    {
        if ('DELETE' !== $request->getMethod()) {
            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        $form = $this->createDeleteForm($this->entity['name'], $request->get('id'));
        $form->handleRequest($request);

        if ($form->isValid()) {
            if (!$entity = $this->em->getRepository($this->entity['class'])->find($request->get('id'))) {
                throw $this->createNotFoundException('The entity to be delete does not exist.');
            }

            $this->em->remove($entity);
            $this->em->flush();
        }

        return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
    }

    public function searchAction(Request $request)
    {
        $searchableFields = $this->getSearchableFields($this->entity['metadata']->fieldMappings);
        $paginator = $this->findBy($this->entity['class'], $request->get('query'), $searchableFields, $request->get('page', 1), $this->config['list_max_results']);
        $fields = $this->getFieldsForSearch($this->entity['metadata']->fieldMappings);

        return $this->render('@EasyAdmin/list.html.twig', array(
            'config'    => $this->config,
            'entity'    => $this->entity,
            'paginator' => $paginator,
            'fields'    => $fields,
        ));
    }

    /**
     * Takes the FQCN of the Doctrine entity and returns all its configured metadata.
     */
    protected function getEntityMetadata($entityClass)
    {
        $factory = new DisconnectedMetadataFactory($this->getDoctrine());
        $metadata = $factory->getClassMetadata($entityClass)->getMetadata();
        $metadata = $metadata[0];

        // add fields for relationships
        $associationFieldMappings = array();
        foreach ($metadata->associationMappings as $fieldName => $relation) {
            if (ClassMetadataInfo::ONE_TO_MANY !== $relation['type']) {
                $associationFieldMappings[$fieldName] = array(
                    'fieldName'    => $fieldName,
                    'type'         => 'association',
                    'targetEntity' => $relation['targetEntity'],
                );
            }
        }<commit_msg>minor #29 explicitly use query parameters, fixes #20 (xabbuh)<commit_after><?php

/*
 * This file is part of the EasyAdminBundle.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Some parts of this file are copied and/or inspired by the
 * DoctrineCRUDGenerator included in the SensioGeneratorBundle.
 *   License: MIT License
 *   Copyright: (c) <NAME> <<EMAIL>>
 *   Source: https://github.com/sensiolabs/SensioGeneratorBundle
 */

namespace JavierEguiluz\Bundle\EasyAdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;

class AdminController extends Controller
{
    protected $allowedActions = array('list', 'edit', 'new', 'show', 'search', 'delete');
    protected $config;
    protected $entity;
    protected $request;

    /**
     * @Route("/", name="admin")
     */
    public function indexAction(Request $request)
    {
        $result = $this->initialize($request);

        // initialize() returns a Response object when an error occurs.
        // This allows to display a detailed error message.
        if ($result instanceof Response) {
            return $result;
        }

        $action = $request->query->get('action', 'list');

        // for now, the homepage redirects to the 'list' action of the first entity
        if (null === $request->query->get('entity')) {
            return $this->redirect($this->generateUrl('admin', array('action' => $action, 'entity' => $this->getNameOfTheFirstConfiguredEntity())));
        }

        return $this->{$action.'Action'}($request);
    }

    protected function initialize(Request $request)
    {
        $this->config = $this->container->getParameter('easy_admin.config');

        if (0 === count($this->config['entities'])) {
            return $this->render('@EasyAdmin/error/no_entities.html.twig', array(), new Response('', 404));
        }

        if (!in_array($action = $request->query->get('action', 'list'), $this->allowedActions)) {
            return $this->render('@EasyAdmin/error/forbidden_action.html.twig', array(
                'action' => $action,
                'allowed_actions' => $this->allowedActions,
            ), new Response('', 404));
        }

        if (null !== $entityName = $request->query->get('entity')) {
            $this->entity['name'] = $entityName;
            $this->entity['class'] = $this->config['entities'][$entityName]['class'];
            $this->entity['metadata'] = $this->getEntityMetadata($this->entity['class']);
        }

        if (!$request->query->has('sortField')) {
            $request->query->set('sortField', 'id');
        }
        if (!$request->query->has('sortDirection') || !in_array(strtoupper($request->query->has('sortDirection')), array('ASC', 'DESC'))) {
            $request->query->set('sortDirection', 'DESC');
        }

        $this->em = $this->getDoctrine()->getManager();
    }

    public function listAction(Request $request)
    {
        $fields = $this->getFieldsForList($this->entity['metadata']->fieldMappings);
        $paginator = $this->findAll($this->entity['class'], $request->query->get('page', 1), $this->config['list_max_results'], $request->query->get('sortField'), $request->query->get('sortDirection'));

        return $this->render('@EasyAdmin/list.html.twig', array(
            'config'    => $this->config,
            'entity'    => $this->entity,
            'paginator' => $paginator,
            'fields'    => $fields,
        ));
    }

    public function editAction(Request $request)
    {
        if (!$item = $this->em->getRepository($this->entity['class'])->find($request->query->get('id'))) {
            throw $this->createNotFoundException(sprintf('Unable to find entity (%s #%d).', $this->entity['name'], $request->query->get('id')));
        }

        $fields = $this->getFieldsForEdit($this->entity['metadata']->fieldMappings);
        $editForm = $this->createEditForm($item, $fields);
        $deleteForm = $this->createDeleteForm($this->entity['name'], $request->query->get('id'));

        $editForm->handleRequest($request);
        if ($editForm->isValid()) {
            $item = $this->prepareEditEntityForPersist($item);
            $this->getDoctrine()->getEntityManager()->flush();

            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        return $this->render('@EasyAdmin/edit.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'form'   => $editForm->createView(),
            'item'   => $item,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function showAction(Request $request)
    {
        if (!$item = $this->em->getRepository($this->entity['class'])->find($request->query->get('id'))) {
            throw $this->createNotFoundException(sprintf('Unable to find entity (%s #%d).', $this->entity['name'], $request->query->get('id')));
        }

        $fields = $this->getFieldsForShow($this->entity['metadata']->fieldMappings);
        $deleteForm = $this->createDeleteForm($this->entity['name'], $request->query->get('id'));

        return $this->render('@EasyAdmin/show.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'item'   => $item,
            'fields' => $fields,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    public function newAction(Request $request)
    {
        $entityFullyQualifiedClassName = $this->entity['class'];
        $item = new $entityFullyQualifiedClassName();

        $fields = $this->getFieldsForNew($this->entity['metadata']->fieldMappings);
        $newForm = $this->createNewForm($item, $fields);

        $newForm->handleRequest($request);
        if ($newForm->isValid()) {
            $item = $this->prepareNewEntityForPersist($item);
            $this->em->persist($item);
            $this->em->flush();

            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        return $this->render('@EasyAdmin/new.html.twig', array(
            'config' => $this->config,
            'entity' => $this->entity,
            'form'   => $newForm->createView(),
            'item'   => $item,
        ));
    }

    public function deleteAction(Request $request)
    {
        if ('DELETE' !== $request->query->getMethod()) {
            return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
        }

        $form = $this->createDeleteForm($this->entity['name'], $request->query->get('id'));
        $form->handleRequest($request);

        if ($form->isValid()) {
            if (!$entity = $this->em->getRepository($this->entity['class'])->find($request->query->get('id'))) {
                throw $this->createNotFoundException('The entity to be delete does not exist.');
            }

            $this->em->remove($entity);
            $this->em->flush();
        }

        return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
    }

    public function searchAction(Request $request)
    {
        $searchableFields = $this->getSearchableFields($this->entity['metadata']->fieldMappings);
        $paginator = $this->findBy($this->entity['class'], $request->query->get('query'), $searchableFields, $request->query->get('page', 1), $this->config['list_max_results']);
        $fields = $this->getFieldsForSearch($this->entity['metadata']->fieldMappings);

        return $this->render('@EasyAdmin/list.html.twig', array(
            'config'    => $this->config,
            'entity'    => $this->entity,
            'paginator' => $paginator,
            'fields'    => $fields,
        ));
    }

    /**
     * Takes the FQCN of the Doctrine entity and returns all its configured metadata.
     */
    protected function getEntityMetadata($entityClass)
    {
        $factory = new DisconnectedMetadataFactory($this->getDoctrine());
        $metadata = $factory->getClassMetadata($entityClass)->getMetadata();
        $metadata = $metadata[0];

        // add fields for relationships
        $associationFieldMappings = array();
        foreach ($metadata->associationMappings as $fieldName => $relation) {
            if (ClassMetadataInfo::ONE_TO_MANY !== $relation['type']) {
                $associationFieldMappings[$fieldName] = array(
                    'fieldName'    => $fieldName,
                    'type'         => 'association',
                    'targetEntity' => $relation['targetEntity'],
                );
            }
        }
{'fraction_non_alphanumeric': 0.18079375549692173, 'fraction_numerical': 0.0013192612137203166, 'mean_word_length': 2.811648858160486, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 417, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1758121', 'n_tokens_mistral': 5129, 'n_tokens_neox': 5029, 'n_words': 922}