Browse Source

#7 References are stored in database

Jérémie Libeau 7 years ago
parent
commit
6ee990a390

+ 3 - 0
README.md

@@ -10,6 +10,7 @@ A Symfony project created on March 28, 2017, 3:50 pm.
 
 * php70
 * php70-yaml
+* mysql
 
 ## Development
 
@@ -22,4 +23,6 @@ A Symfony project created on March 28, 2017, 3:50 pm.
 
 ```
 composer install
+bin/console doctrine:database:create
+bin/console doctrine:schema:update --force
 ```

+ 1 - 1
app/Resources/views/reference/list.html.twig

@@ -28,7 +28,7 @@
         </div>
         <div class="col-md-12">
             <a href="{{ path('create') }}" class="btn btn-success">Créer</a>
-            <a href="{{ asset('references.yml') }}" class="btn btn-default">Télécharger references.yml</a>
+            <a href="{{ path('list', {'_format': 'yml'}) }}" class="btn btn-default">Télécharger references.yml</a>
         </div>
     </div>
 {% endblock %}

+ 20 - 20
app/config/config.yml

@@ -42,26 +42,26 @@ twig:
         - 'bootstrap_3_horizontal_layout.html.twig'
 
 # Doctrine Configuration
-#doctrine:
-#    dbal:
-#        driver:   pdo_mysql
-#        host:     "%database_host%"
-#        port:     "%database_port%"
-#        dbname:   "%database_name%"
-#        user:     "%database_user%"
-#        password: "%database_password%"
-#        charset:  UTF8
-#        # if using pdo_sqlite as your database driver:
-#        #   1. add the path in parameters.yml
-#        #     e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
-#        #   2. Uncomment database_path in parameters.yml.dist
-#        #   3. Uncomment next line:
-#        #path:     "%database_path%"
-#
-#    orm:
-#        auto_generate_proxy_classes: "%kernel.debug%"
-#        naming_strategy: doctrine.orm.naming_strategy.underscore
-#        auto_mapping: true
+doctrine:
+    dbal:
+        driver:   pdo_mysql
+        host:     "%database_host%"
+        port:     "%database_port%"
+        dbname:   "%database_name%"
+        user:     "%database_user%"
+        password: "%database_password%"
+        charset:  UTF8
+        # if using pdo_sqlite as your database driver:
+        #   1. add the path in parameters.yml
+        #     e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
+        #   2. Uncomment database_path in parameters.yml.dist
+        #   3. Uncomment next line:
+        #path:     "%database_path%"
+
+    orm:
+        auto_generate_proxy_classes: "%kernel.debug%"
+        naming_strategy: doctrine.orm.naming_strategy.underscore
+        auto_mapping: true
 
 # Swiftmailer Configuration
 #swiftmailer:

+ 5 - 5
app/config/parameters.yml.dist

@@ -2,11 +2,11 @@
 # Set parameters here that may be different on each deployment target of the app, e.g. development, staging, production.
 # http://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
 parameters:
-    #database_host:     127.0.0.1
-    #database_port:     ~
-    #database_name:     symfony
-    #database_user:     root
-    #database_password: ~
+    database_host:     127.0.0.1
+    database_port:     ~
+    database_name:     references
+    database_user:     root
+    database_password: ~
     # You should uncomment this if you want use pdo_sqlite
     # database_path: "%kernel.root_dir%/data.db3"
 

+ 1 - 5
app/config/services.yml

@@ -14,8 +14,4 @@ services:
     twig.extension.text:
         class: Twig_Extensions_Extension_Text
         tags:
-            - { name: twig.extension }
-    app.manager.reference:
-        class: AppBundle\Entity\ReferenceManger
-        arguments:
-            - "%kernel.root_dir%/../web/references.yml"
+            - { name: twig.extension }

+ 0 - 33
app/data/references.yaml

@@ -831,28 +831,6 @@ references:
   title-short: Simonet
   number: Rec. p. 314
 - type: legal_case
-  id: cetatSimonet
-  authority: Conseil d’État
-  section: Sect.
-  issued: 
-    year: 1957
-    month: 05
-    day: 17
-  title: Simonet
-  title-short: Simonet
-  number: Rec. p. 314
-- type: legal_case
-  id: cetatSimonet
-  authority: Conseil d’État
-  section: Sect.
-  issued: 
-    year: 1957
-    month: 05
-    day: 17
-  title: Simonet
-  title-short: Simonet
-  number: Rec. p. 314
-- type: legal_case
   id: cconst2011150
   authority: Conseil constit.
   section: ''
@@ -942,17 +920,6 @@ references:
   title-short: De Souza Ribeiro c. France
   number: n^o^ 22689/07
 - type: legal_case
-  id: cjceJohnston
-  authority: CJCE
-  section: ''
-  issued:
-    year: 1986
-    month: 05
-    day: 15
-  title: "Marguerite Johnson"
-  title-short: Johnston
-  number: 222/84
-- type: legal_case
   id: cjueRundfunk
   authority: CJUE
   section: ''

+ 35 - 0
src/AppBundle/Command/LoadReferencesCommand.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace AppBundle\Command;
+
+use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+use Symfony\Component\Console\Input\InputArgument;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class LoadReferencesCommand extends ContainerAwareCommand
+{
+    /**
+     * {@inheritdoc}
+     */
+    protected function configure()
+    {
+        $this
+            ->setName('app:load_references')
+            ->addArgument('filename', InputArgument::REQUIRED, 'The YAML file containing references to load.')
+            ->setDescription('Load references form YAML file.');
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    protected function execute(InputInterface $input, OutputInterface $output)
+    {
+        $container = $this->getContainer();
+        $referenceManger = $container->get('doctrine.orm.entity_manager')->getRepository('AppBundle:Reference');
+
+        $filename = $input->getArgument('filename');
+
+        $referenceManger->loadFromFile($filename);
+    }
+}

+ 19 - 0
src/AppBundle/Controller/DefaultController.php

@@ -0,0 +1,19 @@
+<?php
+
+namespace AppBundle\Controller;
+
+use Symfony\Bundle\FrameworkBundle\Controller\Controller;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\Routing\Annotation\Route;
+
+class DefaultController extends Controller
+{
+    /**
+     * @return \Symfony\Component\HttpFoundation\RedirectResponse
+     * @Route("/", name="root")
+     */
+    public function indexAction()
+    {
+        return new RedirectResponse($this->generateUrl('list'));
+    }
+}

+ 66 - 24
src/AppBundle/Controller/ReferenceController.php

@@ -11,23 +11,54 @@ use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\RedirectResponse;
 use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
 
+/**
+ * Class ReferenceController
+ * @package AppBundle\Controller
+ * @Route(path="/references")
+ */
 class ReferenceController extends Controller
 {
     /**
-     * @Route("/", name="list")
+     * @Route(".{_format}", name="list", defaults={"_format": "html"}, requirements={"format": "html|yml|yaml"})
      */
-    public function listAction()
+    public function listAction(Request $request)
+    {
+        $format = $request->get("_format");
+        switch ($format) {
+            case 'yml':
+            case 'yaml':
+                $referenceManager = $this->get('doctrine.orm.entity_manager')
+                    ->getRepository('AppBundle:Reference');
+                $yml = $referenceManager->dumpYAML();
+
+                return new Response(
+                    $yml,
+                    Response::HTTP_OK,
+                    ['Content-Type' => 'application/yaml']
+                );
+                break;
+            default:
+                $referenceManager = $this->get('doctrine.orm.entity_manager')
+                    ->getRepository('AppBundle:Reference');
+                $references = $referenceManager->findAll();
+
+                return $this->render(
+                    ':reference:list.html.twig',
+                    [
+                        'references' => $references,
+                    ]
+                );
+        }
+    }
+
+    /**
+     * @Route("/{id}.{_format}", name="show", defaults={"_format": "html"}, requirements={"format": "html|yml|yaml|md"})
+     */
+    public function showAction(Request $request)
     {
-        $referenceManager = $this->get('app.manager.reference');
-        $references       = $referenceManager->findAll();
 
-        return $this->render(
-            ':reference:list.html.twig',
-            [
-                'references' => $references,
-            ]
-        );
     }
 
     /**
@@ -39,13 +70,17 @@ class ReferenceController extends Controller
     public function createAction(Request $request)
     {
         $reference = new Reference();
-        $form      = $this->createForm(ReferenceType::class, $reference, ['method' => 'PUT']);
+        $form = $this->createForm(
+            ReferenceType::class,
+            $reference,
+            ['method' => 'PUT']
+        );
         $form->handleRequest($request);
 
         if ($form->isSubmitted() && $form->isValid()) {
-            $referenceManager = $this->get('app.manager.reference');
+            $referenceManager = $this->get('doctrine.orm.entity_manager')
+                ->getRepository('AppBundle:Reference');
             $referenceManager->persist($reference);
-            $referenceManager->flush();
 
             return new RedirectResponse($this->generateUrl('list'));
         }
@@ -66,15 +101,19 @@ class ReferenceController extends Controller
      */
     public function editAction(Request $request, $id)
     {
-        $id               = rawurldecode($id);
-        $referenceManager = $this->get('app.manager.reference');
-        $reference        = $referenceManager->find($id);
-        $form             = $this->createForm(ReferenceType::class, $reference, ['method' => 'PATCH']);
+        $id = rawurldecode($id);
+        $referenceManager = $this->get('doctrine.orm.entity_manager')
+            ->getRepository('AppBundle:Reference');
+        $reference = $referenceManager->find($id);
+        $form = $this->createForm(
+            ReferenceType::class,
+            $reference,
+            ['method' => 'PATCH']
+        );
         $form->handleRequest($request);
 
         if ($form->isSubmitted() && $form->isValid()) {
             $referenceManager->persist($reference);
-            $referenceManager->flush();
 
             return new RedirectResponse($this->generateUrl('list'));
         }
@@ -96,17 +135,20 @@ class ReferenceController extends Controller
      */
     public function deleteAction($id)
     {
-        $id               = rawurldecode($id);
-        $referenceManager = $this->get('app.manager.reference');
-        $reference        = $referenceManager->find($id);
+        $id = rawurldecode($id);
+        $referenceManager = $this->get('doctrine.orm.entity_manager')
+            ->getRepository('AppBundle:Reference');
+        $reference = $referenceManager->find($id);
 
-        if ( ! $reference) {
+        if (!$reference) {
             throw $this->createNotFoundException();
         }
         $referenceManager->remove($reference);
-        $referenceManager->flush();
 
-        $response = ['status' => 'ok', 'redirect' => $this->generateUrl('list')];
+        $response = [
+            'status' => 'ok',
+            'redirect' => $this->generateUrl('list'),
+        ];
 
         return new JsonResponse($response);
     }

+ 21 - 1
src/AppBundle/Entity/Reference.php

@@ -9,8 +9,16 @@
 namespace AppBundle\Entity;
 
 
+use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
 use Symfony\Component\Validator\Constraints as Assert;
+use Doctrine\ORM\Mapping as ORM;
 
+/**
+ * Class Reference
+ * @package AppBundle\Entity
+ * @ORM\Entity(repositoryClass="AppBundle\Entity\ReferenceManger")
+ * @UniqueEntity(fields={"id"})
+ */
 class Reference
 {
     /**
@@ -52,12 +60,15 @@ class Reference
      *     "thesis",
      *     "treaty",
      *     "webpage"})
+     * @ORM\Column(type="string")
      */
     public $type;
 
     /**
      * @var string
      * @Assert\NotNull()
+     * @ORM\Column(type="string")
+     * @ORM\Id()
      */
     public $id;
 
@@ -151,7 +162,8 @@ class Reference
     public $eventDate;
 
     /**
-     * @var Date|null
+     * @var Date
+     * @ORM\Column(type="date")
      */
     public $issued;
 
@@ -192,6 +204,7 @@ class Reference
 
     /**
      * @var string|null
+     * @ORM\Column(type="string", nullable=true)
      */
     public $authority;
 
@@ -312,6 +325,7 @@ class Reference
 
     /**
      * @var string|null
+     * @ORM\Column(type="string", nullable=true)
      */
     public $number;
 
@@ -387,6 +401,7 @@ class Reference
 
     /**
      * @var string|null
+     * @ORM\Column(type="string", nullable=true)
      */
     public $section;
 
@@ -402,16 +417,19 @@ class Reference
 
     /**
      * @var string|null
+     * @ORM\Column(type="text", nullable=true)
      */
     public $title;
 
     /**
      * @var string|null
+     * @ORM\Column(type="text", nullable=true)
      */
     public $titleShort;
 
     /**
      * @var string|null
+     * @ORM\Column(type="string", nullable=true)
      */
     public $URL;
 
@@ -436,11 +454,13 @@ class Reference
 
     /**
      * @var string|null
+     * @ORM\Column(type="string", nullable=true)
      */
     public $ECLI;
 
     /**
      * @var string|null
+     * @ORM\Column(type="text", nullable=true)
      */
     public $comments;
 

+ 21 - 63
src/AppBundle/Entity/ReferenceManger.php

@@ -11,6 +11,8 @@ namespace AppBundle\Entity;
 
 use AppBundle\Serializer\DateDenormalizer;
 use Doctrine\Common\Collections\ArrayCollection;
+use Doctrine\ORM\EntityRepository;
+use Doctrine\ORM\Mapping\ClassMetadata;
 use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
 use Symfony\Component\Serializer\Encoder\YamlEncoder;
 use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
@@ -18,7 +20,7 @@ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
 use Symfony\Component\Serializer\Serializer;
 use Symfony\Component\Yaml\Yaml;
 
-class ReferenceManger
+class ReferenceManger extends EntityRepository
 {
     /**
      * @var Serializer
@@ -26,17 +28,13 @@ class ReferenceManger
     protected $serializer;
 
     /**
-     * @var string
-     */
-    protected $storageFilename;
-
-    /**
      * @var Reference[]
      */
     protected $references;
 
-    public function __construct($storageFilename)
+    public function __construct($em, ClassMetadata $class)
     {
+        parent::__construct($em, $class);
         $normalizers = [
             new DateDenormalizer(),
             new ObjectNormalizer(null, null, null, new PhpDocExtractor()),
@@ -54,76 +52,36 @@ class ReferenceManger
         ];
 
         $this->serializer = new Serializer($normalizers, $encoders);
-        $this->storageFilename = $storageFilename;
-    }
-
-    /**
-     * @return Reference[]
-     */
-    public function findAll()
-    {
-        $references = $this->getReferences();
-
-        return $references;
-    }
-
-    public function find($id)
-    {
-        $references = $this->getReferences();
-
-        foreach ($references as $reference) {
-            if ($reference->id === $id) {
-                return $reference;
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * @return Reference[]
-     */
-    public function getReferences()
-    {
-        if ($this->references === null) {
-            $data = file_get_contents($this->storageFilename);
-            /** @var References $references */
-            $this->references = $this->serializer->deserialize($data, 'AppBundle\\Entity\\References', 'yaml');
-        }
-
-        return $this->references->getReferences();
     }
 
     public function persist(Reference $reference)
     {
-        /** @var ArrayCollection $references */
-        $references = $this->getReferences();
-        // Has object are always passed by reference
-        if ($references->contains($reference)) {
-            return true;
-        }
-
-        return $references->add($reference);
+        $this->_em->persist($reference);
+        $this->_em->flush();
     }
 
     public function remove(Reference $reference)
     {
-        /** @var ArrayCollection $references */
-        $references = $this->getReferences();
-
-        return $references->removeElement($reference);
+        $this->_em->remove($reference);
+        $this->_em->flush();
     }
 
-    public function flush()
+    public function loadFromFile($filename)
     {
-        if ($this->references !== null) {
-            $out = $this->serializer->serialize($this->references, 'yaml');
-            file_put_contents($this->storageFilename, $out);
+        $data = file_get_contents($filename);
+        /** @var References $references */
+        $references = $this->serializer->deserialize($data, 'AppBundle\\Entity\\References', 'yaml');
+        foreach ($references->getReferences() as $reference) {
+            $this->_em->persist($reference);
         }
+        $this->_em->flush();
     }
 
-    public function clear()
+    public function dumpYAML()
     {
-        $this->references = null;
+        $references = $this->findAll();
+        $references = new References($references);
+
+        return $this->serializer->serialize($references, 'yaml');
     }
 }

+ 5 - 13
src/AppBundle/Entity/References.php

@@ -9,27 +9,19 @@
 namespace AppBundle\Entity;
 
 
-use Doctrine\Common\Collections\ArrayCollection;
-
 class References
 {
     /**
-     * This is a hack for serialization, because references are stored into elements attribute
      * @var Reference[]
      */
-    private $references;
+    public $references;
 
     /**
-     * @return ArrayCollection
+     * References constructor.
+     * @param \AppBundle\Entity\Reference[] $references
      */
-    public function getReferences()
-    {
-        return $this->references;
-    }
-
-
-    public function setReferences($collection)
+    public function __construct(array $references)
     {
-        $this->references = new ArrayCollection($collection);
+        $this->references = $references;
     }
 }