SnakeCaseLinksHandler.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace Webkul\BagistoApi\State;
  3. use ApiPlatform\Laravel\Eloquent\State\LinksHandlerInterface;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Support\Str;
  6. /**
  7. * Fixes camelCase/snake_case mismatch between GraphQL field names and Eloquent
  8. * relationship names in API Platform's LinksHandler.
  9. *
  10. * GraphQL passes camelCase linkProperty (e.g. "attributeValues") but Link metadata
  11. * stores snake_case fromProperty (e.g. "attribute_values"). This decorator normalizes
  12. * linkProperty to snake_case before delegating to the original handler.
  13. *
  14. * Single-word names like "variants" or "images" are unaffected.
  15. *
  16. * @implements LinksHandlerInterface<\Illuminate\Database\Eloquent\Model>
  17. */
  18. class SnakeCaseLinksHandler implements LinksHandlerInterface
  19. {
  20. public function __construct(
  21. private readonly LinksHandlerInterface $inner,
  22. ) {}
  23. public function handleLinks(Builder $builder, array $uriVariables, array $context): Builder
  24. {
  25. if (isset($context['linkProperty'])) {
  26. $context['linkProperty'] = Str::snake($context['linkProperty']);
  27. }
  28. return $this->inner->handleLinks($builder, $uriVariables, $context);
  29. }
  30. }