Giter Site home page Giter Site logo

sylius / syliusresourcebundle Goto Github PK

View Code? Open in Web Editor NEW
211.0 29.0 155.0 5.94 MB

Simpler CRUD for Symfony applications

Home Page: https://sylius.com

License: MIT License

PHP 98.94% Twig 1.01% Dockerfile 0.04% Makefile 0.01%
sylius resource hacktoberfest

syliusresourcebundle's Introduction

SyliusResourceBundle

Easy CRUD and persistence for Symfony apps.

During our work on Sylius, we noticed a lot of duplicated code across all controllers. We started looking for good solution of the problem. We're not big fans of administration generators (they're cool, but not for our usecase!) - we wanted something simpler and more flexible.

Another idea was to not limit ourselves to one persistence backend. Initial implementation included custom manager classes, which was quite of overhead, so we decided to simply stick with Doctrine Common Persistence interfaces. If you are using Doctrine ORM or any of the ODM's, you're already familiar with those concepts. Resource bundle relies mainly on ObjectManager and ObjectRepository interfaces.

The last annoying problem this bundle is trying to solve, is having separate "backend" and "frontend" controllers, or any other duplication for displaying the same resource, with different presentation (view). We also wanted an easy way to filter some resources from list, sort them or display by id, slug or any other criteria - without having to defining another super simple action for that purpose.

If these are issues you're struggling with, this bundle may be helpful!

Please note that this bundle is not an admin generator. It won't create forms, filters and grids for you. It only provides format agnostic controllers as a foundation to build on, with some basic sorting and filter mechanisms.

Supported branches

  • 1.10 (v1.10.* versions) - bug fixes and improvements of existing features
  • 1.11 (next version - v1.11.0) - new features and bigger changes

Beware! There is no main or master branch on the repository. You should always open a Pull Request to the branch named as the minor version on which your changes should be applied.

Sylius

Sylius Logo.

Sylius is an Open Source eCommerce solution built from decoupled components with powerful API and the highest quality code. Read more on sylius.com.

Development

Build:

docker compose up -d --build

Test:

make test

Documentation

Documentation is available in the docs folder.

Contributing

This page contains all the information about contributing to Sylius.

Follow Sylius' Development

If you want to keep up with the updates and latest features, follow us on the following channels:

Bug tracking

Sylius uses GitHub issues. If you have found bug, please create an issue.

MIT License

License can be found here.

Authors

The bundle was originally created by Paweł Jędrzejewski. See the list of contributors.

syliusresourcebundle's People

Contributors

amenophis avatar aramalipoor avatar arminek avatar arnolanglade avatar bendavies avatar cdaguerre avatar dannyvw avatar dantleech avatar dependabot-preview[bot] avatar ferror avatar gperdomor avatar gsadee avatar isometriks avatar ivannis avatar lchrusciel avatar liverbool avatar loic425 avatar mbabker avatar michalmarcinkowski avatar noresponsemate avatar pamil avatar pjedrzejewski avatar rafikooo avatar sirdomin avatar stloyd avatar strontium-90 avatar tuka217 avatar umpirsky avatar winzou avatar zales0123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

syliusresourcebundle's Issues

Conflict with FOSRestBundle on 2.2

The current version of fos-rest-bundle (0.11.@dev) is in conflict with the Symfony 2.2 RouteCollection update. Maybe an update of composer.json can be resolved this conflict (use the 0.13.@dev version of rest-bundle instead of 0.11.*@dev)

Error parsing 'templates' property in routing.yml for new Resource

This is roughly what I've been following and this specific section is what I was comparing my routing.yml to - http://docs.sylius.org/en/latest/bundles/SyliusResourceBundle/routing.html#using-custom-templates

The line templates: AppTeamBundle:Team/Crud seems to be getting parsed incorrectly. This code/config is from a Bundle which was setup on a prior version ~ 3 months ago and works correctly on the older project (1.0.0-beta.2) still.

When trying to install it on a new project (1.0.0-beta.3) I get an error:

The file "alias: app_team.team_member
section: admin
templates: AppTeamBundle:Team" does not exist in /var/www/vhosts/example/src/App/TeamBundle/Resources/config/routing.yml (which is being imported from "/var/www/vhosts/example/app/config/routing.yml").

