mirror of
				https://gitlab.com/Chill-Projet/chill-bundles.git
				synced 2025-10-31 01:08:26 +00:00 
			
		
		
		
	Compare commits
	
		
			288 Commits
		
	
	
		
			feature-ad
			...
			139_demand
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 003b9e7234 | |||
| 8bd75429c1 | |||
| 199e5a73d8 | |||
| 54d03275cf | |||
| 8683f8faf3 | |||
| 821b67723c | |||
| ae1146c79c | |||
| 050c325195 | |||
| 5e0d869d9b | |||
| 32b8de8997 | |||
| 9f1f7ad3f7 | |||
| 9da4c1ebeb | |||
| 9b7a52064a | |||
| faad3f5f47 | |||
| f548121312 | |||
| 1ecb1abc80 | |||
| 28a45992c6 | |||
| c39097f164 | |||
| 30b127bc88 | |||
| 25d7fc36a4 | |||
| 03bd1674e1 | |||
| b018a50a7e | |||
| 4440cf8a24 | |||
| 242c77a30c | |||
| 22aa4afc02 | |||
| 04e9e30972 | |||
| d536da3581 | |||
| 27f49b2aa3 | |||
| 9ef397e935 | |||
| eca8172c6d | |||
| f3802e36b3 | |||
| 2f9c7c38b5 | |||
| 8e95166c24 | |||
| 30c53b17f7 | |||
| 2610730219 | |||
| d327dae9fa | |||
| 2bdbb20154 | |||
| 14bd211a5f | |||
| 35627203e6 | |||
| f978636d57 | |||
| e095cac7e0 | |||
| c5b0d6e2bd | |||
|  | 905cb66011 | ||
| eaac97221f | |||
|  | 893c38fba4 | ||
|  | f867f4985d | ||
|  | aebeefcf80 | ||
|  | 3fc6c0c479 | ||
|  | ce854cb58f | ||
|  | ed4f1344c2 | ||
|  | 86dbe527d8 | ||
|  | 69a56fb433 | ||
|  | a7fad0ca1b | ||
|  | 9b8c34a9be | ||
| 5acc78507e | |||
| 1722cf721e | |||
| 75ba07f181 | |||
| 5b635fbe58 | |||
| e0dc0a8fdb | |||
| 2aa13dceff | |||
| 55264da092 | |||
| 38f5854c6d | |||
| 3c6d3f30d2 | |||
| a6d6a962cd | |||
| 6256d6a19e | |||
| 9710f8be63 | |||
| d872bf65dd | |||
| 51a4880fdb | |||
| a4d22b0fcb | |||
| 8d051800a4 | |||
|  | c0b59162a1 | ||
| 0e53a081c7 | |||
| d76f6d716f | |||
| f1d5d9840e | |||
| f3eb418409 | |||
| 3e85529468 | |||
| 05798688d0 | |||
| 01f35eed04 | |||
| aef97cca32 | |||
| 87e2ac9386 | |||
| 4a04628d5b | |||
| 0af78f814c | |||
| 929d40ff6e | |||
| 68f6642ff2 | |||
| 91e4d585ff | |||
| eac42581a6 | |||
|  | 4e50d0ace9 | ||
|  | 0b54adeb59 | ||
|  | 5d23de4862 | ||
|  | eda454cb9d | ||
| 6da8f1c107 | |||
| 4fb487dcef | |||
| 0d6a339b53 | |||
| c6525be444 | |||
| cb846891d6 | |||
| 2aed37757e | |||
| 444159b52a | |||
| 7aed8e83ea | |||
| f7a807473d | |||
| f8e91c325d | |||
| a448405ce5 | |||
| a4989f99d6 | |||
| 3f64db3b3a | |||
|  | 7ee5ca0753 | ||
| 41254db72f | |||
|  | 15e301b889 | ||
| 061a7dd537 | |||
|  | c3926991ac | ||
|  | ea0b2407df | ||
| 569679238c | |||
| ed17f78da5 | |||
| dfd9230541 | |||
| 65b751642f | |||
| d6fd827f8b | |||
| 162b0099b2 | |||
| e0b689174a | |||
| edf4430fb1 | |||
| 040884a039 | |||
| f7c08f02c2 | |||
|  | 2fe38945d2 | ||
| cece152c0b | |||
| 4e31b3e424 | |||
| 109bf5ec5d | |||
| 4f3f16d9b0 | |||
|  | fe5745831c | ||
| 3447117742 | |||
| 143f8f43fa | |||
| 36326a2a70 | |||
| bfdfd19711 | |||
|  | efb9bc938a | ||
| dcd1856ebb | |||
| 43f3270171 | |||
| b7fcac8f39 | |||
| e521d06702 | |||
| a260274549 | |||
| b37a7d2690 | |||
| 242c2b31a3 | |||
| 57c420e9dd | |||
| ac67f56b09 | |||
| b24eb93c57 | |||
| 0f59be04a7 | |||
| 54eb15ea35 | |||
| a85f170e2d | |||
| 226f71ab2b | |||
| a887326611 | |||
| 8ed2e7585d | |||
| 7a1ad24f0e | |||
|  | b934c2eeaf | ||
| de0e3f7dfd | |||
| 44c9a65505 | |||
| 038d7ad2e1 | |||
|  | c1b727b1c8 | ||
| a63c38b6aa | |||
| 8915c42008 | |||
| 503293a359 | |||
| 7bdf71315a | |||
| 6f5d457122 | |||
| b4274264a7 | |||
| 8002725c87 | |||
| 2c9edf3741 | |||
| 3f562449e1 | |||
| 1cce39bcb5 | |||
| c93d5ceb16 | |||
| ad690db886 | |||
|  | 1b8462b40d | ||
|  | 8c98f2cf6e | ||
| f3260f57a4 | |||
| b4ad0128e4 | |||
| e1c8278f71 | |||
|  | ed3f46ce7f | ||
| 33457d3cbc | |||
| 6df8e6dec8 | |||
| f9b8f13dd6 | |||
| e919b4322e | |||
| 7503c845df | |||
| 3686a294d3 | |||
| b6131379f9 | |||
| e1fcc41ace | |||
| f2a04cebe6 | |||
| c693002ddb | |||
| ee77c8540a | |||
| a536d2780e | |||
| f880598052 | |||
| e7985ea52f | |||
| f56dc65021 | |||
|  | 4770758aee | ||
| 90fe484d81 | |||
| 2b8bbe019d | |||
| 9e1c151402 | |||
| 088e522292 | |||
| b8e6e98a74 | |||
| 2db847ada2 | |||
| 07e0692783 | |||
| e78d53064b | |||
| e6fcb5ff22 | |||
| f02e33fda7 | |||
| 1bbec9efae | |||
| 3b53c4451c | |||
| 30f490959b | |||
|  | 0a894b0db1 | ||
| c20e9507d5 | |||
| f89c690f1b | |||
|  | 7819c1204c | ||
|  | f61af9d02a | ||
|  | e470a6a97e | ||
|  | cd8c47449b | ||
| 120e7cade5 | |||
| ac550e05e8 | |||
| d6e7fadb4f | |||
|  | 2be1c08c44 | ||
|  | 86c177bbbb | ||
|  | d426d28ba0 | ||
|  | 72e69fc0b3 | ||
| cc8de353d4 | |||
| 4495a5d33b | |||
| 9dffe30aad | |||
| d393e74896 | |||
| daf083dc88 | |||
|  | ce859697b5 | ||
|  | 1587c762f8 | ||
|  | 17c01d9b46 | ||
| a1bb9ea352 | |||
|  | a1895ec65f | ||
|  | c5faa0b99d | ||
|  | e9d142f3e8 | ||
|  | 91860afd80 | ||
|  | bec0700d39 | ||
|  | 05d3d7f5c7 | ||
|  | ebff36d257 | ||
|  | a709b3afb6 | ||
|  | 69a3c6a9b2 | ||
|  | 8c33d876e8 | ||
|  | 1ec2fbcc16 | ||
|  | bc4e29141b | ||
|  | e90ea31683 | ||
|  | 7c99f0b3e0 | ||
|  | c089960707 | ||
|  | 0b2f29f1e8 | ||
|  | 9a4f50472a | ||
|  | 7d1a1c4004 | ||
|  | ebd58d4229 | ||
|  | dd48795f64 | ||
| 3d45b6687f | |||
| 35e6d36ce0 | |||
| 4900c81c11 | |||
| 52472b0ec3 | |||
| ec68e6f761 | |||
| 25bd170f6b | |||
| 6939b4a313 | |||
| d18922ed98 | |||
| e8bf242c42 | |||
| 2050460bb3 | |||
|  | 4add30e895 | ||
| e1dbfdafd7 | |||
| 75becb2294 | |||
| 94e494361f | |||
| cab3b1059d | |||
|  | d27bdf68fb | ||
|  | 82b82920e1 | ||
| 4bb3eadf91 | |||
| 4c82e65c1f | |||
| cf4d7df7ad | |||
| 86d13410c3 | |||
| 19fdf2a503 | |||
| 3a0c25c871 | |||
| 083338da8d | |||
| 37e5c9ceaa | |||
|  | 5448238697 | ||
|  | c5250a1059 | ||
| b2c1a7b8de | |||
| b4583fc6dc | |||
| f7c508939c | |||
| 4cf77a9b0e | |||
| a2160bef7d | |||
|  | c2a4a95eba | ||
| 8641d6bdce | |||
| 5f4d513aa6 | |||
| f47b15de39 | |||
| 7426dc02cf | |||
| a570160aed | |||
| 7596bd5a06 | |||
| 01f9d03b14 | |||
| 66426f5102 | |||
|  | 03243605da | ||
|  | 48e2d2ceab | ||
|  | 777fb25860 | ||
|  | 03601b9707 | ||
| c205bbddd3 | 
							
								
								
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -1,8 +1,8 @@ | ||||
| .composer/* | ||||
| composer.phar | ||||
| composer.lock | ||||
|  | ||||
| docs/build/ | ||||
| .php_cs.cache | ||||
|  | ||||
| ###> symfony/framework-bundle ### | ||||
| /.env.local | ||||
| @@ -19,3 +19,4 @@ docs/build/ | ||||
| /phpunit.xml | ||||
| .phpunit.result.cache | ||||
| ###< phpunit/phpunit ### | ||||
|  | ||||
|   | ||||
| @@ -18,7 +18,7 @@ before_script: | ||||
| # Bring in any services we need http://docs.gitlab.com/ee/ci/docker/using_docker_images.html#what-is-a-service | ||||
| # See http://docs.gitlab.com/ee/ci/services/README.html for examples. | ||||
| services: | ||||
|   - name: postgres:12 | ||||
|   - name: postgis/postgis:12-3.1-alpine | ||||
|     alias: db | ||||
|   - name: redis | ||||
|     alias: redis | ||||
| @@ -30,6 +30,10 @@ variables: | ||||
|   POSTGRES_PASSWORD: postgres | ||||
|   # fetch the chill-app using git submodules | ||||
|   GIT_SUBMODULE_STRATEGY: recursive | ||||
|   REDIS_HOST: redis | ||||
|   REDIS_PORT: 6379 | ||||
|   REDIS_URL: redis://redis:6379 | ||||
|  | ||||
|  | ||||
| # Run our tests | ||||
| test: | ||||
|   | ||||
							
								
								
									
										9
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,9 @@ | ||||
| # Chill framework | ||||
|  | ||||
| Documentation of the Chill software. | ||||
|  | ||||
| The online documentation can be found at http://docs.chill.social | ||||
|  | ||||
| See the [`docs`][1] directory for more. | ||||
|  | ||||
| [1]: docs/README.md | ||||
| @@ -73,7 +73,8 @@ | ||||
|         "symfony/web-profiler-bundle": "^5.0", | ||||
|         "symfony/var-dumper": "4.*", | ||||
|         "symfony/debug-bundle": "^5.1", | ||||
|         "symfony/phpunit-bridge": "^5.2" | ||||
|         "symfony/phpunit-bridge": "^5.2",     | ||||
|         "nelmio/alice": "^3.8" | ||||
|     }, | ||||
|     "scripts": { | ||||
|         "auto-scripts": { | ||||
|   | ||||
							
								
								
									
										747
									
								
								docs/source/development/api.rst
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										747
									
								
								docs/source/development/api.rst
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,747 @@ | ||||
| .. Copyright (C)  2014 Champs Libres Cooperative SCRLFS | ||||
|    Permission is granted to copy, distribute and/or modify this document | ||||
|    under the terms of the GNU Free Documentation License, Version 1.3 | ||||
|    or any later version published by the Free Software Foundation; | ||||
|    with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. | ||||
|    A copy of the license is included in the section entitled "GNU | ||||
|    Free Documentation License". | ||||
|  | ||||
| .. _api: | ||||
|  | ||||
| API | ||||
| ### | ||||
|  | ||||
| Chill provides a basic framework to build REST api. | ||||
|  | ||||
| Basic configuration | ||||
| ******************* | ||||
|  | ||||
| Configure a route | ||||
| ================= | ||||
|  | ||||
| Follow those steps to build a REST api: | ||||
|  | ||||
| 1. Create your model; | ||||
| 2. Configure the API; | ||||
|  | ||||
| You can also: | ||||
|  | ||||
| * hook into the controller to customize some steps; | ||||
| * add more route and steps | ||||
|  | ||||
| .. note:: | ||||
|  | ||||
|     Useful links: | ||||
|  | ||||
|     * `How to use annotation to configure serialization <https://symfony.com/doc/current/serializer.html>`_ | ||||
|     * `How to create your custom normalizer <https://symfony.com/doc/current/serializer/custom_normalizer.html>`_ | ||||
|  | ||||
| Auto-loading the routes | ||||
| ======================= | ||||
|  | ||||
| Ensure that those lines are present in your file `app/config/routing.yml`: | ||||
|  | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    chill_cruds: | ||||
|        resource: 'chill_main_crud_route_loader:load' | ||||
|        type: service | ||||
|  | ||||
|  | ||||
| Create your model | ||||
| ================= | ||||
|  | ||||
| Create your model on the usual way: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Entity\AccompanyingPeriod; | ||||
|  | ||||
|    use Chill\PersonBundle\Entity\AccompanyingPeriod\OriginRepository; | ||||
|    use Doctrine\ORM\Mapping as ORM; | ||||
|  | ||||
|    /** | ||||
|     * @ORM\Entity(repositoryClass=OriginRepository::class) | ||||
|     * @ORM\Table(name="chill_person_accompanying_period_origin") | ||||
|     */ | ||||
|    class Origin | ||||
|    { | ||||
|        /** | ||||
|         * @ORM\Id | ||||
|         * @ORM\GeneratedValue | ||||
|         * @ORM\Column(type="integer") | ||||
|         */ | ||||
|        private $id; | ||||
|  | ||||
|        /** | ||||
|         * @ORM\Column(type="json") | ||||
|         */ | ||||
|        private $label; | ||||
|  | ||||
|        /** | ||||
|         * @ORM\Column(type="date_immutable", nullable=true) | ||||
|         */ | ||||
|        private $noActiveAfter; | ||||
|  | ||||
|        // .. getters and setters | ||||
|  | ||||
|    } | ||||
|  | ||||
|  | ||||
| Configure api | ||||
| ============= | ||||
|  | ||||
| Configure the api using Yaml (see the full configuration: :ref:`api_full_configuration`): | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    # config/packages/chill_main.yaml | ||||
|    chill_main: | ||||
|        apis: | ||||
|            accompanying_period_origin: | ||||
|                base_path: '/api/1.0/person/accompanying-period/origin' | ||||
|                class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin' | ||||
|                name: accompanying_period_origin | ||||
|                base_role: 'ROLE_USER' | ||||
|                actions: | ||||
|                    _index: | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|                    _entity: | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|  | ||||
| .. note:: | ||||
|  | ||||
|    If you are working on a shared bundle (aka "The chill bundles"), you should define your configuration inside the class :code:`ChillXXXXBundleExtension`, using the "prependConfig" feature: | ||||
|  | ||||
|    .. code-block:: php | ||||
|  | ||||
|       namespace Chill\PersonBundle\DependencyInjection; | ||||
|  | ||||
|       use Symfony\Component\DependencyInjection\ContainerBuilder; | ||||
|       use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; | ||||
|       use Symfony\Component\HttpFoundation\Request; | ||||
|  | ||||
|       /** | ||||
|        * Class ChillPersonExtension | ||||
|        * Loads and manages your bundle configuration | ||||
|        * | ||||
|        * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} | ||||
|        * @package Chill\PersonBundle\DependencyInjection | ||||
|        */ | ||||
|       class ChillPersonExtension extends Extension implements PrependExtensionInterface | ||||
|       { | ||||
|           public function prepend(ContainerBuilder $container) | ||||
|           { | ||||
|               $this->prependCruds($container); | ||||
|           } | ||||
|  | ||||
|           /** | ||||
|            * @param ContainerBuilder $container | ||||
|            */ | ||||
|           protected function prependCruds(ContainerBuilder $container) | ||||
|           { | ||||
|               $container->prependExtensionConfig('chill_main', [ | ||||
|                   'apis' => [ | ||||
|                       [ | ||||
|                           'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class, | ||||
|                           'name' => 'accompanying_period_origin', | ||||
|                           'base_path' => '/api/1.0/person/accompanying-period/origin', | ||||
|                           'controller' => \Chill\PersonBundle\Controller\OpeningApiController::class, | ||||
|                           'base_role' => 'ROLE_USER', | ||||
|                           'actions' => [ | ||||
|                               '_index' => [ | ||||
|                                   'methods' => [  | ||||
|                                       Request::METHOD_GET => true, | ||||
|                                       Request::METHOD_HEAD => true | ||||
|                                   ], | ||||
|                               ], | ||||
|                               '_entity' => [ | ||||
|                                   'methods' => [  | ||||
|                                       Request::METHOD_GET => true, | ||||
|                                       Request::METHOD_HEAD => true | ||||
|                                   ] | ||||
|                               ], | ||||
|                           ] | ||||
|                       ] | ||||
|                   ] | ||||
|               ]); | ||||
|           } | ||||
|       } | ||||
|  | ||||
| The :code:`_index` and :code:`_entity` action | ||||
| ********************************************* | ||||
|  | ||||
| The :code:`_index` and :code:`_entity` action are default actions: | ||||
|  | ||||
| * they will call a specific method in the default controller; | ||||
| * they will generate defined routes: | ||||
|  | ||||
| Index: | ||||
|    Name: :code:`chill_api_single_accompanying_period_origin__index` | ||||
|  | ||||
|    Path: :code:`/api/1.0/person/accompanying-period/origin.{_format}` | ||||
|  | ||||
| Entity: | ||||
|    Name: :code:`chill_api_single_accompanying_period_origin__entity` | ||||
|  | ||||
|    Path: :code:`/api/1.0/person/accompanying-period/origin/{id}.{_format}` | ||||
|  | ||||
| Role | ||||
| **** | ||||
|  | ||||
| By default, the key `base_role` is used to check ACL. Take care of creating the :code:`Voter` required to take that into account. | ||||
|  | ||||
| For index action, the role will be called with :code:`NULL` as :code:`$subject`. The retrieved entity will be the subject for single queries. | ||||
|  | ||||
| You can also define a role for each method. In this case, this role is used for the given method, and, if any, the base role is taken into account. | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    # config/packages/chill_main.yaml | ||||
|    chill_main: | ||||
|        apis: | ||||
|            accompanying_period_origin: | ||||
|                base_path: '/api/1.0/person/bla/bla' | ||||
|                class: 'Chill\PersonBundle\Entity\Blah' | ||||
|                name: bla | ||||
|                actions: | ||||
|                    _entity: | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|                        roles: | ||||
|                            GET: MY_ROLE_SEE | ||||
|                            HEAD: MY ROLE_SEE | ||||
|  | ||||
| Customize the controller | ||||
| ************************ | ||||
|  | ||||
| You can customize the controller by hooking into the default actions. Take care of extending :code:`Chill\MainBundle\CRUD\Controller\ApiController`. | ||||
|  | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|  | ||||
|    namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
|    use Chill\MainBundle\CRUD\Controller\ApiController; | ||||
|    use Symfony\Component\HttpFoundation\Request; | ||||
|    use Symfony\Component\HttpFoundation\Response; | ||||
|  | ||||
|    class OpeningApiController extends ApiController | ||||
|    { | ||||
|        protected function customizeQuery(string $action, Request $request, $qb): void | ||||
|        { | ||||
|            $qb->where($qb->expr()->gt('e.noActiveAfter', ':now')) | ||||
|                ->orWhere($qb->expr()->isNull('e.noActiveAfter')); | ||||
|            $qb->setParameter('now', new \DateTime('now')); | ||||
|        }      | ||||
|    } | ||||
|  | ||||
| And set your controller in configuration: | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    chill_main: | ||||
|        apis: | ||||
|            accompanying_period_origin: | ||||
|                base_path: '/api/1.0/person/accompanying-period/origin' | ||||
|                class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin' | ||||
|                name: accompanying_period_origin | ||||
|                # add a controller | ||||
|                controller: 'Chill\PersonBundle\Controller\OpeningApiController' | ||||
|                base_role: 'ROLE_USER' | ||||
|                actions: | ||||
|                    _index: | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|                    _entity: | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|  | ||||
| Create your own actions | ||||
| *********************** | ||||
|  | ||||
| You can add your own actions: | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    chill_main: | ||||
|        apis: | ||||
|            - | ||||
|                class: Chill\PersonBundle\Entity\AccompanyingPeriod | ||||
|                name: accompanying_course | ||||
|                base_path: /api/1.0/person/accompanying-course | ||||
|                controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController | ||||
|                actions: | ||||
|                    # add a custom participation: | ||||
|                    participation: | ||||
|                        methods: | ||||
|                            POST: true | ||||
|                            DELETE: true | ||||
|                            GET: false | ||||
|                            HEAD: false | ||||
|                            PUT: false | ||||
|                        roles: | ||||
|                            POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            GET: null | ||||
|                            HEAD: null | ||||
|                            PUT: null | ||||
|                        single-collection: single | ||||
|  | ||||
| The key :code:`single-collection` with value :code:`single` will add a :code:`/{id}/ + "action name"` (in this example, :code:`/{id}/participation`) into the path, after the base path. If the value is :code:`collection`, no id will be set, but the action name will be append to the path. | ||||
|  | ||||
| Then, create the corresponding action into your controller: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
|    use Chill\MainBundle\CRUD\Controller\ApiController; | ||||
|    use Symfony\Component\HttpFoundation\Request; | ||||
|    use Symfony\Component\HttpFoundation\Response; | ||||
|    use Chill\PersonBundle\Entity\AccompanyingPeriod; | ||||
|    use Symfony\Component\HttpFoundation\Exception\BadRequestException; | ||||
|    use Symfony\Component\EventDispatcher\EventDispatcherInterface; | ||||
|    use Symfony\Component\Validator\Validator\ValidatorInterface; | ||||
|    use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent; | ||||
|    use Chill\PersonBundle\Entity\Person; | ||||
|  | ||||
|    class AccompanyingCourseApiController extends ApiController | ||||
|    { | ||||
|        protected EventDispatcherInterface $eventDispatcher; | ||||
|  | ||||
|        protected ValidatorInterface $validator; | ||||
|  | ||||
|        public function __construct(EventDispatcherInterface $eventDispatcher, $validator) | ||||
|        { | ||||
|            $this->eventDispatcher = $eventDispatcher; | ||||
|            $this->validator = $validator; | ||||
|        } | ||||
|         | ||||
|        public function participationApi($id, Request $request, $_format) | ||||
|        { | ||||
|            /** @var AccompanyingPeriod $accompanyingPeriod */  | ||||
|            $accompanyingPeriod = $this->getEntity('participation', $id, $request); | ||||
|            $person = $this->getSerializer() | ||||
|                ->deserialize($request->getContent(), Person::class, $_format, []); | ||||
|  | ||||
|            if (NULL === $person) { | ||||
|                throw new BadRequestException('person id not found'); | ||||
|            } | ||||
|  | ||||
|            $this->onPostCheckACL('participation', $request, $accompanyingPeriod, $_format); | ||||
|  | ||||
|            switch ($request->getMethod()) { | ||||
|                case Request::METHOD_POST: | ||||
|                    $participation = $accompanyingPeriod->addPerson($person); | ||||
|                    break; | ||||
|                case Request::METHOD_DELETE: | ||||
|                    $participation = $accompanyingPeriod->removePerson($person); | ||||
|                    break; | ||||
|                default: | ||||
|                    throw new BadRequestException("This method is not supported"); | ||||
|            } | ||||
|  | ||||
|            $errors = $this->validator->validate($accompanyingPeriod); | ||||
|  | ||||
|            if ($errors->count() > 0) { | ||||
|                // only format accepted | ||||
|                return $this->json($errors); | ||||
|            } | ||||
|  | ||||
|            $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|            return $this->json($participation); | ||||
|        } | ||||
|    } | ||||
|  | ||||
| Managing association | ||||
| ******************** | ||||
|  | ||||
| ManyToOne association | ||||
| ===================== | ||||
|  | ||||
| In ManyToOne association, you can add associated entities using the :code:`PATCH` request. By default, the serializer deserialize entities only with their id and discriminator type, if any. | ||||
|  | ||||
| Example: | ||||
|  | ||||
| .. code-block:: bash | ||||
|  | ||||
|    curl -X 'PATCH' \ | ||||
|      'http://localhost:8001/api/1.0/person/accompanying-course/2668.json' \ | ||||
|      -H 'accept: */*' \ | ||||
|      -H 'Content-Type: application/json' \ | ||||
|       # see the data sent to the server: \ | ||||
|      -d '{ | ||||
|      "type": "accompanying_period", | ||||
|      "id": 2668, | ||||
|      "origin": { "id": 11 } | ||||
|    }' | ||||
|  | ||||
| ManyToMany associations | ||||
| ======================= | ||||
|  | ||||
| In OneToMany association, you can easily create route for adding and removing entities, using :code:`POST` and :code:`DELETE` requests. | ||||
|  | ||||
| Prepare your entity, creating the methods :code:`addYourEntity` and :code:`removeYourEntity`: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Entity; | ||||
|  | ||||
|    use Chill\MainBundle\Entity\Scope; | ||||
|    use Doctrine\Common\Collections\ArrayCollection; | ||||
|    use Doctrine\Common\Collections\Collection; | ||||
|    use Doctrine\ORM\Mapping as ORM; | ||||
|    use Symfony\Component\Serializer\Annotation\Groups; | ||||
|    use Symfony\Component\Serializer\Annotation\DiscriminatorMap; | ||||
|  | ||||
|    /** | ||||
|     * AccompanyingPeriod Class | ||||
|     * | ||||
|     * @ORM\Entity | ||||
|     * @ORM\Table(name="chill_person_accompanying_period") | ||||
|     * @DiscriminatorMap(typeProperty="type", mapping={ | ||||
|     *  "accompanying_period"=AccompanyingPeriod::class | ||||
|     *  }) | ||||
|     */ | ||||
|    class AccompanyingPeriod | ||||
|    { | ||||
|        /** | ||||
|         * @var Collection | ||||
|         * @ORM\ManyToMany( | ||||
|         *     targetEntity=Scope::class, | ||||
|         *     cascade={} | ||||
|         *     ) | ||||
|         * @Groups({"read"}) | ||||
|         */ | ||||
|        private $scopes; | ||||
|  | ||||
|        public function addScope(Scope $scope): self | ||||
|        { | ||||
|            $this->scopes[] = $scope; | ||||
|  | ||||
|            return $this; | ||||
|        } | ||||
|  | ||||
|        public function removeScope(Scope $scope): void | ||||
|        { | ||||
|            $this->scopes->removeElement($scope); | ||||
|        } | ||||
|  | ||||
|  | ||||
| Create your route into the configuration: | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|    chill_main: | ||||
|        apis: | ||||
|            - | ||||
|                class: Chill\PersonBundle\Entity\AccompanyingPeriod | ||||
|                name: accompanying_course | ||||
|                base_path: /api/1.0/person/accompanying-course | ||||
|                controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController | ||||
|                actions: | ||||
|                    scope: | ||||
|                        methods: | ||||
|                            POST: true | ||||
|                            DELETE: true | ||||
|                            GET: false | ||||
|                            HEAD: false | ||||
|                            PUT: false | ||||
|                            PATCH: false | ||||
|                        roles: | ||||
|                            POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            GET: null | ||||
|                            HEAD: null | ||||
|                            PUT: null | ||||
|                            PATCH: null | ||||
|                        controller_action: null | ||||
|                        path: null | ||||
|                        single-collection: single | ||||
|  | ||||
| This will create a new route, which will accept two methods: DELETE and POST: | ||||
|  | ||||
| .. code-block:: raw | ||||
|  | ||||
|    +--------------+---------------------------------------------------------------------------------------+ | ||||
|    | Property     | Value                                                                                 | | ||||
|    +--------------+---------------------------------------------------------------------------------------+ | ||||
|    | Route Name   | chill_api_single_accompanying_course_scope                                            | | ||||
|    | Path         | /api/1.0/person/accompanying-course/{id}/scope.{_format}                              | | ||||
|    | Path Regex   | {^/api/1\.0/person/accompanying\-course/(?P<id>[^/]++)/scope\.(?P<_format>[^/]++)$}sD | | ||||
|    | Host         | ANY                                                                                   | | ||||
|    | Host Regex   |                                                                                       | | ||||
|    | Scheme       | ANY                                                                                   | | ||||
|    | Method       | POST|DELETE                                                                           | | ||||
|    | Requirements | {id}: \d+                                                                             | | ||||
|    | Class        | Symfony\Component\Routing\Route                                                       | | ||||
|    | Defaults     | _controller: csapi_accompanying_course_controller:scopeApi                            | | ||||
|    | Options      | compiler_class: Symfony\Component\Routing\RouteCompiler                               | | ||||
|    +--------------+---------------------------------------------------------------------------------------+ | ||||
|  | ||||
|  | ||||
|  | ||||
| Then, create the controller action. Call the method: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
|    use Chill\MainBundle\CRUD\Controller\ApiController; | ||||
|    use Symfony\Component\HttpFoundation\Request; | ||||
|    use Symfony\Component\HttpFoundation\Response; | ||||
|    use Chill\MainBundle\Entity\Scope; | ||||
|  | ||||
|    class MyController extends ApiController | ||||
|    { | ||||
|        public function scopeApi($id, Request $request, string $_format): Response | ||||
|        { | ||||
|            return $this->addRemoveSomething('scope', $id, $request, $_format, 'scope', Scope::class, [ 'groups' => [ 'read' ] ]); | ||||
|        } | ||||
|    } | ||||
|  | ||||
| This will allow to add a scope by his id, and delete them. | ||||
|  | ||||
| Curl requests: | ||||
|  | ||||
| .. code-block:: bash | ||||
|  | ||||
|    # add a scope with id 5 | ||||
|    curl -X 'POST' \ | ||||
|      'http://localhost:8001/api/1.0/person/accompanying-course/2868/scope.json' \ | ||||
|      -H 'accept: */*' \ | ||||
|      -H 'Content-Type: application/json' \ | ||||
|      -d '{ | ||||
|      "type": "scope", | ||||
|      "id": 5 | ||||
|    }' | ||||
|  | ||||
|    # remove a scope with id 5 | ||||
|    curl -X 'DELETE' \ | ||||
|      'http://localhost:8001/api/1.0/person/accompanying-course/2868/scope.json' \ | ||||
|      -H 'accept: */*' \ | ||||
|      -H 'Content-Type: application/json' \ | ||||
|      -d '{ | ||||
|      "id": 5, | ||||
|      "type": "scope" | ||||
|    }' | ||||
|  | ||||
| Deserializing an association where multiple types are allowed | ||||
| ============================================================= | ||||
|  | ||||
| Sometimes, multiples types are allowed as association to one entity: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Entity\AccompanyingPeriod; | ||||
|  | ||||
|    use Chill\PersonBundle\Entity\Person; | ||||
|    use Chill\ThirdPartyBundle\Entity\ThirdParty; | ||||
|    use Doctrine\ORM\Mapping as ORM; | ||||
|  | ||||
|    class Resource | ||||
|    { | ||||
|  | ||||
|  | ||||
|        /** | ||||
|         * @ORM\ManyToOne(targetEntity=ThirdParty::class) | ||||
|         * @ORM\JoinColumn(nullable=true) | ||||
|         */ | ||||
|        private $thirdParty; | ||||
|  | ||||
|        /** | ||||
|         * @ORM\ManyToOne(targetEntity=Person::class) | ||||
|         * @ORM\JoinColumn(nullable=true) | ||||
|         */ | ||||
|        private $person; | ||||
|  | ||||
|  | ||||
|        /** | ||||
|         * | ||||
|         * @param $resource Person|ThirdParty | ||||
|         */ | ||||
|        public function setResource($resource): self | ||||
|        { | ||||
|           // ... | ||||
|        } | ||||
|         | ||||
|         | ||||
|        /** | ||||
|         * @return ThirdParty|Person | ||||
|         * @Groups({"read", "write"}) | ||||
|         */ | ||||
|        public function getResource() | ||||
|        { | ||||
|            return $this->person ?? $this->thirdParty; | ||||
|        } | ||||
|    } | ||||
|  | ||||
| This is not well taken into account by the Symfony serializer natively. | ||||
|  | ||||
| You must, then, create your own CustomNormalizer. You can help yourself using this: | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    namespace Chill\PersonBundle\Serializer\Normalizer; | ||||
|  | ||||
|    use Chill\PersonBundle\Entity\Person; | ||||
|    use Chill\ThirdPartyBundle\Entity\ThirdParty; | ||||
|    use Chill\PersonBundle\Entity\AccompanyingPeriod\Resource; | ||||
|    use Chill\PersonBundle\Repository\AccompanyingPeriod\ResourceRepository; | ||||
|    use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; | ||||
|    use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface; | ||||
|    use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait; | ||||
|    use Symfony\Component\Serializer\Normalizer\ObjectToPopulateTrait; | ||||
|    use Symfony\Component\Serializer\Exception; | ||||
|    use Chill\MainBundle\Serializer\Normalizer\DiscriminatedObjectDenormalizer; | ||||
|  | ||||
|  | ||||
|    class AccompanyingPeriodResourceNormalizer implements DenormalizerInterface, DenormalizerAwareInterface | ||||
|    { | ||||
|        use DenormalizerAwareTrait; | ||||
|        use ObjectToPopulateTrait; | ||||
|  | ||||
|        public function __construct(ResourceRepository $repository) | ||||
|        { | ||||
|            $this->repository = $repository; | ||||
|        } | ||||
|  | ||||
|        public function denormalize($data, string $type, string $format = null, array $context = []) | ||||
|        { | ||||
|            // .. snipped for brevity | ||||
|  | ||||
|            if ($resource === NULL) { | ||||
|                $resource = new Resource(); | ||||
|            } | ||||
|  | ||||
|            if (\array_key_exists('resource', $data)) { | ||||
|                $res = $this->denormalizer->denormalize( | ||||
|                    $data['resource'], | ||||
|                    // call for a "multiple type" | ||||
|                    DiscriminatedObjectDenormalizer::TYPE, | ||||
|                    $format, | ||||
|                    // into the context, we add the list of allowed types: | ||||
|                    [  | ||||
|                        DiscriminatedObjectDenormalizer::ALLOWED_TYPES =>  | ||||
|                        [  | ||||
|                            Person::class, ThirdParty::class | ||||
|                        ] | ||||
|                    ] | ||||
|                ); | ||||
|  | ||||
|                $resource->setResource($res); | ||||
|            }  | ||||
|  | ||||
|            return $resource; | ||||
|        } | ||||
|         | ||||
|  | ||||
|        public function supportsDenormalization($data, string $type, string $format = null) | ||||
|        { | ||||
|            return $type === Resource::class; | ||||
|        }   | ||||
|    } | ||||
|  | ||||
| Serialization for collection | ||||
| **************************** | ||||
|  | ||||
| A specific model has been defined for returning collection: | ||||
|  | ||||
| .. code-block:: json | ||||
|  | ||||
|    { | ||||
|        "count": 49, | ||||
|        "results": [ | ||||
|        ], | ||||
|        "pagination": { | ||||
|            "more": true, | ||||
|            "next": "/api/1.0/search.json&q=xxxx......&page=2", | ||||
|            "previous": null, | ||||
|            "first": 0, | ||||
|            "items_per_page": 1 | ||||
|        } | ||||
|    } | ||||
|  | ||||
| Where this is relevant, this model should be re-used in custom controller actions. | ||||
|  | ||||
| In custom actions, this can be achieved quickly by assembling results into a :code:`Chill\MainBundle\Serializer\Model\Collection`. The pagination information is given by using :code:`Paginator` (see :ref:`Pagination <pagination-ref>`). | ||||
|  | ||||
| .. code-block:: php | ||||
|  | ||||
|    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | ||||
|    use Chill\MainBundle\Pagination\PaginatorInterface; | ||||
|  | ||||
|    class MyController extends AbstractController | ||||
|    { | ||||
|  | ||||
|        protected function serializeCollection(PaginatorInterface $paginator, $entities): Response | ||||
|        { | ||||
|            $model = new Collection($entities, $paginator); | ||||
|  | ||||
|            return $this->json($model, Response::HTTP_OK, [], $context); | ||||
|        } | ||||
|    } | ||||
|  | ||||
|  | ||||
| .. _api_full_configuration: | ||||
|  | ||||
| Full configuration example | ||||
| ************************** | ||||
|  | ||||
| .. code-block:: yaml | ||||
|  | ||||
|        apis: | ||||
|            - | ||||
|                class: Chill\PersonBundle\Entity\AccompanyingPeriod | ||||
|                name: accompanying_course | ||||
|                base_path: /api/1.0/person/accompanying-course | ||||
|                controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController | ||||
|                actions: | ||||
|                    _entity: | ||||
|                        roles: | ||||
|                            GET: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            HEAD: null | ||||
|                            POST: null | ||||
|                            DELETE: null | ||||
|                            PUT: null | ||||
|                        controller_action: null | ||||
|                        path: null | ||||
|                        single-collection: single | ||||
|                        methods: | ||||
|                            GET: true | ||||
|                            HEAD: true | ||||
|                            POST: false | ||||
|                            DELETE: false | ||||
|                            PUT: false | ||||
|                    participation: | ||||
|                        methods: | ||||
|                            POST: true | ||||
|                            DELETE: true | ||||
|                            GET: false | ||||
|                            HEAD: false | ||||
|                            PUT: false | ||||
|                        roles: | ||||
|                            POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE | ||||
|                            GET: null | ||||
|                            HEAD: null | ||||
|                            PUT: null | ||||
|                        controller_action: null | ||||
|                        # the requirements for the route. Will be set to `[ 'id' => '\d+' ]` if left empty. | ||||
|                        requirements:         [] | ||||
|                        path: null | ||||
|                        single-collection: single | ||||
|                base_role: null | ||||
|  | ||||
|  | ||||
| @@ -16,6 +16,7 @@ As Chill rely on the `symfony <http://symfony.com>`_ framework, reading the fram | ||||
|  | ||||
|     Instructions to create a new bundle <create-a-new-bundle.rst> | ||||
|     CRUD (Create - Update - Delete) for one entity <crud.rst> | ||||
|     Helpers for building a REST API <api.rst> | ||||
|     Routing <routing.rst> | ||||
|     Menus <menus.rst> | ||||
|     Forms <forms.rst> | ||||
|   | ||||
| @@ -7,6 +7,8 @@ | ||||
|    Free Documentation License". | ||||
|  | ||||
|  | ||||
| .. _pagination-ref: | ||||
|  | ||||
| Pagination | ||||
| ########## | ||||
|  | ||||
| @@ -15,7 +17,7 @@ The Bundle :code:`Chill\MainBundle` provides a **Pagination** api which allow yo | ||||
| A simple example | ||||
| **************** | ||||
|  | ||||
| In the controller, get the :class:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance. | ||||
| In the controller, get the :code:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance. | ||||
|  | ||||
|  | ||||
| .. literalinclude:: pagination/example.php | ||||
|   | ||||
| @@ -82,7 +82,7 @@ Chill will be available at ``http://localhost:8001.`` Currently, there isn't any | ||||
|  | ||||
| .. code-block:: bash | ||||
|  | ||||
|    docker-compose exec --user $(id -u) php bin/console doctrine:fixtures:load | ||||
|    docker-compose exec --user $(id -u) php bin/console doctrine:fixtures:load --purge-with-truncate | ||||
|  | ||||
| There are several users available: | ||||
|  | ||||
|   | ||||
| @@ -18,11 +18,10 @@ | ||||
|        <testsuite name="MainBundle"> | ||||
|          <directory suffix="Test.php">src/Bundle/ChillMainBundle/Tests/</directory> | ||||
|        </testsuite> | ||||
|  | ||||
|        <testsuite name="PersonBundle"> | ||||
|          <directory suffix="Test.php">src/Bundle/ChillPersonBundle/Tests/</directory> | ||||
|          <exclude>src/Bundle/ChillPersonBundle/Tests/Export/*</exclude> | ||||
|         </testsuite> | ||||
|  | ||||
|       </testsuites> | ||||
|  | ||||
|     <listeners> | ||||
|   | ||||
| @@ -0,0 +1,77 @@ | ||||
| <?php | ||||
| /* | ||||
|  * Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop> | ||||
|  * | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  * it under the terms of the GNU Affero General Public License as published by | ||||
|  * the Free Software Foundation, either version 3 of the License, or | ||||
|  * (at your option) any later version. | ||||
|  * | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  * | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
| namespace Chill\MainBundle\CRUD\CompilerPass; | ||||
|  | ||||
| use Symfony\Component\DependencyInjection\ContainerBuilder; | ||||
| use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; | ||||
| use Symfony\Component\DependencyInjection\Reference; | ||||
| use Chill\MainBundle\Routing\MenuComposer; | ||||
| use Symfony\Component\DependencyInjection\Definition; | ||||
|  | ||||
| /** | ||||
|  *  | ||||
|  * | ||||
|  */ | ||||
| class CRUDControllerCompilerPass implements CompilerPassInterface | ||||
| { | ||||
|     public function process(ContainerBuilder $container) | ||||
|     { | ||||
|         $crudConfig = $container->getParameter('chill_main_crud_route_loader_config'); | ||||
|         $apiConfig = $container->getParameter('chill_main_api_route_loader_config'); | ||||
|  | ||||
|         foreach ($crudConfig as $crudEntry) { | ||||
|             $this->configureCrudController($container, $crudEntry, 'crud'); | ||||
|         } | ||||
|  | ||||
|         foreach ($apiConfig as $crudEntry) { | ||||
|             $this->configureCrudController($container, $crudEntry, 'api'); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Add a controller for each definition, and add a methodCall to inject crud configuration to controller | ||||
|      */ | ||||
|     private function configureCrudController(ContainerBuilder $container, array $crudEntry, string $apiOrCrud): void | ||||
|     { | ||||
|         $controllerClass = $crudEntry['controller']; | ||||
|  | ||||
|         $controllerServiceName = 'cs'.$apiOrCrud.'_'.$crudEntry['name'].'_controller'; | ||||
|  | ||||
|         if ($container->hasDefinition($controllerClass)) { | ||||
|             $controller = $container->getDefinition($controllerClass); | ||||
|             $container->removeDefinition($controllerClass); | ||||
|             $alreadyDefined = true; | ||||
|         } else { | ||||
|             $controller = new Definition($controllerClass); | ||||
|             $alreadyDefined = false; | ||||
|         } | ||||
|  | ||||
|         $controller->addTag('controller.service_arguments'); | ||||
|         if (FALSE === $alreadyDefined) { | ||||
|             $controller->setAutoconfigured(true); | ||||
|             $controller->setPublic(true); | ||||
|         } | ||||
|  | ||||
|         $param = 'chill_main_'.$apiOrCrud.'_config_'.$crudEntry['name']; | ||||
|         $container->setParameter($param, $crudEntry); | ||||
|         $controller->addMethodCall('setCrudConfig', ['%'.$param.'%']); | ||||
|  | ||||
|         $container->setDefinition($controllerServiceName, $controller); | ||||
|     } | ||||
|      | ||||
| } | ||||
| @@ -0,0 +1,237 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\CRUD\Controller; | ||||
|  | ||||
| use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Symfony\Component\HttpFoundation\Response; | ||||
| use Symfony\Component\Validator\Validator\ValidatorInterface; | ||||
| use Chill\MainBundle\Pagination\PaginatorFactory; | ||||
| use Chill\MainBundle\Pagination\PaginatorInterface; | ||||
|  | ||||
| class AbstractCRUDController extends AbstractController | ||||
| { | ||||
|     /** | ||||
|      * The crud configuration  | ||||
|      * | ||||
|      * This configuration si defined by `chill_main['crud']` or `chill_main['apis']` | ||||
|      * | ||||
|      * @var array | ||||
|      */ | ||||
|     protected array $crudConfig = []; | ||||
|  | ||||
|     /** | ||||
|      * get the instance of the entity with the given id | ||||
|      *  | ||||
|      * @param string $id | ||||
|      * @return object | ||||
|      * @throw Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the object is not found | ||||
|      */ | ||||
|     protected function getEntity($action, $id, Request $request): object | ||||
|     { | ||||
|         $e = $this->getDoctrine() | ||||
|             ->getRepository($this->getEntityClass()) | ||||
|             ->find($id); | ||||
|  | ||||
|         if (NULL === $e) { | ||||
|             throw $this->createNotFoundException(sprintf("The object %s for id %s is not found", $this->getEntityClass(), $id)); | ||||
|         } | ||||
|  | ||||
|         return $e; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Count the number of entities | ||||
|      * | ||||
|      * By default, count all entities. You can customize the query by  | ||||
|      * using the method `customizeQuery`. | ||||
|      *  | ||||
|      * @param string $action | ||||
|      * @param Request $request | ||||
|      * @return int | ||||
|      */ | ||||
|     protected function countEntities(string $action, Request $request, $_format): int | ||||
|     { | ||||
|         return $this->buildQueryEntities($action, $request) | ||||
|             ->select('COUNT(e)') | ||||
|             ->getQuery() | ||||
|             ->getSingleScalarResult() | ||||
|             ; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Query the entity. | ||||
|      *  | ||||
|      * By default, get all entities. You can customize the query by using the | ||||
|      * method `customizeQuery`. | ||||
|      *  | ||||
|      * The method `orderEntity` is called internally to order entities. | ||||
|      *  | ||||
|      * It returns, by default, a query builder. | ||||
|      *  | ||||
|      */ | ||||
|     protected function queryEntities(string $action, Request $request, string $_format, PaginatorInterface $paginator) | ||||
|     { | ||||
|         $query = $this->buildQueryEntities($action, $request) | ||||
|             ->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber()) | ||||
|             ->setMaxResults($paginator->getItemsPerPage()); | ||||
|          | ||||
|         // allow to order queries and return the new query | ||||
|         return $this->orderQuery($action, $query, $request, $paginator, $_format); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Add ordering fields in the query build by self::queryEntities | ||||
|      *  | ||||
|      */ | ||||
|     protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format) | ||||
|     { | ||||
|         return $query; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Build the base query for listing all entities. | ||||
|      * | ||||
|      * This method is used internally by `countEntities` `queryEntities` | ||||
|      *  | ||||
|      * This base query does not contains any `WHERE` or `SELECT` clauses. You | ||||
|      * can add some by using the method `customizeQuery`. | ||||
|      * | ||||
|      * The alias for the entity is "e". | ||||
|      *  | ||||
|      * @param string $action | ||||
|      * @param Request $request | ||||
|      * @return QueryBuilder | ||||
|      */ | ||||
|     protected function buildQueryEntities(string $action, Request $request) | ||||
|     { | ||||
|         $qb = $this->getDoctrine()->getManager() | ||||
|             ->createQueryBuilder() | ||||
|             ->select('e') | ||||
|             ->from($this->getEntityClass(), 'e') | ||||
|             ; | ||||
|  | ||||
|         $this->customizeQuery($action, $request, $qb); | ||||
|  | ||||
|         return $qb; | ||||
|     } | ||||
|  | ||||
|     protected function customizeQuery(string $action, Request $request, $query): void {} | ||||
|  | ||||
|     /** | ||||
|      * Get the result of the query | ||||
|      */ | ||||
|     protected function getQueryResult(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query)  | ||||
|     { | ||||
|         return $query->getQuery()->getResult(); | ||||
|     } | ||||
|  | ||||
|     protected function onPreIndex(string $action, Request $request, string $_format): ?Response | ||||
|     {  | ||||
|         return null;  | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * method used by indexAction | ||||
|      */ | ||||
|     protected function onPreIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator): ?Response | ||||
|     {  | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * method used by indexAction | ||||
|      */ | ||||
|     protected function onPostIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * method used by indexAction | ||||
|      */ | ||||
|     protected function onPostIndexFetchQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $entities): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * Get the complete FQDN of the class | ||||
|      *  | ||||
|      * @return string the complete fqdn of the class | ||||
|      */ | ||||
|     protected function getEntityClass(): string | ||||
|     { | ||||
|         return $this->crudConfig['class']; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * called on post fetch entity  | ||||
|      */ | ||||
|     protected function onPostFetchEntity(string $action, Request $request, $entity, $_format): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called on post check ACL | ||||
|      */ | ||||
|     protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * check the acl. Called by every action. | ||||
|      *  | ||||
|      * By default, check the role given by `getRoleFor` for the value given in  | ||||
|      * $entity. | ||||
|      *  | ||||
|      * Throw an \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException | ||||
|      * if not accessible. | ||||
|      *  | ||||
|      * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException | ||||
|      */ | ||||
|     protected function checkACL(string $action, Request $request, string $_format, $entity = null) | ||||
|     { | ||||
|         $this->denyAccessUnlessGranted($this->getRoleFor($action, $request, $entity, $_format), $entity); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      *  | ||||
|      * @return string the crud name | ||||
|      */ | ||||
|     protected function getCrudName(): string | ||||
|     { | ||||
|         return $this->crudConfig['name']; | ||||
|     } | ||||
|  | ||||
|     protected function getActionConfig(string $action) | ||||
|     { | ||||
|         return $this->crudConfig['actions'][$action]; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Set the crud configuration | ||||
|      * | ||||
|      * Used by the container to inject configuration for this crud. | ||||
|      */ | ||||
|     public function setCrudConfig(array $config): void | ||||
|     { | ||||
|         $this->crudConfig = $config; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @return PaginatorFactory | ||||
|      */ | ||||
|     protected function getPaginatorFactory(): PaginatorFactory | ||||
|     { | ||||
|         return $this->container->get('chill_main.paginator_factory'); | ||||
|     } | ||||
|  | ||||
|     protected function getValidator(): ValidatorInterface | ||||
|     { | ||||
|         return $this->get('validator'); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										452
									
								
								src/Bundle/ChillMainBundle/CRUD/Controller/ApiController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										452
									
								
								src/Bundle/ChillMainBundle/CRUD/Controller/ApiController.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,452 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\CRUD\Controller; | ||||
|  | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Symfony\Component\HttpFoundation\Response; | ||||
| use Symfony\Component\Routing\Annotation\Route; | ||||
| use Symfony\Component\Serializer\SerializerInterface; | ||||
| use Chill\MainBundle\Serializer\Model\Collection; | ||||
| use Chill\MainBundle\Pagination\PaginatorInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; | ||||
| use Symfony\Component\Validator\ConstraintViolationListInterface; | ||||
| use Symfony\Component\Serializer\Exception\NotEncodableValueException; | ||||
| use Symfony\Component\HttpFoundation\Exception\BadRequestException; | ||||
|  | ||||
| class ApiController extends AbstractCRUDController | ||||
| { | ||||
|     /** | ||||
|      * The view action. | ||||
|      *  | ||||
|      * Some steps may be overriden during this process of rendering: | ||||
|      *  | ||||
|      * This method: | ||||
|      *  | ||||
|      * 1.  fetch the entity, using `getEntity` | ||||
|      * 2.  launch `onPostFetchEntity`. If postfetch is an instance of Response, | ||||
|      *     this response is returned. | ||||
|      * 2.  throw an HttpNotFoundException if entity is null | ||||
|      * 3.  check ACL using `checkACL` ; | ||||
|      * 4.  launch `onPostCheckACL`. If the result is an instance of Response,  | ||||
|      *     this response is returned ; | ||||
|      * 5.  Serialize the entity and return the result. The serialization context is given by `getSerializationContext` | ||||
|      *  | ||||
|      */ | ||||
|     protected function entityGet(string $action, Request $request, $id, $_format = 'html'): Response | ||||
|     { | ||||
|         $entity = $this->getEntity($action, $id, $request, $_format); | ||||
|          | ||||
|         $postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format); | ||||
|          | ||||
|         if ($postFetch instanceof Response) { | ||||
|             return $postFetch; | ||||
|         } | ||||
|          | ||||
|         $response = $this->checkACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $response = $this->onPostCheckACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         $response = $this->onBeforeSerialize($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         if ($_format === 'json') { | ||||
|             $context = $this->getContextForSerialization($action, $request, $_format, $entity); | ||||
|  | ||||
|             return $this->json($entity, Response::HTTP_OK, [], $context); | ||||
|         } else { | ||||
|             throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This format is not implemented"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function onBeforeSerialize(string $action, Request $request, $_format, $entity): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Base method for handling api action | ||||
|      * | ||||
|      * @return void | ||||
|      */ | ||||
|     public function entityApi(Request $request, $id, $_format): Response | ||||
|     { | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_GET: | ||||
|             case Request::METHOD_HEAD: | ||||
|                 return $this->entityGet('_entity', $request, $id, $_format); | ||||
|             case Request::METHOD_PUT: | ||||
|             case Request::METHOD_PATCH: | ||||
|                 return $this->entityPut('_entity', $request, $id, $_format); | ||||
|             default: | ||||
|                 throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This method is not implemented"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function entityPut($action, Request $request, $id, string $_format): Response | ||||
|     { | ||||
|         $entity = $this->getEntity($action, $id, $request, $_format); | ||||
|          | ||||
|         $postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format); | ||||
|         if ($postFetch instanceof Response) { | ||||
|             return $postFetch; | ||||
|         } | ||||
|          | ||||
|         if (NULL === $entity) { | ||||
|             throw $this->createNotFoundException(sprintf("The %s with id %s " | ||||
|                 . "is not found", $this->getCrudName(), $id)); | ||||
|         } | ||||
|          | ||||
|         $response = $this->checkACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $response = $this->onPostCheckACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         $response = $this->onBeforeSerialize($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         try { | ||||
|             $entity = $this->deserialize($action, $request, $_format, $entity); | ||||
|         } catch (NotEncodableValueException $e) { | ||||
|             throw new BadRequestException("invalid json", 400, $e); | ||||
|         } | ||||
|  | ||||
|         $errors = $this->validate($action, $request, $_format, $entity); | ||||
|  | ||||
|         $response = $this->onAfterValidation($action, $request, $_format, $entity, $errors); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         if ($errors->count() > 0) { | ||||
|             $response = $this->json($errors); | ||||
|             $response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY); | ||||
|  | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|         $response = $this->onAfterFlush($action, $request, $_format, $entity, $errors); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         return $this->json( | ||||
|             $entity, | ||||
|             Response::HTTP_OK, | ||||
|             [],  | ||||
|             $this->getContextForSerializationPostAlter($action, $request, $_format, $entity) | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     protected function onAfterValidation(string $action, Request $request, string $_format, $entity, ConstraintViolationListInterface $errors, array $more = []): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     protected function onAfterFlush(string $action, Request $request, string $_format, $entity, ConstraintViolationListInterface $errors, array $more = []): ?Response | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     protected function getValidationGroups(string $action, Request $request, string $_format, $entity): ?array | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     protected function validate(string $action, Request $request, string $_format, $entity, array $more = []): ConstraintViolationListInterface | ||||
|     { | ||||
|         $validationGroups = $this->getValidationGroups($action, $request, $_format, $entity); | ||||
|          | ||||
|         return $this->getValidator()->validate($entity, null, $validationGroups); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Deserialize the content of the request into the class associated with the curd | ||||
|      */ | ||||
|     protected function deserialize(string $action, Request $request, string $_format, $entity = null): object | ||||
|     { | ||||
|         $default = []; | ||||
|  | ||||
|         if (NULL !== $entity) { | ||||
|             $default[AbstractNormalizer::OBJECT_TO_POPULATE] = $entity; | ||||
|         } | ||||
|  | ||||
|         $context = \array_merge( | ||||
|             $default, | ||||
|             $this->getContextForSerialization($action, $request, $_format, $entity) | ||||
|         ); | ||||
|  | ||||
|         return $this->getSerializer()->deserialize($request->getContent(), $this->getEntityClass(), $_format, $context); | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * Base action for indexing entities | ||||
|      */ | ||||
|     public function indexApi(Request $request, string $_format) | ||||
|     { | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_GET: | ||||
|             case REQUEST::METHOD_HEAD: | ||||
|                 return $this->indexApiAction('_index', $request, $_format); | ||||
|             default: | ||||
|                 throw $this->createNotFoundException("This method is not supported"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Build an index page. | ||||
|      *  | ||||
|      * Some steps may be overriden during this process of rendering. | ||||
|      *  | ||||
|      * This method: | ||||
|      *  | ||||
|      * 1.  Launch `onPreIndex` | ||||
|      * x.  check acl. If it does return a response instance, return it | ||||
|      * x.  launch `onPostCheckACL`. If it does return a response instance, return it | ||||
|      * 1.  count the items, using `countEntities` | ||||
|      * 2.  build a paginator element from the the number of entities ; | ||||
|      * 3.  Launch `onPreIndexQuery`. If it does return a response instance, return it | ||||
|      * 3.  build a query, using `queryEntities` | ||||
|      * x.  fetch the results, using `getQueryResult` | ||||
|      * x.  Launch `onPostIndexFetchQuery`. If it does return a response instance, return it | ||||
|      * 4.  Serialize the entities in a Collection, using `SerializeCollection` | ||||
|      *  | ||||
|      * @param string $action | ||||
|      * @param Request $request | ||||
|      * @return type | ||||
|      */ | ||||
|     protected function indexApiAction($action, Request $request, $_format) | ||||
|     { | ||||
|         $this->onPreIndex($action, $request, $_format); | ||||
|          | ||||
|         $response = $this->checkACL($action, $request, $_format); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         if (!isset($entity)) { | ||||
|             $entity = ''; | ||||
|         } | ||||
|          | ||||
|         $response = $this->onPostCheckACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $totalItems = $this->countEntities($action, $request, $_format); | ||||
|         $paginator = $this->getPaginatorFactory()->create($totalItems); | ||||
|          | ||||
|         $response = $this->onPreIndexBuildQuery($action, $request, $_format, $totalItems,  | ||||
|             $paginator); | ||||
|          | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $query = $this->queryEntities($action, $request, $_format, $paginator); | ||||
|          | ||||
|         $response = $this->onPostIndexBuildQuery($action, $request, $_format, $totalItems,  | ||||
|             $paginator, $query); | ||||
|          | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $entities = $this->getQueryResult($action, $request, $_format, $totalItems, $paginator, $query); | ||||
|          | ||||
|         $response = $this->onPostIndexFetchQuery($action, $request, $_format, $totalItems,  | ||||
|             $paginator, $entities); | ||||
|          | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         return $this->serializeCollection($action, $request, $_format, $paginator, $entities);     | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Add or remove an associated entity, using `add` and `remove` methods. | ||||
|      * | ||||
|      * This method: | ||||
|      * | ||||
|      * 1. Fetch the base entity (throw 404 if not found) | ||||
|      * 2. checkACL,  | ||||
|      * 3. run onPostCheckACL, return response if any, | ||||
|      * 4. deserialize posted data into the entity given by $postedDataType, with the context in $postedDataContext | ||||
|      * 5. run 'add+$property' for POST method, or 'remove+$property' for DELETE method | ||||
|      * 6. validate the base entity (not the deserialized one). Groups are fetched from getValidationGroups, validation is perform by `validate` | ||||
|      * 7. run onAfterValidation | ||||
|      * 8. if errors, return a 422 response with errors | ||||
|      * 9. flush the data  | ||||
|      * 10. run onAfterFlush | ||||
|      * 11. return a 202 response for DELETE with empty body, or HTTP 200 for post with serialized posted entity | ||||
|      * | ||||
|      * @param string action | ||||
|      * @param mixed id | ||||
|      * @param Request $request | ||||
|      * @param string $_format | ||||
|      * @param string $property the name of the property. This will be used to make a `add+$property` and `remove+$property` method | ||||
|      * @param string $postedDataType the type of the posted data (the content) | ||||
|      * @param string $postedDataContext a context to deserialize posted data (the content) | ||||
|      * @throw BadRequestException if unable to deserialize the posted data | ||||
|      * @throw BadRequestException if the method is not POST or DELETE | ||||
|      * | ||||
|      */  | ||||
|     protected function addRemoveSomething(string $action, $id, Request $request, string $_format, string $property, string $postedDataType, $postedDataContext = []): Response | ||||
|     { | ||||
|         $entity = $this->getEntity($action, $id, $request); | ||||
|  | ||||
|         $postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format); | ||||
|         if ($postFetch instanceof Response) { | ||||
|             return $postFetch; | ||||
|         } | ||||
|  | ||||
|         $response = $this->checkACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         $response = $this->onPostCheckACL($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         $response = $this->onBeforeSerialize($action, $request, $_format, $entity); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         try { | ||||
|             $postedData = $this->getSerializer()->deserialize($request->getContent(), $postedDataType, $_format, $postedDataContext); | ||||
|         } catch (\Symfony\Component\Serializer\Exception\UnexpectedValueException $e) { | ||||
|             throw new BadRequestException(sprintf("Unable to deserialize posted ". | ||||
|                 "data: %s", $e->getMessage()), 0, $e); | ||||
|         } | ||||
|  | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_DELETE: | ||||
|                 // oups... how to use property accessor to remove element ? | ||||
|                 $entity->{'remove'.\ucfirst($property)}($postedData); | ||||
|                 break; | ||||
|             case Request::METHOD_POST: | ||||
|                 $entity->{'add'.\ucfirst($property)}($postedData); | ||||
|                 break; | ||||
|             default: | ||||
|                 throw new BadRequestException("this method is not supported"); | ||||
|         } | ||||
|  | ||||
|         $errors = $this->validate($action, $request, $_format, $entity, [$postedData]); | ||||
|  | ||||
|         $response = $this->onAfterValidation($action, $request, $_format, $entity, $errors, [$postedData]); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         if ($errors->count() > 0) { | ||||
|             // only format accepted | ||||
|             return $this->json($errors, 422); | ||||
|         } | ||||
|  | ||||
|         $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|  | ||||
|         $response = $this->onAfterFlush($action, $request, $_format, $entity, $errors, [$postedData]); | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|  | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_DELETE: | ||||
|                 return $this->json('', Response::HTTP_OK); | ||||
|             case Request::METHOD_POST: | ||||
|                 return $this->json( | ||||
|                     $postedData, | ||||
|                     Response::HTTP_OK, | ||||
|                     [],  | ||||
|                     $this->getContextForSerializationPostAlter($action, $request, $_format, $entity, [$postedData]) | ||||
|                 ); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Serialize collections | ||||
|      * | ||||
|      */ | ||||
|     protected function serializeCollection(string $action, Request $request, string $_format, PaginatorInterface $paginator, $entities): Response | ||||
|     { | ||||
|         $model = new Collection($entities, $paginator); | ||||
|  | ||||
|         $context = $this->getContextForSerialization($action, $request, $_format, $entities); | ||||
|  | ||||
|         return $this->json($model, Response::HTTP_OK, [], $context); | ||||
|     } | ||||
|      | ||||
|  | ||||
|     protected function getContextForSerialization(string $action, Request $request, string $_format, $entity): array | ||||
|     { | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_GET: | ||||
|                 return [ 'groups' => [ 'read' ]]; | ||||
|             case Request::METHOD_PUT: | ||||
|             case Request::METHOD_PATCH: | ||||
|                 return [ 'groups' => [ 'write' ]]; | ||||
|             default: | ||||
|                 throw new \LogicException("get context for serialization is not implemented for this method"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the context for serialization post alter query (in case of  | ||||
|      * PATCH, PUT, or POST method) | ||||
|      * | ||||
|      * This is called **after** the entity was altered. | ||||
|      */ | ||||
|     protected function getContextForSerializationPostAlter(string $action, Request $request, string $_format, $entity, array $more = []): array | ||||
|     { | ||||
|         return [ 'groups' => [ 'read' ]]; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * get the role given from the config. | ||||
|      */ | ||||
|     protected function getRoleFor(string $action, Request $request, $entity, $_format): string | ||||
|     { | ||||
|         $actionConfig = $this->getActionConfig($action); | ||||
|  | ||||
|         if (NULL !== $actionConfig['roles'][$request->getMethod()]) { | ||||
|             return $actionConfig['roles'][$request->getMethod()]; | ||||
|         } | ||||
|  | ||||
|         if ($this->crudConfig['base_role']) { | ||||
|             return $this->crudConfig['base_role']; | ||||
|         } | ||||
|  | ||||
|         throw new \RuntimeException(sprintf("the config does not have any role for the ". | ||||
|             "method %s nor a global role for the whole action. Add those to your ". | ||||
|             "configuration or override the required method", $request->getMethod())); | ||||
|          | ||||
|     } | ||||
|  | ||||
|     protected function getSerializer(): SerializerInterface | ||||
|     { | ||||
|         return $this->get('serializer'); | ||||
|     } | ||||
| } | ||||
| @@ -34,6 +34,7 @@ use Chill\MainBundle\CRUD\Form\CRUDDeleteEntityForm; | ||||
| use Chill\MainBundle\Pagination\PaginatorFactory; | ||||
| use Chill\MainBundle\Pagination\PaginatorInterface; | ||||
| use Chill\MainBundle\Security\Authorization\AuthorizationHelper; | ||||
| use Symfony\Component\Serializer\SerializerInterface; | ||||
|  | ||||
| /** | ||||
|  * Class CRUDController | ||||
| @@ -484,7 +485,7 @@ class CRUDController extends AbstractController | ||||
|      * @param mixed $id | ||||
|      * @return Response | ||||
|      */ | ||||
|     protected function viewAction(string $action, Request $request, $id)  | ||||
|     protected function viewAction(string $action, Request $request, $id, $_format = 'html'): Response | ||||
|     { | ||||
|         $entity = $this->getEntity($action, $id, $request); | ||||
|          | ||||
| @@ -496,7 +497,7 @@ class CRUDController extends AbstractController | ||||
|          | ||||
|         if (NULL === $entity) { | ||||
|             throw $this->createNotFoundException(sprintf("The %s with id %s " | ||||
|                 . "is not found"), $this->getCrudName(), $id); | ||||
|                 . "is not found", $this->getCrudName(), $id)); | ||||
|         } | ||||
|          | ||||
|         $response = $this->checkACL($action, $entity); | ||||
| @@ -508,17 +509,36 @@ class CRUDController extends AbstractController | ||||
|         if ($response instanceof Response) { | ||||
|             return $response; | ||||
|         } | ||||
|          | ||||
|         $defaultTemplateParameters = [ | ||||
|             'entity' => $entity, | ||||
|             'crud_name' => $this->getCrudName() | ||||
|         ]; | ||||
|          | ||||
|         return $this->render( | ||||
|             $this->getTemplateFor($action, $entity, $request),  | ||||
|             $this->generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters) | ||||
|  | ||||
|         if ($_format === 'html') { | ||||
|             $defaultTemplateParameters = [ | ||||
|                 'entity' => $entity, | ||||
|                 'crud_name' => $this->getCrudName() | ||||
|             ]; | ||||
|              | ||||
|             return $this->render( | ||||
|                 $this->getTemplateFor($action, $entity, $request),  | ||||
|                 $this->generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters) | ||||
|             ); | ||||
|         } elseif ($_format === 'json') { | ||||
|             $context = $this->getContextForSerialization($action, $request, $entity, $_format); | ||||
|  | ||||
|             return $this->json($entity, Response::HTTP_OK, [], $context); | ||||
|         } else { | ||||
|             throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This format is not implemented"); | ||||
|         } | ||||
|  | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the context for the serialization | ||||
|      */ | ||||
|     public function getContextForSerialization(string $action, Request $request, $entity, string $_format): array | ||||
|     { | ||||
|         return []; | ||||
|     } | ||||
|      | ||||
|  | ||||
|      | ||||
|     /** | ||||
|      * The edit action. | ||||
| @@ -799,7 +819,7 @@ class CRUDController extends AbstractController | ||||
|      */ | ||||
|     protected function getRoleFor($action) | ||||
|     { | ||||
|         if (NULL !== ($this->getActionConfig($action)['role'])) { | ||||
|         if (\array_key_exists('role', $this->getActionConfig($action))) { | ||||
|             return $this->getActionConfig($action)['role']; | ||||
|         } | ||||
|          | ||||
| @@ -1181,6 +1201,7 @@ class CRUDController extends AbstractController | ||||
|                 AuthorizationHelper::class => AuthorizationHelper::class, | ||||
|                 EventDispatcherInterface::class => EventDispatcherInterface::class, | ||||
|                 Resolver::class => Resolver::class, | ||||
|                 SerializerInterface::class => SerializerInterface::class, | ||||
|             ] | ||||
|         ); | ||||
|     } | ||||
|   | ||||
| @@ -23,6 +23,9 @@ namespace Chill\MainBundle\CRUD\Routing; | ||||
| use Symfony\Component\Config\Loader\Loader; | ||||
| use Symfony\Component\Routing\Route; | ||||
| use Symfony\Component\Routing\RouteCollection; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Chill\MainBundle\CRUD\Controller\ApiController; | ||||
| use Chill\MainBundle\CRUD\Controller\CRUDController; | ||||
|  | ||||
| /** | ||||
|  * Class CRUDRoutesLoader | ||||
| @@ -32,24 +35,34 @@ use Symfony\Component\Routing\RouteCollection; | ||||
|  */ | ||||
| class CRUDRoutesLoader extends Loader | ||||
| { | ||||
|     /** | ||||
|      * @var array | ||||
|      */ | ||||
|     protected $config = []; | ||||
|     protected array $crudConfig = []; | ||||
|  | ||||
|     protected array $apiCrudConfig = []; | ||||
|      | ||||
|     /** | ||||
|      * @var bool | ||||
|      */ | ||||
|     private $isLoaded = false; | ||||
|  | ||||
|     private const ALL_SINGLE_METHODS = [ | ||||
|         Request::METHOD_GET, | ||||
|         Request::METHOD_POST, | ||||
|         Request::METHOD_PUT, | ||||
|         Request::METHOD_DELETE | ||||
|     ]; | ||||
|  | ||||
|     private const ALL_INDEX_METHODS = [ Request::METHOD_GET, Request::METHOD_HEAD ]; | ||||
|      | ||||
|     /** | ||||
|      * CRUDRoutesLoader constructor. | ||||
|      * | ||||
|      * @param $config | ||||
|      * @param $crudConfig the config from cruds | ||||
|      * @param $apicrudConfig the config from api_crud | ||||
|      */ | ||||
|     public function __construct($config) | ||||
|     public function __construct(array $crudConfig, array $apiConfig) | ||||
|     { | ||||
|         $this->config = $config; | ||||
|         $this->crudConfig = $crudConfig; | ||||
|         $this->apiConfig = $apiConfig; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
| @@ -63,53 +76,125 @@ class CRUDRoutesLoader extends Loader | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * @return RouteCollection | ||||
|      * Load routes for CRUD and CRUD Api | ||||
|      */ | ||||
|     public function load($resource, $type = null) | ||||
|     public function load($resource, $type = null): RouteCollection | ||||
|     { | ||||
|      | ||||
|         if (true === $this->isLoaded) { | ||||
|             throw new \RuntimeException('Do not add the "CRUD" loader twice'); | ||||
|         } | ||||
|          | ||||
|  | ||||
|         $collection = new RouteCollection(); | ||||
|          | ||||
|         foreach ($this->config as $config) { | ||||
|             $collection->addCollection($this->loadConfig($config)); | ||||
|         foreach ($this->crudConfig as $crudConfig) { | ||||
|             $collection->addCollection($this->loadCrudConfig($crudConfig)); | ||||
|         } | ||||
|          | ||||
|         foreach ($this->apiConfig as $crudConfig) { | ||||
|             $collection->addCollection($this->loadApi($crudConfig)); | ||||
|         } | ||||
|  | ||||
|         return $collection; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * @param $config | ||||
|      * Load routes for CRUD (without api) | ||||
|      * | ||||
|      * @param $crudConfig | ||||
|      * @return RouteCollection | ||||
|      */ | ||||
|     protected function loadConfig($config): RouteCollection | ||||
|     protected function loadCrudConfig($crudConfig): RouteCollection | ||||
|     { | ||||
|         $collection = new RouteCollection(); | ||||
|         foreach ($config['actions'] as $name => $action) { | ||||
|         $controller ='cscrud_'.$crudConfig['name'].'_controller'; | ||||
|  | ||||
|         foreach ($crudConfig['actions'] as $name => $action) { | ||||
|             // defaults (controller name) | ||||
|             $defaults = [ | ||||
|                 '_controller' => 'cscrud_'.$config['name'].'_controller'.':'.($action['controller_action'] ?? $name) | ||||
|                 '_controller' => $controller.':'.($action['controller_action'] ?? $name) | ||||
|             ]; | ||||
|              | ||||
|             if ($name === 'index') { | ||||
|                 $path = "{_locale}".$config['base_path']; | ||||
|                 $path = "{_locale}".$crudConfig['base_path']; | ||||
|                 $route = new Route($path, $defaults); | ||||
|             } elseif ($name === 'new') { | ||||
|                 $path = "{_locale}".$config['base_path'].'/'.$name; | ||||
|                 $path = "{_locale}".$crudConfig['base_path'].'/'.$name; | ||||
|                 $route = new Route($path, $defaults); | ||||
|             } else { | ||||
|                 $path = "{_locale}".$config['base_path'].($action['path'] ?? '/{id}/'.$name); | ||||
|                 $path = "{_locale}".$crudConfig['base_path'].($action['path'] ?? '/{id}/'.$name); | ||||
|                 $requirements = $action['requirements'] ?? [ | ||||
|                     '{id}' => '\d+' | ||||
|                 ]; | ||||
|                 $route = new Route($path, $defaults, $requirements); | ||||
|             } | ||||
|              | ||||
|             $collection->add('chill_crud_'.$config['name'].'_'.$name, $route); | ||||
|             $collection->add('chill_crud_'.$crudConfig['name'].'_'.$name, $route); | ||||
|         } | ||||
|          | ||||
|         return $collection; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Load routes for api single | ||||
|      * | ||||
|      * @param $crudConfig | ||||
|      * @return RouteCollection | ||||
|      */ | ||||
|     protected function loadApi(array $crudConfig): RouteCollection | ||||
|     { | ||||
|         $collection = new RouteCollection(); | ||||
|         $controller ='csapi_'.$crudConfig['name'].'_controller'; | ||||
|  | ||||
|         foreach ($crudConfig['actions'] as $name => $action) { | ||||
|             // filter only on single actions | ||||
|             $singleCollection = $action['single-collection'] ?? $name === '_entity' ? 'single' : NULL; | ||||
|             if ('collection' === $singleCollection) { | ||||
| //                continue; | ||||
|             } | ||||
|  | ||||
|             // compute default action | ||||
|             switch ($name) { | ||||
|                 case '_entity': | ||||
|                     $controllerAction = 'entityApi'; | ||||
|                     break; | ||||
|                 case '_index': | ||||
|                     $controllerAction = 'indexApi'; | ||||
|                     break; | ||||
|                 default: | ||||
|                     $controllerAction = $name.'Api'; | ||||
|                     break; | ||||
|             } | ||||
|  | ||||
|             $defaults = [ | ||||
|                 '_controller' => $controller.':'.($action['controller_action'] ?? $controllerAction) | ||||
|             ]; | ||||
|  | ||||
|             // path are rewritten | ||||
|             // if name === 'default', we rewrite it to nothing :-) | ||||
|             $localName = \in_array($name, [ '_entity', '_index' ]) ? '' : '/'.$name; | ||||
|             if ('collection' === $action['single-collection'] || '_index' === $name) { | ||||
|                 $localPath = $action['path'] ?? $localName.'.{_format}'; | ||||
|             } else { | ||||
|                 $localPath = $action['path'] ?? '/{id}'.$localName.'.{_format}'; | ||||
|             } | ||||
|             $path = $crudConfig['base_path'].$localPath; | ||||
|  | ||||
|             $requirements = $action['requirements'] ?? [ '{id}' => '\d+' ]; | ||||
|  | ||||
|             $methods = \array_keys(\array_filter($action['methods'], function($value, $key) { return $value; }, | ||||
|                 ARRAY_FILTER_USE_BOTH)); | ||||
|  | ||||
|             if (count($methods) === 0) { | ||||
|                 throw new \RuntimeException("The api configuration named \"{$crudConfig['name']}\", action \"{$name}\", ". | ||||
|                     "does not have any allowed methods. You should remove this action from the config ". | ||||
|                     "or allow, at least, one method");  | ||||
|             } | ||||
|  | ||||
|             $route = new Route($path, $defaults, $requirements); | ||||
|             $route->setMethods($methods); | ||||
|              | ||||
|             $collection->add('chill_api_single_'.$crudConfig['name'].'_'.$name, $route); | ||||
|         } | ||||
|  | ||||
|         return $collection; | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -14,6 +14,7 @@ use Chill\MainBundle\DependencyInjection\CompilerPass\NotificationCounterCompile | ||||
| use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass; | ||||
| use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass; | ||||
| use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass; | ||||
| use Chill\MainBundle\CRUD\CompilerPass\CRUDControllerCompilerPass; | ||||
| use Chill\MainBundle\Templating\Entity\CompilerPass as RenderEntityCompilerPass; | ||||
|  | ||||
|  | ||||
| @@ -33,5 +34,6 @@ class ChillMainBundle extends Bundle | ||||
|         $container->addCompilerPass(new ACLFlagsCompilerPass()); | ||||
|         $container->addCompilerPass(new GroupingCenterCompilerPass()); | ||||
|         $container->addCompilerPass(new RenderEntityCompilerPass()); | ||||
|         $container->addCompilerPass(new CRUDControllerCompilerPass()); | ||||
|     } | ||||
| } | ||||
|   | ||||
							
								
								
									
										63
									
								
								src/Bundle/ChillMainBundle/Controller/AddressController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										63
									
								
								src/Bundle/ChillMainBundle/Controller/AddressController.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,63 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Controller; | ||||
|  | ||||
| use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; | ||||
| use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | ||||
| use Symfony\Component\HttpFoundation\Response; | ||||
| use Symfony\Component\HttpFoundation\Exception\BadRequestException; | ||||
| use Symfony\Component\Routing\Annotation\Route; | ||||
| use Chill\MainBundle\Entity\Address; | ||||
| use Chill\MainBundle\Entity\AddressReference; | ||||
|  | ||||
| /** | ||||
|  * Class AddressController | ||||
|  * | ||||
|  * @package Chill\MainBundle\Controller | ||||
|  */ | ||||
| class AddressController extends AbstractController | ||||
| { | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * Get API Data for showing endpoint | ||||
|      * | ||||
|      * @Route( | ||||
|      *     "/{_locale}/main/api/1.0/address/{address_id}/show.{_format}", | ||||
|      *     name="chill_main_address_api_show" | ||||
|      * ) | ||||
|      * @ParamConverter("address", options={"id": "address_id"}) | ||||
|      */ | ||||
|     public function showAddress(Address $address, $_format): Response | ||||
|     { | ||||
|         // TODO check ACL ? | ||||
|         switch ($_format) { | ||||
|             case 'json': | ||||
|                 return $this->json($address); | ||||
|             default: | ||||
|                 throw new BadRequestException('Unsupported format'); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * Get API Data for showing endpoint | ||||
|      * | ||||
|      * @Route( | ||||
|      *     "/{_locale}/main/api/1.0/address-reference/{address_reference_id}/show.{_format}", | ||||
|      *     name="chill_main_address_reference_api_show" | ||||
|      * ) | ||||
|      * @ParamConverter("addressReference", options={"id": "address_reference_id"}) | ||||
|      */ | ||||
|     public function showAddressReference(AddressReference $addressReference, $_format): Response | ||||
|     { | ||||
|         // TODO check ACL ? | ||||
|         switch ($_format) { | ||||
|             case 'json': | ||||
|                 return $this->json($addressReference); | ||||
|             default: | ||||
|                 throw new BadRequestException('Unsupported format'); | ||||
|         } | ||||
|  | ||||
|     } | ||||
| } | ||||
| @@ -22,6 +22,7 @@ | ||||
|  | ||||
| namespace Chill\MainBundle\Controller; | ||||
|  | ||||
| use Chill\MainBundle\Serializer\Model\Collection; | ||||
| use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Chill\MainBundle\Search\UnknowSearchDomainException; | ||||
| @@ -34,6 +35,7 @@ use Symfony\Component\HttpFoundation\JsonResponse; | ||||
| use Chill\MainBundle\Search\SearchProvider; | ||||
| use Symfony\Contracts\Translation\TranslatorInterface; | ||||
| use Chill\MainBundle\Pagination\PaginatorFactory; | ||||
| use Chill\MainBundle\Search\SearchApi; | ||||
|  | ||||
| /** | ||||
|  * Class SearchController | ||||
| @@ -42,32 +44,24 @@ use Chill\MainBundle\Pagination\PaginatorFactory; | ||||
|  */ | ||||
| class SearchController extends AbstractController | ||||
| { | ||||
|     /** | ||||
|      * | ||||
|      * @var SearchProvider | ||||
|      */ | ||||
|     protected $searchProvider; | ||||
|     protected SearchProvider $searchProvider; | ||||
|      | ||||
|     /** | ||||
|      * | ||||
|      * @var TranslatorInterface | ||||
|      */ | ||||
|     protected $translator; | ||||
|     protected TranslatorInterface $translator; | ||||
|      | ||||
|     /** | ||||
|      * | ||||
|      * @var PaginatorFactory | ||||
|      */ | ||||
|     protected $paginatorFactory; | ||||
|     protected PaginatorFactory $paginatorFactory; | ||||
|  | ||||
|     protected SearchApi $searchApi; | ||||
|      | ||||
|     function __construct( | ||||
|         SearchProvider $searchProvider,  | ||||
|         TranslatorInterface $translator, | ||||
|         PaginatorFactory $paginatorFactory | ||||
|         PaginatorFactory $paginatorFactory, | ||||
|         SearchApi $searchApi | ||||
|     ) { | ||||
|         $this->searchProvider = $searchProvider; | ||||
|         $this->translator = $translator; | ||||
|         $this->paginatorFactory = $paginatorFactory; | ||||
|         $this->searchApi = $searchApi; | ||||
|     } | ||||
|  | ||||
|      | ||||
| @@ -152,6 +146,19 @@ class SearchController extends AbstractController | ||||
|               array('results' => $results, 'pattern' => $pattern) | ||||
|               ); | ||||
|     } | ||||
|  | ||||
|     public function searchApi(Request $request, $_format): JsonResponse | ||||
|     { | ||||
|         //TODO this is an incomplete implementation | ||||
|         $query = $request->query->get('q', ''); | ||||
|  | ||||
|         $results = $this->searchApi->getResults($query, 0, 150); | ||||
|         $paginator = $this->paginatorFactory->create(count($results)); | ||||
|  | ||||
|         $collection = new Collection($results, $paginator); | ||||
|  | ||||
|         return $this->json($collection); | ||||
|     } | ||||
|      | ||||
|     public function advancedSearchListAction(Request $request) | ||||
|     { | ||||
|   | ||||
| @@ -0,0 +1,95 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\DataFixtures\ORM; | ||||
|  | ||||
| use Doctrine\Common\DataFixtures\AbstractFixture; | ||||
| use Doctrine\Common\DataFixtures\OrderedFixtureInterface; | ||||
| use Symfony\Component\DependencyInjection\ContainerAwareInterface; | ||||
| use Symfony\Component\DependencyInjection\ContainerInterface; | ||||
| use Doctrine\Persistence\ObjectManager; | ||||
| use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes; | ||||
| use Chill\MainBundle\Entity\AddressReference; | ||||
| use Chill\MainBundle\Doctrine\Model\Point; | ||||
|  | ||||
| /** | ||||
|  * Load reference addresses into database | ||||
|  * | ||||
|  * @author Champs Libres | ||||
|  */ | ||||
| class LoadAddressReferences extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface { | ||||
|  | ||||
|  | ||||
|     protected $faker; | ||||
|  | ||||
|     public function __construct() | ||||
|     { | ||||
|         $this->faker = \Faker\Factory::create('fr_FR'); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @var ContainerInterface | ||||
|      */ | ||||
|     private $container; | ||||
|  | ||||
|     public function setContainer(ContainerInterface $container = null) | ||||
|     { | ||||
|         $this->container = $container; | ||||
|     } | ||||
|  | ||||
|     public function getOrder() { | ||||
|         return 51; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * Create a random point | ||||
|      * | ||||
|      * @return Point | ||||
|      */ | ||||
|     private function getRandomPoint() | ||||
|     { | ||||
|         $lonBrussels = 4.35243; | ||||
|         $latBrussels = 50.84676; | ||||
|         $lon = $lonBrussels + 0.01 * rand(-5, 5); | ||||
|         $lat = $latBrussels + 0.01 * rand(-5, 5); | ||||
|         return Point::fromLonLat($lon, $lat); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Create a random reference address | ||||
|      * | ||||
|      * @return AddressReference | ||||
|      */ | ||||
|     private function getRandomAddressReference() | ||||
|     { | ||||
|         $ar= new AddressReference(); | ||||
|  | ||||
|         $ar->setRefId($this->faker->numerify('ref-id-######')); | ||||
|         $ar->setStreet($this->faker->streetName); | ||||
|         $ar->setStreetNumber(rand(0,199)); | ||||
|         $ar ->setPoint($this->getRandomPoint()); | ||||
|         $ar->setPostcode($this->getReference( | ||||
|             LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)] | ||||
|         )); | ||||
|  | ||||
|         $ar->setMunicipalityCode($ar->getPostcode()->getCode()); | ||||
|  | ||||
|         return $ar | ||||
|         ; | ||||
|     } | ||||
|  | ||||
|     public function load(ObjectManager $manager) { | ||||
|  | ||||
|         echo "loading some reference address... \n"; | ||||
|  | ||||
|         for ($i=0; $i<10; $i++) { | ||||
|             $ar = $this->getRandomAddressReference(); | ||||
|             $manager->persist($ar); | ||||
|         } | ||||
|  | ||||
|         $manager->flush(); | ||||
|     } | ||||
|  | ||||
|  | ||||
| } | ||||
| @@ -55,11 +55,11 @@ class LoadCenters extends AbstractFixture implements OrderedFixtureInterface | ||||
|     public function load(ObjectManager $manager) | ||||
|     { | ||||
|         foreach (static::$centers as $new) { | ||||
|             $centerA = new Center(); | ||||
|             $centerA->setName($new['name']); | ||||
|             $center = new Center(); | ||||
|             $center->setName($new['name']); | ||||
|  | ||||
|             $manager->persist($centerA); | ||||
|             $this->addReference($new['ref'], $centerA); | ||||
|             $manager->persist($center); | ||||
|             $this->addReference($new['ref'], $center); | ||||
|             static::$refs[] = $new['ref']; | ||||
|         } | ||||
|          | ||||
|   | ||||
| @@ -35,6 +35,7 @@ use Chill\MainBundle\Doctrine\DQL\OverlapsI; | ||||
| use Symfony\Component\DependencyInjection\Definition; | ||||
| use Symfony\Component\DependencyInjection\Reference; | ||||
| use Chill\MainBundle\Doctrine\DQL\Replace; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
|  | ||||
| /** | ||||
|  * Class ChillMainExtension | ||||
| @@ -47,11 +48,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
| { | ||||
|     /** | ||||
|      * widget factory | ||||
|      *  | ||||
|      * | ||||
|      * @var WidgetFactoryInterface[] | ||||
|      */ | ||||
|     protected $widgetFactories = array(); | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @param WidgetFactoryInterface $factory | ||||
|      */ | ||||
| @@ -59,7 +60,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|     { | ||||
|         $this->widgetFactories[] = $factory; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @return WidgetFactoryInterface[] | ||||
|      */ | ||||
| @@ -67,7 +68,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|     { | ||||
|         return $this->widgetFactories; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * {@inheritDoc} | ||||
|      * @param array $configs | ||||
| @@ -79,31 +80,31 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|         // configuration for main bundle | ||||
|         $configuration = $this->getConfiguration($configs, $container); | ||||
|         $config = $this->processConfiguration($configuration, $configs); | ||||
|          | ||||
|  | ||||
|         $container->setParameter('chill_main.installation_name', | ||||
|             $config['installation_name']); | ||||
|  | ||||
|         $container->setParameter('chill_main.available_languages', | ||||
|             $config['available_languages']); | ||||
|          | ||||
|         $container->setParameter('chill_main.routing.resources',  | ||||
|             $config['routing']['resources']);  | ||||
|          | ||||
|  | ||||
|         $container->setParameter('chill_main.routing.resources', | ||||
|             $config['routing']['resources']); | ||||
|  | ||||
|         $container->setParameter('chill_main.pagination.item_per_page', | ||||
|             $config['pagination']['item_per_page']); | ||||
|          | ||||
|         $container->setParameter('chill_main.notifications',  | ||||
|  | ||||
|         $container->setParameter('chill_main.notifications', | ||||
|             $config['notifications']); | ||||
|          | ||||
|         $container->setParameter('chill_main.redis',  | ||||
|  | ||||
|         $container->setParameter('chill_main.redis', | ||||
|             $config['redis']); | ||||
|          | ||||
|         $container->setParameter('chill_main.phone_helper',  | ||||
|  | ||||
|         $container->setParameter('chill_main.phone_helper', | ||||
|             $config['phone_helper'] ?? []); | ||||
|          | ||||
|  | ||||
|         // add the key 'widget' without the key 'enable' | ||||
|         $container->setParameter('chill_main.widgets',  | ||||
|             isset($config['widgets']['homepage']) ?  | ||||
|         $container->setParameter('chill_main.widgets', | ||||
|             isset($config['widgets']['homepage']) ? | ||||
|                 array('homepage' => $config['widgets']['homepage']): | ||||
|                 array() | ||||
|                 ); | ||||
| @@ -131,10 +132,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|         $loader->load('services/templating.yaml'); | ||||
|         $loader->load('services/timeline.yaml'); | ||||
|         $loader->load('services/search.yaml'); | ||||
|          | ||||
|         $this->configureCruds($container, $config['cruds'], $loader); | ||||
|         $loader->load('services/serializer.yaml'); | ||||
|  | ||||
|         $this->configureCruds($container, $config['cruds'], $config['apis'], $loader); | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @param array $config | ||||
|      * @param ContainerBuilder $container | ||||
| @@ -144,11 +146,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|     { | ||||
|         return new Configuration($this->widgetFactories, $container); | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @param ContainerBuilder $container | ||||
|      */ | ||||
|     public function prepend(ContainerBuilder $container)  | ||||
|     public function prepend(ContainerBuilder $container) | ||||
|     { | ||||
|         //add installation_name and date_format to globals | ||||
|         $chillMainConfig = $container->getExtensionConfig($this->getAlias()); | ||||
| @@ -163,7 +165,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|             'form_themes' => array('@ChillMain/Form/fields.html.twig') | ||||
|         ); | ||||
|         $container->prependExtensionConfig('twig', $twigConfig); | ||||
|          | ||||
|  | ||||
|         //add DQL function to ORM (default entity_manager) | ||||
|         $container->prependExtensionConfig('doctrine', array( | ||||
|            'orm' => array( | ||||
| @@ -182,78 +184,152 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface, | ||||
|               ) | ||||
|            ) | ||||
|         )); | ||||
|          | ||||
|  | ||||
|         //add dbal types (default entity_manager) | ||||
|         $container->prependExtensionConfig('doctrine', array( | ||||
|            'dbal' => [ | ||||
|                'types' => [ | ||||
|                    'dateinterval' => \Chill\MainBundle\Doctrine\Type\NativeDateIntervalType::class | ||||
|                    'dateinterval' => [ | ||||
|                        'class' => \Chill\MainBundle\Doctrine\Type\NativeDateIntervalType::class | ||||
|                    ], | ||||
|                    'point' => [ | ||||
|                        'class' => \Chill\MainBundle\Doctrine\Type\PointType::class | ||||
|                    ] | ||||
|                ] | ||||
|            ] | ||||
|         )); | ||||
|          | ||||
|  | ||||
|         //add current route to chill main | ||||
|         $container->prependExtensionConfig('chill_main', array( | ||||
|            'routing' => array( | ||||
|               'resources' => array( | ||||
|                  '@ChillMainBundle/config/routes.yaml' | ||||
|               ) | ||||
|                | ||||
|  | ||||
|            ) | ||||
|         )); | ||||
|          | ||||
|  | ||||
|         //add a channel to log app events | ||||
|         $container->prependExtensionConfig('monolog', array( | ||||
|             'channels' => array('chill') | ||||
|         )); | ||||
|  | ||||
|         //add crud api | ||||
|         $this->prependCruds($container); | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @param ContainerBuilder $container | ||||
|      * @param array $config the config under 'cruds' key | ||||
|      * @return null | ||||
|      * Load parameter for configuration and set parameters for api | ||||
|      */ | ||||
|     protected function configureCruds(ContainerBuilder $container, $config, Loader\YamlFileLoader $loader) | ||||
|     protected function configureCruds( | ||||
|         ContainerBuilder $container, | ||||
|         array $crudConfig, | ||||
|         array $apiConfig, | ||||
|         Loader\YamlFileLoader $loader | ||||
|     ): void | ||||
|     { | ||||
|         if (count($config) === 0) { | ||||
|         if (count($crudConfig) === 0) { | ||||
|             return; | ||||
|         } | ||||
|          | ||||
|  | ||||
|         $loader->load('services/crud.yaml'); | ||||
|          | ||||
|         $container->setParameter('chill_main_crud_route_loader_config', $config); | ||||
|          | ||||
|         $definition = new Definition(); | ||||
|         $definition | ||||
|             ->setClass(\Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader::class) | ||||
|             ->addArgument('%chill_main_crud_route_loader_config%') | ||||
|             ; | ||||
|          | ||||
|         $container->setDefinition('chill_main_crud_route_loader', $definition); | ||||
|          | ||||
|         $alreadyExistingNames = []; | ||||
|          | ||||
|         foreach ($config as $crudEntry) { | ||||
|             $controller = $crudEntry['controller']; | ||||
|             $controllerServiceName = 'cscrud_'.$crudEntry['name'].'_controller'; | ||||
|             $name = $crudEntry['name']; | ||||
|              | ||||
|             // check for existing crud names | ||||
|             if (\in_array($name, $alreadyExistingNames)) { | ||||
|                 throw new LogicException(sprintf("the name %s is defined twice in CRUD", $name)); | ||||
|             } | ||||
|              | ||||
|             if (!$container->has($controllerServiceName)) { | ||||
|                 $controllerDefinition = new Definition($controller); | ||||
|                 $controllerDefinition->addTag('controller.service_arguments'); | ||||
|                 $controllerDefinition->setAutoconfigured(true); | ||||
|                 $controllerDefinition->setClass($crudEntry['controller']); | ||||
|                 $container->setDefinition($controllerServiceName, $controllerDefinition); | ||||
|             } | ||||
|              | ||||
|             $container->setParameter('chill_main_crud_config_'.$name, $crudEntry); | ||||
|             $container->getDefinition($controllerServiceName) | ||||
|                 ->addMethodCall('setCrudConfig', ['%chill_main_crud_config_'.$name.'%']); | ||||
|         } | ||||
|  | ||||
|         $container->setParameter('chill_main_crud_route_loader_config', $crudConfig); | ||||
|         $container->setParameter('chill_main_api_route_loader_config', $apiConfig); | ||||
|  | ||||
|         // Note: the controller are loaded inside compiler pass | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * @param ContainerBuilder $container | ||||
|      */ | ||||
|     protected function prependCruds(ContainerBuilder $container) | ||||
|     { | ||||
|         $container->prependExtensionConfig('chill_main', [ | ||||
|             'apis' => [ | ||||
|                 [ | ||||
|                     'class' => \Chill\MainBundle\Entity\Address::class, | ||||
|                     'name' => 'address', | ||||
|                     'base_path' => '/api/1.0/main/address', | ||||
|                     'base_role' => 'ROLE_USER', | ||||
|                     'actions' => [ | ||||
|                         '_index' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ], | ||||
|                         ], | ||||
|                         '_entity' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_POST => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ] | ||||
|                         ], | ||||
|                     ] | ||||
|                 ], | ||||
|                 [ | ||||
|                     'class' => \Chill\MainBundle\Entity\AddressReference::class, | ||||
|                     'name' => 'address_reference', | ||||
|                     'base_path' => '/api/1.0/main/address-reference', | ||||
|                     'base_role' => 'ROLE_USER', | ||||
|                     'actions' => [ | ||||
|                         '_index' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ], | ||||
|                         ], | ||||
|                         '_entity' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ] | ||||
|                         ], | ||||
|                     ] | ||||
|                 ], | ||||
|                 [ | ||||
|                     'class' => \Chill\MainBundle\Entity\PostalCode::class, | ||||
|                     'name' => 'postal_code', | ||||
|                     'base_path' => '/api/1.0/main/postal-code', | ||||
|                     'base_role' => 'ROLE_USER', | ||||
|                     'actions' => [ | ||||
|                         '_index' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ], | ||||
|                         ], | ||||
|                         '_entity' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ] | ||||
|                         ], | ||||
|                     ] | ||||
|                 ], | ||||
|                 [ | ||||
|                     'class' => \Chill\MainBundle\Entity\Country::class, | ||||
|                     'name' => 'country', | ||||
|                     'base_path' => '/api/1.0/main/country', | ||||
|                     'base_role' => 'ROLE_USER', | ||||
|                     'actions' => [ | ||||
|                         '_index' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ], | ||||
|                         ], | ||||
|                         '_entity' => [ | ||||
|                             'methods' => [ | ||||
|                                 Request::METHOD_GET => true, | ||||
|                                 Request::METHOD_HEAD => true | ||||
|                             ] | ||||
|                         ], | ||||
|                     ] | ||||
|                 ] | ||||
|             ] | ||||
|         ]); | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -8,6 +8,7 @@ use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface; | ||||
| use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; | ||||
| use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait; | ||||
| use Symfony\Component\DependencyInjection\ContainerBuilder; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
|  | ||||
|  | ||||
| /** | ||||
| @@ -140,7 +141,7 @@ class Configuration implements ConfigurationInterface | ||||
|                                         ->scalarNode('controller_action') | ||||
|                                             ->defaultNull() | ||||
|                                             ->info('the method name to call in the route. Will be set to the action name if left empty.') | ||||
|                                             ->example("'action'") | ||||
|                                             ->example("action") | ||||
|                                         ->end() | ||||
|                                         ->scalarNode('path') | ||||
|                                             ->defaultNull() | ||||
| @@ -168,6 +169,80 @@ class Configuration implements ConfigurationInterface | ||||
|                     ->end() | ||||
|  | ||||
|                 ->end() | ||||
|  | ||||
|  | ||||
|                 ->arrayNode('apis') | ||||
|                     ->defaultValue([]) | ||||
|                     ->arrayPrototype() | ||||
|                         ->children() | ||||
|                             ->scalarNode('class')->cannotBeEmpty()->isRequired()->end() | ||||
|                             ->scalarNode('controller') | ||||
|                                 ->cannotBeEmpty() | ||||
|                                 ->defaultValue(\Chill\MainBundle\CRUD\Controller\ApiController::class) | ||||
|                             ->end() | ||||
|                             ->scalarNode('name')->cannotBeEmpty()->isRequired()->end() | ||||
|                             ->scalarNode('base_path')->cannotBeEmpty()->isRequired()->end() | ||||
|                             ->scalarNode('base_role')->defaultNull()->end() | ||||
|                             ->arrayNode('actions') | ||||
|                                 ->useAttributeAsKey('name') | ||||
|                                 ->arrayPrototype() | ||||
|                                     ->children() | ||||
|                                         ->scalarNode('controller_action') | ||||
|                                             ->defaultNull() | ||||
|                                             ->info('the method name to call in the controller. Will be set to the concatenation '. | ||||
|                                                 'of action name + \'Api\' if left empty.') | ||||
|                                             ->example("showApi") | ||||
|                                         ->end() | ||||
|                                         ->scalarNode('path') | ||||
|                                             ->defaultNull() | ||||
|                                             ->info('the path that will be **appended** after the base path. Do not forget to add ' . | ||||
|                                                 'arguments for the method. By default, will set to the action name, including an `{id}` '. | ||||
|                                                 'parameter. A suffix of action name will be appended, except if the action name '. | ||||
|                                                 'is "_entity".') | ||||
|                                             ->example('/{id}/my-action') | ||||
|                                         ->end() | ||||
|                                         ->arrayNode('requirements') | ||||
|                                             ->ignoreExtraKeys(false) | ||||
|                                             ->info('the requirements for the route. Will be set to `[ \'id\' => \'\d+\' ]` if left empty.') | ||||
|                                         ->end() | ||||
|                                         ->enumNode('single-collection') | ||||
|                                             ->values(['single', 'collection']) | ||||
|                                             ->defaultValue('single') | ||||
|                                             ->info('indicates if the returned object is a single element or a collection. '. | ||||
|                                                     'If the action name is `_index`, this value will always be considered as '. | ||||
|                                                     '`collection`') | ||||
|                                         ->end() | ||||
|                                         ->arrayNode('methods') | ||||
|                                             ->addDefaultsIfNotSet() | ||||
|                                             ->info('the allowed methods') | ||||
|                                             ->children() | ||||
|                                                 ->booleanNode(Request::METHOD_GET)->defaultTrue()->end() | ||||
|                                                 ->booleanNode(Request::METHOD_HEAD)->defaultTrue()->end() | ||||
|                                                 ->booleanNode(Request::METHOD_POST)->defaultFalse()->end() | ||||
|                                                 ->booleanNode(Request::METHOD_DELETE)->defaultFalse()->end() | ||||
|                                                 ->booleanNode(Request::METHOD_PUT)->defaultFalse()->end() | ||||
|                                                 ->booleanNode(Request::METHOD_PATCH)->defaultFalse()->end() | ||||
|                                             ->end() | ||||
|                                         ->end() | ||||
|                                         ->arrayNode('roles') | ||||
|                                             ->addDefaultsIfNotSet() | ||||
|                                             ->info("The role require for each http method") | ||||
|                                             ->children() | ||||
|                                                 ->scalarNode(Request::METHOD_GET)->defaultNull()->end() | ||||
|                                                 ->scalarNode(Request::METHOD_HEAD)->defaultNull()->end() | ||||
|                                                 ->scalarNode(Request::METHOD_POST)->defaultNull()->end() | ||||
|                                                 ->scalarNode(Request::METHOD_DELETE)->defaultNull()->end() | ||||
|                                                 ->scalarNode(Request::METHOD_PUT)->defaultNull()->end() | ||||
|                                                 ->scalarNode(Request::METHOD_PATCH)->defaultNull()->end() | ||||
|                                             ->end() | ||||
|                                         ->end() | ||||
|                                     ->end() | ||||
|                                 ->end() | ||||
|                             ->end() | ||||
|                         ->end() | ||||
|                     ->end() | ||||
|  | ||||
|                 ->end() | ||||
|                ->end() // end of root/children | ||||
|             ->end() // end of root | ||||
|         ; | ||||
|   | ||||
| @@ -0,0 +1,65 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Event; | ||||
|  | ||||
| use Chill\MainBundle\Entity\User; | ||||
| use Doctrine\Common\EventSubscriber; | ||||
| use Doctrine\ORM\Events; | ||||
| use Doctrine\Persistence\Event\LifecycleEventArgs; | ||||
| use Chill\MainBundle\Doctrine\Model\TrackCreationInterface; | ||||
| use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface; | ||||
| use Symfony\Component\Security\Core\Security; | ||||
|  | ||||
|  | ||||
| class TrackCreateUpdateSubscriber implements EventSubscriber | ||||
| { | ||||
|     private Security $security; | ||||
|  | ||||
|     /** | ||||
|      * @param Security $security | ||||
|      */ | ||||
|     public function __construct(Security $security) | ||||
|     { | ||||
|         $this->security = $security; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * {@inheritDoc} | ||||
|      */ | ||||
|     public function getSubscribedEvents() | ||||
|     { | ||||
|         return [ | ||||
|             Events::prePersist, | ||||
|             Events::preUpdate | ||||
|         ]; | ||||
|     } | ||||
|  | ||||
|     public function prePersist(LifecycleEventArgs $args): void | ||||
|     { | ||||
|         $object = $args->getObject(); | ||||
|  | ||||
|         if ($object instanceof TrackCreationInterface | ||||
|             && $this->security->getUser() instanceof User) { | ||||
|             $object->setCreatedBy($this->security->getUser()); | ||||
|             $object->setCreatedAt(new \DateTimeImmutable('now')); | ||||
|         } | ||||
|  | ||||
|         $this->onUpdate($object); | ||||
|     } | ||||
|  | ||||
|     public function preUpdate(LifecycleEventArgs $args): void | ||||
|     { | ||||
|         $object = $args->getObject(); | ||||
|  | ||||
|         $this->onUpdate($object); | ||||
|     } | ||||
|  | ||||
|     protected function onUpdate(object $object): void | ||||
|     { | ||||
|         if ($object instanceof TrackUpdateInterface  | ||||
|             && $this->security->getUser() instanceof User) { | ||||
|             $object->setUpdatedBy($this->security->getUser()); | ||||
|             $object->setUpdatedAt(new \DateTimeImmutable('now')); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										103
									
								
								src/Bundle/ChillMainBundle/Doctrine/Model/Point.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										103
									
								
								src/Bundle/ChillMainBundle/Doctrine/Model/Point.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,103 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Model; | ||||
|  | ||||
| use \JsonSerializable; | ||||
|  | ||||
| /** | ||||
|  * Description of Point | ||||
|  * | ||||
|  */ | ||||
| class Point implements JsonSerializable { | ||||
|     private float $lat; | ||||
|     private float $lon; | ||||
|     public static string $SRID = '4326'; | ||||
|  | ||||
|     private function __construct(float $lon, float $lat) | ||||
|     { | ||||
|         $this->lat = $lat; | ||||
|         $this->lon = $lon; | ||||
|     } | ||||
|  | ||||
|     public function toGeoJson(): string | ||||
|     { | ||||
|         $array = $this->toArrayGeoJson(); | ||||
|         return \json_encode($array); | ||||
|     } | ||||
|  | ||||
|     public function jsonSerialize(): array | ||||
|     { | ||||
|         return $this->toArrayGeoJson(); | ||||
|     } | ||||
|  | ||||
|     public function toArrayGeoJson(): array | ||||
|     { | ||||
|         return [ | ||||
|             "type" => "Point", | ||||
|             "coordinates" => [ $this->lon, $this->lat ] | ||||
|         ]; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @return string | ||||
|      */ | ||||
|     public function toWKT(): string | ||||
|     { | ||||
|         return 'SRID='.self::$SRID.';POINT('.$this->lon.' '.$this->lat.')'; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @param type $geojson | ||||
|      * @return Point | ||||
|      */ | ||||
|     public static function fromGeoJson(string $geojson): Point | ||||
|     { | ||||
|         $a = json_decode($geojson); | ||||
|         //check if the geojson string is correct | ||||
|         if (NULL === $a or !isset($a->type) or !isset($a->coordinates)){ | ||||
|             throw PointException::badJsonString($geojson); | ||||
|         } | ||||
|  | ||||
|         if ($a->type != 'Point'){ | ||||
|             throw PointException::badGeoType(); | ||||
|         } | ||||
|  | ||||
|         $lat = $a->coordinates[1]; | ||||
|         $lon = $a->coordinates[0]; | ||||
|  | ||||
|         return Point::fromLonLat($lon, $lat); | ||||
|     } | ||||
|  | ||||
|     public static function fromLonLat(float $lon, float $lat): Point | ||||
|     { | ||||
|         if (($lon > -180 && $lon < 180) && ($lat > -90 && $lat < 90)) | ||||
|         { | ||||
|             return new Point($lon, $lat); | ||||
|         } else { | ||||
|             throw PointException::badCoordinates($lon, $lat); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static function fromArrayGeoJson(array $array): Point | ||||
|     { | ||||
|         if ($array['type'] == 'Point' && | ||||
|                 isset($array['coordinates'])) | ||||
|         { | ||||
|             return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function getLat(): float | ||||
|     { | ||||
|         return $this->lat; | ||||
|     } | ||||
|  | ||||
|     public function getLon(): float | ||||
|     { | ||||
|         return $this->lon; | ||||
|     } | ||||
| } | ||||
|  | ||||
|  | ||||
							
								
								
									
										27
									
								
								src/Bundle/ChillMainBundle/Doctrine/Model/PointException.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								src/Bundle/ChillMainBundle/Doctrine/Model/PointException.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,27 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Model; | ||||
|  | ||||
| use \Exception; | ||||
|  | ||||
| /** | ||||
|  * Description of PointException | ||||
|  * | ||||
|  */ | ||||
| class PointException extends Exception { | ||||
|  | ||||
|     public static function badCoordinates($lon, $lat): self | ||||
|     { | ||||
|         return new self("Input coordinates are not valid in the used coordinate system (longitude = $lon , latitude = $lat)"); | ||||
|     } | ||||
|  | ||||
|     public static function badJsonString($str): self | ||||
|     { | ||||
|         return new self("The JSON string is not valid: $str"); | ||||
|     } | ||||
|  | ||||
|     public static function badGeoType(): self | ||||
|     { | ||||
|         return new self("The geoJSON object type is not valid"); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,12 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Model; | ||||
|  | ||||
| use Chill\MainBundle\Entity\User; | ||||
|  | ||||
| interface TrackCreationInterface | ||||
| { | ||||
|     public function setCreatedBy(User $user): self; | ||||
|  | ||||
|     public function setCreatedAt(\DateTimeInterface $datetime): self; | ||||
| } | ||||
| @@ -0,0 +1,12 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Model; | ||||
|  | ||||
| use Chill\MainBundle\Entity\User; | ||||
|  | ||||
| interface TrackUpdateInterface | ||||
| { | ||||
|     public function setUpdatedBy(User $user): self; | ||||
|  | ||||
|     public function setUpdatedAt(\DateTimeInterface $datetime): self; | ||||
| } | ||||
							
								
								
									
										75
									
								
								src/Bundle/ChillMainBundle/Doctrine/Type/PointType.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										75
									
								
								src/Bundle/ChillMainBundle/Doctrine/Type/PointType.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,75 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Doctrine\Type; | ||||
|  | ||||
| use Chill\MainBundle\Doctrine\Model\Point; | ||||
| use Doctrine\DBAL\Types\Type; | ||||
| use Doctrine\DBAL\Platforms\AbstractPlatform; | ||||
| use Chill\MainBundle\Doctrine\Model\PointException; | ||||
|  | ||||
|  | ||||
| /** | ||||
|  * A Type for Doctrine to implement the Geography Point type | ||||
|  * implemented by Postgis on postgis+postgresql databases | ||||
|  * | ||||
|  */ | ||||
| class PointType extends Type { | ||||
|  | ||||
|     const POINT = 'point'; | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @param array $fieldDeclaration | ||||
|      * @param AbstractPlatform $platform | ||||
|      * @return type | ||||
|      */ | ||||
|     public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform) | ||||
|     { | ||||
|         return 'geometry(POINT,'.Point::$SRID.')'; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @param type $value | ||||
|      * @param AbstractPlatform $platform | ||||
|      * @return Point | ||||
|      */ | ||||
|     public function convertToPHPValue($value, AbstractPlatform $platform) | ||||
|     { | ||||
|         if ($value === NULL){ | ||||
|             return NULL; | ||||
|         } else { | ||||
|             return Point::fromGeoJson($value); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function getName() | ||||
|     { | ||||
|         return self::POINT; | ||||
|     } | ||||
|  | ||||
|     public function convertToDatabaseValue($value, AbstractPlatform $platform) | ||||
|     { | ||||
|         if ($value === NULL){ | ||||
|             return NULL; | ||||
|         } else { | ||||
|             return $value->toWKT(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function canRequireSQLConversion() | ||||
|     { | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     public function convertToPHPValueSQL($sqlExpr, $platform) | ||||
|     { | ||||
|         return 'ST_AsGeoJSON('.$sqlExpr.') '; | ||||
|     } | ||||
|  | ||||
|     public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform) | ||||
|     { | ||||
|         return $sqlExpr; | ||||
|     } | ||||
| } | ||||
|  | ||||
| @@ -4,6 +4,8 @@ namespace Chill\MainBundle\Entity; | ||||
|  | ||||
| use Doctrine\ORM\Mapping as ORM; | ||||
| use Symfony\Component\Validator\Context\ExecutionContextInterface; | ||||
| use Chill\MainBundle\Doctrine\Model\Point; | ||||
| use Chill\ThirdPartyBundle\Entity\ThirdParty; | ||||
|  | ||||
| /** | ||||
|  * Address | ||||
| @@ -28,14 +30,14 @@ class Address | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=255) | ||||
|      */ | ||||
|     private $streetAddress1 = ''; | ||||
|     private $street = ''; | ||||
|  | ||||
|     /** | ||||
|      * @var string | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=255) | ||||
|      */ | ||||
|     private $streetAddress2 = ''; | ||||
|     private $streetNumber = ''; | ||||
|  | ||||
|     /** | ||||
|      * @var PostalCode | ||||
| @@ -43,7 +45,56 @@ class Address | ||||
|      * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode") | ||||
|      */ | ||||
|     private $postcode; | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=16, nullable=true) | ||||
|      */ | ||||
|     private $floor; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=16, nullable=true) | ||||
|      */ | ||||
|     private $corridor; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=16, nullable=true) | ||||
|      */ | ||||
|     private $steps; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $buildingName; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=16, nullable=true) | ||||
|      */ | ||||
|     private $flat; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $distribution; | ||||
|  | ||||
|     /** | ||||
|      * @var string|null | ||||
|      * | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $extra; | ||||
|  | ||||
|     /** | ||||
|      * Indicates when the address starts validation. Used to build an history | ||||
|      * of address. By default, the current date. | ||||
| @@ -53,27 +104,55 @@ class Address | ||||
|      * @ORM\Column(type="date") | ||||
|      */ | ||||
|     private $validFrom; | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * Indicates when the address ends. Used to build an history | ||||
|      * of address. | ||||
|      * | ||||
|      * @var \DateTime|null | ||||
|      * | ||||
|      * @ORM\Column(type="date", nullable=true) | ||||
|      */ | ||||
|     private $validTo; | ||||
|  | ||||
|     /** | ||||
|      * True if the address is a "no address", aka homeless person, ... | ||||
|      * | ||||
|      * @var bool | ||||
|      */ | ||||
|     private $isNoAddress = false; | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * A geospatial field storing the coordinates of the Address | ||||
|      * | ||||
|      * @var Point|null | ||||
|      * | ||||
|      * @ORM\Column(type="point", nullable=true) | ||||
|      */ | ||||
|     private $point; | ||||
|  | ||||
|     /** | ||||
|      * A ThirdParty reference for person's addresses that are linked to a third party | ||||
|      * | ||||
|      * @var ThirdParty|null | ||||
|      * | ||||
|      * @ORM\ManyToOne(targetEntity="Chill\ThirdPartyBundle\Entity\ThirdParty") | ||||
|      * @ORM\JoinColumn(nullable=true) | ||||
|      */ | ||||
|     private $linkedToThirdParty; | ||||
|  | ||||
|     /** | ||||
|      * A list of metadata, added by customizable fields | ||||
|      *  | ||||
|      * | ||||
|      * @var array | ||||
|      */ | ||||
|     private $customs = []; | ||||
|      | ||||
|  | ||||
|     public function __construct() | ||||
|     { | ||||
|         $this->validFrom = new \DateTime(); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * Get id | ||||
|      * | ||||
| @@ -85,7 +164,7 @@ class Address | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set streetAddress1 | ||||
|      * Set streetAddress1 (legacy function) | ||||
|      * | ||||
|      * @param string $streetAddress1 | ||||
|      * | ||||
| @@ -93,23 +172,23 @@ class Address | ||||
|      */ | ||||
|     public function setStreetAddress1($streetAddress1) | ||||
|     { | ||||
|         $this->streetAddress1 = $streetAddress1 === NULL ? '' : $streetAddress1; | ||||
|         $this->street = $streetAddress1 === NULL ? '' : $streetAddress1; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get streetAddress1 | ||||
|      * Get streetAddress1 (legacy function) | ||||
|      * | ||||
|      * @return string | ||||
|      */ | ||||
|     public function getStreetAddress1() | ||||
|     { | ||||
|         return $this->streetAddress1; | ||||
|         return $this->street; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set streetAddress2 | ||||
|      * Set streetAddress2 (legacy function) | ||||
|      * | ||||
|      * @param string $streetAddress2 | ||||
|      * | ||||
| @@ -117,19 +196,19 @@ class Address | ||||
|      */ | ||||
|     public function setStreetAddress2($streetAddress2) | ||||
|     { | ||||
|         $this->streetAddress2 = $streetAddress2 === NULL ? '' : $streetAddress2; | ||||
|         $this->streetNumber = $streetAddress2 === NULL ? '' : $streetAddress2; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get streetAddress2 | ||||
|      * Get streetAddress2 (legacy function) | ||||
|      * | ||||
|      * @return string | ||||
|      */ | ||||
|     public function getStreetAddress2() | ||||
|     { | ||||
|         return $this->streetAddress2; | ||||
|         return $this->streetNumber; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
| @@ -155,7 +234,7 @@ class Address | ||||
|     { | ||||
|         return $this->postcode; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @return \DateTime | ||||
|      */ | ||||
| @@ -173,19 +252,19 @@ class Address | ||||
|         $this->validFrom = $validFrom; | ||||
|         return $this; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * Get IsNoAddress | ||||
|      *  | ||||
|      * | ||||
|      * Indicate true if the address is a fake address (homeless, ...) | ||||
|      *  | ||||
|      * | ||||
|      * @return bool | ||||
|      */ | ||||
|     public function getIsNoAddress(): bool | ||||
|     { | ||||
|         return $this->isNoAddress; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @return bool | ||||
|      */ | ||||
| @@ -196,9 +275,9 @@ class Address | ||||
|  | ||||
|     /** | ||||
|      * Set IsNoAddress | ||||
|      *  | ||||
|      * | ||||
|      * Indicate true if the address is a fake address (homeless, ...) | ||||
|      *  | ||||
|      * | ||||
|      * @param bool $isNoAddress | ||||
|      * @return $this | ||||
|      */ | ||||
| @@ -207,10 +286,10 @@ class Address | ||||
|         $this->isNoAddress = $isNoAddress; | ||||
|         return $this; | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * Get customs informations in the address | ||||
|      *  | ||||
|      * | ||||
|      * @return array | ||||
|      */ | ||||
|     public function getCustoms(): array | ||||
| @@ -220,27 +299,27 @@ class Address | ||||
|  | ||||
|     /** | ||||
|      * Store custom informations in the address | ||||
|      *  | ||||
|      * | ||||
|      * @param array $customs | ||||
|      * @return $this | ||||
|      */ | ||||
|     public function setCustoms(array $customs): self | ||||
|     { | ||||
|         $this->customs = $customs; | ||||
|          | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|          | ||||
|  | ||||
|     /** | ||||
|      * Validate the address. | ||||
|      *  | ||||
|      * | ||||
|      * Check that: | ||||
|      *  | ||||
|      * | ||||
|      * * if the address is not home address: | ||||
|      *     * the postal code is present | ||||
|      *     * the valid from is not null | ||||
|      *     * the address street 1 is greater than 2 | ||||
|      *  | ||||
|      * | ||||
|      * @param ExecutionContextInterface $context | ||||
|      * @param array $payload | ||||
|      */ | ||||
| @@ -252,18 +331,18 @@ class Address | ||||
|                 ->atPath('validFrom') | ||||
|                 ->addViolation(); | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if ($this->isNoAddress()) { | ||||
|             return; | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if (empty($this->getStreetAddress1())) { | ||||
|             $context | ||||
|                 ->buildViolation("address.street1-should-be-set") | ||||
|                 ->atPath('streetAddress1') | ||||
|                 ->addViolation(); | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if (!$this->getPostcode() instanceof PostalCode) { | ||||
|             $context | ||||
|                 ->buildViolation("address.postcode-should-be-set") | ||||
| @@ -271,7 +350,7 @@ class Address | ||||
|                 ->addViolation(); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|  | ||||
|     /** | ||||
|      * @param Address $original | ||||
|      * @return Address | ||||
| @@ -286,5 +365,149 @@ class Address | ||||
|             ; | ||||
|     } | ||||
|  | ||||
|     public function getStreet(): ?string | ||||
|     { | ||||
|         return $this->street; | ||||
|     } | ||||
|  | ||||
|     public function setStreet(string $street): self | ||||
|     { | ||||
|         $this->street = $street; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getStreetNumber(): ?string | ||||
|     { | ||||
|         return $this->streetNumber; | ||||
|     } | ||||
|  | ||||
|     public function setStreetNumber(string $streetNumber): self | ||||
|     { | ||||
|         $this->streetNumber = $streetNumber; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getFloor(): ?string | ||||
|     { | ||||
|         return $this->floor; | ||||
|     } | ||||
|  | ||||
|     public function setFloor(?string $floor): self | ||||
|     { | ||||
|         $this->floor = $floor; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getCorridor(): ?string | ||||
|     { | ||||
|         return $this->corridor; | ||||
|     } | ||||
|  | ||||
|     public function setCorridor(?string $corridor): self | ||||
|     { | ||||
|         $this->corridor = $corridor; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getSteps(): ?string | ||||
|     { | ||||
|         return $this->steps; | ||||
|     } | ||||
|  | ||||
|     public function setSteps(?string $steps): self | ||||
|     { | ||||
|         $this->steps = $steps; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getBuildingName(): ?string | ||||
|     { | ||||
|         return $this->buildingName; | ||||
|     } | ||||
|  | ||||
|     public function setBuildingName(?string $buildingName): self | ||||
|     { | ||||
|         $this->buildingName = $buildingName; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getFlat(): ?string | ||||
|     { | ||||
|         return $this->flat; | ||||
|     } | ||||
|  | ||||
|     public function setFlat(?string $flat): self | ||||
|     { | ||||
|         $this->flat = $flat; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getDistribution(): ?string | ||||
|     { | ||||
|         return $this->distribution; | ||||
|     } | ||||
|  | ||||
|     public function setDistribution(?string $distribution): self | ||||
|     { | ||||
|         $this->distribution = $distribution; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getExtra(): ?string | ||||
|     { | ||||
|         return $this->extra; | ||||
|     } | ||||
|  | ||||
|     public function setExtra(?string $extra): self | ||||
|     { | ||||
|         $this->extra = $extra; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getValidTo(): ?\DateTimeInterface | ||||
|     { | ||||
|         return $this->validTo; | ||||
|     } | ||||
|  | ||||
|     public function setValidTo(\DateTimeInterface $validTo): self | ||||
|     { | ||||
|         $this->validTo = $validTo; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getPoint(): ?Point | ||||
|     { | ||||
|         return $this->point; | ||||
|     } | ||||
|  | ||||
|     public function setPoint(?Point $point): self | ||||
|     { | ||||
|         $this->point = $point; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getLinkedToThirdParty() | ||||
|     { | ||||
|         return $this->linkedToThirdParty; | ||||
|     } | ||||
|  | ||||
|     public function setLinkedToThirdParty($linkedToThirdParty): self | ||||
|     { | ||||
|         $this->linkedToThirdParty = $linkedToThirdParty; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
| } | ||||
|  | ||||
|   | ||||
							
								
								
									
										164
									
								
								src/Bundle/ChillMainBundle/Entity/AddressReference.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										164
									
								
								src/Bundle/ChillMainBundle/Entity/AddressReference.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,164 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Entity; | ||||
|  | ||||
| use Doctrine\ORM\Mapping as ORM; | ||||
| use Chill\MainBundle\Doctrine\Model\Point; | ||||
|  | ||||
| /** | ||||
|  * @ORM\Entity() | ||||
|  * @ORM\Table(name="chill_main_address_reference") | ||||
|  * @ORM\HasLifecycleCallbacks() | ||||
|  */ | ||||
| class AddressReference | ||||
| { | ||||
|     /** | ||||
|      * @ORM\Id | ||||
|      * @ORM\GeneratedValue | ||||
|      * @ORM\Column(type="integer") | ||||
|      */ | ||||
|     private $id; | ||||
|  | ||||
|     /** | ||||
|      * @ORM\Column(type="string", length=255) | ||||
|      */ | ||||
|     private $refId; | ||||
|  | ||||
|     /** | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $street; | ||||
|  | ||||
|     /** | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $streetNumber; | ||||
|  | ||||
|     /** | ||||
|      * @var PostalCode | ||||
|      * | ||||
|      * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode") | ||||
|      */ | ||||
|     private $postcode; | ||||
|  | ||||
|     /** | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $municipalityCode; | ||||
|  | ||||
|     /** | ||||
|      * @ORM\Column(type="string", length=255, nullable=true) | ||||
|      */ | ||||
|     private $source; | ||||
|  | ||||
|     /** | ||||
|      * A geospatial field storing the coordinates of the Address | ||||
|      * | ||||
|      * @var Point | ||||
|      * | ||||
|      * @ORM\Column(type="point") | ||||
|      */ | ||||
|     private $point; | ||||
|  | ||||
|  | ||||
|     public function getId(): ?int | ||||
|     { | ||||
|         return $this->id; | ||||
|     } | ||||
|  | ||||
|     public function getRefId(): ?string | ||||
|     { | ||||
|         return $this->refId; | ||||
|     } | ||||
|  | ||||
|     public function setRefId(string $refId): self | ||||
|     { | ||||
|         $this->refId = $refId; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getStreet(): ?string | ||||
|     { | ||||
|         return $this->street; | ||||
|     } | ||||
|  | ||||
|     public function setStreet(?string $street): self | ||||
|     { | ||||
|         $this->street = $street; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getStreetNumber(): ?string | ||||
|     { | ||||
|         return $this->streetNumber; | ||||
|     } | ||||
|  | ||||
|     public function setStreetNumber(?string $streetNumber): self | ||||
|     { | ||||
|         $this->streetNumber = $streetNumber; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set postcode | ||||
|      * | ||||
|      * @param PostalCode $postcode | ||||
|      * | ||||
|      * @return Address | ||||
|      */ | ||||
|     public function setPostcode(PostalCode $postcode = null) | ||||
|     { | ||||
|         $this->postcode = $postcode; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get postcode | ||||
|      * | ||||
|      * @return PostalCode | ||||
|      */ | ||||
|     public function getPostcode() | ||||
|     { | ||||
|         return $this->postcode; | ||||
|     } | ||||
|  | ||||
|     public function getMunicipalityCode(): ?string | ||||
|     { | ||||
|         return $this->municipalityCode; | ||||
|     } | ||||
|  | ||||
|     public function setMunicipalityCode(?string $municipalityCode): self | ||||
|     { | ||||
|         $this->municipalityCode = $municipalityCode; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getSource(): ?string | ||||
|     { | ||||
|         return $this->source; | ||||
|     } | ||||
|  | ||||
|     public function setSource(?string $source): self | ||||
|     { | ||||
|         $this->source = $source; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
|  | ||||
|     public function getPoint(): ?Point | ||||
|     { | ||||
|         return $this->point; | ||||
|     } | ||||
|  | ||||
|     public function setPoint(?Point $point): self | ||||
|     { | ||||
|         $this->point = $point; | ||||
|  | ||||
|         return $this; | ||||
|     } | ||||
| } | ||||
| @@ -24,13 +24,16 @@ use Doctrine\ORM\Mapping as ORM; | ||||
| use Doctrine\Common\Collections\Collection; | ||||
| use Doctrine\Common\Collections\ArrayCollection; | ||||
| use Chill\MainBundle\Entity\RoleScope; | ||||
| use Symfony\Component\Serializer\Annotation\Groups; | ||||
| use Symfony\Component\Serializer\Annotation\DiscriminatorMap; | ||||
|  | ||||
| /** | ||||
|  * @ORM\Entity() | ||||
|  * @ORM\Table(name="scopes") | ||||
|  * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region") | ||||
|  * | ||||
|  * @author Julien Fastré <julien.fastre@champs-libres.coop> | ||||
|  * @DiscriminatorMap(typeProperty="type", mapping={ | ||||
|  *    "scope"=Scope::class | ||||
|  * }) | ||||
|  */ | ||||
| class Scope | ||||
| { | ||||
| @@ -40,6 +43,7 @@ class Scope | ||||
|      * @ORM\Id | ||||
|      * @ORM\Column(name="id", type="integer") | ||||
|      * @ORM\GeneratedValue(strategy="AUTO") | ||||
|      * @Groups({"read"}) | ||||
|      */ | ||||
|     private $id; | ||||
|      | ||||
| @@ -49,6 +53,7 @@ class Scope | ||||
|      * @var array | ||||
|      * | ||||
|      * @ORM\Column(type="json_array") | ||||
|      * @Groups({"read"}) | ||||
|      */ | ||||
|     private $name = []; | ||||
|      | ||||
|   | ||||
| @@ -7,6 +7,7 @@ use Doctrine\Common\Collections\Collection; | ||||
| use Doctrine\Common\Collections\ArrayCollection; | ||||
| use Symfony\Component\Security\Core\User\AdvancedUserInterface; | ||||
| use Symfony\Component\Validator\Context\ExecutionContextInterface; | ||||
| use Symfony\Component\Serializer\Annotation\DiscriminatorMap; | ||||
|  | ||||
| /** | ||||
|  * User | ||||
| @@ -14,6 +15,9 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface; | ||||
|  * @ORM\Entity(repositoryClass="Chill\MainBundle\Repository\UserRepository") | ||||
|  * @ORM\Table(name="users") | ||||
|  * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region") | ||||
|  * @DiscriminatorMap(typeProperty="type", mapping={ | ||||
|  *    "user"=User::class | ||||
|  * }) | ||||
|  */ | ||||
| class User implements AdvancedUserInterface { | ||||
|      | ||||
|   | ||||
| @@ -33,8 +33,8 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType; | ||||
|  * A type to create/update Address entity | ||||
|  * | ||||
|  * Options: | ||||
|  *  | ||||
|  * - `has_valid_from` (boolean): show if an entry "has valid from" must be  | ||||
|  * | ||||
|  * - `has_valid_from` (boolean): show if an entry "has valid from" must be | ||||
|  * shown. | ||||
|  * - `null_if_empty` (boolean): replace the address type by null if the street | ||||
|  * or the postCode is empty. This is useful when the address is not required and | ||||
| @@ -45,10 +45,10 @@ class AddressType extends AbstractType | ||||
|     public function buildForm(FormBuilderInterface $builder, array $options) | ||||
|     { | ||||
|         $builder | ||||
|               ->add('streetAddress1', TextType::class, array( | ||||
|               ->add('street', TextType::class, array( | ||||
|                  'required' => !$options['has_no_address'] // true if has no address is false | ||||
|               )) | ||||
|               ->add('streetAddress2', TextType::class, array( | ||||
|               ->add('streetNumber', TextType::class, array( | ||||
|                  'required' => false | ||||
|               )) | ||||
|               ->add('postCode', PostalCodeType::class, array( | ||||
| @@ -57,7 +57,7 @@ class AddressType extends AbstractType | ||||
|                  'required' => !$options['has_no_address'] // true if has no address is false | ||||
|               )) | ||||
|             ; | ||||
|          | ||||
|  | ||||
|         if ($options['has_valid_from']) { | ||||
|             $builder | ||||
|               ->add('validFrom', DateType::class, array( | ||||
| @@ -67,7 +67,7 @@ class AddressType extends AbstractType | ||||
|                  ) | ||||
|               ); | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if ($options['has_no_address']) { | ||||
|             $builder | ||||
|                 ->add('isNoAddress', ChoiceType::class, [ | ||||
| @@ -79,12 +79,12 @@ class AddressType extends AbstractType | ||||
|                     'label' => 'address.address_homeless' | ||||
|                 ]); | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if ($options['null_if_empty'] === TRUE) { | ||||
|             $builder->setDataMapper(new AddressDataMapper()); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|  | ||||
|     public function configureOptions(OptionsResolver $resolver) | ||||
|     { | ||||
|         $resolver | ||||
|   | ||||
| @@ -27,6 +27,7 @@ use Symfony\Component\Form\FormBuilderInterface; | ||||
| use Chill\MainBundle\Form\Type\DataTransformer\ObjectToIdTransformer; | ||||
| use Doctrine\Persistence\ObjectManager; | ||||
| use Chill\MainBundle\Form\Type\Select2ChoiceType; | ||||
| use Chill\MainBundle\Templating\TranslatableStringHelper; | ||||
|  | ||||
| /** | ||||
|  * Extends choice to allow adding select2 library on widget | ||||
| @@ -41,15 +42,26 @@ class Select2CountryType extends AbstractType | ||||
|      */ | ||||
|     private $requestStack; | ||||
|  | ||||
|     /** | ||||
|      * | ||||
|      * @var TranslatableStringHelper | ||||
|      */ | ||||
|     protected $translatableStringHelper; | ||||
|  | ||||
|     /** | ||||
|      * @var ObjectManager | ||||
|      */ | ||||
|     private $em; | ||||
|  | ||||
|     public function __construct(RequestStack $requestStack,ObjectManager $em) | ||||
|     public function __construct( | ||||
|         RequestStack $requestStack, | ||||
|         ObjectManager $em, | ||||
|         TranslatableStringHelper $translatableStringHelper | ||||
|         ) | ||||
|     { | ||||
|         $this->requestStack = $requestStack; | ||||
|         $this->em = $em; | ||||
|         $this->translatableStringHelper = $translatableStringHelper; | ||||
|     } | ||||
|  | ||||
|     public function getBlockPrefix() | ||||
| @@ -75,7 +87,7 @@ class Select2CountryType extends AbstractType | ||||
|         $choices = array(); | ||||
|  | ||||
|         foreach ($countries as $c) { | ||||
|             $choices[$c->getId()] = $c->getName()[$locale]; | ||||
|             $choices[$c->getId()] = $this->translatableStringHelper->localize($c->getName()); | ||||
|         } | ||||
|  | ||||
|         asort($choices, SORT_STRING | SORT_FLAG_CASE); | ||||
|   | ||||
| @@ -27,6 +27,7 @@ use Symfony\Component\Form\FormBuilderInterface; | ||||
| use Chill\MainBundle\Form\Type\DataTransformer\MultipleObjectsToIdTransformer; | ||||
| use Doctrine\Persistence\ObjectManager; | ||||
| use Chill\MainBundle\Form\Type\Select2ChoiceType; | ||||
| use Chill\MainBundle\Templating\TranslatableStringHelper; | ||||
|  | ||||
| /** | ||||
|  * Extends choice to allow adding select2 library on widget for languages (multiple) | ||||
| @@ -43,10 +44,21 @@ class Select2LanguageType extends AbstractType | ||||
|      */ | ||||
|     private $em; | ||||
|  | ||||
|     public function __construct(RequestStack $requestStack,ObjectManager $em) | ||||
|     /** | ||||
|      * | ||||
|      * @var TranslatableStringHelper | ||||
|      */ | ||||
|     protected $translatableStringHelper; | ||||
|  | ||||
|     public function __construct( | ||||
|         RequestStack $requestStack, | ||||
|         ObjectManager $em, | ||||
|         TranslatableStringHelper $translatableStringHelper | ||||
|         ) | ||||
|     { | ||||
|         $this->requestStack = $requestStack; | ||||
|         $this->em = $em; | ||||
|         $this->translatableStringHelper = $translatableStringHelper; | ||||
|     } | ||||
|  | ||||
|     public function getBlockPrefix() | ||||
| @@ -72,7 +84,7 @@ class Select2LanguageType extends AbstractType | ||||
|         $choices = array(); | ||||
|  | ||||
|         foreach ($languages as $l) { | ||||
|             $choices[$l->getId()] = $l->getName()[$locale]; | ||||
|             $choices[$l->getId()] = $this->translatableStringHelper->localize($l->getName()); | ||||
|         } | ||||
|  | ||||
|         asort($choices, SORT_STRING | SORT_FLAG_CASE); | ||||
|   | ||||
| @@ -0,0 +1,50 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Repository; | ||||
|  | ||||
| use Chill\MainBundle\Entity\AddressReference; | ||||
| use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; | ||||
| use Doctrine\Persistence\ManagerRegistry; | ||||
|  | ||||
| /** | ||||
|  * @method AddressReference|null find($id, $lockMode = null, $lockVersion = null) | ||||
|  * @method AddressReference|null findOneBy(array $criteria, array $orderBy = null) | ||||
|  * @method AddressReference[]    findAll() | ||||
|  * @method AddressReference[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) | ||||
|  */ | ||||
| class AddressReferenceRepository extends ServiceEntityRepository | ||||
| { | ||||
|     public function __construct(ManagerRegistry $registry) | ||||
|     { | ||||
|         parent::__construct($registry, AddressReference::class); | ||||
|     } | ||||
|  | ||||
|     // /** | ||||
|     //  * @return AddressReference[] Returns an array of AddressReference objects | ||||
|     //  */ | ||||
|     /* | ||||
|     public function findByExampleField($value) | ||||
|     { | ||||
|         return $this->createQueryBuilder('a') | ||||
|             ->andWhere('a.exampleField = :val') | ||||
|             ->setParameter('val', $value) | ||||
|             ->orderBy('a.id', 'ASC') | ||||
|             ->setMaxResults(10) | ||||
|             ->getQuery() | ||||
|             ->getResult() | ||||
|         ; | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|     /* | ||||
|     public function findOneBySomeField($value): ?AddressReference | ||||
|     { | ||||
|         return $this->createQueryBuilder('a') | ||||
|             ->andWhere('a.exampleField = :val') | ||||
|             ->setParameter('val', $value) | ||||
|             ->getQuery() | ||||
|             ->getOneOrNullResult() | ||||
|         ; | ||||
|     } | ||||
|     */ | ||||
| } | ||||
| @@ -28,7 +28,7 @@ | ||||
| // @import "bootstrap/scss/card"; | ||||
| // @import "bootstrap/scss/breadcrumb"; | ||||
| // @import "bootstrap/scss/pagination"; | ||||
| // @import "bootstrap/scss/badge"; | ||||
| @import "bootstrap/scss/badge"; | ||||
| // @import "bootstrap/scss/jumbotron"; | ||||
| // @import "bootstrap/scss/alert"; | ||||
| // @import "bootstrap/scss/progress"; | ||||
| @@ -41,7 +41,7 @@ | ||||
| // @import "bootstrap/scss/popover"; | ||||
| // @import "bootstrap/scss/carousel"; | ||||
| // @import "bootstrap/scss/spinners"; | ||||
| // @import "bootstrap/scss/utilities"; | ||||
| @import "bootstrap/scss/utilities"; | ||||
| // @import "bootstrap/scss/print"; | ||||
|  | ||||
| @import "custom"; | ||||
|   | ||||
| @@ -5,7 +5,7 @@ | ||||
|         @include button($green, $white); | ||||
|     } | ||||
|  | ||||
|     &.bt-reset, &.bt-delete { | ||||
|     &.bt-reset, &.bt-delete, &.bt-remove { | ||||
|         @include button($red, $white); | ||||
|     } | ||||
|  | ||||
| @@ -24,6 +24,7 @@ | ||||
|         &.bt-save::before, | ||||
|         &.bt-new::before, | ||||
|         &.bt-delete::before, | ||||
|         &.bt-remove::before, | ||||
|         &.bt-update::before, | ||||
|         &.bt-edit::before, | ||||
|         &.bt-cancel::before, | ||||
| @@ -56,7 +57,12 @@ | ||||
|             // add a trash | ||||
|             content: ""; | ||||
|         } | ||||
|  | ||||
|          | ||||
|        &.bt-remove::before { | ||||
|            // add a times | ||||
|            content: ""; | ||||
|        } | ||||
|                  | ||||
|         &.bt-edit::before, &.bt-update::before { | ||||
|             // add a pencil | ||||
|             content: ""; | ||||
| @@ -94,6 +100,7 @@ | ||||
|             &.bt-save::before, | ||||
|             &.bt-new::before, | ||||
|             &.bt-delete::before, | ||||
|             &.bt-remove::before, | ||||
|             &.bt-update::before, | ||||
|             &.bt-edit::before, | ||||
|             &.bt-cancel::before, | ||||
| @@ -123,6 +130,7 @@ | ||||
|             &.bt-save::before, | ||||
|             &.bt-new::before, | ||||
|             &.bt-delete::before, | ||||
|             &.bt-remove::before, | ||||
|             &.bt-update::before, | ||||
|             &.bt-edit::before, | ||||
|             &.bt-cancel::before, | ||||
|   | ||||
| @@ -39,19 +39,18 @@ div.subheader { | ||||
|   height: 130px; | ||||
| } | ||||
|  | ||||
| div.vue-component { | ||||
|   padding: 1.5em; | ||||
|   margin: 2em 0; | ||||
|   border: 2px dashed grey; | ||||
|   position: relative; | ||||
|   &:before { | ||||
|     content: "vuejs component"; | ||||
|     position: absolute; | ||||
|     left: 1.5em; | ||||
|     top: -0.9em; | ||||
|     background-color: white; | ||||
|     color: grey; | ||||
|     padding: 0 0.3em; | ||||
|   } | ||||
|   dd { margin-left: 1em; } | ||||
| //// SCRATCH BUTTONS | ||||
| .sc-button { | ||||
|    &.disabled { | ||||
|       cursor: default; | ||||
|       &.bt-remove { | ||||
|          background-color: #d9d9d9; | ||||
|       } | ||||
|    } | ||||
| } | ||||
|  | ||||
| //// à ranger | ||||
| .discret { | ||||
|    color: grey; | ||||
|    margin-right: 1em; | ||||
| } | ||||
|   | ||||
| @@ -0,0 +1,41 @@ | ||||
| <template> | ||||
|     | ||||
|    <div v-if="address.address"> | ||||
|       {{ address.address.street }}, {{ address.address.streetNumber }} | ||||
|    </div> | ||||
|    <div v-if="address.city"> | ||||
|       {{ address.city.code }} {{ address.city.name }} | ||||
|    </div> | ||||
|    <div v-if="address.country"> | ||||
|       {{ address.country.name }} | ||||
|    </div> | ||||
|     | ||||
|    <add-address | ||||
|       @addNewAddress="addNewAddress"> | ||||
|    </add-address> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
| import { mapState } from 'vuex'; | ||||
|  | ||||
| import AddAddress from '../_components/AddAddress.vue'; | ||||
|  | ||||
| export default { | ||||
|    name: 'App', | ||||
|    components: { | ||||
|       AddAddress | ||||
|    }, | ||||
|    computed: { | ||||
|       address() { | ||||
|          return this.$store.state.address; | ||||
|       } | ||||
|    }, | ||||
|    methods: { | ||||
|       addNewAddress({ address, modal }) { | ||||
|          console.log('@@@ CLICK button addNewAdress', address); | ||||
|          this.$store.dispatch('addAddress', address.selected); | ||||
|          modal.showModal = false; | ||||
|       } | ||||
|    } | ||||
| }; | ||||
| </script> | ||||
| @@ -0,0 +1,16 @@ | ||||
| import { createApp } from 'vue' | ||||
| import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n' | ||||
| import { addressMessages } from './js/i18n' | ||||
| import { store } from './store' | ||||
|  | ||||
| import App from './App.vue'; | ||||
|  | ||||
| const i18n = _createI18n(addressMessages); | ||||
|  | ||||
| const app = createApp({ | ||||
|    template: `<app></app>`, | ||||
| }) | ||||
| .use(store) | ||||
| .use(i18n) | ||||
| .component('app', App) | ||||
| .mount('#address'); | ||||
| @@ -0,0 +1,22 @@ | ||||
| const addressMessages = { | ||||
|    fr: { | ||||
|       add_an_address: 'Ajouter une adresse', | ||||
|       select_an_address: 'Sélectionner une adresse', | ||||
|       fill_an_address: 'Compléter l\'adresse', | ||||
|       select_country: 'Choisir le pays', | ||||
|       select_city: 'Choisir une localité', | ||||
|       select_address: 'Choisir une adresse', | ||||
|       isNoAddress: 'L\'adresse n\'est pas celle d\'un domicile fixe ?', | ||||
|       floor: 'Étage', | ||||
|       corridor: 'Couloir', | ||||
|       steps: 'Escalier', | ||||
|       flat: 'Appartement', | ||||
|       buildingName: 'Nom du batiment', | ||||
|       extra: 'Complément d\'adresse', | ||||
|       distribution: 'Service particulier de distribution' | ||||
|    } | ||||
| }; | ||||
|  | ||||
| export { | ||||
|    addressMessages | ||||
| }; | ||||
| @@ -0,0 +1,43 @@ | ||||
| import 'es6-promise/auto'; | ||||
| import { createStore } from 'vuex'; | ||||
|  | ||||
| // le fetch POST serait rangé dans la logique du composant qui appelle AddAddress | ||||
| //import { postAddress } from '... api'  | ||||
|  | ||||
| const debug = process.env.NODE_ENV !== 'production'; | ||||
|  | ||||
| const store = createStore({ | ||||
|    strict: debug, | ||||
|    state: { | ||||
|       address: {}, | ||||
|       errorMsg: {} | ||||
|    }, | ||||
|    getters: { | ||||
|    }, | ||||
|    mutations: { | ||||
|       addAddress(state, address) { | ||||
|          console.log('@M addAddress address', address); | ||||
|          state.address = address; | ||||
|       } | ||||
|    }, | ||||
|    actions: { | ||||
|       addAddress({ commit }, payload) { | ||||
|          console.log('@A addAddress payload', payload); | ||||
|          commit('addAddress', payload); // à remplacer par  | ||||
|           | ||||
|          // fetch POST qui envoie l'adresse, et récupère la confirmation que c'est ok.  | ||||
|          // La confirmation est l'adresse elle-même. | ||||
|          // | ||||
|          //   postAddress(payload)  | ||||
|          //   .fetch(address => new Promise((resolve, reject) => { | ||||
|          //      commit('addAddress', address); | ||||
|          //      resolve(); | ||||
|          //   })) | ||||
|          //   .catch((error) => {  | ||||
|          //      state.errorMsg.push(error.message);  | ||||
|          //   });  | ||||
|       } | ||||
|    } | ||||
| }); | ||||
|  | ||||
| export { store }; | ||||
| @@ -0,0 +1,46 @@ | ||||
| /* | ||||
| * Endpoint countries GET | ||||
| * TODO | ||||
| */ | ||||
| const fetchCountries = () => { | ||||
|    console.log('<<< fetching countries'); | ||||
|    return [ | ||||
|       {id: 1, name: 'France', countryCode: 'FR'}, | ||||
|       {id: 2, name: 'Belgium', countryCode: 'BE'} | ||||
|    ]; | ||||
| }; | ||||
|  | ||||
| /* | ||||
| * Endpoint cities GET  | ||||
| * TODO | ||||
| */ | ||||
| const fetchCities = (country) => {    | ||||
|    console.log('<<< fetching cities for', country); | ||||
|    return [ | ||||
|       {id: 1, name: 'Bruxelles', code: '1000', country: 'BE'}, | ||||
|       {id: 2, name: 'Aisne', code: '85045', country: 'FR'}, | ||||
|       {id: 3, name: 'Saint-Gervais', code: '85230', country: 'FR'} | ||||
|    ]; | ||||
| }; | ||||
|  | ||||
| /* | ||||
| * Endpoint chill_main_address_reference_api_show | ||||
| * method GET, get AddressReference Object | ||||
| * @returns {Promise} a promise containing all AddressReference object | ||||
| */ | ||||
| const fetchReferenceAddresses = (city) => { | ||||
|     console.log('<<< fetching references addresses for', city); // city n'est pas utilisé pour le moment | ||||
|      | ||||
|     const url = `/api/1.0/main/address-reference.json`; | ||||
|     return fetch(url) | ||||
|        .then(response => { | ||||
|           if (response.ok) { return response.json(); } | ||||
|           throw Error('Error with request resource response'); | ||||
|        }); | ||||
| }; | ||||
|  | ||||
| export { | ||||
|    fetchCountries, | ||||
|    fetchCities, | ||||
|    fetchReferenceAddresses | ||||
| }; | ||||
| @@ -0,0 +1,219 @@ | ||||
| <template> | ||||
|    <button class="sc-button bt-create centered mt-4" @click="openModal"> | ||||
|       {{ $t('add_an_address') }} | ||||
|    </button> | ||||
|  | ||||
|    <teleport to="body"> | ||||
|       <modal v-if="modal.showModal" | ||||
|          v-bind:modalDialogClass="modal.modalDialogClass" | ||||
|          @close="modal.showModal = false"> | ||||
|  | ||||
|          <template v-slot:header> | ||||
|             <h3 class="modal-title">{{ $t('add_an_address') }}</h3> | ||||
|          </template> | ||||
|  | ||||
|          <template v-slot:body> | ||||
|              | ||||
|             <h4>{{ $t('select_an_address') }}</h4> | ||||
|              | ||||
|             <label for="isNoAddress"> | ||||
|                <input type="checkbox"  | ||||
|                   name="isNoAddress"  | ||||
|                   v-bind:placeholder="$t('isNoAddress')"  | ||||
|                   v-model="isNoAddress"  | ||||
|                   v-bind:value="value"/> | ||||
|                {{ $t('isNoAddress') }} | ||||
|             </label> | ||||
|  | ||||
|             <country-selection | ||||
|                v-bind:address="address" | ||||
|                v-bind:getCities="getCities"> | ||||
|             </country-selection> | ||||
|              | ||||
|             <city-selection | ||||
|                v-bind:address="address" | ||||
|                v-bind:getReferenceAddresses="getReferenceAddresses"> | ||||
|             </city-selection> | ||||
|              | ||||
|             <address-selection | ||||
|                v-bind:address="address" | ||||
|                v-bind:updateMapCenter="updateMapCenter"> | ||||
|             </address-selection> | ||||
|  | ||||
|             <address-map | ||||
|                v-bind:address="address" | ||||
|                ref="addressMap"> | ||||
|             </address-map> | ||||
|              | ||||
|             <address-more  | ||||
|                v-if="!isNoAddress" | ||||
|                v-bind:address="address"> | ||||
|             </address-more> | ||||
|                          | ||||
|             <!-- | ||||
|             <div class="address_form__fields__isNoAddress"></div> | ||||
|             <div class="address_form__select"> | ||||
|                <div class="address_form__select__header"></div> | ||||
|                <div class="address_form__select__left"></div> | ||||
|                <div class="address_form__map"></div> | ||||
|             </div> | ||||
|             <div class="address_form__fields"> | ||||
|                <div class="address_form__fields__header"></div> | ||||
|                <div class="address_form__fields__left"></div> | ||||
|                <div class="address_form__fields__right"></div> | ||||
|             </div> | ||||
|           | ||||
|             à discuter,  | ||||
|             mais je pense qu'il est préférable de profiter de l'imbriquation des classes css  | ||||
|              | ||||
|             div.address_form { | ||||
|                div.select { | ||||
|                   div.header {} | ||||
|                   div.left {} | ||||
|                   div.map {} | ||||
|                } | ||||
|             } | ||||
|           | ||||
|             --> | ||||
|          </template> | ||||
|  | ||||
|          <template v-slot:footer> | ||||
|             <button class="sc-button green"  | ||||
|                @click.prevent="$emit('addNewAddress', { address, modal })"> | ||||
|                <i class="fa fa-plus fa-fw"></i>{{ $t('action.add')}} | ||||
|             </button> | ||||
|          </template> | ||||
|  | ||||
|       </modal> | ||||
|    </teleport> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
| import Modal from './Modal'; | ||||
| import { fetchCountries, fetchCities, fetchReferenceAddresses } from '../_api/AddAddress' | ||||
| import CountrySelection from './AddAddress/CountrySelection'; | ||||
| import CitySelection from './AddAddress/CitySelection'; | ||||
| import AddressSelection from './AddAddress/AddressSelection'; | ||||
| import AddressMap from './AddAddress/AddressMap'; | ||||
| import AddressMore from './AddAddress/AddressMore' | ||||
|  | ||||
| export default { | ||||
|    name: 'AddAddresses', | ||||
|    components: { | ||||
|       Modal, | ||||
|       CountrySelection, | ||||
|       CitySelection, | ||||
|       AddressSelection, | ||||
|       AddressMap, | ||||
|       AddressMore | ||||
|    }, | ||||
|    props: [ | ||||
|    ], | ||||
|    emits: ['addNewAddress'], | ||||
|    data() { | ||||
|       return { | ||||
|          modal: { | ||||
|             showModal: false, | ||||
|             modalDialogClass: "modal-dialog-scrollable modal-xl" | ||||
|          }, | ||||
|          address: { | ||||
|             loaded: { | ||||
|                countries: [], | ||||
|                cities: [], | ||||
|                addresses: [], | ||||
|             }, | ||||
|             selected: { | ||||
|                country: {}, | ||||
|                city: {}, | ||||
|                address: {}, | ||||
|             }, | ||||
|             addressMap: { | ||||
|                center : [48.8589, 2.3469], // Note: LeafletJs demands [lat, lon] cfr https://macwright.com/lonlat/ | ||||
|                zoom: 12 | ||||
|             }, | ||||
|             isNoAddress: false, | ||||
|             floor: null, | ||||
|             corridor: null, | ||||
|             steps: null, | ||||
|             floor: null, | ||||
|             flat: null, | ||||
|             buildingName: null, | ||||
|             extra: null, | ||||
|             distribution: null, | ||||
|          }, | ||||
|          errorMsg: {} | ||||
|       } | ||||
|    }, | ||||
|    computed: { | ||||
|       isNoAddress: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.isNoAddress = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.isNoAddress; | ||||
|          } | ||||
|       } | ||||
|    }, | ||||
|    methods: { | ||||
|       openModal() { | ||||
|          this.modal.showModal = true; | ||||
|          this.resetAll(); | ||||
|          this.getCountries(); | ||||
|           | ||||
|          //this.$nextTick(function() { | ||||
|          //   this.$refs.search.focus(); // positionner le curseur à l'ouverture de la modale | ||||
|          //}) | ||||
|       }, | ||||
|       getCountries() { | ||||
|          console.log('getCountries'); | ||||
|          this.address.loaded.countries = fetchCountries(); // à remplacer par | ||||
|          //  fetchCountries().then(countries => new Promise((resolve, reject) => { | ||||
|          //     this.address.loaded.countries = countries; | ||||
|          //     resolve() | ||||
|          //  })) | ||||
|          //  .catch((error) => {  | ||||
|          //     this.errorMsg.push(error.message);  | ||||
|          //  });  | ||||
|       }, | ||||
|       getCities(country) { | ||||
|          console.log('getCities for', country.name); | ||||
|          this.address.loaded.cities = fetchCities(); // à remplacer par | ||||
|          //  fetchCities(country).then(cities => new Promise((resolve, reject) => { | ||||
|          //     this.address.loaded.cities = cities; | ||||
|          //     resolve() | ||||
|          //  })) | ||||
|          //  .catch((error) => {  | ||||
|          //     this.errorMsg.push(error.message);  | ||||
|          //  });  | ||||
|       }, | ||||
|       getReferenceAddresses(city) { | ||||
|          console.log('getReferenceAddresses for', city.name); | ||||
|          fetchReferenceAddresses(city)  // il me semble que le paramètre city va limiter le poids des adresses de références reçues | ||||
|             .then(addresses => new Promise((resolve, reject) => { | ||||
|                console.log('addresses', addresses); | ||||
|                this.address.loaded.addresses = addresses.results; | ||||
|                resolve(); | ||||
|             })) | ||||
|             .catch((error) => {  | ||||
|                this.errorMsg.push(error.message);  | ||||
|             });  | ||||
|       }, | ||||
|       updateMapCenter(point) { | ||||
|          console.log('point', point); | ||||
|          this.address.addressMap.center[0] = point.coordinates[1];  // TODO use reverse() | ||||
|          this.address.addressMap.center[1] = point.coordinates[0]; | ||||
|          this.$refs.addressMap.update(); // cast child methods | ||||
|       }, | ||||
|       resetAll() { | ||||
|          console.log('reset all selected'); | ||||
|          this.address.loaded.addresses = []; | ||||
|          this.address.selected.address = {};  | ||||
|          this.address.loaded.cities = []; | ||||
|          this.address.selected.city = {}; | ||||
|          this.address.selected.country = {}; | ||||
|          console.log('cities and addresses', this.address.loaded.cities, this.address.loaded.addresses); | ||||
|       } | ||||
|    } | ||||
| } | ||||
| </script> | ||||
| @@ -0,0 +1,47 @@ | ||||
| <template> | ||||
|    <div class="container"> | ||||
|       <div id='address_map' style='height:400px; width:400px;'></div> | ||||
|    </div> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
|  | ||||
| import L from 'leaflet'; | ||||
| import markerIconPng from 'leaflet/dist/images/marker-icon.png' | ||||
| import 'leaflet/dist/leaflet.css'; | ||||
|  | ||||
| let map; | ||||
|  | ||||
| export default { | ||||
|    name: 'AddressMap', | ||||
|    props: ['address'], | ||||
|    computed: { | ||||
|       center() { | ||||
|          return this.address.addressMap.center; | ||||
|       }, | ||||
|    }, | ||||
|    methods:{ | ||||
|       init() { | ||||
|          map = L.map('address_map').setView([48.8589, 2.3469], 12); | ||||
|  | ||||
|          L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { | ||||
|             attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' | ||||
|          }).addTo(map); | ||||
|  | ||||
|          const markerIcon = L.icon({ | ||||
|             iconUrl: markerIconPng, | ||||
|          }); | ||||
|  | ||||
|          L.marker([48.8589, 2.3469], {icon: markerIcon}).addTo(map); | ||||
|  | ||||
|       }, | ||||
|       update() { | ||||
|          console.log('update map with : ', this.address.addressMap.center) | ||||
|          map.setView(this.address.addressMap.center, 12); | ||||
|       } | ||||
|    }, | ||||
|    mounted(){ | ||||
|       this.init() | ||||
|    } | ||||
| } | ||||
| </script> | ||||
| @@ -0,0 +1,112 @@ | ||||
| <template> | ||||
|    <div> | ||||
|       <h4>{{ $t('fill_an_address') }}</h4> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="floor" | ||||
|          :placeholder="$t('floor')" | ||||
|          v-model="floor"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="corridor" | ||||
|          :placeholder="$t('corridor')" | ||||
|          v-model="corridor"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="steps" | ||||
|          :placeholder="$t('steps')" | ||||
|          v-model="steps"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="flat" | ||||
|          :placeholder="$t('flat')" | ||||
|          v-model="flat"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="buildingName" | ||||
|          :placeholder="$t('buildingName')" | ||||
|          v-model="buildingName"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="extra" | ||||
|          :placeholder="$t('extra')" | ||||
|          v-model="extra"/> | ||||
|       <input  | ||||
|          type="text" | ||||
|          name="distribution" | ||||
|          :placeholder="$t('distribution')" | ||||
|          v-model="distribution"/> | ||||
|    </div> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
| export default { | ||||
|    name: "AddressMore", | ||||
|    props: ['address'], | ||||
|    computed: { | ||||
|       floor: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.floor = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.floor; | ||||
|          } | ||||
|       }, | ||||
|       corridor: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.corridor = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.corridor; | ||||
|          } | ||||
|       }, | ||||
|       steps: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.steps = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.steps; | ||||
|          } | ||||
|       }, | ||||
|       flat: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.flat = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.flat; | ||||
|          } | ||||
|       }, | ||||
|       buildingName: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.buildingName = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.buildingName; | ||||
|          } | ||||
|       }, | ||||
|       extra: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.extra = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.extra; | ||||
|          } | ||||
|       }, | ||||
|       distribution: { | ||||
|          set(value) { | ||||
|             console.log('value', value); | ||||
|             this.address.distribution = value; | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.distribution; | ||||
|          } | ||||
|       } | ||||
|    } | ||||
| } | ||||
| </script> | ||||
| @@ -0,0 +1,38 @@ | ||||
| <template> | ||||
|    <div class="container"> | ||||
|       <select  | ||||
|          v-model="selected"> | ||||
|          <option :value="{}" disabled selected>{{ $t('select_address') }}</option> | ||||
|          <option  | ||||
|             v-for="item in this.addresses"  | ||||
|             v-bind:item="item"  | ||||
|             v-bind:key="item.id"  | ||||
|             v-bind:value="item"> | ||||
|             {{ item.street }}, {{ item.streetNumber }} | ||||
|          </option> | ||||
|       </select> | ||||
|    </div> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
|  | ||||
| export default { | ||||
|    name: 'AddressSelection', | ||||
|    props: ['address', 'updateMapCenter'], | ||||
|    computed: { | ||||
|       addresses() {  | ||||
|          return this.address.loaded.addresses;  | ||||
|       }, | ||||
|       selected: { | ||||
|          set(value) { | ||||
|             console.log('selected value', value); | ||||
|             this.address.selected.address = value; | ||||
|             this.updateMapCenter(value.point); | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.selected.address; | ||||
|          } | ||||
|       }, | ||||
|    } | ||||
| }; | ||||
| </script> | ||||
| @@ -0,0 +1,38 @@ | ||||
| <template> | ||||
|    <div class="container"> | ||||
|       <select  | ||||
|          v-model="selected"> | ||||
|          <option :value="{}" disabled selected>{{ $t('select_city') }}</option> | ||||
|          <option  | ||||
|             v-for="item in this.cities"  | ||||
|             v-bind:item="item"  | ||||
|             v-bind:key="item.id"  | ||||
|             v-bind:value="item"> | ||||
|             {{ item.code }}-{{ item.name }} | ||||
|          </option> | ||||
|       </select> | ||||
|    </div> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
|  | ||||
| export default { | ||||
|    name: 'CitySelection', | ||||
|    props: ['address', 'getReferenceAddresses'], | ||||
|    computed: { | ||||
|       cities() {  | ||||
|          return this.address.loaded.cities;  | ||||
|       }, | ||||
|       selected: { | ||||
|          set(value) { | ||||
|             console.log('selected value', value.name); | ||||
|             this.address.selected.city = value; | ||||
|             this.getReferenceAddresses(value); | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.selected.city; | ||||
|          } | ||||
|       }, | ||||
|    } | ||||
| }; | ||||
| </script> | ||||
| @@ -0,0 +1,38 @@ | ||||
| <template> | ||||
|    <div class="container"> | ||||
|       <select  | ||||
|          v-model="selected"> | ||||
|          <option :value="{}" disabled selected>{{ $t('select_country') }}</option> | ||||
|          <option  | ||||
|             v-for="item in this.countries"  | ||||
|             v-bind:item="item"  | ||||
|             v-bind:key="item.id"  | ||||
|             v-bind:value="item"> | ||||
|             {{ item.name }} | ||||
|          </option> | ||||
|       </select> | ||||
|    </div> | ||||
| </template> | ||||
|  | ||||
| <script> | ||||
|  | ||||
| export default { | ||||
|    name: 'CountrySelection', | ||||
|    props: ['address', 'getCities'], | ||||
|    computed: { | ||||
|       countries() {  | ||||
|          return this.address.loaded.countries;  | ||||
|       }, | ||||
|       selected: { | ||||
|          set(value) { | ||||
|             console.log('selected value', value.name); | ||||
|             this.address.selected.country = value; | ||||
|             this.getCities(value); | ||||
|          }, | ||||
|          get() { | ||||
|             return this.address.selected.country; | ||||
|          } | ||||
|       } | ||||
|    } | ||||
| }; | ||||
| </script> | ||||
| @@ -0,0 +1,80 @@ | ||||
| <template> | ||||
|    <transition name="modal"> | ||||
|       <div class="modal-mask"> | ||||
|          <!-- :: styles bootstrap :: --> | ||||
|          <div class="modal-dialog" :class="modalDialogClass"> | ||||
|             <div class="modal-content"> | ||||
|                <div class="modal-header"> | ||||
|                   <slot name="header"></slot> | ||||
|                   <button class="close sc-button grey" @click="$emit('close')"> | ||||
|                      <i class="fa fa-times" aria-hidden="true"></i></button> | ||||
|                </div> | ||||
|                <div class="body-head"> | ||||
|                   <slot name="body-head"></slot> | ||||
|                </div> | ||||
|                <div class="modal-body"> | ||||
|                   <slot name="body"></slot> | ||||
|                </div> | ||||
|                <div class="modal-footer"> | ||||
|                   <button class="sc-button cancel" @click="$emit('close')">{{ $t('action.close') }}</button> | ||||
|                   <slot name="footer"></slot> | ||||
|                </div> | ||||
|             </div> | ||||
|          </div> | ||||
|          <!-- :: end styles bootstrap :: --> | ||||
|       </div> | ||||
|    </transition> | ||||
| </template>  | ||||
|  | ||||
| <script> | ||||
| /* | ||||
|  *    This Modal component is a mix between Vue3 modal implementation  | ||||
|  *    [+] with 'v-if:showModal' directive:parameter, html scope is added/removed not just shown/hidden | ||||
|  *    [+] with slot we can pass content from parent component | ||||
|  *    [+] some classes are passed from parent component | ||||
|  *    and Bootstrap 4.6 _modal.scss module | ||||
|  *    [+] using bootstrap css classes, the modal have a responsive behaviour,  | ||||
|  *    [+] modal design can be configured using css classes (size, scroll) | ||||
|  */ | ||||
| export default { | ||||
|    name: 'Modal', | ||||
|    props: ['modalDialogClass'], | ||||
|    emits: ['close'] | ||||
| } | ||||
| </script> | ||||
|  | ||||
| <style lang="scss"> | ||||
|    .modal-mask { | ||||
|       position: fixed; | ||||
|       z-index: 9998; | ||||
|       top: 0; | ||||
|       left: 0; | ||||
|       width: 100%; | ||||
|       height: 100%; | ||||
|       background-color: rgba(0, 0, 0, 0.75); | ||||
|       display: table; | ||||
|       transition: opacity 0.3s ease; | ||||
|    } | ||||
|    .modal-header .close { // bootstrap classes, override sc-button 0 radius | ||||
|       border-top-right-radius: 0.3rem; | ||||
|    } | ||||
|    /* | ||||
|    * The following styles are auto-applied to elements with | ||||
|    * transition="modal" when their visibility is toggled | ||||
|    * by Vue.js. | ||||
|    * | ||||
|    * You can easily play with the modal transition by editing | ||||
|    * these styles. | ||||
|    */ | ||||
|    .modal-enter { | ||||
|       opacity: 0; | ||||
|    } | ||||
|    .modal-leave-active { | ||||
|       opacity: 0; | ||||
|    } | ||||
|    .modal-enter .modal-container, | ||||
|    .modal-leave-active .modal-container { | ||||
|       -webkit-transform: scale(1.1); | ||||
|       transform: scale(1.1); | ||||
|    } | ||||
| </style> | ||||
| @@ -0,0 +1,59 @@ | ||||
| import { createI18n } from 'vue-i18n' | ||||
|  | ||||
| const datetimeFormats = { | ||||
|    fr: { | ||||
|       short: { | ||||
|          year: "numeric", | ||||
|          month: "numeric", | ||||
|          day: "numeric" | ||||
|       }, | ||||
|       text: { | ||||
|          year: "numeric", | ||||
|          month: "long", | ||||
|          day: "numeric", | ||||
|       }, | ||||
|       long: { | ||||
|          year: "numeric", | ||||
|          month: "numeric", | ||||
|          day: "numeric", | ||||
|          hour: "numeric", | ||||
|          minute: "numeric", | ||||
|          hour12: false | ||||
|       } | ||||
|    } | ||||
| }; | ||||
| const messages = { | ||||
|    fr: { | ||||
|       action: { | ||||
|          actions: "Actions", | ||||
|          show: "Voir", | ||||
|          edit: "Modifier", | ||||
|          create: "Créer", | ||||
|          remove: "Enlever", | ||||
|          delete: "Supprimer", | ||||
|          save: "Enregistrer", | ||||
|          add: "Ajouter", | ||||
|          show_modal: "Ouvrir une modale", | ||||
|          ok: "OK", | ||||
|          cancel: "Annuler", | ||||
|          close: "Fermer", | ||||
|          next: "Suivant", | ||||
|          previous: "Précédent", | ||||
|          back: "Retour", | ||||
|          check_all: "cocher tout", | ||||
|          reset: "réinitialiser" | ||||
|       }, | ||||
|    } | ||||
| }; | ||||
|  | ||||
| const _createI18n = (appMessages) => { | ||||
|    Object.assign(messages.fr, appMessages.fr); | ||||
|    return createI18n({ | ||||
|       locale: 'fr', | ||||
|       fallbackLocale: 'fr', | ||||
|       datetimeFormats, | ||||
|       messages, | ||||
|    }) | ||||
| }; | ||||
|  | ||||
| export { _createI18n } | ||||
| @@ -6,8 +6,8 @@ | ||||
|             <div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div> | ||||
|         {% endif %} | ||||
|         <div class="chill_address_address"> | ||||
|         {% if address.streetAddress1 is not empty %}<p class="street street1">{{ address.streetAddress1 }}</p>{% endif %} | ||||
|         {% if address.streetAddress2 is not empty %}<p class="street street2">{{ address.streetAddress2 }}</p>{% endif %} | ||||
|         {% if address.street is not empty %}<p class="street street1">{{ address.street }}</p>{% endif %} | ||||
|         {% if address.streetNumber is not empty %}<p class="street street2">{{ address.streetNumber }}</p>{% endif %} | ||||
|         {% if address.postCode is not empty %} | ||||
|         <p class="postalCode"><span class="code">{{ address.postCode.code }}</span> <span class="name">{{ address.postCode.name }}</span></p> | ||||
|         <p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p> | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| <footer class="footer"> | ||||
|     <p>{{ 'This program is free software: you can redistribute it and/or modify it under the terms of the <strong>GNU Affero General Public License</strong>'|trans|raw }} | ||||
|         <br/> <a href="https://{{ app.request.locale }}.wikibooks.org/wiki/Chill" target="_blank">{{ 'User manual'|trans }}</a></p> | ||||
| </footer> | ||||
|         <br/> <a name="bottom" href="https://{{ app.request.locale }}.wikibooks.org/wiki/Chill" target="_blank">{{ 'User manual'|trans }}</a></p> | ||||
| </footer> | ||||
|   | ||||
| @@ -1 +1 @@ | ||||
| <img class="logo" src="{{ asset('build/images/logo-chill-sans-slogan_white.png') }}"> | ||||
| <img name="top" class="logo" src="{{ asset('build/images/logo-chill-sans-slogan_white.png') }}"> | ||||
|   | ||||
							
								
								
									
										36
									
								
								src/Bundle/ChillMainBundle/Search/Model/Result.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								src/Bundle/ChillMainBundle/Search/Model/Result.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Search\Model; | ||||
|  | ||||
| class Result | ||||
| { | ||||
|     private float $relevance; | ||||
|  | ||||
|     /** | ||||
|      * mixed an arbitrary result | ||||
|      */ | ||||
|     private $result; | ||||
|  | ||||
|     /** | ||||
|      * @param float $relevance | ||||
|      * @param $result | ||||
|      */ | ||||
|     public function __construct(float $relevance, $result) | ||||
|     { | ||||
|         $this->relevance = $relevance; | ||||
|         $this->result = $result; | ||||
|     } | ||||
|  | ||||
|     public function getRelevance(): float | ||||
|     { | ||||
|         return $this->relevance; | ||||
|     } | ||||
|  | ||||
|     public function getResult() | ||||
|     { | ||||
|         return $this->result; | ||||
|     } | ||||
|  | ||||
|  | ||||
|      | ||||
| } | ||||
							
								
								
									
										89
									
								
								src/Bundle/ChillMainBundle/Search/SearchApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								src/Bundle/ChillMainBundle/Search/SearchApi.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,89 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Search; | ||||
|  | ||||
| use Chill\PersonBundle\Entity\Person; | ||||
| use Chill\ThirdPartyBundle\Entity\ThirdParty; | ||||
| use Doctrine\ORM\EntityManagerInterface; | ||||
| use Chill\MainBundle\Search\SearchProvider; | ||||
| use Symfony\Component\VarDumper\Resources\functions\dump; | ||||
|  | ||||
| /** | ||||
|  *  ***Warning*** This is an incomplete implementation ***Warning*** | ||||
|  */ | ||||
| class SearchApi | ||||
| { | ||||
|     private EntityManagerInterface $em; | ||||
|     private SearchProvider $search; | ||||
|  | ||||
|     public function __construct(EntityManagerInterface $em, SearchProvider $search) | ||||
|     { | ||||
|         $this->em = $em; | ||||
|         $this->search = $search; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @return Model/Result[] | ||||
|      */ | ||||
|     public function getResults(string $query, int $offset, int $maxResult): array | ||||
|     { | ||||
|         // **warning again**: this is an incomplete implementation  | ||||
|         $results = []; | ||||
|  | ||||
|         foreach ($this->getPersons($query) as $p) { | ||||
|             $results[] = new Model\Result((float)\rand(0, 100) / 100, $p); | ||||
|         } | ||||
|         foreach ($this->getThirdParties($query) as $t) { | ||||
|             $results[] = new Model\Result((float)\rand(0, 100) / 100, $t); | ||||
|         } | ||||
|  | ||||
|         \usort($results, function(Model\Result $a, Model\Result $b) { | ||||
|             return ($a->getRelevance() <=> $b->getRelevance()) * -1; | ||||
|         }); | ||||
|  | ||||
|         return $results; | ||||
|     } | ||||
|  | ||||
|     public function countResults(string $query): int | ||||
|     { | ||||
|         return 0; | ||||
|     } | ||||
|  | ||||
|     private function getThirdParties(string $query) | ||||
|     { | ||||
|         $thirdPartiesIds = $this->em->createQuery('SELECT t.id FROM '.ThirdParty::class.' t') | ||||
|             ->getScalarResult(); | ||||
|         $nbResults = rand(0, 15); | ||||
|  | ||||
|         if ($nbResults === 1) { | ||||
|             $nbResults++; | ||||
|         } elseif ($nbResults === 0) { | ||||
|             return []; | ||||
|         } | ||||
|         $ids = \array_map(function ($e) use ($thirdPartiesIds) { return $thirdPartiesIds[$e]['id'];},  | ||||
|             \array_rand($thirdPartiesIds, $nbResults)); | ||||
|  | ||||
|         $a = $this->em->getRepository(ThirdParty::class) | ||||
|             ->findById($ids); | ||||
|         return $a; | ||||
|     } | ||||
|  | ||||
|     private function getPersons(string $query) | ||||
|     { | ||||
|         $params = [ | ||||
|             SearchInterface::SEARCH_PREVIEW_OPTION => false | ||||
|             ]; | ||||
|         $search = $this->search->getResultByName($query, 'person_regular', 0, 50, $params, 'json'); | ||||
|         $ids = \array_map(function($r) { return $r['id']; }, $search['results']); | ||||
|  | ||||
|  | ||||
|         if (count($ids) === 0) { | ||||
|             return []; | ||||
|         } | ||||
|  | ||||
|         return $this->em->getRepository(Person::class) | ||||
|             ->findById($ids) | ||||
|             ; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @@ -204,7 +204,7 @@ class SearchProvider | ||||
|     } | ||||
|      | ||||
|     public function getResultByName($pattern, $name, $start = 0, $limit = 50, | ||||
|           array $options = array(), $format)  | ||||
|           array $options = array(), $format = 'html')  | ||||
|     { | ||||
|         $terms = $this->parse($pattern); | ||||
|         $search = $this->getByName($name); | ||||
|   | ||||
							
								
								
									
										28
									
								
								src/Bundle/ChillMainBundle/Serializer/Model/Collection.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								src/Bundle/ChillMainBundle/Serializer/Model/Collection.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,28 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Model; | ||||
|  | ||||
| use Chill\MainBundle\Pagination\PaginatorInterface; | ||||
|  | ||||
| class Collection | ||||
| { | ||||
|     private PaginatorInterface $paginator; | ||||
|  | ||||
|     private $items; | ||||
|  | ||||
|     public function __construct($items, PaginatorInterface $paginator) | ||||
|     { | ||||
|         $this->items = $items; | ||||
|         $this->paginator = $paginator; | ||||
|     } | ||||
|  | ||||
|     public function getPaginator(): PaginatorInterface | ||||
|     { | ||||
|         return $this->paginator; | ||||
|     } | ||||
|  | ||||
|     public function getItems() | ||||
|     { | ||||
|         return $this->items; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,29 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Chill\MainBundle\Entity\Address; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||||
|  | ||||
| class AddressNormalizer implements NormalizerAwareInterface, NormalizerInterface | ||||
| { | ||||
|     use NormalizerAwareTrait; | ||||
|  | ||||
|     public function normalize($address, string $format = null, array $context = []) | ||||
|     { | ||||
|         $data['address_id'] = $address->getId(); | ||||
|         $data['text'] = $address->getStreet().', '.$address->getBuildingName(); | ||||
|         $data['postcode']['name'] = $address->getPostCode()->getName(); | ||||
|  | ||||
|         return $data; | ||||
|     } | ||||
|  | ||||
|     public function supportsNormalization($data, string $format = null) | ||||
|     { | ||||
|         return $data instanceof Address; | ||||
|     } | ||||
|  | ||||
|      | ||||
| } | ||||
| @@ -0,0 +1,44 @@ | ||||
| <?php | ||||
| /* | ||||
|  *  | ||||
|  * Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop> | ||||
|  *  | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  *  it under the terms of the GNU Affero General Public License as | ||||
|  * published by the Free Software Foundation, either version 3 of the | ||||
|  *  License, or (at your option) any later version. | ||||
|  *  | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  *  | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Chill\MainBundle\Entity\Center; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||||
|  | ||||
| /** | ||||
|  *  | ||||
|  * | ||||
|  */ | ||||
| class CenterNormalizer implements NormalizerInterface | ||||
| { | ||||
|     public function normalize($center, string $format = null, array $context = array()) | ||||
|     { | ||||
|         /** @var Center $center */ | ||||
|         return [ | ||||
|             'id' => $center->getId(), | ||||
|             'name' => $center->getName() | ||||
|         ]; | ||||
|     } | ||||
|  | ||||
|     public function supportsNormalization($data, string $format = null): bool | ||||
|     { | ||||
|         return $data instanceof Center; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,41 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Chill\MainBundle\Serializer\Model\Collection; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; | ||||
|  | ||||
| class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface | ||||
| { | ||||
|     use NormalizerAwareTrait;  | ||||
|  | ||||
|     public function supportsNormalization($data, string $format = null): bool | ||||
|     { | ||||
|         return $data instanceof Collection; | ||||
|     } | ||||
|  | ||||
|     public function normalize($collection, string $format = null, array $context = []) | ||||
|     { | ||||
|         /** @var $collection Collection */ | ||||
|         /** @var $collection Chill\MainBundle\Pagination\PaginatorInterface */  | ||||
|         $paginator = $collection->getPaginator(); | ||||
|  | ||||
|         $data['count'] = $paginator->getTotalItems(); | ||||
|         $pagination['first'] = $paginator->getCurrentPageFirstItemNumber(); | ||||
|         $pagination['items_per_page'] = $paginator->getItemsPerPage(); | ||||
|         $pagination['next']  = $paginator->hasNextPage() ?  | ||||
|             $paginator->getNextPage()->generateUrl() : null; | ||||
|         $pagination['previous'] = $paginator->hasPreviousPage() ? | ||||
|             $paginator->getPreviousPage()->generateUrl() : null; | ||||
|         $pagination['more'] = $paginator->hasNextPage(); | ||||
|         $data['pagination'] = $pagination; | ||||
|  | ||||
|         // normalize results | ||||
|         $data['results'] = $this->normalizer->normalize($collection->getItems(), | ||||
|             $format, $context); | ||||
|  | ||||
|         return $data; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,60 @@ | ||||
| <?php | ||||
| /* | ||||
|  * | ||||
|  * Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop> | ||||
|  * | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  *  it under the terms of the GNU Affero General Public License as | ||||
|  * published by the Free Software Foundation, either version 3 of the | ||||
|  *  License, or (at your option) any later version. | ||||
|  * | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  * | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; | ||||
|  | ||||
| class DateNormalizer implements NormalizerInterface, DenormalizerInterface | ||||
| { | ||||
|     public function normalize($date, string $format = null, array $context = array()) | ||||
|     { | ||||
|         /** @var \DateTimeInterface $date */ | ||||
|         return [ | ||||
|             'datetime' => $date->format(\DateTimeInterface::ISO8601) | ||||
|         ]; | ||||
|     } | ||||
|  | ||||
|     public function supportsNormalization($data, string $format = null): bool | ||||
|     { | ||||
|         return $data instanceof \DateTimeInterface; | ||||
|     } | ||||
|  | ||||
|     public function denormalize($data, string $type, string $format = null, array $context = []) | ||||
|     { | ||||
|         switch ($type) { | ||||
|             case \DateTime::class: | ||||
|                 return \DateTime::createFromFormat(\DateTimeInterface::ISO8601, $data['datetime']); | ||||
|             case \DateTimeInterface::class: | ||||
|             case \DateTimeImmutable::class: | ||||
|             default: | ||||
|                 return \DateTimeImmutable::createFromFormat(\DateTimeInterface::ISO8601, $data['datetime']); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public function supportsDenormalization($data, string $type, string $format = null): bool | ||||
|     { | ||||
|         return $type === \DateTimeInterface::class || | ||||
|             $type === \DateTime::class || | ||||
|             $type === \DateTimeImmutable::class || | ||||
|             (\is_array($data) && array_key_exists('datetime', $data)); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,71 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface; | ||||
| use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait; | ||||
| use Symfony\Component\Serializer\Exception\RuntimeException; | ||||
|  | ||||
|  | ||||
| /** | ||||
|  * Denormalize an object given a list of supported class | ||||
|  */ | ||||
| class DiscriminatedObjectDenormalizer implements ContextAwareDenormalizerInterface, DenormalizerAwareInterface | ||||
| { | ||||
|     use DenormalizerAwareTrait; | ||||
|  | ||||
|     /** | ||||
|      * The type to set for enabling this type | ||||
|      */ | ||||
|     public const TYPE = '@multi'; | ||||
|  | ||||
|     /** | ||||
|      * Should be present in context and contains an array of | ||||
|      * allowed types.  | ||||
|      */ | ||||
|     public const ALLOWED_TYPES = 'denormalize_multi.allowed_types'; | ||||
|  | ||||
|     /** | ||||
|      * {@inheritDoc} | ||||
|      */ | ||||
|     public function denormalize($data, string $type, string $format = null, array $context = []) | ||||
|     { | ||||
|         foreach ($context[self::ALLOWED_TYPES] as $localType) { | ||||
|             if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) { | ||||
|                 try { | ||||
|                     return $this->denormalizer->denormalize($data, $localType, $format, $context);               } catch (RuntimeException $e) { | ||||
|                     $lastException = $e; | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         throw new RuntimeException(sprintf("Could not find any denormalizer for those ". | ||||
|             "ALLOWED_TYPES: %s", \implode(", ", $context[self::ALLOWED_TYPES]))); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * {@inheritDoc} | ||||
|      */ | ||||
|     public function supportsDenormalization($data, string $type, string $format = null, array $context = []) | ||||
|     { | ||||
|         if (self::TYPE !== $type) { | ||||
|             return false; | ||||
|         } | ||||
|  | ||||
|         if (0 === count($context[self::ALLOWED_TYPES] ?? [])) { | ||||
|             throw new \LogicException("The context should contains a list of  | ||||
|                 allowed types"); | ||||
|         } | ||||
|  | ||||
|         foreach ($context[self::ALLOWED_TYPES] as $localType) { | ||||
|             if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) { | ||||
|                 return true; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @@ -0,0 +1,71 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; | ||||
| use Doctrine\ORM\EntityManagerInterface; | ||||
| use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; | ||||
| use Doctrine\ORM\Mapping\ClassMetadata; | ||||
| use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; | ||||
| use Symfony\Component\Serializer\Mapping\ClassMetadataInterface as SerializerMetadata; | ||||
|  | ||||
|  | ||||
| class DoctrineExistingEntityNormalizer implements DenormalizerInterface | ||||
| { | ||||
|     private EntityManagerInterface $em; | ||||
|  | ||||
|     private ClassMetadataFactoryInterface $serializerMetadataFactory; | ||||
|  | ||||
|  | ||||
|     public function __construct(EntityManagerInterface $em, ClassMetadataFactoryInterface $serializerMetadataFactory) | ||||
|     { | ||||
|         $this->em = $em; | ||||
|         $this->serializerMetadataFactory = $serializerMetadataFactory; | ||||
|     } | ||||
|  | ||||
|     public function denormalize($data, string $type, string $format = null, array $context = []) | ||||
|     { | ||||
|         if (\array_key_exists(AbstractNormalizer::OBJECT_TO_POPULATE, $context)) { | ||||
|             return $context[AbstractNormalizer::OBJECT_TO_POPULATE]; | ||||
|         } | ||||
|  | ||||
|         return $this->em->getRepository($type) | ||||
|             ->find($data['id']); | ||||
|     } | ||||
|  | ||||
|     public function supportsDenormalization($data, string $type, string $format = null) | ||||
|     { | ||||
|         if (FALSE === \is_array($data)) { | ||||
|             return false; | ||||
|         } | ||||
|  | ||||
|         if (FALSE === \array_key_exists('id', $data)) { | ||||
|             return false; | ||||
|         }  | ||||
|  | ||||
|         if (FALSE === $this->em->getClassMetadata($type) instanceof ClassMetadata) { | ||||
|             return false;  | ||||
|         } | ||||
|  | ||||
|         // does have serializer metadata, and class discriminator ? | ||||
|         if ($this->serializerMetadataFactory->hasMetadataFor($type)) { | ||||
|  | ||||
|             $classDiscriminator = $this->serializerMetadataFactory | ||||
|                 ->getMetadataFor($type)->getClassDiscriminatorMapping(); | ||||
|  | ||||
|             if ($classDiscriminator) { | ||||
|                 $typeProperty = $classDiscriminator->getTypeProperty(); | ||||
|  | ||||
|                 // check that only 2 keys | ||||
|                 // that the second key is property | ||||
|                 // and that the type match the class for given type property  | ||||
|                 return count($data) === 2 | ||||
|                     && \array_key_exists($typeProperty, $data)  | ||||
|                     && $type === $classDiscriminator->getClassForType($data[$typeProperty]); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         // we do not have any class discriminator. Check that the id is the only one key | ||||
|         return count($data) === 1; | ||||
|     } | ||||
| }     | ||||
| @@ -0,0 +1,46 @@ | ||||
| <?php | ||||
| /* | ||||
|  * | ||||
|  * Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop> | ||||
|  * | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  *  it under the terms of the GNU Affero General Public License as | ||||
|  * published by the Free Software Foundation, either version 3 of the | ||||
|  *  License, or (at your option) any later version. | ||||
|  * | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  * | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
|  | ||||
| namespace Chill\MainBundle\Serializer\Normalizer; | ||||
|  | ||||
| use Chill\MainBundle\Entity\User; | ||||
| use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||||
|  | ||||
| /** | ||||
|  * | ||||
|  * @internal we keep this normalizer, because the property 'text' may be replace by a rendering in the future | ||||
|  */ | ||||
| class UserNormalizer implements NormalizerInterface | ||||
| { | ||||
|     public function normalize($user, string $format = null, array $context = array()) | ||||
|     { | ||||
|         /** @var User $user */ | ||||
|         return [ | ||||
|             'type' => 'user', | ||||
|             'id' => $user->getId(), | ||||
|             'username' => $user->getUsername(), | ||||
|             'text' => $user->getUsername() | ||||
|         ]; | ||||
|     } | ||||
|  | ||||
|     public function supportsNormalization($data, string $format = null): bool | ||||
|     { | ||||
|         return $data instanceof User; | ||||
|     } | ||||
| } | ||||
| @@ -172,6 +172,7 @@ abstract class AbstractExportTest extends WebTestCase | ||||
|      */ | ||||
|     public function testInitiateQuery($modifiers, $acl, $data) | ||||
|     { | ||||
|         var_dump($data); | ||||
|         $query = $this->getExport()->initiateQuery($modifiers, $acl, $data); | ||||
|          | ||||
|         $this->assertTrue($query instanceof QueryBuilder || $query instanceof NativeQuery, | ||||
|   | ||||
| @@ -9,15 +9,7 @@ class LoginControllerTest extends WebTestCase | ||||
| { | ||||
|     public function testLogin() | ||||
|     { | ||||
|         $client = static::createClient(array( | ||||
|             'framework' => array( | ||||
|                 'default_locale' => 'en', | ||||
|                 'translator' => array( | ||||
|                     'fallback' => 'en' | ||||
|                 ) | ||||
|             ), | ||||
|              | ||||
|         )); | ||||
|         $client = static::createClient(); | ||||
|  | ||||
|         //load login page and submit form | ||||
|         $crawler = $client->request('GET', '/login'); | ||||
| @@ -42,17 +34,17 @@ class LoginControllerTest extends WebTestCase | ||||
|         //on the home page, there must be a logout link | ||||
|         $client->followRedirects(true); | ||||
|         $crawler = $client->request('GET', '/'); | ||||
|          | ||||
|   | ||||
|         $this->assertRegExp('/center a_social/', $client->getResponse() | ||||
|                                     ->getContent()); | ||||
|         $logoutLinkFilter = $crawler->filter('a:contains("Logout")'); | ||||
|         $logoutLinkFilter = $crawler->filter('a:contains("Se déconnecter")'); | ||||
|          | ||||
|         //check there is > 0 logout link | ||||
|         $this->assertGreaterThan(0, $logoutLinkFilter->count(), 'check that a logout link is present'); | ||||
|          | ||||
|         //click on logout link | ||||
|         $client->followRedirects(false); | ||||
|         $client->click($crawler->selectLink('Logout')->link()); | ||||
|         $client->click($crawler->selectLink('Se déconnecter')->link()); | ||||
|          | ||||
|         $this->assertTrue($client->getResponse()->isRedirect()); | ||||
|         $client->followRedirect(); #redirect to login page | ||||
|   | ||||
| @@ -32,21 +32,7 @@ use Chill\MainBundle\Search\SearchInterface; | ||||
|  */ | ||||
| class SearchControllerTest extends WebTestCase | ||||
| { | ||||
|     /* | ||||
|     public function setUp() | ||||
|     { | ||||
|         static::bootKernel(); | ||||
|          | ||||
|         //add a default service | ||||
|         $this->addSearchService( | ||||
|               $this->createDefaultSearchService('<p>I am default</p>', 10), 'default' | ||||
|               ); | ||||
|         //add a domain service | ||||
|         $this->addSearchService( | ||||
|               $this->createDefaultSearchService('<p>I am domain bar</p>', 20), 'bar' | ||||
|               ); | ||||
|     } | ||||
|      | ||||
|     | ||||
|     /** | ||||
|      * Test the behaviour when no domain is provided in the search pattern :  | ||||
|      * the default search should be enabled | ||||
| @@ -105,29 +91,6 @@ class SearchControllerTest extends WebTestCase | ||||
|         $this->assertTrue($client->getResponse()->isNotFound()); | ||||
|     } | ||||
|      | ||||
|      | ||||
|     public function testSearchWithinSpecificSearchName() | ||||
|     { | ||||
|         /* | ||||
|         //add a search service which will be supported | ||||
|         $this->addSearchService( | ||||
|               $this->createNonDefaultDomainSearchService("<p>I am domain foo</p>", 100, TRUE), 'foo' | ||||
|               ); | ||||
|          | ||||
|         $client = $this->getAuthenticatedClient(); | ||||
|         $crawler = $client->request('GET', '/fr/search',  | ||||
|               array('q' => '@foo default search', 'name' => 'foo')); | ||||
|  | ||||
|         //$this->markTestSkipped(); | ||||
|         $this->assertEquals(0, $crawler->filter('p:contains("I am default")')->count(),  | ||||
|               "The mocked default results are not shown"); | ||||
|         $this->assertEquals(0, $crawler->filter('p:contains("I am domain bar")')->count(), | ||||
|               "The mocked non-default results are not shown"); | ||||
|         $this->assertEquals(1, $crawler->filter('p:contains("I am domain foo")')->count(),  | ||||
|               "The mocked nnon default results for foo are shown"); | ||||
|         */ | ||||
|     } | ||||
|      | ||||
|     private function getAuthenticatedClient() | ||||
|     { | ||||
|         return static::createClient(array(), array( | ||||
|   | ||||
| @@ -37,11 +37,12 @@ class UserControllerTest extends WebTestCase | ||||
|          | ||||
|         $username = 'Test_user'.  uniqid(); | ||||
|         $password = 'Password1234!'; | ||||
|         dump($crawler->text()); | ||||
|         // Fill in the form and submit it | ||||
|         $form = $crawler->selectButton('Créer')->form(array( | ||||
|             'chill_mainbundle_user[username]'  => $username, | ||||
|             'chill_mainbundle_user[plainPassword][password][first]' => $password, | ||||
|             'chill_mainbundle_user[plainPassword][password][second]' => $password | ||||
|             'chill_mainbundle_user[plainPassword][first]' => $password, | ||||
|             'chill_mainbundle_user[plainPassword][second]' => $password | ||||
|         )); | ||||
|  | ||||
|         $this->client->submit($form); | ||||
| @@ -119,8 +120,8 @@ class UserControllerTest extends WebTestCase | ||||
|         $crawler = $this->client->click($link); | ||||
|          | ||||
|         $form = $crawler->selectButton('Changer le mot de passe')->form(array( | ||||
|             'chill_mainbundle_user_password[password][first]' => $newPassword, | ||||
|             'chill_mainbundle_user_password[password][second]' => $newPassword, | ||||
|             'chill_mainbundle_user_password[new_password][first]' => $newPassword, | ||||
|             'chill_mainbundle_user_password[new_password][second]' => $newPassword, | ||||
|         )); | ||||
|          | ||||
|         $this->client->submit($form); | ||||
|   | ||||
| @@ -1,179 +0,0 @@ | ||||
| <?php | ||||
|  | ||||
| /* | ||||
|  * Chill is a software for social workers | ||||
|  * Copyright (C) 2015 Champs-Libres Coopérative <info@champs-libres.coop> | ||||
|  * | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  * it under the terms of the GNU Affero General Public License as published by | ||||
|  * the Free Software Foundation, either version 3 of the License, or | ||||
|  * (at your option) any later version. | ||||
|  * | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  * | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
|  | ||||
| namespace Chill\MainBundle\Tests\DependencyInjection; | ||||
|  | ||||
| use Chill\MainBundle\DependencyInjection\ConfigConsistencyCompilerPass; | ||||
| use Symfony\Component\DependencyInjection\ContainerBuilderInterface; | ||||
|  | ||||
| /** | ||||
|  * Description of ConfigConsistencyCompilerPassTest | ||||
|  * | ||||
|  * @author Julien Fastré <julien.fastre@champs-libres.coop> | ||||
|  */ | ||||
| class ConfigConsistencyCompilerPassTest extends \PHPUnit\Framework\TestCase | ||||
| { | ||||
|      | ||||
|     /** | ||||
|      *  | ||||
|      * | ||||
|      * @var \Chill\MainBundle\DependencyInjection\ConfigConsistencyCompilerPass  | ||||
|      */ | ||||
|     private $configConsistencyCompilerPass; | ||||
|      | ||||
|     public function setUp() | ||||
|     { | ||||
|         $this->configConsistencyCompilerPass = new ConfigConsistencyCompilerPass(); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Test that everything is fine is configuration is correct | ||||
|      *  | ||||
|      */ | ||||
|     public function testLanguagesArePresent() | ||||
|     { | ||||
|         try { | ||||
|             $this ->configConsistencyCompilerPass | ||||
|                   ->process( | ||||
|                         $this->mockContainer( | ||||
|                               $this->mockTranslatorDefinition(array('fr')), | ||||
|                               array('fr', 'nl') | ||||
|                         ) | ||||
|                     ); | ||||
|             $this->assertTrue(TRUE, 'the config consistency can process'); | ||||
|         } catch (\Exception $ex) { | ||||
|             $this->assertTrue(FALSE,  | ||||
|                   'the config consistency can process'); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Test that everything is fine is configuration is correct | ||||
|      * if multiple fallback languages are present | ||||
|      *  | ||||
|      */ | ||||
|     public function testMultiplesLanguagesArePresent() | ||||
|     { | ||||
|         try { | ||||
|             $this ->configConsistencyCompilerPass | ||||
|                   ->process( | ||||
|                         $this->mockContainer( | ||||
|                               $this->mockTranslatorDefinition(array('fr', 'nl')), | ||||
|                               array('fr', 'nl', 'en') | ||||
|                         ) | ||||
|                     ); | ||||
|             $this->assertTrue(TRUE, 'the config consistency can process'); | ||||
|         } catch (\Exception $ex) { | ||||
|             $this->assertTrue(FALSE,  | ||||
|                   'the config consistency can process'); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|      | ||||
|      | ||||
|     /** | ||||
|      * Test that a runtime exception is throw if the available language does  | ||||
|      * not contains the fallback locale | ||||
|      *  | ||||
|      * @expectedException \RuntimeException | ||||
|      * @expectedExceptionMessageRegExp /The chill_main.available_languages parameter does not contains fallback locales./ | ||||
|      */ | ||||
|     public function testLanguageNotPresent() | ||||
|     { | ||||
|         $container = $this->mockContainer( | ||||
|               $this->mockTranslatorDefinition(array('en')), array('fr') | ||||
|               ); | ||||
|          | ||||
|         $this->configConsistencyCompilerPass->process($container); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Test that a logic exception is thrown if the setFallbackLocale | ||||
|      * method is not defined in translator definition | ||||
|      *  | ||||
|      * @expectedException \LogicException | ||||
|      */ | ||||
|     public function testSetFallbackNotDefined() | ||||
|     { | ||||
|         $container = $this->mockContainer( | ||||
|               $this->mockTranslatorDefinition(NULL), array('fr') | ||||
|               ); | ||||
|         $this->configConsistencyCompilerPass->process($container); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * @return ContainerBuilder | ||||
|      */ | ||||
|     private function mockContainer($definition, $availableLanguages) | ||||
|     { | ||||
|         $container = $this | ||||
|               ->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder') | ||||
|               ->getMock(); | ||||
|          | ||||
|         $container->method('getParameter') | ||||
|               ->will($this->returnCallback( | ||||
|                         function($parameter) use ($availableLanguages) { | ||||
|                             if ($parameter === 'chill_main.available_languages') { | ||||
|                                 return $availableLanguages; | ||||
|                             } else { | ||||
|                                 throw new \LogicException("the parameter '$parameter' " | ||||
|                                       . "is not defined in stub test"); | ||||
|                             } | ||||
|                         } | ||||
|                     )); | ||||
|          | ||||
|         $container->method('findDefinition') | ||||
|               ->will($this->returnCallback( | ||||
|                     function($id) use ($definition) {  | ||||
|                         if (in_array($id, array('translator', 'translator.default'))) { | ||||
|                             return $definition; | ||||
|                         } else { | ||||
|                             throw new \LogicException("the id $id is not defined in test"); | ||||
|                         } | ||||
|                   })); | ||||
|                    | ||||
|          | ||||
|         return $container; | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      *  | ||||
|      * @param type $languages | ||||
|      * @return 'Symfony\Component\DependencyInjection\Definition' | ||||
|      */ | ||||
|     private function mockTranslatorDefinition(array $languages = NULL) | ||||
|     { | ||||
|         $definition = $this | ||||
|               ->getMockBuilder('Symfony\Component\DependencyInjection\Definition') | ||||
|               ->getMock(); | ||||
|          | ||||
|         if (NULL !== $languages) { | ||||
|             $definition->method('getMethodCalls') | ||||
|                   ->willReturn(array( | ||||
|                     ['setFallbackLocales', array($languages)] | ||||
|                      )); | ||||
|         } else { | ||||
|             $definition->method('getMethodCalls') | ||||
|                   ->willReturn(array(['nothing', array()])); | ||||
|         } | ||||
|          | ||||
|         return $definition; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										119
									
								
								src/Bundle/ChillMainBundle/Tests/Doctrine/Model/PointTest.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										119
									
								
								src/Bundle/ChillMainBundle/Tests/Doctrine/Model/PointTest.php
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,119 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Tests\Doctrine\Model; | ||||
|  | ||||
| use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; | ||||
| use Chill\MainBundle\Doctrine\Model\Point; | ||||
|  | ||||
| /** | ||||
|  * Test the point model methods | ||||
|  * | ||||
|  * @author Julien Minet <julien.minet@champs-libres.coop> | ||||
|  */ | ||||
| class ExportControllerTest extends KernelTestCase | ||||
| { | ||||
|  | ||||
|     public function testToWKT() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat); | ||||
|  | ||||
|         $this->assertEquals($point->toWKT(),'SRID=4326;POINT(4.8634 50.47382)'); | ||||
|     } | ||||
|  | ||||
|     public function testToGeojson() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat); | ||||
|  | ||||
|         $this->assertEquals($point->toGeoJson(),'{"type":"Point","coordinates":[4.8634,50.47382]}'); | ||||
|     } | ||||
|  | ||||
|     public function testToArrayGeoJson() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat); | ||||
|  | ||||
|         $this->assertEquals( | ||||
|             $point->toArrayGeoJson(), | ||||
|             [ | ||||
|                 'type' => 'Point', | ||||
|                 'coordinates' => [4.8634, 50.47382] | ||||
|             ] | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     public function testJsonSerialize() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat); | ||||
|  | ||||
|         $this->assertEquals( | ||||
|             $point->jsonSerialize(), | ||||
|             [ | ||||
|                 'type' => 'Point', | ||||
|                 'coordinates' => [4.8634, 50.47382] | ||||
|             ] | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     public function testFromGeoJson() | ||||
|     { | ||||
|         $geojson = '{"type":"Point","coordinates":[4.8634,50.47382]}'; | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat);; | ||||
|  | ||||
|         $this->assertEquals($point, Point::fromGeoJson($geojson)); | ||||
|     } | ||||
|  | ||||
|     public function testFromLonLat() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat);; | ||||
|  | ||||
|         $this->assertEquals($point, Point::fromLonLat($lon, $lat)); | ||||
|     } | ||||
|  | ||||
|     public function testFromArrayGeoJson() | ||||
|     { | ||||
|         $array = [ | ||||
|             'type' => 'Point', | ||||
|             'coordinates' => [4.8634, 50.47382] | ||||
|         ]; | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat);; | ||||
|  | ||||
|         $this->assertEquals($point, Point::fromArrayGeoJson($array)); | ||||
|     } | ||||
|  | ||||
|     public function testGetLat() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat);; | ||||
|  | ||||
|         $this->assertEquals($lat, $point->getLat()); | ||||
|     } | ||||
|  | ||||
|     public function testGetLon() | ||||
|     { | ||||
|         $lon = 4.8634; | ||||
|         $lat = 50.47382; | ||||
|         $point = $this->preparePoint($lon, $lat);; | ||||
|  | ||||
|         $this->assertEquals($lon, $point->getLon()); | ||||
|     } | ||||
|  | ||||
|     private function preparePoint($lon, $lat) | ||||
|     { | ||||
|         return Point::fromLonLat($lon, $lat); | ||||
|     } | ||||
|  | ||||
| } | ||||
| @@ -624,8 +624,9 @@ class ExportManagerTest extends KernelTestCase | ||||
|         $exportManager->addFormatter($formatter, 'spreadsheet'); | ||||
|          | ||||
|         //ob_start(); | ||||
|         $response = $exportManager->generate('dummy',  | ||||
|                 array(PickCenterType::CENTERS_IDENTIFIERS => array($center)),  | ||||
|         $response = $exportManager->generate( | ||||
|                 'dummy',  | ||||
|                 array($center),  | ||||
|                 array( | ||||
|                     ExportType::FILTER_KEY => array( | ||||
|                         'filter_foo' => array( | ||||
|   | ||||
| @@ -54,13 +54,20 @@ class PageTest extends KernelTestCase | ||||
|           $number = 1,  | ||||
|           $itemPerPage = 10, | ||||
|           $route = 'route', | ||||
|           array $routeParameters = array() | ||||
|           array $routeParameters = array(), | ||||
|           $totalItems = 100 | ||||
|     ) { | ||||
|         $urlGenerator = $this->prophet->prophesize(); | ||||
|         $urlGenerator->willImplement(UrlGeneratorInterface::class); | ||||
|          | ||||
|         return new Page($number, $itemPerPage, $urlGenerator->reveal(), $route,  | ||||
|               $routeParameters); | ||||
|         return new Page( | ||||
|             $number,  | ||||
|             $itemPerPage,  | ||||
|             $urlGenerator->reveal(),  | ||||
|             $route,  | ||||
|             $routeParameters, | ||||
|             $totalItems | ||||
|         ); | ||||
|     } | ||||
|      | ||||
|     public function testPageNumber() { | ||||
|   | ||||
| @@ -21,9 +21,10 @@ namespace Chill\MainBundle\Test\Search; | ||||
|  | ||||
| use Chill\MainBundle\Search\SearchProvider; | ||||
| use Chill\MainBundle\Search\SearchInterface; | ||||
| use PHPUnit\Framework\TestCase; | ||||
|  | ||||
|  | ||||
| class SearchProviderTest extends \PHPUnit\Framework\TestCase | ||||
| class SearchProviderTest extends TestCase | ||||
| { | ||||
|      | ||||
|     /** | ||||
| @@ -311,4 +312,4 @@ class SearchProviderTest extends \PHPUnit\Framework\TestCase | ||||
|          | ||||
|         return $mock; | ||||
|     } | ||||
| } | ||||
| } | ||||
|   | ||||
| @@ -50,7 +50,7 @@ class AuthorizationHelperTest extends KernelTestCase | ||||
|      */ | ||||
|     private function getAuthorizationHelper() | ||||
|     { | ||||
|         return static::$kernel->getContainer() | ||||
|         return static::$container | ||||
|                 ->get('chill.main.security.authorization.helper') | ||||
|                 ; | ||||
|     } | ||||
|   | ||||
| @@ -39,8 +39,7 @@ class TokenManagerTest extends KernelTestCase | ||||
|     { | ||||
|         self::bootKernel(); | ||||
|          | ||||
|         $logger = self::$kernel | ||||
|             ->getContainer() | ||||
|         $logger = self::$container | ||||
|             ->get('logger'); | ||||
|          | ||||
|         $this->tokenManager = new TokenManager('secret', $logger); | ||||
|   | ||||
| @@ -0,0 +1,51 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\MainBundle\Tests\Serializer\Normalizer; | ||||
|  | ||||
| use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; | ||||
| use Chill\MainBundle\Serializer\Normalizer\DoctrineExistingEntityNormalizer; | ||||
| use Doctrine\ORM\EntityManagerInterface; | ||||
| use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; | ||||
| use Chill\MainBundle\Entity\User; | ||||
|  | ||||
|  | ||||
| class DoctrineExistingEntityNormalizerTest extends KernelTestCase | ||||
| { | ||||
|     protected DoctrineExistingEntityNormalizer $normalizer; | ||||
|  | ||||
|     protected function setUp() | ||||
|     { | ||||
|         self::bootKernel(); | ||||
|         $em = self::$container->get(EntityManagerInterface::class);  | ||||
|         $serializerFactory = self::$container->get(ClassMetadataFactoryInterface::class); | ||||
|  | ||||
|         $this->normalizer = new DoctrineExistingEntityNormalizer($em, $serializerFactory); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @dataProvider dataProviderUserId | ||||
|      */ | ||||
|     public function testGetMappedClass($userId) | ||||
|     { | ||||
|         $data = [ 'type' => 'user', 'id' => $userId];  | ||||
|         $supports = $this->normalizer->supportsDenormalization($data, User::class); | ||||
|  | ||||
|         $this->assertTrue($supports); | ||||
|     } | ||||
|  | ||||
|     public function dataProviderUserId() | ||||
|     { | ||||
|         self::bootKernel(); | ||||
|  | ||||
|         $userIds = self::$container->get(EntityManagerInterface::class) | ||||
|             ->getRepository(User::class) | ||||
|             ->createQueryBuilder('u') | ||||
|             ->select('u.id') | ||||
|             ->setMaxResults(1) | ||||
|             ->getQuery() | ||||
|             ->getResult() | ||||
|             ; | ||||
|  | ||||
|         yield [ $userIds[0]['id'] ]; | ||||
|     } | ||||
| } | ||||
| @@ -36,53 +36,19 @@ class ChillMenuTwigFunctionTest extends KernelTestCase | ||||
|     public static function setUpBeforeClass() | ||||
|     { | ||||
|         self::bootKernel(array('environment' => 'test')); | ||||
|         static::$templating = static::$kernel | ||||
|                 ->getContainer()->get('templating'); | ||||
|         static::$templating = static::$container | ||||
|             ->get('templating'); | ||||
|         $pathToBundle = static::$container->getParameter('kernel.bundles_metadata')['ChillMainBundle']['path']; | ||||
|         //load templates in Tests/Resources/views | ||||
|         static::$kernel->getContainer()->get('twig.loader') | ||||
|                 ->addPath(static::$kernel->getContainer()->getParameter('kernel.root_dir') | ||||
|                     .'/Resources/views/', $namespace = 'tests'); | ||||
|         static::$container->get('twig.loader') | ||||
|             ->addPath($pathToBundle.'/Resources/test/views/', $namespace = 'tests'); | ||||
|     } | ||||
|      | ||||
|     public function testNormalMenu() | ||||
|     { | ||||
|         $content = static::$templating->render('@tests/menus/normalMenu.html.twig'); | ||||
|         $crawler = new Crawler($content); | ||||
|          | ||||
|         $ul = $crawler->filter('ul')->getNode(0); | ||||
|         $this->assertEquals( 'ul', $ul->tagName); | ||||
|          | ||||
|         $lis = $crawler->filter('ul')->children(); | ||||
|         $this->assertEquals(3, count($lis)); | ||||
|          | ||||
|         $lis->each(function(Crawler $node, $i) { | ||||
|                 $this->assertEquals('li', $node->getNode(0)->tagName); | ||||
|                  | ||||
|                 $a = $node->children()->getNode(0); | ||||
|                 $this->assertEquals('a', $a->tagName); | ||||
|                 switch($i) { | ||||
|                     case 0:  | ||||
|                         $this->assertEquals('/dummy?param=fake', $a->getAttribute('href')); | ||||
|                         $this->assertEquals('active', $a->getAttribute('class')); | ||||
|                         $this->assertEquals('test0', $a->nodeValue); | ||||
|                         break; | ||||
|                     case 1: | ||||
|                         $this->assertEquals('/dummy1?param=fake', $a->getAttribute('href')); | ||||
|                         $this->assertEmpty($a->getAttribute('class')); | ||||
|                         $this->assertEquals('test1', $a->nodeValue); | ||||
|                         break; | ||||
|                     case 3: | ||||
|                         $this->assertEquals('/dummy2/fake', $a->getAttribute('href')); | ||||
|                         $this->assertEmpty($a->getAttribute('class')); | ||||
|                         $this->assertEquals('test2', $a->nodeValue); | ||||
|                 } | ||||
|         }); | ||||
|     } | ||||
|      | ||||
|     public function testMenuOverrideTemplate() | ||||
|     { | ||||
|         $this->markTestSkipped("this hacks seems not working now"); | ||||
|         $content = static::$templating->render('@tests/menus/overrideTemplate.html.twig'); | ||||
|         $this->assertEquals('fake template', $content); | ||||
|         $this->assertContains('ul', $content,  | ||||
|             "test that the file contains an ul tag" | ||||
|         ); | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -28,7 +28,7 @@ class MenuComposerTest extends KernelTestCase | ||||
|     public function setUp() | ||||
|     { | ||||
|         self::bootKernel(array('environment' => 'test')); | ||||
|         $this->menuComposer = static::$kernel->getContainer() | ||||
|         $this->menuComposer = static::$container | ||||
|                 ->get('chill.main.menu_composer'); | ||||
|     } | ||||
|      | ||||
| @@ -42,50 +42,5 @@ class MenuComposerTest extends KernelTestCase | ||||
|         $routes = $this->menuComposer->getRoutesFor('dummy0'); | ||||
|          | ||||
|         $this->assertInternalType('array', $routes); | ||||
|         $this->assertCount(3, $routes); | ||||
|         //check that the keys are sorted | ||||
|         $orders = array_keys($routes); | ||||
|         foreach ($orders as $key => $order){ | ||||
|             if (array_key_exists($key + 1, $orders)) { | ||||
|                 $this->assertGreaterThan($order, $orders[$key + 1], | ||||
|                         'Failing to assert that routes are ordered'); | ||||
|             } | ||||
|         } | ||||
|          | ||||
|         //check that the array are identical, order is not important : | ||||
|          | ||||
|         $expected = array( | ||||
|             50 => array( | ||||
|                 'key'   => 'chill_main_dummy_0', | ||||
|                 'label' => 'test0', | ||||
|                 'otherkey' => 'othervalue' | ||||
|                 ), | ||||
|             51 => array( | ||||
|                 'key'   => 'chill_main_dummy_1', | ||||
|                 'label' => 'test1', | ||||
|                 'helper'=> 'great helper' | ||||
|             ), | ||||
|             52 => array( | ||||
|                 'key'   => 'chill_main_dummy_2', | ||||
|                 'label' => 'test2' | ||||
|             )); | ||||
|          | ||||
|          | ||||
|         foreach ($expected as $order => $route ){ | ||||
|              | ||||
|         } | ||||
|          | ||||
|         //compare arrays | ||||
|         foreach($expected as $order => $route) { | ||||
|             //check the key are the one expected | ||||
|             $this->assertTrue(isset($routes[$order])); | ||||
|              | ||||
|             if (isset($routes[$order])){ #avoid an exception if routes with order does not exists | ||||
|                 //sort arrays. Order matters for phpunit::assertSame | ||||
|                 ksort($route); | ||||
|                 ksort($routes[$order]); | ||||
|                 $this->assertSame($route, $routes[$order]); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|   | ||||
							
								
								
									
										59
									
								
								src/Bundle/ChillMainBundle/chill.api.specs.yaml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										59
									
								
								src/Bundle/ChillMainBundle/chill.api.specs.yaml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,59 @@ | ||||
| --- | ||||
| openapi: "3.0.0" | ||||
| info: | ||||
|   version: "1.0.0" | ||||
|   title: "Chill api" | ||||
|   description: "Api documentation for chill. Currently, work in progress" | ||||
| servers: | ||||
|   - url: "/api" | ||||
|     description: "Your current dev server" | ||||
|  | ||||
| components: | ||||
|   parameters: | ||||
|     _format: | ||||
|       name: _format | ||||
|       in: path | ||||
|       required: true | ||||
|       schema: | ||||
|         type: string | ||||
|         enum: | ||||
|           - json | ||||
|  | ||||
| paths: | ||||
|   /1.0/search.json: | ||||
|     get: | ||||
|       summary: perform a search across multiple entities | ||||
|       tags: | ||||
|         - search | ||||
|         - person | ||||
|         - thirdparty | ||||
|       description: > | ||||
|         **Warning**: This is currently a stub (not really implemented | ||||
|  | ||||
|         The search is performed across multiple entities. The entities must be listed into  | ||||
|         `type` parameters. | ||||
|  | ||||
|         The results are ordered by relevance, from the most to the lowest relevant. | ||||
|  | ||||
|       parameters: | ||||
|         - name: q | ||||
|           in: query | ||||
|           required: true | ||||
|           description: the pattern to search | ||||
|           schema: | ||||
|             type: string | ||||
|         - name: type[] | ||||
|           in: query | ||||
|           required: true | ||||
|           description: the type entities amongst the search is performed | ||||
|           schema: | ||||
|             type: array | ||||
|             items: | ||||
|               type: string | ||||
|               enum: | ||||
|                 - person | ||||
|                 - thirdparty | ||||
|       responses: | ||||
|         200: | ||||
|           description: "OK" | ||||
|  | ||||
| @@ -62,5 +62,7 @@ module.exports = function(encore, entries) | ||||
|     buildCKEditor(encore); | ||||
|     encore.addEntry('ckeditor5', __dirname + '/Resources/public/modules/ckeditor5/index.js'); | ||||
|  | ||||
|     // Address | ||||
|     encore.addEntry('address', __dirname + '/Resources/public/vuejs/Address/index.js'); | ||||
|  | ||||
| }; | ||||
|   | ||||
| @@ -69,6 +69,13 @@ chill_main_search: | ||||
|     requirements: | ||||
|         _format: html|json | ||||
|  | ||||
| chill_main_search_global: | ||||
|     path: '/api/1.0/search.{_format}' | ||||
|     controller: Chill\MainBundle\Controller\SearchController::searchApi | ||||
|     format: 'json' | ||||
|     requirements: | ||||
|         _format: 'json' | ||||
|  | ||||
| chill_main_advanced_search: | ||||
|     path: /{_locale}/search/advanced/{name} | ||||
|     controller: Chill\MainBundle\Controller\SearchController::advancedSearchAction | ||||
| @@ -86,7 +93,3 @@ login_check: | ||||
|  | ||||
| logout: | ||||
|     path:    /logout | ||||
|  | ||||
| chill_main_test: | ||||
|     path: /{_locale}/main/test | ||||
|     controller: Chill\MainBundle\Controller\DefaultController::testAction | ||||
|   | ||||
| @@ -3,6 +3,18 @@ parameters: | ||||
|  | ||||
| services: | ||||
|  | ||||
|     Chill\MainBundle\Serializer\Normalizer\: | ||||
|         resource: '../Serializer/Normalizer' | ||||
|         autowire: true | ||||
|         tags: | ||||
|             - { name: 'serializer.normalizer', priority: 64 } | ||||
|  | ||||
|     Chill\MainBundle\Doctrine\Event\: | ||||
|         resource: '../Doctrine/Event/' | ||||
|         autowire: true | ||||
|         tags:  | ||||
|             - { name: 'doctrine.event_subscriber' } | ||||
|  | ||||
|     chill.main.helper.translatable_string: | ||||
|         class: Chill\MainBundle\Templating\TranslatableStringHelper | ||||
|         arguments: | ||||
|   | ||||
| @@ -16,6 +16,7 @@ services: | ||||
|             $searchProvider: '@chill_main.search_provider' | ||||
|             $translator: '@Symfony\Contracts\Translation\TranslatorInterface' | ||||
|             $paginatorFactory: '@Chill\MainBundle\Pagination\PaginatorFactory' | ||||
|             $searchApi: '@Chill\MainBundle\Search\SearchApi' | ||||
|         tags: ['controller.service_arguments'] | ||||
|  | ||||
|     Chill\MainBundle\Controller\PermissionsGroupController: | ||||
|   | ||||
| @@ -1,7 +1,8 @@ | ||||
| services: | ||||
|     Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader: | ||||
|         arguments: | ||||
|             $config: '%chill_main_crud_route_loader_config%' | ||||
|             $crudConfig: '%chill_main_crud_route_loader_config%' | ||||
|             $apiConfig:  '%chill_main_api_route_loader_config%' | ||||
|         tags: [ routing.loader ] | ||||
|  | ||||
|     Chill\MainBundle\CRUD\Resolver\Resolver: | ||||
| @@ -13,4 +14,4 @@ services: | ||||
|         arguments: | ||||
|             $resolver: '@Chill\MainBundle\CRUD\Resolver\Resolver' | ||||
|         tags: | ||||
|             - { name: twig.extension } | ||||
|             - { name: twig.extension } | ||||
|   | ||||
| @@ -23,6 +23,7 @@ services: | ||||
|         arguments: | ||||
|             - "@request_stack" | ||||
|             - "@doctrine.orm.entity_manager" | ||||
|             - "@chill.main.helper.translatable_string" | ||||
|         tags: | ||||
|             - { name: form.type, alias: select2_chill_country } | ||||
|  | ||||
| @@ -31,6 +32,7 @@ services: | ||||
|         arguments: | ||||
|             - "@request_stack" | ||||
|             - "@doctrine.orm.entity_manager" | ||||
|             - "@chill.main.helper.translatable_string" | ||||
|         tags: | ||||
|             - { name: form.type, alias: select2_chill_language } | ||||
|  | ||||
|   | ||||
| @@ -6,6 +6,7 @@ services: | ||||
|             - "@request_stack" | ||||
|             - "@router" | ||||
|             - "%chill_main.pagination.item_per_page%" | ||||
|  | ||||
|     Chill\MainBundle\Pagination\PaginatorFactory: '@chill_main.paginator_factory' | ||||
|              | ||||
|     chill_main.paginator.twig_extensions: | ||||
|   | ||||
| @@ -1,3 +1,10 @@ | ||||
| services: | ||||
|     chill_main.search_provider: | ||||
|         class: Chill\MainBundle\Search\SearchProvider | ||||
|         class: Chill\MainBundle\Search\SearchProvider | ||||
|  | ||||
|     Chill\MainBundle\Search\SearchProvider: '@chill_main.search_provider' | ||||
|  | ||||
|     Chill\MainBundle\Search\SearchApi: | ||||
|         arguments: | ||||
|           $em: '@Doctrine\ORM\EntityManagerInterface' | ||||
|           $search: '@Chill\MainBundle\Search\SearchProvider' | ||||
|   | ||||
							
								
								
									
										11
									
								
								src/Bundle/ChillMainBundle/config/services/serializer.yaml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								src/Bundle/ChillMainBundle/config/services/serializer.yaml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,11 @@ | ||||
| --- | ||||
| services: | ||||
|      | ||||
|     # note: the autowiring for serializers and normalizers is declared  | ||||
|     # into ../services.yaml | ||||
|  | ||||
|     Chill\MainBundle\Serializer\Normalizer\DoctrineExistingEntityNormalizer: | ||||
|         autowire: true | ||||
|         tags: | ||||
|             - { name: 'serializer.normalizer', priority: 8 } | ||||
|  | ||||
| @@ -0,0 +1,32 @@ | ||||
| <?php declare(strict_types=1); | ||||
|  | ||||
| namespace Chill\Migrations\Main; | ||||
|  | ||||
| use Doctrine\DBAL\Schema\Schema; | ||||
| use Doctrine\Migrations\AbstractMigration; | ||||
|  | ||||
| /** | ||||
|  * Create the postgis extension | ||||
|  */ | ||||
| final class Version20210414091001 extends AbstractMigration | ||||
| { | ||||
|     public function up(Schema $schema) : void | ||||
|     { | ||||
|         $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); | ||||
|  | ||||
|         $this->addSql('CREATE EXTENSION IF NOT EXISTS postgis;'); | ||||
|  | ||||
|     } | ||||
|  | ||||
|     public function down(Schema $schema) : void | ||||
|     { | ||||
|         $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); | ||||
|  | ||||
|         $this->addSql('DROP EXTENSION IF NOT EXISTS postgis;'); | ||||
|     } | ||||
|  | ||||
|     public function getDescription(): string | ||||
|     { | ||||
|         return "Enable the postgis extension in public schema"; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,50 @@ | ||||
| <?php | ||||
|  | ||||
| declare(strict_types=1); | ||||
|  | ||||
| namespace Chill\Migrations\Main; | ||||
|  | ||||
| use Doctrine\DBAL\Schema\Schema; | ||||
| use Doctrine\Migrations\AbstractMigration; | ||||
|  | ||||
| /** | ||||
|  * Add new fields to address, including a Point geometry field. | ||||
|  */ | ||||
| final class Version20210420115006 extends AbstractMigration | ||||
| { | ||||
|     public function getDescription() : string | ||||
|     { | ||||
|         return 'Add a Point data type and modify the Address entity'; | ||||
|     } | ||||
|  | ||||
|     public function up(Schema $schema) : void | ||||
|     { | ||||
|         $this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetaddress1 TO street;'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetaddress2 TO streetNumber;'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD floor VARCHAR(16) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD corridor VARCHAR(16) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD steps VARCHAR(16) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD buildingName VARCHAR(255) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD flat VARCHAR(16) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD distribution VARCHAR(255) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD extra VARCHAR(255) DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD validTo DATE DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD point geometry(POINT,4326) DEFAULT NULL'); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     public function down(Schema $schema) : void | ||||
|     { | ||||
|         $this->addSql('ALTER TABLE chill_main_address RENAME COLUMN street TO streetaddress1;'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetNumber TO streetaddress2;'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP floor'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP corridor'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP steps'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP buildingName'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP flat'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP distribution'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP extra'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP validTo'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP point'); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,33 @@ | ||||
| <?php | ||||
|  | ||||
| declare(strict_types=1); | ||||
|  | ||||
| namespace Chill\Migrations\Main; | ||||
|  | ||||
| use Doctrine\DBAL\Schema\Schema; | ||||
| use Doctrine\Migrations\AbstractMigration; | ||||
|  | ||||
| /** | ||||
|  * Add a AddressReference table for storing authoritative address data | ||||
|  */ | ||||
| final class Version20210503085107 extends AbstractMigration | ||||
| { | ||||
|     public function getDescription(): string | ||||
|     { | ||||
|         return 'Add a AddressReference table for storing authoritative address data'; | ||||
|     } | ||||
|  | ||||
|     public function up(Schema $schema): void | ||||
|     { | ||||
|         $this->addSql('CREATE SEQUENCE chill_main_address_reference_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); | ||||
|         $this->addSql('CREATE TABLE chill_main_address_reference (id INT NOT NULL, postcode_id INT DEFAULT NULL, refId VARCHAR(255) NOT NULL, street VARCHAR(255) DEFAULT NULL, streetNumber VARCHAR(255) DEFAULT NULL, municipalityCode VARCHAR(255) DEFAULT NULL, source VARCHAR(255) DEFAULT NULL, point geometry(POINT,4326) NOT NULL, PRIMARY KEY(id))'); | ||||
|         $this->addSql('CREATE INDEX IDX_CA6C1BD7EECBFDF1 ON chill_main_address_reference (postcode_id)'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address_reference ADD CONSTRAINT FK_CA6C1BD7EECBFDF1 FOREIGN KEY (postcode_id) REFERENCES chill_main_postal_code (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); | ||||
|     } | ||||
|  | ||||
|     public function down(Schema $schema): void | ||||
|     { | ||||
|         $this->addSql('DROP SEQUENCE chill_main_address_reference_id_seq CASCADE'); | ||||
|         $this->addSql('DROP TABLE chill_main_address_reference'); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,58 @@ | ||||
| <?php | ||||
|  | ||||
| declare(strict_types=1); | ||||
|  | ||||
| namespace Chill\Migrations\Main; | ||||
|  | ||||
| use Doctrine\DBAL\Schema\Schema; | ||||
| use Doctrine\Migrations\AbstractMigration; | ||||
|  | ||||
| /** | ||||
|  * Add linkedToThirdParty field to Address | ||||
|  */ | ||||
| final class Version20210505153727 extends AbstractMigration | ||||
| { | ||||
|     public function getDescription(): string | ||||
|     { | ||||
|         return 'Add linkedToThirdParty field to Address'; | ||||
|     } | ||||
|  | ||||
|     public function up(Schema $schema): void | ||||
|     { | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD linkedToThirdParty_id INT DEFAULT NULL'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address ADD CONSTRAINT FK_165051F6114B8DD9 FOREIGN KEY (linkedToThirdParty_id) REFERENCES chill_3party.third_party (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); | ||||
|         $this->addSql('CREATE INDEX IDX_165051F6114B8DD9 ON chill_main_address (linkedToThirdParty_id)'); | ||||
|         $this->addSql(' | ||||
|             CREATE TABLE chill_main_address_legacy AS | ||||
|             TABLE chill_main_address; | ||||
|         '); | ||||
|         $this->addSql(' | ||||
|             WITH hydrated_addresses AS ( | ||||
|                 SELECT *, rank() OVER (PARTITION BY pa_a.person_id ORDER BY validfrom) | ||||
|                 FROM chill_main_address AS aa JOIN chill_person_persons_to_addresses AS pa_a ON aa.id = pa_a.address_id | ||||
|             ) | ||||
|             UPDATE chill_main_address AS b | ||||
|             SET validto = ( | ||||
|                 SELECT validfrom - INTERVAL \'1 DAY\' | ||||
|                 FROM hydrated_addresses | ||||
|                 WHERE hydrated_addresses.id = ( | ||||
|                     SELECT a1.id | ||||
|                     FROM hydrated_addresses AS a1 JOIN hydrated_addresses AS a2 ON a2.person_id = a1.person_id AND a2.rank = (a1.rank-1) | ||||
|                     WHERE a2.id = b.id | ||||
|                 ) | ||||
|             ); | ||||
|         '); | ||||
|     } | ||||
|  | ||||
|     public function down(Schema $schema): void | ||||
|     { | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP CONSTRAINT FK_165051F6114B8DD9'); | ||||
|         $this->addSql('DROP INDEX IDX_165051F6114B8DD9'); | ||||
|         $this->addSql('ALTER TABLE chill_main_address DROP linkedToThirdParty_id'); | ||||
|         $this->addSql('DROP TABLE IF EXISTS chill_main_address_legacy'); | ||||
|         $this->addSql(' | ||||
|             UPDATE chill_main_address | ||||
|             SET validto = null; | ||||
|         '); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,175 @@ | ||||
| <?php | ||||
|  | ||||
| namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
| use Chill\MainBundle\CRUD\Controller\ApiController; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Symfony\Component\HttpFoundation\Response; | ||||
| use Chill\PersonBundle\Entity\AccompanyingPeriod; | ||||
| use Symfony\Component\HttpFoundation\Exception\BadRequestException; | ||||
| use Symfony\Component\EventDispatcher\EventDispatcherInterface; | ||||
| use Symfony\Component\Validator\Validator\ValidatorInterface; | ||||
| use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent; | ||||
| use Chill\PersonBundle\Entity\Person; | ||||
| use Chill\ThirdPartyBundle\Entity\ThirdParty; | ||||
| use Symfony\Component\Serializer\Exception\RuntimeException; | ||||
| use Chill\PersonBundle\Entity\AccompanyingPeriod\Resource; | ||||
| use Chill\PersonBundle\Entity\AccompanyingPeriod\Comment; | ||||
| use Chill\PersonBundle\Entity\SocialWork\SocialIssue; | ||||
| use Chill\MainBundle\Entity\Scope; | ||||
| use Symfony\Component\Workflow\Registry; | ||||
|  | ||||
| class AccompanyingCourseApiController extends ApiController | ||||
| { | ||||
|     protected EventDispatcherInterface $eventDispatcher; | ||||
|  | ||||
|     protected ValidatorInterface $validator; | ||||
|  | ||||
|     private Registry $registry; | ||||
|  | ||||
|     public function __construct( | ||||
|         EventDispatcherInterface $eventDispatcher, | ||||
|         ValidatorInterface $validator, | ||||
|         Registry $registry | ||||
|     ) { | ||||
|         $this->eventDispatcher = $eventDispatcher; | ||||
|         $this->validator = $validator; | ||||
|         $this->registry = $registry; | ||||
|     } | ||||
|  | ||||
|     public function confirmApi($id, Request $request, $_format): Response | ||||
|     { | ||||
|         /** @var AccompanyingPeriod $accompanyingPeriod */  | ||||
|         $accompanyingPeriod = $this->getEntity('participation', $id, $request); | ||||
|  | ||||
|         $this->checkACL('confirm', $request, $_format, $accompanyingPeriod); | ||||
| $workflow = $this->registry->get($accompanyingPeriod); | ||||
|  | ||||
|         if (FALSE === $workflow->can($accompanyingPeriod, 'confirm')) { | ||||
|             throw new BadRequestException('It is not possible to confirm this period'); | ||||
|         } | ||||
|  | ||||
|         $workflow->apply($accompanyingPeriod, 'confirm'); | ||||
|  | ||||
|         $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|         return $this->json($accompanyingPeriod, Response::HTTP_OK, [], [ | ||||
|             'groups' => [ 'read' ] | ||||
|         ]); | ||||
|     } | ||||
|      | ||||
|     public function participationApi($id, Request $request, $_format) | ||||
|     { | ||||
|         /** @var AccompanyingPeriod $accompanyingPeriod */  | ||||
|         $accompanyingPeriod = $this->getEntity('participation', $id, $request); | ||||
|         $person = $this->getSerializer() | ||||
|             ->deserialize($request->getContent(), Person::class, $_format, []); | ||||
|  | ||||
|         if (NULL === $person) { | ||||
|             throw new BadRequestException('person id not found'); | ||||
|         } | ||||
|  | ||||
|         // TODO add acl | ||||
|         // | ||||
|         $this->onPostCheckACL('participation', $request, $_format, $accompanyingPeriod); | ||||
|  | ||||
|         switch ($request->getMethod()) { | ||||
|             case Request::METHOD_POST: | ||||
|                 $participation = $accompanyingPeriod->addPerson($person); | ||||
|                 break; | ||||
|             case Request::METHOD_DELETE: | ||||
|                 $participation = $accompanyingPeriod->removePerson($person); | ||||
|                 break; | ||||
|             default: | ||||
|                 throw new BadRequestException("This method is not supported"); | ||||
|         } | ||||
|  | ||||
|         $errors = $this->validator->validate($accompanyingPeriod); | ||||
|  | ||||
|         if ($errors->count() > 0) { | ||||
|             // only format accepted | ||||
|             return $this->json($errors, 422); | ||||
|         } | ||||
|  | ||||
|         $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|         return $this->json($participation, 200, [], ['groups' => [ 'read' ]]); | ||||
|     } | ||||
|  | ||||
|     public function resourceApi($id, Request $request, string $_format): Response | ||||
|     { | ||||
|         return $this->addRemoveSomething('resource', $id, $request, $_format, 'resource', Resource::class); | ||||
|     } | ||||
|  | ||||
|     public function scopeApi($id, Request $request, string $_format): Response | ||||
|     { | ||||
|         return $this->addRemoveSomething('scope', $id, $request, $_format, 'scope', Scope::class, [ 'groups' => [ 'read' ] ]); | ||||
|     } | ||||
|  | ||||
|     public function commentApi($id, Request $request, string $_format): Response | ||||
|     { | ||||
|         return $this->addRemoveSomething('comment', $id, $request, $_format, 'comment', Comment::class); | ||||
|     } | ||||
|  | ||||
|     public function socialIssueApi($id, Request $request, string $_format): Response | ||||
|     { | ||||
|         return $this->addRemoveSomething('socialissue', $id, $request, $_format, 'socialIssue', SocialIssue::class, [ 'groups' => [ 'read' ] ]); | ||||
|     } | ||||
|  | ||||
|     public function requestorApi($id, Request $request, string $_format): Response | ||||
|     { | ||||
|         /** @var AccompanyingPeriod $accompanyingPeriod */ | ||||
|         $action = 'requestor'; | ||||
|         $accompanyingPeriod = $this->getEntity($action, $id, $request); | ||||
|         // a requestor may be a person or a thirdParty | ||||
|  | ||||
|         $this->checkACL($action, $request, $_format, $accompanyingPeriod); | ||||
|         $this->onPostCheckACL($action, $request, $_format, $accompanyingPeriod); | ||||
|  | ||||
|         if (Request::METHOD_DELETE === $request->getMethod()) { | ||||
|             $accompanyingPeriod->setRequestor(NULL); | ||||
|         } elseif (Request::METHOD_POST === $request->getMethod()) { | ||||
|             $requestor = null; | ||||
|             $exceptions = []; | ||||
|             foreach ([Person::class, ThirdParty::class] as $class) { | ||||
|                 try { | ||||
|                     $requestor = $this->getSerializer() | ||||
|                         ->deserialize($request->getContent(), $class, $_format, []); | ||||
|                 } catch (RuntimeException $e) { | ||||
|                     $exceptions[] = $e; | ||||
|                 }  | ||||
|             } | ||||
|             if ($requestor === null) { | ||||
|                 throw new BadRequestException('Could not find any person or requestor', 0, $exceptions[0]); | ||||
|             } | ||||
|  | ||||
|             $accompanyingPeriod->setRequestor($requestor); | ||||
|         } else { | ||||
|             throw new BadRequestException('method not supported'); | ||||
|         } | ||||
|  | ||||
|         $errors = $this->validator->validate($accompanyingPeriod); | ||||
|  | ||||
|         if ($errors->count() > 0) { | ||||
|             // only format accepted | ||||
|             return $this->json($errors, 422); | ||||
|         } | ||||
|  | ||||
|         $this->getDoctrine()->getManager()->flush(); | ||||
|  | ||||
|         return $this->json($accompanyingPeriod->getRequestor(), 200, [], ['groups' => [ 'read']]); | ||||
|     } | ||||
|  | ||||
|     protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response | ||||
|     { | ||||
|         $this->eventDispatcher->dispatch( | ||||
|             AccompanyingPeriodPrivacyEvent::ACCOMPANYING_PERIOD_PRIVACY_EVENT, | ||||
|             new AccompanyingPeriodPrivacyEvent($entity, [ | ||||
|                 'action' => $action, | ||||
|                 'request' => $request->getMethod() | ||||
|             ]) | ||||
|         ); | ||||
|  | ||||
|         return null; | ||||
|     } | ||||
| } | ||||
| @@ -4,17 +4,22 @@ namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
| use Chill\PersonBundle\Entity\AccompanyingPeriod; | ||||
| use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation; | ||||
| use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent; | ||||
| use Chill\PersonBundle\Entity\Person; | ||||
| use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter; | ||||
| use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; | ||||
| use Symfony\Bundle\FrameworkBundle\Controller\Controller; | ||||
| use Symfony\Component\HttpFoundation\JsonResponse; | ||||
| use Symfony\Component\HttpFoundation\Response; | ||||
| use Symfony\Component\HttpFoundation\Exception\BadRequestException; | ||||
| use Symfony\Component\Routing\Annotation\Route; | ||||
| use Symfony\Component\Serializer\Encoder\JsonEncoder; | ||||
| use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; | ||||
| use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; | ||||
| use Symfony\Component\Serializer\Serializer; | ||||
| use Symfony\Component\Serializer\SerializerInterface; | ||||
| use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; | ||||
| use Symfony\Component\HttpFoundation\Request; | ||||
| use Symfony\Component\Validator\Validator\ValidatorInterface; | ||||
|  | ||||
| /** | ||||
|  * Class AccompanyingCourseController | ||||
| @@ -23,6 +28,56 @@ use Symfony\Component\Serializer\SerializerInterface; | ||||
|  */ | ||||
| class AccompanyingCourseController extends Controller | ||||
| { | ||||
|     protected SerializerInterface $serializer; | ||||
|  | ||||
|     protected EventDispatcherInterface $dispatcher; | ||||
|  | ||||
|     protected ValidatorInterface $validator; | ||||
|  | ||||
|     public function __construct( | ||||
|         SerializerInterface $serializer, | ||||
|         EventDispatcherInterface $dispatcher, | ||||
|         ValidatorInterface $validator | ||||
|     ) { | ||||
|         $this->serializer = $serializer; | ||||
|         $this->dispatcher = $dispatcher; | ||||
|         $this->validator = $validator; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @Route("/{_locale}/person/parcours/new", name="chill_person_accompanying_course_new") | ||||
|      */ | ||||
|     public function newAction(Request $request): Response | ||||
|     { | ||||
|         $period = new AccompanyingPeriod(); | ||||
|         $em = $this->getDoctrine()->getManager(); | ||||
|  | ||||
|         if ($request->query->has('person_id')) { | ||||
|             $personIds = $request->query->get('person_id'); | ||||
|  | ||||
|             if (FALSE === \is_array($personIds)) { | ||||
|                 throw new BadRequestException("person_id parameter should be an array"); | ||||
|             } | ||||
|  | ||||
|             foreach ($personIds as $personId) { | ||||
|                 $person = $em->getRepository(Person::class)->find($personId); | ||||
|                 if (NULL !== $person) { | ||||
|                     $period->addPerson($person); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         $this->denyAccessUnlessGranted(AccompanyingPeriodVoter::SEE, $period); | ||||
|  | ||||
|         $em->persist($period); | ||||
|         $em->flush(); | ||||
|  | ||||
|         return $this->redirectToRoute('chill_person_accompanying_course_show', [ | ||||
|             'accompanying_period_id' => $period->getId() | ||||
|         ]); | ||||
|           | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Homepage of Accompanying Course section | ||||
|      * | ||||
| @@ -67,46 +122,4 @@ class AccompanyingCourseController extends Controller | ||||
|         ]); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Sérialise temporairement quelques données pour donner à manger au composant vuejs | ||||
|      * @Route( | ||||
|      *     "/{_locale}/api/parcours/{accompanying_period_id}/show", | ||||
|      *     name="chill_person_accompanying_course_api_show") | ||||
|      * @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"}) | ||||
|      * @param SerializerInterface $serializer | ||||
|      */ | ||||
|     public function showAPI(AccompanyingPeriod $accompanyingCourse): Response | ||||
|     { | ||||
|         $persons = []; | ||||
|         foreach ($accompanyingCourse->getParticipations() as $k => $participation ) { | ||||
|             /** | ||||
|              * @var AccompanyingPeriodParticipation $participation | ||||
|              * @var Person $person | ||||
|              */ | ||||
|             $person = $participation->getPerson(); | ||||
|             $persons[$k] = [ | ||||
|                 'id' => $person->getId(), | ||||
|                 'firstname' => $person->getFirstName(), | ||||
|                 'lastname' => $person->getLastName(), | ||||
|                 'email' => $person->getEmail(), | ||||
|                 'phone' => $person->getPhonenumber(), | ||||
|                 'startdate' => ($participation->getStartDate()) ? $participation->getStartDate()->format('Y-m-d') : null, | ||||
|                 'enddate' => ($participation->getEndDate()) ? $participation->getEndDate()->format('Y-m-d') : null | ||||
|             ]; | ||||
|         } | ||||
|         $data = [ | ||||
|             'id' => $accompanyingCourse->getId(), | ||||
|             'remark' => $accompanyingCourse->getRemark(), | ||||
|             'closing_motive' => $accompanyingCourse->getClosingMotive() ? $accompanyingCourse->getClosingMotive()->getName()['fr'] : null, | ||||
|             'opening_date' => ($accompanyingCourse->getOpeningDate()) ? $accompanyingCourse->getOpeningDate()->format('Y-m-d') : null, | ||||
|             'closing_date' => ($accompanyingCourse->getClosingDate()) ? $accompanyingCourse->getClosingDate()->format('Y-m-d') : null, | ||||
|             'persons' => $persons | ||||
|         ]; | ||||
|  | ||||
|         $serialized = \json_encode($data); | ||||
|         $response = new Response($serialized); | ||||
|         $response->headers->set('Content-Type', 'application/json'); | ||||
|         return $response; | ||||
|     } | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -0,0 +1,30 @@ | ||||
| <?php | ||||
| /* | ||||
|  * Copyright (C) 2015-2021 Champs-Libres Coopérative <info@champs-libres.coop> | ||||
|  * | ||||
|  * This program is free software: you can redistribute it and/or modify | ||||
|  * it under the terms of the GNU Affero General Public License as published by | ||||
|  * the Free Software Foundation, either version 3 of the License, or | ||||
|  * (at your option) any later version. | ||||
|  * | ||||
|  * This program is distributed in the hope that it will be useful, | ||||
|  * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|  * GNU Affero General Public License for more details. | ||||
|  * | ||||
|  * You should have received a copy of the GNU Affero General Public License | ||||
|  * along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
|  */ | ||||
| namespace Chill\PersonBundle\Controller; | ||||
|  | ||||
| use Symfony\Bundle\FrameworkBundle\Controller\Controller; | ||||
| use Symfony\Component\HttpFoundation\JsonResponse; | ||||
|  | ||||
|  | ||||
| class ApiPersonController extends Controller | ||||
| { | ||||
|     public function viewAction($id, $_format)  | ||||
|     { | ||||
|          | ||||
|     } | ||||
| } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user