Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Platform Extensions Laravel Package

avkluchko/api-platform-extensions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require avkluchko/api-platform-extensions
    

    For non-Flex projects, enable the bundle in config/bundles.php:

    return [
        // ...
        AVKluchko\ApiPlatformExtensions\ApiPlatformExtensionsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Enable AdminGroupsContextBuilder for automatic admin serialization groups:

    # config/services.yaml
    AVKluchko\ApiPlatformExtensions\Serializer\AdminGroupsContextBuilder:
        decorates: 'api_platform.serializer.context_builder'
        arguments: ['@AVKluchko\ApiPlatformExtensions\Serializer\AdminGroupsContextBuilder.inner']
    
  3. Verify: Test by accessing an API endpoint with an admin user. The response should include fields marked with @Groups({"admin:read"}).


Implementation Patterns

Common Workflows

  1. Serialization Groups for Admins:

    • Use @Groups({"admin:read", "admin:write"}) in your entity properties.
    • The AdminGroupsContextBuilder automatically adds these groups when the user is authenticated as an admin.
    • Example:
      use AVKluchko\ApiPlatformExtensions\Serializer\AdminGroupsContextBuilder;
      
      #[Groups(["default", "admin:read"])]
      private $sensitiveData;
      
  2. Event Subscribers:

    • Extend API Platform events (e.g., KernelEvents::VIEW, ApiPlatform\Event\LifecycleEvent).
    • Example subscriber for modifying responses:
      use AVKluchko\ApiPlatformExtensions\EventSubscriber\ModifyResponseSubscriber;
      
      class CustomResponseSubscriber extends ModifyResponseSubscriber {
          public function onKernelView(KernelEvent $event) {
              $response = $event->getResponse();
              // Custom logic
          }
      }
      
    • Register in services.yaml:
      services:
          App\EventSubscriber\CustomResponseSubscriber:
              tags: ['kernel.event_subscriber']
      
  3. Doctrine Extensions:

    • Use SoftDeletable or Timestampable traits for entities:
      use AVKluchko\ApiPlatformExtensions\Doctrine\SoftDeletable;
      use AVKluchko\ApiPlatformExtensions\Doctrine\Timestampable;
      
      class User implements SoftDeletable, Timestampable {
          // ...
      }
      
  4. Security Integration:

    • Combine with Symfony's security system to restrict access:
      # config/packages/security.yaml
      access_control:
          - { path: ^/admin, roles: ROLE_ADMIN }
      

Integration Tips

  • API Platform Version: Ensure compatibility with api-platform/core:^2.5.
  • Symfony Flex: If using Flex, the bundle auto-registers. For manual setups, verify bundles.php.
  • Testing: Use symfony/phpunit-bridge for testing event subscribers and serializers.

Gotchas and Tips

Pitfalls

  1. Admin Groups Override:

    • If AdminGroupsContextBuilder is misconfigured, admin-specific fields may not serialize. Verify the decorator setup in services.yaml.
    • Debug with:
      bin/console debug:container AVKluchko\ApiPlatformExtensions\Serializer\AdminGroupsContextBuilder
      
  2. Event Subscriber Priority:

    • Subscribers may conflict if not ordered correctly. Use the priority option in tags:
      tags:
          - { name: kernel.event_subscriber, priority: 100 }
      
  3. Soft Deletes:

    • Ensure SoftDeletable entities are queried with isDeleted = false in repositories or DQL:
      $query->andWhere('u.isDeleted = :deleted')
            ->setParameter('deleted', false);
      
  4. Serialization Groups:

    • Avoid naming conflicts with existing groups (e.g., default, admin). Prefix custom groups (e.g., app:admin).

Debugging

  • Check Serialization Context:

    bin/console debug:container api_platform.serializer.context_builder
    

    Look for the decorated AdminGroupsContextBuilder.

  • Event Debugging: Enable Symfony's event dispatcher debug mode:

    $dispatcher->addListener(KernelEvents::VIEW, function ($event) {
        var_dump($event->getResponse()->getContent());
    });
    

Extension Points

  1. Custom Context Builders: Extend AdminGroupsContextBuilder to add dynamic groups:

    class CustomAdminGroupsContextBuilder extends AdminGroupsContextBuilder {
        protected function getAdminGroups(): array {
            return ['admin:read', 'admin:write', 'custom:group'];
        }
    }
    
  2. Doctrine Lifecycle Callbacks: Override prePersist, preUpdate, etc., in traits like Timestampable:

    use AVKluchko\ApiPlatformExtensions\Doctrine\Timestampable;
    
    class Post implements Timestampable {
        protected $createdAt;
        protected $updatedAt;
    
        public function prePersist() {
            $this->createdAt = new \DateTime();
            $this->updatedAt = new \DateTime();
        }
    }
    
  3. API Resource Extensions: Use ApiResource extensions for custom metadata:

    use AVKluchko\ApiPlatformExtensions\ApiResource\ExtensionInterface;
    
    class CustomExtension implements ExtensionInterface {
        public function getOperations() {
            return [
                'get' => ['method' => 'GET', 'path' => '/custom-path'],
            ];
        }
    }
    

Configuration Quirks

  • Symfony 5.1+: Ensure symfony/config and symfony/dependency-injection versions match (^5.1.5).
  • PHP 8.0: Test for strict typing issues if upgrading from PHP 7.1.
  • Doctrine ORM: Requires ^2.5. For newer versions, check for compatibility or fork the package.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor