-
Notifications
You must be signed in to change notification settings - Fork 611
/
CategoryType.php
68 lines (59 loc) · 2.05 KB
/
CategoryType.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\gql\types\generators;
use Craft;
use craft\elements\Category as CategoryElement;
use craft\gql\base\Generator;
use craft\gql\base\GeneratorInterface;
use craft\gql\base\ObjectType;
use craft\gql\base\SingleGeneratorInterface;
use craft\gql\GqlEntityRegistry;
use craft\gql\interfaces\elements\Category as CategoryInterface;
use craft\gql\types\elements\Category;
use craft\helpers\Gql as GqlHelper;
/**
* Class CategoryType
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.3.0
*/
class CategoryType extends Generator implements GeneratorInterface, SingleGeneratorInterface
{
/**
* @inheritdoc
*/
public static function generateTypes(mixed $context = null): array
{
$categoryGroups = Craft::$app->getCategories()->getAllGroups();
$gqlTypes = [];
foreach ($categoryGroups as $categoryGroup) {
$requiredContexts = CategoryElement::gqlScopesByContext($categoryGroup);
if (!GqlHelper::isSchemaAwareOf($requiredContexts)) {
continue;
}
// Generate a type for each category group
$type = static::generateType($categoryGroup);
$gqlTypes[$type->name] = $type;
}
return $gqlTypes;
}
/**
* @inheritdoc
*/
public static function generateType(mixed $context): ObjectType
{
$typeName = CategoryElement::gqlTypeName($context);
return GqlEntityRegistry::getOrCreate($typeName, fn() => new Category([
'name' => $typeName,
'fields' => function() use ($context, $typeName) {
$contentFieldGqlTypes = self::getContentFields($context);
$categoryGroupFields = array_merge(CategoryInterface::getFieldDefinitions(), $contentFieldGqlTypes);
return Craft::$app->getGql()->prepareFieldDefinitions($categoryGroupFields, $typeName);
},
]));
}
}