I tried a few bits but the actually fix is just swapping the / for a \ so it becomes;
templates: AppTeamBundle:Team\Crud.

To me it feels like this is a bug with the parsing rather than a valid change to the setup which just hasn't been represented in the documentation.

The routing config was originally like this;

app_team_admin:
    resource: |
        alias: app_team.team_member
        section: admin
        templates: AppTeamBundle:Team/Crud
        except: ['show']
        redirect: update
        grid: app_team_admin
        vars:
            all:
                subheader: app_team.ui.team_member # define a translation key for your entity subheader
            index:
                icon: 'users' # choose an icon that will be displayed next to the subheader
    type: sylius.resource
    prefix: /admin

Already transitioned resource transition

Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? yes
Sylius version 1.1.*

Steps to reproduce this scenario:

  1. create custom order
  2. as admin1 open detail of the order above
  3. open anonymous tab in browser, login as admin2 and open detail of the order above
  4. as admin2 in anonymous tab click on cancel order
  5. as admin1 in normal tab click on cancel order - BadRequestHttpException - Sylius/Bundle/ResourceBundle/Controller/ResourceController.php (line 556)

I think this is not common use case. But we have many admins and it already happened multiple times, that admin1 and admin2 have displayed order detail at the same time without refreshing the page.

Issue using Sonata User

Hi guys, I'm building an app with Sylius, everything was working fine before recent updates. My problem now comes from the events you implemented in the resource bundle. In the file LoadMetaDataSubscriber.php, on line 70:

        $eventArgs->getEntityManager()->getConfiguration()->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata);

It gaves me an error on SonataUserBundle:

[Doctrine\Common\Persistence\Mapping\MappingException]
The class 'Sonata\UserBundle\Model\User' was not found in the chain configured namespaces FOS\UserBundle\Entity, Sonata\MediaBundle\Entity, Application\Sonata\MediaBundle\Entity, Sonata\UserBundle\Entity, Application\Sonata\UserBundle\Entity, blanked\SiteBundle\Entity, Sylius\Bundle\CartBundle\Entity, Sylius\Bundle\MoneyBundle\Model, Sylius\Bundle\SalesBundle\Model, Sylius\Bundle\CartBundle\Model, Sylius\Bundle\InventoryBundle\Model

Apparently sylius is searching for Sonata\UserBundle\Model\User and I am extending Sonata\UserBundle\Entity\User.
Do I did something wrong? maybe on configuring sylius?

Thanks for help

Controller deprecation

The "Sylius\Bundle\ResourceBundle\Controller\ResourceController" class extends "Symfony\Bundle\FrameworkBundle\Controller\Controller" that is deprecated since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

doctrine.resolve_target_entities fails with sylius resource class parameter

Sylius version affected: 1.1.8 and higher

Since this version the following was introduced:

It's no longer required to put Sylius bundles before Doctrine Bundle (#9527)

Then having DoctrineBundle loaded before SyliusResourceBundle fails the following config definition:

doctrine:
    orm:
        resolve_target_entities:
            Sylius\Component\Core\Model\ShopUserInterface: '%sylius.model.shop_user.class%'

...since %sylius.model.shop_user.class% is not defined.

Any solutions?

Sorting links are broken when a defaut sorting config is defined for the resource

For example, in the product BO. With the default resource config no sorting links appear. With this config, it works :

sylius_backend_product_index:
    pattern: /
    methods: [GET]
    defaults:
        _controller: sylius.controller.product:indexAction
        _sylius:
            template: SyliusWebBundle:Backend/Product:index.html.twig
            method: createFilterPaginator
            arguments: [$criteria]
        criteria: {}

Doctrine class metadata not found for extended interface

Sylius version affected: 1.x

Description
For any resource, it should be possible to get the Doctrine class metadata using any of the interfaces for the resource defined at the component / core / app level.

Steps to reproduce

  1. Create a new project from Sylius-Standard.
  2. Try to get Doctrine class metadata using Sylius\Component\Core\Model\ProductInterface.

Possible Solution
I think there is a design problem.

If you look at https://github.com/Sylius/SyliusResourceBundle/blob/v1.5.0/src/Bundle/DependencyInjection/Compiler/DoctrineTargetEntitiesResolverPass.php

it does not go up the inheritance chain - and it's not safe to do so, as we can't tell which interfaces should be mapped, and which should not. So if we set interface to a child interface, things would stop working if you try using the parent interface(s).

What is actually expected is that all of the interfaces should work, e.g.:

  • Sylius\Component\Product\Model\ProductInterface
  • Sylius\Component\Core\Model\ProductInterface
  • App\Model\ProductInterface (for example)

So we need a way to map multiple interfaces.

Configuration override for ressource

Sylius version affected: 1.7.0 (probably all)

Description
Configuration at project level should prevail over configuration at plugin level.

Steps to reproduce

  1. Install Sylius/AdminOrderCreationPlugin
php bin/console sylius:debug:resource sylius.customer
+--------------------+-----------------------------------------------------------------+
| name               | customer                                                        |
| application        | sylius                                                          |
| driver             | doctrine/orm                                                    |
| classes.model      | App\Entity\Customer\Customer                                    |
| classes.repository | Sylius\AdminOrderCreationPlugin\Doctrine\ORM\CustomerRepository |
| classes.interface  | Sylius\Component\Customer\Model\CustomerInterface               |
| classes.controller | Sylius\Bundle\ResourceBundle\Controller\ResourceController      |
| classes.factory    | Sylius\Component\Resource\Factory\Factory                       |
| classes.form       | Sylius\Bundle\CustomerBundle\Form\Type\CustomerType             |
+--------------------+-----------------------------------------------------------------+

Repository used is : Sylius\AdminOrderCreationPlugin\Doctrine\ORM\CustomerRepository

  1. Create a CustomerRepository in the projet.
    And configure your ressource (in config/packages/_sylius.yaml) :
sylius_customer:
    resources:
        customer:
            classes:
                model: App\Entity\Customer\Customer
                repository: App\Entity\Customer\CustomerRepository

Then

php bin/console sylius:debug:resource sylius.customer
+--------------------+-----------------------------------------------------------------+
| name               | customer                                                        |
| application        | sylius                                                          |
| driver             | doctrine/orm                                                    |
| classes.model      | App\Entity\Customer\Customer                                    |
| classes.repository | Sylius\AdminOrderCreationPlugin\Doctrine\ORM\CustomerRepository |
| classes.interface  | Sylius\Component\Customer\Model\CustomerInterface               |
| classes.controller | Sylius\Bundle\ResourceBundle\Controller\ResourceController      |
| classes.factory    | Sylius\Component\Resource\Factory\Factory                       |
| classes.form       | Sylius\Bundle\CustomerBundle\Form\Type\CustomerType             |
+--------------------+-----------------------------------------------------------------+

Question
Do you think it's a bug or I configured something wrong?

Thank you in advance for your help.

[DX] Making API tests more thourough

The API test of this plugin are very basic. This means that the code behind it can change without anyone noticing one thing that definitely needs to be fixed is that most of the tests only test for a response code and not for the response itself. Which leads to endpoints that should return something return an empty response but the response code is fine so nobody notices it.

Remove FosRestBundle and BazingaHateoasBundle dependency.

Reason 1

The two bundles are very usefull to build RESTfull API via HAL, I also like to support JSONAPI, so I suggest move they into a new package, maybe named as HAL extension for SyliusResourceBundle.

Reason 2

I'd like transform my entity to json using fractal instead of jmsserializer.

even though jmsserializer is flexiable and powerful , but it makes my API not stable enough, because they share the same metadata, for example, someone adds a 'roles' property to my user class within 'Default' groups.

Acme\Component\User\Model\User:
    exclusion_policy: ALL
    xml_root_name: xiaolvmo_user
    properties:
        id:
            expose: true
            type: integer
            groups: [Default]
        username:
            expose: true
            type: string
            groups: [Default]
        roles:
            expose: true
            type: ArrayCollection<Acme\Component\User\Model\Role>
            groups: [Default]

