├── resources └── img │ └── plugin-logo.png ├── src ├── db │ └── Table.php ├── events │ ├── RegisterSourceNodeTypesEvent.php │ └── RegisterIgnoredTypesEvent.php ├── icon.svg ├── icon-masked.svg ├── gql │ ├── resolvers │ │ ├── SourceNode.php │ │ ├── DeletedNode.php │ │ └── UpdatedNode.php │ ├── types │ │ ├── ChangedNode.php │ │ └── SourceNode.php │ └── queries │ │ └── Sourcing.php ├── helpers │ └── Gql.php ├── templates │ └── settings.html ├── models │ └── Settings.php ├── migrations │ └── Install.php ├── services │ ├── Builds.php │ ├── SourceNodes.php │ └── Deltas.php └── Plugin.php ├── LICENSE.md └── composer.json /resources/img/plugin-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/craftcms/gatsby-helper/HEAD/resources/img/plugin-logo.png -------------------------------------------------------------------------------- /src/db/Table.php: -------------------------------------------------------------------------------- 1 | 12 | * @since 1.0 13 | */ 14 | abstract class Table 15 | { 16 | public const DELETED_ELEMENTS = '{{%gatsby_deletedelements}}'; 17 | } 18 | -------------------------------------------------------------------------------- /src/events/RegisterSourceNodeTypesEvent.php: -------------------------------------------------------------------------------- 1 | 16 | * @since 1.0 17 | */ 18 | class RegisterSourceNodeTypesEvent extends Event 19 | { 20 | /** 21 | * @var array Source node type list 22 | */ 23 | public array $types = []; 24 | } 25 | -------------------------------------------------------------------------------- /src/events/RegisterIgnoredTypesEvent.php: -------------------------------------------------------------------------------- 1 | 16 | * @since 1.0 17 | */ 18 | class RegisterIgnoredTypesEvent extends Event 19 | { 20 | /** 21 | * @var array List of element type classes ignored for change tracking 22 | */ 23 | public array $types = []; 24 | } 25 | -------------------------------------------------------------------------------- /src/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /src/icon-masked.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /src/gql/resolvers/SourceNode.php: -------------------------------------------------------------------------------- 1 | 18 | * @since 1.0.0 19 | */ 20 | class SourceNode extends Resolver 21 | { 22 | public static function resolve($source, array $arguments, $context, ResolveInfo $resolveInfo): array 23 | { 24 | return Plugin::getInstance()->getSourceNodes()->getSourceNodeTypes(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/helpers/Gql.php: -------------------------------------------------------------------------------- 1 | 16 | * @since 1.0.0 17 | */ 18 | class Gql extends GqlHelper 19 | { 20 | /** 21 | * Return true if active schema can query gatsby data. 22 | * 23 | * @return bool 24 | */ 25 | public static function canQueryGatsbyData(): bool 26 | { 27 | $allowedEntities = self::extractAllowedEntitiesFromSchema(); 28 | return isset($allowedEntities['gatsby']); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/templates/settings.html: -------------------------------------------------------------------------------- 1 | {% import '_includes/forms' as forms %} 2 | 3 | {{ forms.autosuggestField({ 4 | first: true, 5 | label: 'Preview Webhook URL'|t('gatsby-helper'), 6 | instructions: 'The Gatsby webhook URL that should be called when content changes in Live Preview.'|t('gatsby-helper'), 7 | name: 'previewWebhookUrl', 8 | value: settings.previewWebhookUrl, 9 | suggestEnvVars: true, 10 | suggestAliases: true, 11 | }) }} 12 | 13 | {{ forms.autosuggestField({ 14 | label: 'Build Webhook URL'|t('gatsby-helper'), 15 | instructions: 'The Gatsby webhook URL that should be called when an element is saved.'|t('gatsby-helper'), 16 | name: 'buildWebhookUrl', 17 | value: settings.buildWebhookUrl, 18 | suggestEnvVars: true, 19 | suggestAliases: true, 20 | }) }} 21 | -------------------------------------------------------------------------------- /src/models/Settings.php: -------------------------------------------------------------------------------- 1 | 9 | * @since 1.0.0 10 | */ 11 | class Settings extends Model 12 | { 13 | /** 14 | * The address of the preview server, including protocol and port. 15 | * 16 | * @var string 17 | * @deprecated 18 | */ 19 | public string $previewServerUrl = ''; 20 | 21 | /** 22 | * The full URL where the plugin should let Gatsby know to trigger preview 23 | * 24 | * @var string 25 | */ 26 | public string $previewWebhookUrl = ''; 27 | 28 | /** 29 | * The full URL where the plugin should let Gatsby know to trigger a site build 30 | * 31 | * @var string 32 | */ 33 | public string $buildWebhookUrl = ''; 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Pixel & Tonic, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/gql/resolvers/DeletedNode.php: -------------------------------------------------------------------------------- 1 | 18 | * @since 1.0.0 19 | */ 20 | class DeletedNode extends Resolver 21 | { 22 | public static function resolve($source, array $arguments, $context, ResolveInfo $resolveInfo): array 23 | { 24 | $deletedNodes = Plugin::getInstance()->getDeltas()->getDeletedNodesSinceTimeStamp($arguments['since']); 25 | $resolved = []; 26 | 27 | foreach ($deletedNodes as $element) { 28 | $resolved[] = [ 29 | 'nodeId' => $element['elementId'], 30 | 'siteId' => $element['siteId'], 31 | 'nodeType' => $element['typeName'], 32 | ]; 33 | } 34 | 35 | return $resolved; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/migrations/Install.php: -------------------------------------------------------------------------------- 1 | 17 | * @since 1.0.0 18 | */ 19 | class Install extends Migration 20 | { 21 | /** 22 | * @inheritdoc 23 | */ 24 | public function safeUp() 25 | { 26 | $this->createTable(Table::DELETED_ELEMENTS, [ 27 | 'id' => $this->primaryKey(), 28 | 'elementId' => $this->integer(), 29 | 'siteId' => $this->integer()->notNull(), 30 | 'typeName' => $this->string()->notNull(), 31 | 'dateDeleted' => $this->dateTime()->notNull(), 32 | ]); 33 | 34 | $this->createIndex(null, Table::DELETED_ELEMENTS, ['elementId', 'siteId'], true); 35 | 36 | return true; 37 | } 38 | 39 | /** 40 | * @inheritdoc 41 | */ 42 | public function safeDown() 43 | { 44 | $this->dropTableIfExists(Table::DELETED_ELEMENTS); 45 | 46 | return true; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "craftcms/gatsby-helper", 3 | "description": "Plugin for enabling support for the Gatsby Craft CMS source plugin.", 4 | "type": "craft-plugin", 5 | "keywords": [ 6 | "craft", 7 | "cms", 8 | "craftcms", 9 | "craft-plugin", 10 | "gatsby" 11 | ], 12 | "support": { 13 | "docs": "https://github.com/craftcms/gatsby-helper", 14 | "issues": "https://github.com/craftcms/gatsby-helper/issues" 15 | }, 16 | "license": "MIT", 17 | "authors": [ 18 | { 19 | "name": "Pixel & Tonic", 20 | "homepage": "https://pixelandtonic.com/" 21 | } 22 | ], 23 | "minimum-stability": "dev", 24 | "prefer-stable": true, 25 | "require": { 26 | "craftcms/cms": "^4.0.0-RC2|^5.0.0-beta.1" 27 | }, 28 | "require-dev": { 29 | "craftcms/ecs": "dev-main", 30 | "craftcms/phpstan": "dev-main" 31 | }, 32 | "autoload": { 33 | "psr-4": { 34 | "craft\\gatsbyhelper\\": "src/" 35 | } 36 | }, 37 | "extra": { 38 | "name": "Gatsby Helper", 39 | "handle": "gatsby-helper", 40 | "developerUrl": "https://craftcms.com/" 41 | }, 42 | "scripts": { 43 | "check-cs": "ecs check --ansi", 44 | "fix-cs": "ecs check --ansi --fix", 45 | "phpstan": "phpstan --memory-limit=1G" 46 | }, 47 | "config": { 48 | "platform": { 49 | "php": "8.0.2" 50 | }, 51 | "allow-plugins": { 52 | "yiisoft/yii2-composer": true, 53 | "craftcms/plugin-installer": true 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/services/Builds.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | 11 | namespace craft\gatsbyhelper\services; 12 | 13 | use Craft; 14 | use craft\base\Component; 15 | use craft\gatsbyhelper\Plugin; 16 | use craft\helpers\App; 17 | use yii\base\Application; 18 | 19 | /** 20 | * Builds Service 21 | * 22 | * @author Pixel & Tonic, Inc. 23 | * @since 1.0.0 24 | * 25 | * @property-read null|string|false $lastContentUpdateTime 26 | * @property-read string $version 27 | */ 28 | class Builds extends Component 29 | { 30 | private bool $_buildQueued = false; 31 | 32 | /** 33 | * Trigger a Gatsby build. 34 | */ 35 | public function triggerBuild(): void 36 | { 37 | $buildWebhookUrl = App::parseEnv(Plugin::getInstance()->getSettings()->buildWebhookUrl); 38 | 39 | if (!empty($buildWebhookUrl) && $this->_buildQueued === false) { 40 | $this->_buildQueued = true; 41 | Craft::$app->on(Application::EVENT_AFTER_REQUEST, function() use ($buildWebhookUrl) { 42 | $guzzle = Craft::createGuzzleClient([ 43 | 'headers' => [ 44 | 'x-preview-update-source' => 'Craft CMS', 45 | 'Content-type' => 'application/json', 46 | ], 47 | ]); 48 | $guzzle->request('POST', $buildWebhookUrl); 49 | }, null, false); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/gql/types/ChangedNode.php: -------------------------------------------------------------------------------- 1 | 19 | * @since 1.0.0 20 | */ 21 | class ChangedNode extends ObjectType 22 | { 23 | /** 24 | * @return string 25 | */ 26 | public static function getName(): string 27 | { 28 | return 'UpdatedNode'; 29 | } 30 | 31 | /** 32 | * @return Type 33 | */ 34 | public static function getType(): Type 35 | { 36 | if ($type = GqlEntityRegistry::getEntity(self::getName())) { 37 | return $type; 38 | } 39 | 40 | $type = GqlEntityRegistry::createEntity(self::getName(), new self([ 41 | 'name' => static::getName(), 42 | 'fields' => self::class . '::getFieldDefinitions', 43 | 'description' => 'Updated data node.', 44 | ])); 45 | 46 | return $type; 47 | } 48 | 49 | /** 50 | * @return array 51 | */ 52 | public static function getFieldDefinitions(): array 53 | { 54 | return Craft::$app->getGql()->prepareFieldDefinitions([ 55 | 'nodeType' => [ 56 | 'name' => 'nodeType', 57 | 'type' => Type::nonNull(Type::string()), 58 | 'description' => 'Node type.', 59 | ], 60 | 'elementType' => [ 61 | 'name' => 'elementType', 62 | 'type' => Type::string(), 63 | 'description' => 'Element type.', 64 | ], 65 | 'nodeId' => [ 66 | 'name' => 'nodeId', 67 | 'type' => Type::nonNull(Type::id()), 68 | 'description' => 'Node id.', 69 | ], 70 | 'siteId' => [ 71 | 'name' => 'siteId', 72 | 'type' => Type::id(), 73 | 'description' => 'Site id.', 74 | ], 75 | ], self::getName()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/gql/types/SourceNode.php: -------------------------------------------------------------------------------- 1 | 19 | * @since 1.0.0 20 | */ 21 | class SourceNode extends ObjectType 22 | { 23 | /** 24 | * @return string 25 | */ 26 | public static function getName(): string 27 | { 28 | return 'SourceNode'; 29 | } 30 | 31 | /** 32 | * @return Type 33 | */ 34 | public static function getType(): Type 35 | { 36 | if ($type = GqlEntityRegistry::getEntity(self::getName())) { 37 | return $type; 38 | } 39 | 40 | $type = GqlEntityRegistry::createEntity(self::getName(), new self([ 41 | 'name' => static::getName(), 42 | 'fields' => self::class . '::getFieldDefinitions', 43 | 'description' => 'Source node definition.', 44 | ])); 45 | 46 | return $type; 47 | } 48 | 49 | /** 50 | * @return array 51 | */ 52 | public static function getFieldDefinitions(): array 53 | { 54 | return Craft::$app->getGql()->prepareFieldDefinitions([ 55 | 'list' => [ 56 | 'name' => 'list', 57 | 'type' => Type::nonNull(Type::string()), 58 | 'description' => 'The GraphQL query to use for fetching a node list of this source node type.', 59 | ], 60 | 'node' => [ 61 | 'name' => 'node', 62 | 'type' => Type::nonNull(Type::string()), 63 | 'description' => 'The GraphQL query to use for fetching a specific node of this source node type.', 64 | ], 65 | 'filterArgument' => [ 66 | 'name' => 'filterArgument', 67 | 'type' => Type::string(), 68 | 'description' => 'The name of the argument to use when querying for a list of nodes to narrow down a specific type of nodes.', 69 | ], 70 | 'filterTypeExpression' => [ 71 | 'name' => 'filterTypeExpression', 72 | 'type' => Type::string(), 73 | 'description' => 'Regular expression to apply to a specific node type name to extract the node type. The first matched group will be used as the value for filter argument. ', 74 | ], 75 | 'targetInterface' => [ 76 | 'name' => 'targetInterface', 77 | 'type' => Type::string(), 78 | 'description' => 'Which target interface should be used to infer specific type implementations.', 79 | ], 80 | ], self::getName()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/gql/resolvers/UpdatedNode.php: -------------------------------------------------------------------------------- 1 | 24 | * @since 1.0.0 25 | */ 26 | class UpdatedNode extends Resolver 27 | { 28 | public static function resolve($source, array $arguments, $context, ResolveInfo $resolveInfo): array 29 | { 30 | if (empty($arguments['site'])) { 31 | $arguments['site'] = [Craft::$app->getSites()->getPrimarySite()->handle]; 32 | } 33 | 34 | $siteIds = []; 35 | foreach ($arguments['site'] as $handle) { 36 | $site = Craft::$app->getSites()->getSiteByHandle($handle, false); 37 | if ($site) { 38 | $siteIds[] = $site->id; 39 | } 40 | } 41 | 42 | $updatedNodes = Plugin::getInstance()->getDeltas()->getUpdatedNodesSinceTimeStamp($arguments['since'], $siteIds); 43 | $resolved = []; 44 | $allowedInterfaces = array_keys(Plugin::getInstance()->getSourceNodes()->getSourceNodeTypes()); 45 | 46 | foreach ($allowedInterfaces as &$allowedInterface) { 47 | $allowedInterface = GqlEntityRegistry::prefixTypeName($allowedInterface); 48 | } 49 | 50 | $schema = Craft::$app->getGql()->getSchemaDef(); 51 | 52 | foreach ($updatedNodes as $updatedNode) { 53 | $element = Craft::$app->getElements()->getElementById($updatedNode['id'], $updatedNode['type']); 54 | 55 | // if element wasn't found - keep on going 56 | if ($element == null) { 57 | continue; 58 | } 59 | 60 | // Don't care about elements that don't bother implementing GQL. 61 | if ($element->getGqlTypeName() === 'Element') { 62 | continue; 63 | } 64 | 65 | // try to find the matching type; 66 | // if it's not included in the schema - move on to the next element instead of freaking out 67 | // https://github.com/craftcms/gatsby-helper/issues/31 68 | try { 69 | /** @var Element $gqlType */ 70 | $gqlType = $schema->getType(GqlEntityRegistry::prefixTypeName($element->getGqlTypeName())); 71 | } catch (GqlException $e) { 72 | Craft::error($e->getMessage()); 73 | continue; 74 | } 75 | $registeredInterfaces = $gqlType->getInterfaces(); 76 | 77 | foreach ($registeredInterfaces as $registeredInterface) { 78 | $interfaceName = $registeredInterface->name; 79 | 80 | // Make sure Gatsby can handle updates to these elements. 81 | if ($interfaceName !== GqlEntityRegistry::prefixTypeName(ElementInterface::getName()) && !in_array($interfaceName, $allowedInterfaces, true)) { 82 | continue 2; 83 | } 84 | } 85 | 86 | $resolved[] = [ 87 | 'nodeId' => $updatedNode['id'], 88 | 'nodeType' => $element->getGqlTypeName(), 89 | 'siteId' => $updatedNode['siteId'], 90 | 'elementType' => get_class($element), 91 | ]; 92 | } 93 | 94 | return $resolved; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/gql/queries/Sourcing.php: -------------------------------------------------------------------------------- 1 | 26 | * @since 1.0.0 27 | */ 28 | class Sourcing extends Query 29 | { 30 | /** 31 | * @inheritdoc 32 | */ 33 | public static function getQueries($checkToken = true): array 34 | { 35 | if ($checkToken && !GqlHelper::canQueryGatsbyData()) { 36 | return []; 37 | } 38 | 39 | return [ 40 | 'sourceNodeInformation' => [ 41 | 'type' => Type::listOf(SourceNode::getType()), 42 | 'resolve' => SourceNodeResolver::class . '::resolve', 43 | 'description' => 'Return sourcing data for Gatsby source queries.', 44 | ], 45 | 'configVersion' => [ 46 | 'type' => Type::string(), 47 | 'resolve' => function() { 48 | return Craft::$app->getInfo()->configVersion; 49 | }, 50 | 'description' => 'Return the current config version.', 51 | ], 52 | 'lastUpdateTime' => [ 53 | 'type' => DateTime::getType(), 54 | 'resolve' => function() { 55 | return Plugin::getInstance()->getDeltas()->getLastContentUpdateTime(); 56 | }, 57 | 'description' => 'Return the last time content was updated on this site.', 58 | ], 59 | 'primarySiteId' => [ 60 | 'type' => Type::string(), 61 | 'resolve' => function() { 62 | return Craft::$app->getSites()->getPrimarySite()->handle; 63 | }, 64 | 'description' => 'Return the primary site id.', 65 | ], 66 | 'nodesUpdatedSince' => [ 67 | 'type' => Type::listOf(ChangedNode::getType()), 68 | 'args' => [ 69 | 'since' => [ 70 | 'name' => 'since', 71 | 'type' => Type::nonNull(Type::string()), 72 | ], 73 | 'site' => [ 74 | 'name' => 'site', 75 | 'type' => Type::listOf(Type::string()), 76 | 'description' => 'Determines which site(s) the elements should be queried in. Defaults to the current (requested) site.', 77 | ], 78 | ], 79 | 'resolve' => UpdatedNodeResolver::class . '::resolve', 80 | 'description' => 'Return the list of nodes updated since a point in time.', 81 | ], 82 | 'nodesDeletedSince' => [ 83 | 'type' => Type::listOf(ChangedNode::getType()), 84 | 'args' => [ 85 | 'since' => [ 86 | 'name' => 'since', 87 | 'type' => Type::nonNull(Type::string()), 88 | ], 89 | ], 90 | 'resolve' => DeletedNodeResolver::class . '::resolve', 91 | 'description' => 'Return the list of nodes deleted since a point in time.', 92 | ], 93 | 'gatsbyHelperVersion' => [ 94 | 'type' => Type::string(), 95 | 'resolve' => function() { 96 | return Plugin::getInstance()->version; 97 | }, 98 | 'description' => 'Return the verison of the currently installed Helper plugin version.', 99 | ], 100 | 'gqlTypePrefix' => [ 101 | 'name' => 'gqlTypePrefix', 102 | 'type' => Type::string(), 103 | 'resolve' => function() { 104 | return Craft::$app->getConfig()->getGeneral()->gqlTypePrefix; 105 | }, 106 | 'description' => 'Return the value of the `gqlTypePrefix` config setting.', 107 | ], 108 | 'craftVersion' => [ 109 | 'name' => 'craftVersion', 110 | 'type' => Type::string(), 111 | 'description' => 'Return the value of the `gqlTypePrefix` config setting.', 112 | 'resolve' => function() { 113 | return Craft::$app->version; 114 | }, 115 | ], 116 | ]; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/services/SourceNodes.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | 11 | namespace craft\gatsbyhelper\services; 12 | 13 | use craft\base\Component; 14 | use craft\gatsbyhelper\events\RegisterSourceNodeTypesEvent; 15 | use craft\gql\GqlEntityRegistry; 16 | use craft\gql\interfaces\elements\Asset as AssetInterface; 17 | use craft\gql\interfaces\elements\Category as CategoryInterface; 18 | use craft\gql\interfaces\elements\Entry as EntryInterface; 19 | use craft\gql\interfaces\elements\GlobalSet as GlobalSetInterface; 20 | use craft\gql\interfaces\elements\Tag as TagInterface; 21 | use craft\gql\interfaces\elements\User as UserInterface; 22 | use craft\helpers\Gql; 23 | 24 | /** 25 | * SourceNodes Service 26 | * 27 | * @author Pixel & Tonic, Inc. 28 | * @since 1.0.0 29 | * 30 | * @property-read array|mixed $sourceNodeTypes 31 | * @property-read array[]|mixed $sourcingData 32 | */ 33 | class SourceNodes extends Component 34 | { 35 | /** 36 | * @event RegisterSourceNodesEvent The event that is triggered when registering source node types. 37 | * 38 | * Plugins get a chance to specify additional elements that should be Gatsby source nodes. 39 | * 40 | * --- 41 | * ```php 42 | * use craft\events\RegisterSourceNodeTypesEvent; 43 | * use craft\gatsbyhelper\services\SourceNodes; 44 | * use yii\base\Event; 45 | * 46 | * Event::on(SourceNodes::class, SourceNodes::EVENT_REGISTER_SOURCE_NODE_TYPES, function(RegisterSourceNodeTypesEvent $event) { 47 | * $event->types[BookInterface::getName()] = [ 48 | * 'node' => 'book', 49 | * 'list' => 'books', 50 | * 'filterArgument' => 'type', 51 | * 'filterTypeExpression' => '(.+)_Book', 52 | * 'targetInterface' => BookInterface::getName(), 53 | * ]; 54 | * }); 55 | * ``` 56 | */ 57 | public const EVENT_REGISTER_SOURCE_NODE_TYPES = 'registerSourceNodeTypes'; 58 | 59 | /** 60 | * Return the query filters to use for querying source data with Gatsby 61 | * 62 | * @return array 63 | */ 64 | public function getSourceNodeTypes(): array 65 | { 66 | $nodeTypes = []; 67 | 68 | if (Gql::canQueryEntries()) { 69 | $nodeTypes[EntryInterface::getName()] = [ 70 | 'node' => 'entry', 71 | 'list' => 'entries', 72 | 'filterArgument' => 'type', 73 | 'filterTypeExpression' => '(?:.+)_(.+)_Entry+$', 74 | 'targetInterface' => EntryInterface::getName(), 75 | ]; 76 | } 77 | 78 | if (Gql::canQueryAssets()) { 79 | $nodeTypes[AssetInterface::getName()] = [ 80 | 'node' => 'asset', 81 | 'list' => 'assets', 82 | 'filterArgument' => 'volume', 83 | 'filterTypeExpression' => '(.+)_Asset$', 84 | 'targetInterface' => AssetInterface::getName(), 85 | ]; 86 | } 87 | 88 | if (Gql::canQueryCategories()) { 89 | $nodeTypes[CategoryInterface::getName()] = [ 90 | 'node' => 'category', 91 | 'list' => 'categories', 92 | 'filterArgument' => 'group', 93 | 'filterTypeExpression' => '(.+)_Category$', 94 | 'targetInterface' => CategoryInterface::getName(), 95 | ]; 96 | } 97 | 98 | if (Gql::canQueryGlobalSets()) { 99 | $nodeTypes[GlobalSetInterface::getName()] = [ 100 | 'node' => 'globalSet', 101 | 'list' => 'globalSets', 102 | 'filterArgument' => 'handle', 103 | 'filterTypeExpression' => '(.+)_GlobalSet$', 104 | 'targetInterface' => GlobalSetInterface::getName(), 105 | ]; 106 | } 107 | 108 | if (Gql::canQueryTags()) { 109 | $nodeTypes[TagInterface::getName()] = [ 110 | 'node' => 'tag', 111 | 'list' => 'tags', 112 | 'filterArgument' => 'group', 113 | 'filterTypeExpression' => '(.+)_Tag$', 114 | 'targetInterface' => TagInterface::getName(), 115 | ]; 116 | } 117 | 118 | if (Gql::canQueryUsers()) { 119 | $nodeTypes[UserInterface::getName()] = [ 120 | 'node' => 'user', 121 | 'list' => 'users', 122 | 'filterArgument' => '', 123 | 'filterTypeExpression' => '', 124 | 'targetInterface' => UserInterface::getName(), 125 | ]; 126 | } 127 | 128 | $event = new RegisterSourceNodeTypesEvent([ 129 | 'types' => $nodeTypes, 130 | ]); 131 | 132 | $this->trigger(self::EVENT_REGISTER_SOURCE_NODE_TYPES, $event); 133 | 134 | foreach ($event->types as &$sourceNodeType) { 135 | $sourceNodeType['targetInterface'] = GqlEntityRegistry::prefixTypeName($sourceNodeType['targetInterface']); 136 | } 137 | 138 | return $event->types; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/services/Deltas.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | 11 | namespace craft\gatsbyhelper\services; 12 | 13 | use Craft; 14 | use craft\base\Component; 15 | use craft\base\Element; 16 | use craft\db\Query; 17 | use craft\db\Table as CraftTable; 18 | use craft\elements\MatrixBlock; 19 | use craft\gatsbyhelper\db\Table; 20 | use craft\gatsbyhelper\events\RegisterIgnoredTypesEvent; 21 | use craft\helpers\DateTimeHelper; 22 | use craft\helpers\Db; 23 | use DateTime; 24 | use yii\db\Expression; 25 | 26 | /** 27 | * Deltas Service 28 | * 29 | * @author Pixel & Tonic, Inc. 30 | * @since 1.0.0 31 | * 32 | * @property-read null|string|false $lastContentUpdateTime 33 | * @property-read string $version 34 | */ 35 | class Deltas extends Component 36 | { 37 | /** 38 | * @event RegisterIgnoredTypesEvent The event that is triggered when registering ignored element types. 39 | * 40 | * Plugins get a chance to specify which element types should not be updated individually. 41 | * 42 | * --- 43 | * ```php 44 | * use craft\events\RegisterIgnoredTypesEvent; 45 | * use craft\gatsbyhelper\services\Deltas; 46 | * use yii\base\Event; 47 | * 48 | * Event::on(Deltas::class, Deltas::EVENT_REGISTER_IGNORED_TYPES, function(RegisterIgnoredTypesEvent $event) { 49 | * $event->types[] = MyType::class; 50 | * }); 51 | * ``` 52 | */ 53 | public const EVENT_REGISTER_IGNORED_TYPES = 'registerIgnoredTypes'; 54 | 55 | /** 56 | * Get the last time content was updated or deleted. 57 | * 58 | * @return false|string|null 59 | * @throws \Exception 60 | */ 61 | public function getLastContentUpdateTime(): bool|string|null 62 | { 63 | $lastUpdated = (new Query()) 64 | ->select(new Expression('MAX([[dateUpdated]])')) 65 | ->from([CraftTable::ELEMENTS]) 66 | ->where(['dateDeleted' => null]) 67 | ->scalar(); 68 | 69 | $lastDeleted = (new Query()) 70 | ->select(new Expression('MAX([[dateDeleted]])')) 71 | ->from([Table::DELETED_ELEMENTS]) 72 | ->scalar(); 73 | 74 | if (!$lastDeleted) { 75 | return $lastUpdated; 76 | } 77 | 78 | if (!$lastUpdated) { 79 | return $lastDeleted; 80 | } 81 | 82 | if (DateTimeHelper::toDateTime($lastUpdated) < DateTimeHelper::toDateTime($lastDeleted)) { 83 | return $lastDeleted; 84 | } 85 | 86 | return $lastUpdated; 87 | } 88 | 89 | /** 90 | * Get updated nodes since a specific timestamp. 91 | * 92 | * @param string $timestamp 93 | * @param int[] $siteIds 94 | * @return array 95 | */ 96 | public function getUpdatedNodesSinceTimeStamp(string $timestamp, array $siteIds): array 97 | { 98 | $structureUpdates = (new Query()) 99 | ->select(['elementId', 'structureId']) 100 | ->from([CraftTable::STRUCTUREELEMENTS]) 101 | ->andWhere(['>', 'dateUpdated', Db::prepareDateForDb($timestamp)]) 102 | ->pairs(); 103 | 104 | return (new Query()) 105 | ->select(['e.id', 'e.type', 'es.siteId']) 106 | ->from(['e' => CraftTable::ELEMENTS]) 107 | ->innerJoin(['es' => CraftTable::ELEMENTS_SITES], ['and', '[[e.id]] = [[es.elementId]]', ['es.siteId' => $siteIds]]) 108 | ->where(['e.dateDeleted' => null]) 109 | ->andWhere(['not in', 'e.type', $this->_getIgnoredTypes()]) 110 | ->andWhere( 111 | [ 112 | 'or', 113 | ['>', 'e.dateUpdated', Db::prepareDateForDb($timestamp)], 114 | ['IN', 'e.id', array_keys($structureUpdates)], 115 | ] 116 | ) 117 | ->andWhere(['e.revisionId' => null]) 118 | ->andWhere(['e.draftId' => null]) 119 | ->all(); 120 | } 121 | 122 | /** 123 | * Get deleted nodes since a specific timestamp. 124 | * 125 | * @param string $timestamp 126 | * @return array 127 | */ 128 | public function getDeletedNodesSinceTimeStamp(string $timestamp): array 129 | { 130 | return (new Query()) 131 | ->select(['elementId', 'siteId', 'typeName']) 132 | ->from([Table::DELETED_ELEMENTS]) 133 | ->where(['>', 'dateDeleted', Db::prepareDateForDb($timestamp)]) 134 | ->all(); 135 | } 136 | 137 | /** 138 | * Register a deleted element. 139 | * 140 | * @param Element $element 141 | * @return bool 142 | */ 143 | public function registerDeletedElement(Element $element): bool 144 | { 145 | if (in_array(get_class($element), $this->_getIgnoredTypes(), true)) { 146 | return false; 147 | } 148 | 149 | // In case this is being deleted _again_ 150 | Db::delete(Table::DELETED_ELEMENTS, ['elementId' => $element->id]); 151 | 152 | $sites = Craft::$app->getSites()->getAllSiteIds(true); 153 | 154 | $rows = []; 155 | foreach ($sites as $site) { 156 | $rows[] = [$element->id, $site, $element->getGqlTypeName(), Db::prepareDateForDb(new DateTime())]; 157 | } 158 | 159 | return (bool)Db::batchInsert(Table::DELETED_ELEMENTS, ['elementId', 'siteId', 'typeName', 'dateDeleted'], $rows); 160 | } 161 | 162 | /** 163 | * Return a list of all the element types that should be ignored. 164 | * 165 | * @return string[] 166 | */ 167 | private function _getIgnoredTypes(): array 168 | { 169 | $event = new RegisterIgnoredTypesEvent([ 170 | 'types' => [ 171 | MatrixBlock::class, 172 | ], 173 | ]); 174 | 175 | $this->trigger(self::EVENT_REGISTER_IGNORED_TYPES, $event); 176 | 177 | return $event->types; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/Plugin.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | 11 | namespace craft\gatsbyhelper; 12 | 13 | use Craft; 14 | use craft\base\Element; 15 | use craft\base\Model; 16 | use craft\elements\Entry; 17 | use craft\events\RegisterGqlQueriesEvent; 18 | use craft\events\RegisterGqlSchemaComponentsEvent; 19 | use craft\events\RegisterPreviewTargetsEvent; 20 | use craft\gatsbyhelper\gql\queries\Sourcing as SourcingDataQueries; 21 | use craft\gatsbyhelper\models\Settings; 22 | use craft\gatsbyhelper\services\Builds; 23 | use craft\gatsbyhelper\services\Deltas; 24 | use craft\gatsbyhelper\services\SourceNodes; 25 | use craft\helpers\ElementHelper; 26 | use craft\services\Gql; 27 | use yii\base\Event; 28 | 29 | /** 30 | * @author Pixel & Tonic, Inc. 31 | * @since 1.0.0 32 | * 33 | * @method Settings getSettings() 34 | * @property-read Deltas $deltas 35 | * @property-read Settings $settings 36 | * @property-read SourceNodes $sourceNodes 37 | */ 38 | class Plugin extends \craft\base\Plugin 39 | { 40 | /** 41 | * @inheritdoc 42 | */ 43 | public static function config(): array 44 | { 45 | return [ 46 | 'components' => [ 47 | 'builds' => ['class' => Builds::class], 48 | 'deltas' => ['class' => Deltas::class], 49 | 'sourceNodes' => ['class' => SourceNodes::class], 50 | ], 51 | ]; 52 | } 53 | 54 | /** 55 | * @inheritdoc 56 | */ 57 | public string $schemaVersion = '2.0.0'; 58 | 59 | /** 60 | * @inheritdoc 61 | */ 62 | public bool $hasCpSettings = true; 63 | 64 | /** 65 | * @inheritdoc 66 | */ 67 | public string $minVersionRequired = '1.0.3'; 68 | 69 | /** 70 | * @inheritdoc 71 | */ 72 | public function init(): void 73 | { 74 | parent::init(); 75 | $this->_registerGqlQueries(); 76 | $this->_registerGqlComponents(); 77 | $this->_registerElementListeners(); 78 | $this->_registerLivePreviewListener(); 79 | } 80 | 81 | /** 82 | * Return the SourceNodes service. 83 | * 84 | * @return SourceNodes 85 | * @throws \yii\base\InvalidConfigException 86 | */ 87 | public function getSourceNodes(): SourceNodes 88 | { 89 | return $this->get('sourceNodes'); 90 | } 91 | 92 | /** 93 | * Return the Deltas service. 94 | * 95 | * @return Deltas 96 | * @throws \yii\base\InvalidConfigException 97 | */ 98 | public function getDeltas(): Deltas 99 | { 100 | return $this->get('deltas'); 101 | } 102 | 103 | /** 104 | * Return the Builds service. 105 | * 106 | * @return Builds 107 | * @throws \yii\base\InvalidConfigException 108 | */ 109 | public function getBuilds(): Builds 110 | { 111 | return $this->get('builds'); 112 | } 113 | 114 | /** 115 | * @inheritdoc 116 | */ 117 | protected function createSettingsModel(): Model 118 | { 119 | return new Settings(); 120 | } 121 | 122 | /** 123 | * @inheritdoc 124 | */ 125 | protected function settingsHtml(): null|string 126 | { 127 | return Craft::$app->getView()->renderTemplate('gatsby-helper/settings', [ 128 | 'settings' => $this->getSettings(), 129 | ]); 130 | } 131 | 132 | /** 133 | * Register the Gql queries 134 | */ 135 | private function _registerGqlQueries(): void 136 | { 137 | Event::on( 138 | Gql::class, 139 | Gql::EVENT_REGISTER_GQL_QUERIES, 140 | static function(RegisterGqlQueriesEvent $event) { 141 | // Add my GraphQL queries 142 | $event->queries = array_merge( 143 | $event->queries, 144 | SourcingDataQueries::getQueries() 145 | ); 146 | } 147 | ); 148 | } 149 | 150 | /** 151 | * Register the Gql schema components 152 | */ 153 | private function _registerGqlComponents(): void 154 | { 155 | Event::on( 156 | Gql::class, 157 | Gql::EVENT_REGISTER_GQL_SCHEMA_COMPONENTS, 158 | static function(RegisterGqlSchemaComponentsEvent $event) { 159 | $label = 'Gatsby'; 160 | 161 | $event->queries[$label] = [ 162 | 'gatsby:read' => ['label' => 'Allow discovery of sourcing data for Gatsby.'], 163 | ]; 164 | } 165 | ); 166 | } 167 | 168 | /** 169 | * Register the Element listeners 170 | */ 171 | private function _registerElementListeners(): void 172 | { 173 | Event::on( 174 | Element::class, 175 | Element::EVENT_AFTER_DELETE, 176 | function(Event $event) { 177 | /** @var Element $element */ 178 | $element = $event->sender; 179 | 180 | $this->getDeltas()->registerDeletedElement($element); 181 | 182 | /** @var Element $element */ 183 | $element = $event->sender; 184 | $rootElement = ElementHelper::rootElement($element); 185 | 186 | // If the element or it's root element is a draft, don't trigger a build. 187 | if ($rootElement->getIsDraft() || $rootElement->getIsRevision()) { 188 | return; 189 | } 190 | 191 | $this->getBuilds()->triggerBuild(); 192 | } 193 | ); 194 | 195 | Event::on( 196 | Element::class, 197 | Element::EVENT_AFTER_SAVE, 198 | function(Event $event) { 199 | /** @var Element $element */ 200 | $element = $event->sender; 201 | $rootElement = ElementHelper::rootElement($element); 202 | 203 | // If the element or it's root element is a draft, don't trigger a build. 204 | if ($rootElement->getIsDraft() || $rootElement->getIsRevision()) { 205 | return; 206 | } 207 | 208 | $this->getBuilds()->triggerBuild(); 209 | } 210 | ); 211 | } 212 | 213 | /** 214 | * Inject the live preview listener code. 215 | */ 216 | private function _registerLivePreviewListener(): void 217 | { 218 | $previewWebhookUrl = Craft::parseEnv($this->getSettings()->previewWebhookUrl); 219 | 220 | if (!empty($previewWebhookUrl)) { 221 | Event::on( 222 | Entry::class, 223 | Entry::EVENT_REGISTER_PREVIEW_TARGETS, 224 | function(RegisterPreviewTargetsEvent $event) use ($previewWebhookUrl) { 225 | /** @var Element $element */ 226 | $element = $event->sender; 227 | 228 | $gqlTypeName = $element->getGqlTypeName(); 229 | 230 | $elementId = method_exists($element, 'getCanonicalId') ? $element->getCanonicalId() : $element->getSourceId(); 231 | 232 | $js = <<siteId} 255 | }; 256 | 257 | if (doPreview) { 258 | payload.token = await event.target.elementEditor.getPreviewToken(); 259 | } else { 260 | currentlyPreviewing = null; 261 | } 262 | 263 | http.open('POST', "$previewWebhookUrl", true); 264 | http.setRequestHeader('Content-type', 'application/json'); 265 | http.setRequestHeader('x-preview-update-source', 'Craft CMS'); 266 | http.send(JSON.stringify(payload)); 267 | } 268 | 269 | Garnish.on(Craft.Preview, 'beforeUpdateIframe', function(event) { 270 | alertGatsby(event, true); 271 | }); 272 | 273 | Garnish.on(Craft.Preview, 'beforeClose', function(event) { 274 | alertGatsby(event, false); 275 | }); 276 | 277 | Garnish.\$win.on('beforeunload', function(event) { 278 | alertGatsby(event, false); 279 | }); 280 | } 281 | JS; 282 | 283 | Craft::$app->view->registerJs($js); 284 | }); 285 | } 286 | } 287 | } 288 | --------------------------------------------------------------------------------