|
|
@@ -0,0 +1,67 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace Webkul\BagistoApi\Resolver;
|
|
|
+
|
|
|
+use ApiPlatform\GraphQl\Resolver\QueryItemResolverInterface;
|
|
|
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
|
|
+use Webkul\BagistoApi\Models\Category;
|
|
|
+use Webkul\BagistoApi\Service\GenericIdNormalizer;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Category item resolver supporting lookup by either `id` or `slug`.
|
|
|
+ *
|
|
|
+ * - id : numeric id or IRI (delegates to the same logic as BaseQueryItemResolver)
|
|
|
+ * - slug : category translation slug (e.g. "ready-to-go-wig")
|
|
|
+ *
|
|
|
+ * When both are provided, `id` takes precedence.
|
|
|
+ */
|
|
|
+class CategoryItemResolver implements QueryItemResolverInterface
|
|
|
+{
|
|
|
+ public function __invoke(?object $item, array $context): object
|
|
|
+ {
|
|
|
+ $args = $context['args'] ?? [];
|
|
|
+
|
|
|
+ $id = $args['id'] ?? null;
|
|
|
+ $slug = $args['slug'] ?? null;
|
|
|
+
|
|
|
+ // 优先使用 id
|
|
|
+ if ($id !== null && $id !== '') {
|
|
|
+ $numericId = GenericIdNormalizer::extractNumericId($id);
|
|
|
+
|
|
|
+ if ($numericId === null) {
|
|
|
+ GenericIdNormalizer::validateAndExtract($id, 'bagistoapi::app.graphql.category.invalid-id-format');
|
|
|
+ }
|
|
|
+
|
|
|
+ $resource = Category::find($numericId);
|
|
|
+
|
|
|
+ if (! $resource) {
|
|
|
+ throw new BadRequestHttpException(
|
|
|
+ __('bagistoapi::app.graphql.category.not-found', ['id' => $id])
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ return $resource;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 使用 slug 查询
|
|
|
+ if ($slug !== null && $slug !== '') {
|
|
|
+ $resource = Category::query()
|
|
|
+ ->whereHas('translations', function ($query) use ($slug) {
|
|
|
+ $query->where('slug', $slug);
|
|
|
+ })
|
|
|
+ ->first();
|
|
|
+
|
|
|
+ if (! $resource) {
|
|
|
+ throw new BadRequestHttpException(
|
|
|
+ __('bagistoapi::app.graphql.category.not-found', ['id' => $slug])
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ return $resource;
|
|
|
+ }
|
|
|
+
|
|
|
+ throw new BadRequestHttpException(
|
|
|
+ __('bagistoapi::app.graphql.category.id-required')
|
|
|
+ );
|
|
|
+ }
|
|
|
+}
|