if Order also has user relation, then it will output roles, which may be not what need. serializing the roles property may trigger a doctrine/orm lazy loading, which hurt performance. so the API is very fragile because of jmsserializer.

[Enhancement] adding a special filter criteria : _app.user

Hi guys,

While coding the my account order section, I'm facing a problem. I need to filter orders that belongs to the current user. Of course, I could do it by writing a custom action in a controller... But the listAction of the ResourceBundle does 90% of what I need, except filtering orders with the current logged user.

Could we introduce a special criteria for filtering a resources linked to the current user ? Does it make sense in this bundle ?

What I need would be something like

sylius_account_order_index:
    pattern: /account/orders
    methods: [GET]
    defaults:
        _controller: app.controller.order:indexAction
        _sylius:
            criteria:
                user: _app.user

Call to a member function implementsInterface() on null

Description

bin/console doctrine:mapping:convert xml config/doctrine
Symfony\Component\Debug\Exception\FatalThrowableError {#1527
  -originalClassName: "Error"
  #message: "Call to a member function implementsInterface() on null"
  #code: 0
  #file: "vendor/sylius/resource-bundle/src/Bundle/EventListener/AbstractDoctrineSubscriber.php"
  #line: 38
  #severity: E_ERROR
  trace: {
    vendor/sylius/resource-bundle/src/Bundle/EventListener/AbstractDoctrineSubscriber.php:38 { …}
    vendor/sylius/resource-bundle/src/Bundle/EventListener/ORMMappedSuperClassSubscriber.php:86 { …}
    vendor/sylius/resource-bundle/src/Bundle/EventListener/ORMMappedSuperClassSubscriber.php:40 { …}
    vendor/symfony/doctrine-bridge/ContainerAwareEventManager.php:58 { …}
    vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:242 { …}
    vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:306 { …}
    vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78 { …}
    vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:193 { …}
    vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:91 { …}
    vendor/doctrine/orm/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php:113 { …}
    vendor/doctrine/doctrine-bundle/Command/Proxy/ConvertMappingDoctrineCommand.php:37 { …}
    vendor/symfony/console/Command/Command.php:255 { …}
    vendor/symfony/console/Application.php:1019 { …}
    vendor/symfony/framework-bundle/Console/Application.php:97 { …}
    vendor/symfony/console/Application.php:271 { …}
    vendor/symfony/framework-bundle/Console/Application.php:83 { …}
    vendor/symfony/console/Application.php:147 { …}
    bin/console:38 {
      › $application = new Application($kernel);
      › $application->run($input);
      › 
      arguments: {
        $input: Symfony\Component\Console\Input\ArgvInput {#4 …}
      }
    }
  }
}

return $metadata->getReflectionClass()->implementsInterface(ResourceInterface::class);

Steps to reproduce
Run bin/console doctrine:mapping:convert xml config/doctrine in a Sylius Standard application

Possible Solution
Add this line

$parentMetadata->wakeupReflection($this->getReflectionService());
to
private function unsetAssociationMappings(ClassMetadataInfo $metadata): void
{
/** @psalm-suppress InvalidArgument */
if (false === $this->isResource($metadata)) {

API Bundle: PUT should respond with 201 + create a resource if resource not found

Sylius version affected: 1.x.x

Description
Currently if you try to PUT some resource that doesn't yet exists, e.g. PUT /api/v1/products/notYetExistingProduct you'll get a 404 response and nothing will be created.
I would expect 201 + creation of the new resource.

It's especially important when creating a sync script with some external catalog. Currently I have to do two requests per each product: first try to PUT, if 404 then POST.

Steps to reproduce
PUT /api/v1/products/notYetExistingProduct

[Doc][WIP] Request configuration reference

Right know the documentation includes reference for resource configuration and routing generation, but not for request configuration of individual routes.
Some options are mentioned on the action specific pages, like show, index, create, update, delete, but these do not cover all available options.
I will compile the list of all available options for reference, but the effort can be extended to cover these options individually with details and examples.

[Question] about Rest integration

Hi,
we are currently evaluating ResourceBundle for one of our projects.
As long as ResourceController already extends FoSRestBundle , is it already possible to use rest routes on a resource service controller ?

I've tried to expose a simple controller but on index action Serializer complains about resources ( Logger, PagerFanta, etc. ) , is it an already designed use case and is there already some example code ?

Thanks in advance

xavier

Only annotation mapping is supported by make:entity

Sylius version affected: 1.6.5 sylius/sylius-standard

When i execute this command :
php bin/console make:entity --no-debug
or
php bin/console make:entity

i've got this error:

Class name of the entity to create or update (e.g. VictoriousJellybean):
 > test

 created: src/Entity/Test.php
 created: src/Repository/TestRepository.php

                                                                                                                        
 [ERROR] Only annotation mapping is supported by make:entity, but the <info>App\Entity\Test</info> class uses a         
         different format. If you would like this command to generate the properties & getter/setter methods, add your  
         mapping configuration, and then re-run this command with the <info>--regenerate</info> flag. 

I fix with my hack : #103
but it's not working now... :(

[Enhancement] Handle stopPropagation in ResourceController.php for pre_* events

Do you think it can be possible to handle stopPropagation in ResourceController.php for pre_* events ?

I need this for exemple when i need to check a user quota before add an new item.
I will put my event that check quota with a lower prority (execute before) and stop propagation inside if the quota check get error.

I can add it like explained here : http://symfony.com/doc/current/components/event_dispatcher/introduction.html#event-dispatcher-event-propagation

Do you think this is needed for Sylius uses ??

LogicException when submitting invalid (empty) fields for resource creation

When I make a POST request with invalid POST data to /LOCALE/account/address-book/add, I'm getting a 500 response and a LogicException saying "Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid().".

This appears to be caused by line 188 in ResourceController.php, which reads as follows:

if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

Is there a reason why the isSubmitted() check is not performed here?

Getting resources via criterias and findBy

I tried to use findBy instead of createFilterPaginator in the product backend. Here is my conf :

sylius_backend_product_index:
    pattern: /
    methods: [GET]
    defaults:
        _controller: sylius.controller.product:indexAction
        _sylius:
            template: SyliusWebBundle:Backend/Product:index.html.twig
            paginate: false
            method: findBy
            arguments: [$criteria, $sorting]
        criteria: {}
        sorting: { createdAt: desc }

When submitting a request to findBy via the product filter form, I get the following exception :

[Semantical Error] line 0, col 107 near 'sku = :sku ORDER': Error: Class Sylius\Bundle\CoreBundle\Entity\Product has no field or association named sku 

It seems it is nearly impossible to inject services into controller that extends ResourceController in Symfony 4.3+

I am using Symfony 4.3.3 and Sylius 1.5.2.

public function showAction(Request $request, TheServiceINeed $service): Response

// This is not allowed.
// Warning: Declaration of ProductController::showAction(Request $request, TheServiceINeed $service): Response should be compatible with ResourceController::showAction(Request $request): Response

I cannot add new arguments to constructor, otherwise

Too few arguments to function My\Controller\ProductController::__construct(), 17 passed in
/Users/me/Sites/sylius-app/var/cache/dev/ContainerEReeqxC/getSylius_Controller_ProductService.php 
on line 26 and exactly 21 expected

And of course: $this->get('my_service');, is not preferred anymore

[Enhancement] Event on create / update / delete

I want to implement a new event, which take resource as subject, at the beginning of createAction, updateAction and deleteAction to allow developper to make some tests before and throw a 404, or a redirect with a flash if the test is not conclusive.

Is it OK for you ?

Resource Bundle doesn't work with doctrine entities

Given the following configuration

sylius_resource:
    app.store:
        classes:
            model: 'App\Entity\Store'
            factory: 'App\Factory\Store'
            repository: 'App\Repository\StoreRepository'

On the update action it loads the entity through a doctrine mapping and returns the proxy object with which it then tries to construct a default form type. For this it tries to load the model but fails because for the Proxy class Proxies\__CG__\App\Entity\Store there is no model registered. In Sylius this problem doesn't seem to show up because it takes the data_class from the form which is set in most cases.

Is this correct or is some other part of the Sylius magic failing because I am testing this when it is not part of a Sylius project.

Cache clear fails when Doctrine ORM is not present.

Sylius version affected: 1.x.y

Description
When adding Sylius resource bundle on a symfony/skeleton
Cache clear fails with message:

The doctrine/orm package is required when the doctrine.orm config is set. 

Steps to reproduce

$ symfony new acme --version="^4.4"
$ (cd acme && composer require sylius/resource-bundle)

Possible Solution

1/ Improve dependency injection to make it optional.
2/ Move doctrine/orm from dev packages to prod packages.

[Enhancement] Configuration / ParametersParser as Service

Hi,
Actually, Configuration instance is created into ResourceController constructor.

What do you think to create automatically one service for each controller ?

Loading process can be done just one time into constructor, instead of each time it is called into the controller.

The Configuration can be injected into the controller.

Maybe we can declare ParametersParser as service, and inject it into Configuration ?

Any opinion about this ?

Class 'Webmozart\Assert\Assert' not found

Sylius version affected: 1.6.4

Description
When I install SyliusResourceBundle using composer install --no-dev, I have this error:
Attempted to load class "Assert" from namespace "Webmozart\Assert" in ORMMappedSuperClassSubscriber.php line 52.

Steps to reproduce

  • Install a new Symfony web project: composer create-project symfony/website-skeleton:^3.0 test-resource-bundle
  • Go to test-resource-bundle and add SyliusResourceBundle: composer require sylius/resource-bundle
  • Configure an entity following the official documentation https://github.com/Sylius/SyliusResourceBundle/blob/157545489d301200f55c412468b2bde09f2e1f5d/docs/configuration.md
  • Now let's say we're ready to go prod and we reinstall dependencies using composer install --no-dev.
  • We have this error when attempting to access any page: Attempted to load class "Assert" from namespace "Webmozart\Assert" in ORMMappedSuperClassSubscriber.php line 52.

Possible Solution
Maybe require webmozart/assert as a dependency would be OK or remove the usage of Webmozart\Assert\Assert in Sylius\Bundle\ResourceBundle\EventListener\ORMMappedSuperClassSubscriber.

[CI] Add a "prefer-lowest" build on Travis

It looks like all of the Travis builds are testing with the latest versions of dependencies within whatever constraints are used on a build (i.e. the different Symfony versions or with #182 different versions of the state machine packages). Is there a reason there isn't a build that passes the --prefer-lowest flag into Composer to force a build with the minimum declared dependencies? In part, this helps ensure the minimums are correctly defined.

Not possible to set your own response by an event for non-HTML requests

Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no
Sylius version 1.0.0

ResouceController:

if ($event->isStopped() && !$configuration->isHtmlRequest()) {
    throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
    $this->flashHelper->addFlashFromEvent($configuration, $event);

    if ($event->hasResponse()) {
        return $event->getResponse();
    }

    return $this->redirectHandler->redirectToResource($configuration, $resource);
}

It should be possible to set your own response for non-HTML requests.

Call to a member function isAbstract() on null / ORMTranslatableListener.php

Sylius version affected: 1.5.2

Description
I would like create entity witth symfony maker on fresh install sylius:

php bin/console make:entity

 Class name of the entity to create or update (e.g. GrumpyPizza):
 > Voyage\Option

 created: src/Entity/Voyage/Option.php
 created: src/Repository/Voyage/OptionRepository.php

In ORMTranslatableListener.php line 64:
                                                  
  Call to a member function isAbstract() on null  

Steps to reproduce

Possible Solution
in /vendor/sylius/resource-bundle/src/Bundle/EventListener/ORMTranslatableListener.php/ORMTranslatableListener.php
on line 64 i've replaced :

if ($reflection->isAbstract()) {
            return;
 }

by

if ($reflection && $reflection->isAbstract()) {
            return;
 }

Add getSection at ResourceControllerEvent

Describe the proposed solution
Add setSection to ResourceControllerEvent and pass section from request configuration:

        // sylius/resource-bundle/src/Bundle/Controller/EventDispatcher.php
        // ...
        $event = new ResourceControllerEvent($resource);
        $event->setSection($requestConfiguration->getSection());

Alternative solution
Add whole requestConfiguration to event.

Additional context
When we subscribe to (for example) sylius.product.show event to embed some tracker html code like Google tag manager - we don't want to embed it at admin area. So we should somehow know what section (shop, admin, admin_api, etc) we're at to skip non-shop sections.

I will provide PR if this idea looks good for core team.

Extend ResourceController

Hi,

Resource Bundle is really handy and I use it for a resource for which I need to add actions.

sylius_resource:
    dp.geozone:
        driver: doctrine/orm
        classes:
            model: Dp\ShopBundle\Entity\GeoZone

When I try to extend ResourceController, I get the error:

An exception has been thrown during the rendering of a template ("Warning: Missing
argument 1 for 
Sylius\Bundle\ResourceBundle\Controller\ResourceController::__construct(), 
called in...

I registered that service as it's done in Sylius Bundles hoping it would feed the __construct method:

<service id="dp.controller.geozone" class="%dp.controller.geozone.class%">
        <argument>dp</argument>
        <argument>geozone</argument>
        <argument>DpShopBundle:GeoZone</argument>
        <call method="setContainer">
            <argument type="service" id="service_container" />
        </call>
</service>

but with no luck. What am I missing? Thanks!

Duplicate initialisation of repositories

Sylius version affected: all

Description
If you request a repository from the service container it will return a different repository instance than the one you will get from the EntityManager via getRepository

Steps to reproduce

    $repository = $client->getContainer()->get('app.repository.book');

    $em = $client->getContainer()->get('app.manager.book');
    $repositoryAlias = $em->getRepository(Book::class);
    $this->assertTrue($repository === $repositoryAlias);

    $em = $client->getContainer()->get('doctrine.orm.entity_manager');
    $repositoryAlias = $em->getRepository(Book::class);
    $this->assertTrue($repository === $repositoryAlias);

image

Possible Solution
#220

$fetchJoinCollection should be either true by default or let developer decide what should be passed in Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository::getPaginator

Sylius version affected: 1.6.0 at least

Description

The setting shipped in 1.6 can return much less result than expected.

Steps to reproduce
Consider I was trying to get a Pagerfanta for product with specific variant code pattern, with $fetchJoinCollection set as false. In doctrine/orm/lib/Doctrine/ORM/Tools/Pagination/Paginator.php getIterator it will execute something like

SELECT 
...
FROM product p
JOIN variant pv ON ...
WHERE
...
LIMIT 100

Since 1 product can have more than 1 variants, number of distinct products returned is likely be less than 100.

Possible Solution
With $fetchJoinCollection set to true, doctrine will first select all distinct IDs first and then select all tuples afterwards to ensure number of products returned matches what setMaxResults set.

Long long time ago $fetchJoinCollection was set to true and everything works fine.

Allow changing the Responce with EventListeners

The current implementation only dispatches an event but does not allow to actually change the content or something else like a redirect.

When something is disallowed I'd rather set a flash message and redirect to another page to thrown an exception.

Or asking a confirmation for delete for example.

The FOSUserBundle has solves this nicely so we can take as an example.

Sonata/Admin integration

Instead of an custom admin backend interface use Sonata/Admin.

  • Applications, that already integrate SA don't need two separate backends
  • You don't need to maintain the infrastructure yourself ;)

Maybe there are reasons, why you don't use it, but I don't know :)

[Resource] Forms create resource objects without factories

I've initially mentioned this in Sylius/Sylius#7547 but wanted to get it out into its own ticket.

When submitting a form with no data given, the forms empty_data closure creates the correct data object before setting data. Unfortunately, this means that for all resources implementing TranslatableInterface, they won't have a locale injected, which is normally done by the TranslatableFactory.

I think the AbstractResourceType form type should receive a factory instance (maybe optional) that is then used in the forms empty_data closure instead of relying on the Symfony default closure.

I can get started on a pull request, there's just the issue of BC breaks. If AbstractResourceType were to require a resource factory, the constructor would have to use the following signature:

public function __construct($dataClass, FactoryInterface $factory, array $validationGroups = [])

Since this would constitute a BC break, what route should we take? We could make the factory optional and rely on new $class() if no factory was given to avoid the BC break.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.