Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing repository interface is not mandatory anymore #875

Draft
wants to merge 1 commit into
base: 1.11
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"sylius-labs/coding-standard": "^4.0",
"sylius/grid-bundle": "^1.7 || v1.12.0-ALPHA.1",
"symfony/dependency-injection": "^5.4 || ^6.0",
"symfony/console": "^5.4 || ^6.0",
"symfony/dotenv": "^5.4 || ^6.0",
"symfony/stopwatch": "^5.4 || ^6.0",
"symfony/uid": "^5.4 || ^6.0",
Expand Down
11 changes: 5 additions & 6 deletions docs/create_new_resource.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,9 @@ class BookRepository extends ServiceEntityRepository
}
```

The generated code is not compatible with Sylius Resource yet, so we need to make few changes.
The generated code could be not compatible with Sylius Resource in some cases, so we need to make few changes.
Copy link
Member Author

@loic425 loic425 May 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hum I think I should move all this part on Index operation without any grid.


* First, your repository should implement the `Sylius\Component\Resource\Repository\RepositoryInterface` interface
* Then, add the `Sylius\Bundle\ResourceBundle\Doctrine\ORM\ResourceRepositoryTrait` trait
* Add the `Sylius\Bundle\ResourceBundle\Doctrine\ORM\PaginatedRepositoryTrait` trait

Your repository should look like this:

Expand All @@ -139,7 +138,7 @@ namespace App\Repository;
use App\Entity\Book;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\ResourceRepositoryTrait;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\PaginatedRepositoryTrait;
use Sylius\Resource\Doctrine\Persistence\RepositoryInterface;

/**
Expand All @@ -150,9 +149,9 @@ use Sylius\Resource\Doctrine\Persistence\RepositoryInterface;
* @method Book[] findAll()
* @method Book[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class BookRepository extends ServiceEntityRepository implements RepositoryInterface
class BookRepository extends ServiceEntityRepository
{
use ResourceRepositoryTrait;
use PaginatedRepositoryTrait;

public function __construct(ManagerRegistry $registry)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Sylius\Bundle\ResourceBundle\DependencyInjection\Compiler;

use Sylius\Resource\Doctrine\Persistence\RepositoryInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
Expand All @@ -35,6 +36,13 @@ public function process(ContainerBuilder $container): void
$repositoryId = sprintf('%s.repository.%s', $applicationName, $resourceName);

if ($container->has($repositoryId)) {
$repositoryDefinition = $container->findDefinition($repositoryId);

// Do not register repositories that do not implement the Sylius repository interface
if (!\is_a($repositoryDefinition->getClass() ?? '', RepositoryInterface::class, true)) {
continue;
}

$repositoryRegistry->addMethodCall('register', [$alias, new Reference($repositoryId)]);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Doctrine\Common\Persistence\ObjectManager as DeprecatedObjectManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\Persistence\ObjectManager;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Bundle\ResourceBundle\SyliusResourceBundle;
Expand Down Expand Up @@ -54,6 +55,14 @@ protected function addRepository(ContainerBuilder $container, MetadataInterface
$repositoryClass = $metadata->getClass('repository');
}

$entityAttributeRepositoryClass = (new \ReflectionClass($metadata->getClass('model')))
->getAttributes(Entity::class)[0]
->newInstance()->repositoryClass;

if (null !== $entityAttributeRepositoryClass) {
$repositoryClass = $entityAttributeRepositoryClass;
}

$serviceId = $metadata->getServiceId('repository');
$managerReference = new Reference($metadata->getServiceId('manager'));
$definition = new Definition($repositoryClass);
Expand All @@ -73,7 +82,6 @@ protected function addRepository(ContainerBuilder $container, MetadataInterface
} else {
if (is_a($repositoryClass, ServiceEntityRepository::class, true)) {
$definition->setArguments([new Reference('doctrine')]);
$container->setDefinition($serviceId, $definition);
} else {
$definition->setArguments([$managerReference, $this->getClassMetadataDefinition($metadata)]);
}
Expand Down
107 changes: 107 additions & 0 deletions src/Bundle/Doctrine/ORM/PaginatedRepositoryTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Sylius Sp. z o.o.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Sylius\Bundle\ResourceBundle\Doctrine\ORM;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Doctrine\ORM\QueryAdapter;
use Pagerfanta\Pagerfanta;
use Sylius\Resource\Model\ResourceInterface;

/**
* @property EntityManagerInterface $_em
* @property ClassMetadata $_class
*
* @method QueryBuilder createQueryBuilder(string $alias, string $indexBy = null)
*/
trait PaginatedRepositoryTrait
{
/**
* @return iterable<int, ResourceInterface>
*/
public function createPaginator(array $criteria = [], array $sorting = []): iterable
{
$queryBuilder = $this->createQueryBuilder('o');

$this->applyCriteria($queryBuilder, $criteria);
$this->applySorting($queryBuilder, $sorting);

return $this->getPaginator($queryBuilder);
}

protected function getPaginator(QueryBuilder $queryBuilder): Pagerfanta
{
if (!class_exists(QueryAdapter::class)) {
throw new \LogicException('You can not use the "paginator" if Pargefanta Doctrine ORM Adapter is not available. Try running "composer require pagerfanta/doctrine-orm-adapter".');
}

// Use output walkers option in the query adapter should be false as it affects performance greatly (see sylius/sylius#3775)
return new Pagerfanta(new QueryAdapter($queryBuilder, false, false));
}

/**
* @param array $objects
*/
protected function getArrayPaginator($objects): Pagerfanta
{
return new Pagerfanta(new ArrayAdapter($objects));
}

protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = []): void
{
foreach ($criteria as $property => $value) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}

$name = $this->getPropertyName($property);

if (null === $value) {
$queryBuilder->andWhere($queryBuilder->expr()->isNull($name));
} elseif (is_array($value)) {
$queryBuilder->andWhere($queryBuilder->expr()->in($name, $value));
} elseif ('' !== $value) {
$parameter = str_replace('.', '_', $property);
$queryBuilder
->andWhere($queryBuilder->expr()->eq($name, ':' . $parameter))
->setParameter($parameter, $value)
;
}
}
}

protected function applySorting(QueryBuilder $queryBuilder, array $sorting = []): void
{
foreach ($sorting as $property => $order) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}

if (!empty($order)) {
$queryBuilder->addOrderBy($this->getPropertyName($property), $order);
}
}
}

protected function getPropertyName(string $name): string
{
if (!str_contains($name, '.')) {
return 'o' . '.' . $name;
}

return $name;
}
}
83 changes: 2 additions & 81 deletions src/Bundle/Doctrine/ORM/ResourceRepositoryTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,18 @@

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Doctrine\ORM\QueryAdapter;
use Pagerfanta\Pagerfanta;
use Sylius\Resource\Model\ResourceInterface;

/**
* @property EntityManagerInterface $_em
* @property ClassMetadata $_class
*
* @method QueryBuilder createQueryBuilder(string $alias, string $indexBy = null)
* @method ?object find($id, $lockMode = null, $lockVersion = null)
*/
trait ResourceRepositoryTrait
{
use PaginatedRepositoryTrait;

public function add(ResourceInterface $resource): void
{
$this->_em->persist($resource);
Expand All @@ -43,80 +40,4 @@ public function remove(ResourceInterface $resource): void
$this->_em->flush();
}
}

/**
* @return iterable<int, ResourceInterface>
*/
public function createPaginator(array $criteria = [], array $sorting = []): iterable
{
$queryBuilder = $this->createQueryBuilder('o');

$this->applyCriteria($queryBuilder, $criteria);
$this->applySorting($queryBuilder, $sorting);

return $this->getPaginator($queryBuilder);
}

protected function getPaginator(QueryBuilder $queryBuilder): Pagerfanta
{
if (!class_exists(QueryAdapter::class)) {
throw new \LogicException('You can not use the "paginator" if Pargefanta Doctrine ORM Adapter is not available. Try running "composer require pagerfanta/doctrine-orm-adapter".');
}

// Use output walkers option in the query adapter should be false as it affects performance greatly (see sylius/sylius#3775)
return new Pagerfanta(new QueryAdapter($queryBuilder, false, false));
}

/**
* @param array $objects
*/
protected function getArrayPaginator($objects): Pagerfanta
{
return new Pagerfanta(new ArrayAdapter($objects));
}

protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = []): void
{
foreach ($criteria as $property => $value) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}

$name = $this->getPropertyName($property);

if (null === $value) {
$queryBuilder->andWhere($queryBuilder->expr()->isNull($name));
} elseif (is_array($value)) {
$queryBuilder->andWhere($queryBuilder->expr()->in($name, $value));
} elseif ('' !== $value) {
$parameter = str_replace('.', '_', $property);
$queryBuilder
->andWhere($queryBuilder->expr()->eq($name, ':' . $parameter))
->setParameter($parameter, $value)
;
}
}
}

protected function applySorting(QueryBuilder $queryBuilder, array $sorting = []): void
{
foreach ($sorting as $property => $order) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}

if (!empty($order)) {
$queryBuilder->addOrderBy($this->getPropertyName($property), $order);
}
}
}

protected function getPropertyName(string $name): string
{
if (false === strpos($name, '.')) {
return 'o' . '.' . $name;
}

return $name;
}
}
3 changes: 3 additions & 0 deletions src/Component/spec/Symfony/Request/State/ProviderSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ function it_calls_repository_as_string(
RepositoryInterface $repository,
\stdClass $stdClass,
): void {
$operation->getName()->willReturn('operation_name');
$operation->getRepository()->willReturn('App\Repository');
$operation->getRepositoryMethod()->willReturn(null);
$operation->getRepositoryArguments()->willReturn(null);
Expand Down Expand Up @@ -133,6 +134,7 @@ function it_calls_repository_as_string_with_specific_repository_method(
RepositoryInterface $repository,
\stdClass $stdClass,
): void {
$operation->getName()->willReturn('operation_name');
$operation->getRepository()->willReturn('App\Repository');
$operation->getRepositoryMethod()->willReturn('find');
$operation->getRepositoryArguments()->willReturn(null);
Expand All @@ -158,6 +160,7 @@ function it_calls_repository_as_string_with_specific_repository_method_an_argume
ArgumentParserInterface $argumentParser,
\stdClass $stdClass,
): void {
$operation->getName()->willReturn('operation_name');
$operation->getRepository()->willReturn('App\Repository');
$operation->getRepositoryMethod()->willReturn('find');
$operation->getRepositoryArguments()->willReturn(['id' => "request.attributes.get('id')"]);
Expand Down
14 changes: 13 additions & 1 deletion src/Component/src/Symfony/Request/State/Provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Sylius\Resource\State\ProviderInterface;
use Sylius\Resource\Symfony\ExpressionLanguage\ArgumentParserInterface;
use Sylius\Resource\Symfony\Request\RepositoryArgumentResolver;
use Webmozart\Assert\Assert;

final class Provider implements ProviderInterface
{
Expand Down Expand Up @@ -59,11 +60,22 @@ public function provide(Operation $operation, Context $context): object|array|nu
$method = $operation->getRepositoryMethod() ?? $defaultMethod;

if (!$this->locator->has($repository)) {
throw new \RuntimeException(sprintf('Repository "%s" not found on operation "%s"', $repository, $operation->getName() ?? ''));
throw new \RuntimeException(sprintf('Repository "%s" not found on operation "%s".', $repository, $operation->getName() ?? ''));
}

/** @var object $repositoryInstance */
$repositoryInstance = $this->locator->get($repository);

Assert::true(
(new \ReflectionClass($repositoryInstance))->hasMethod($method),
sprintf(
'Repository "%s" does not contain "%s" method. Configure it or configure another repository method in your operation "%s".',
$repositoryInstance::class,
$method,
$operation->getName() ?? '',
),
);

// make it as callable
/** @var callable $repository */
$repository = [$repositoryInstance, $method];
Expand Down
5 changes: 5 additions & 0 deletions tests/Application/config/packages/doctrine.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ doctrine:
type: attribute
dir: '%kernel.project_dir%/src/BoardGameBlog/Domain'
prefix: 'App\BoardGameBlog\Domain'
Calendar:
is_bundle: false
type: attribute
dir: '%kernel.project_dir%/src/Calendar/Entity'
prefix: 'App\Calendar\Entity'
Subscription:
is_bundle: false
type: attribute
Expand Down
3 changes: 3 additions & 0 deletions tests/Application/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ services:
App\BoardGameBlog\:
resource: '../src/BoardGameBlog'

App\Calendar\:
resource: '../src/Calendar'

App\Subscription\:
resource: '../src/Subscription'

Expand Down
1 change: 1 addition & 0 deletions tests/Application/config/sylius/resources.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ sylius_resource:
mapping:
paths:
- '%kernel.project_dir%/src/BoardGameBlog/Infrastructure/Sylius/Resource'
- '%kernel.project_dir%/src/Calendar/Entity'
- '%kernel.project_dir%/src/Subscription/Entity'

translation:
Expand Down
Loading
Loading