From 6b7f4459fe10fff4395a204e19228149af42f02e Mon Sep 17 00:00:00 2001 From: Eric Rosas Date: Fri, 27 Sep 2024 14:08:48 -0700 Subject: [PATCH] Initial commit --- CHANGELOG.md | 37 +++++ LICENSE.md | 9 ++ README.md | 53 +++++++ composer.json | 44 ++++++ src/ElementStatusEvents.php | 104 ++++++++++++++ src/behaviors/ElementStatusBehavior.php | 66 +++++++++ src/commands/ScheduledElements.php | 182 ++++++++++++++++++++++++ src/events/StatusChangeEvent.php | 61 ++++++++ 8 files changed, 556 insertions(+) create mode 100644 CHANGELOG.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 src/ElementStatusEvents.php create mode 100644 src/behaviors/ElementStatusBehavior.php create mode 100644 src/commands/ScheduledElements.php create mode 100644 src/events/StatusChangeEvent.php diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..070b875 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,37 @@ +# Element Status Events Changelog + +## 2.0.1 - 2022-04-26 +- Remove deprecated `enabledForSite()` element query parameter + +## 2.0.0 - 2019-03-28 +### Added +- Added event object `StatusChangeEvent` with access to element via `getElement()` and check methods: + - `changedTo(string $nameOfStatus)` + - `changedToPublished()` + - `changedToUnpublished()` + +- Added Craft CLI command `element-status-events/scheduled` to take scheduled elements into account. + +### Changed +- No need to bootstrap or register the extension. +- Extension implements `BootstrapInterface`. +- Event `ElementStatusEvents::EVENT_STATUS_CHANGED`. + +## 1.3.0 - 2019-01-18 +### Changed +- Converted from module to extension. + +## 1.2.1 - 2019-01-18 +### Fixed +- Fixed missing variable. + +## 1.2.0 - 2019-01-17 +### Changed +- Removed the `ElementStatusService::EVENT_ELEMENT_STATUSES_CHANGED` event as it cannot be guaranteed that it will be triggered under every circumstance. + +## 1.1.0 - 2019-01-15 +### Changed +- Changed the module to use a service so that it can be loaded from any other module or plugin without having to be bootstrapped. + +## 1.0.0 - 2019-01-14 +- Initial release. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..2cdbdf9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2022 Cast Iron Coding + +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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a6ecee9 --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# Element Status Events for Craft CMS 3 + +The Element Status Events extension provides events that are triggered whenever an element’s status changes. It is intended to be used a helper component for other Craft modules and plugins. + +To get an understanding of how the module works, read the [Challenge #6 – The Chicken or the Egg](https://craftcodingchallenge.com/challenge-6-the-chicken-or-the-egg) solution. + +## Requirements + +This extension requires Craft CMS 3.0.0 or later. + +## Usage + +Install it manually using composer or add it as a dependency to your plugin. +``` +composer require putyourlightson/craft-element-status-events +``` + +If you work with scheduled Entries (future published or expired), make sure to set up cron that calls: +``` +php craft element-status-events/scheduled +``` + + +## Events + +Whenever an element’s status is changed, `ElementStatusEvents::EVENT_STATUS_CHANGED` is fired. The `StatusChangeEvent` object provides information about the change. + +```php + +use putyourlightson\elementstatusevents\ElementStatusEvents; +use putyourlightson\elementstatusevents\events\StatusChangeEvent; + +// ... + +Event::on( + ElementStatusEvents::class, + ElementStatusEvents::EVENT_STATUS_CHANGED, + function(StatusChangeEvent $event) { + $oldStatus = $event->statusBeforeSave; + $newStatus = $event->element->getStatus(); + $isLive = $event->changedToPublished(); + $isDeath = $event->changedToUnpublished(); + $isScheduled = $event->changedTo('pending'); + } +); +``` + + +## License + +This extension is licensed for free under the MIT License. + +Created by [PutYourLightsOn](https://putyourlightson.com/) in cooperation with [Oliver Stark](https://github.com/ostark) diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..0b213f7 --- /dev/null +++ b/composer.json @@ -0,0 +1,44 @@ +{ + "name": "putyourlightson/craft-element-status-events", + "description": "Element status events extension for Craft CMS.", + "version": "2.1.0", + "type": "yii2-extension", + "homepage": "https://github.com/lsst-epo/craft-element-status-events", + "license": "MIT", + "keywords": [ + "craft", + "cms", + "craftcms", + "element", + "status", + "events" + ], + "authors": [ + { + "name": "Ben Croker", + "homepage": "https://putyourlightson.com", + "role": "Developer" + }, + { + "name": "Oliver Stark", + "homepage": "https://www.fortrabbit.com", + "role": "Developer" + } + ], + "require": { + "craftcms/cms": "^4.0.0" + }, + "autoload": { + "psr-4": { + "putyourlightson\\elementstatusevents\\": "src/" + } + }, + "support": { + "docs": "https://github.com/lsst-epo/craft-element-status-events", + "source": "https://github.com/lsst-epo/craft-element-status-events", + "issues": "https://github.com/lsst-epo/craft-element-status-events/issues" + }, + "extra": { + "bootstrap": "putyourlightson\\elementstatusevents\\ElementStatusEvents" + } +} diff --git a/src/ElementStatusEvents.php b/src/ElementStatusEvents.php new file mode 100644 index 0000000..2584270 --- /dev/null +++ b/src/ElementStatusEvents.php @@ -0,0 +1,104 @@ +controllerMap[$group] = ScheduledElements::class; + } + + /** + * Bootstrap the extension + * + * @param YiiApp $app + */ + public function bootstrap($app) + { + // Make sure it's Craft + if (!($app instanceof CraftWebApp || $app instanceof CraftConsoleApp)) { + return; + } + + Event::on(Elements::class, Elements::EVENT_BEFORE_SAVE_ELEMENT, [$this, 'rememberPreviousStatus']); + Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, [$this, 'fireEventOnChange']); + + if ($app instanceof CraftConsoleApp) { + // Tell Craft about the concrete implementation of CacheInterface + Craft::$container->set(CacheInterface::class, Craft::$app->getCache()); + self::registerScheduledCommand($app); + } + } + + /** + * Register event listener + * + * @param ElementEvent $event + */ + public function rememberPreviousStatus(ElementEvent $event) + { + /** @var Element|ElementStatusBehavior $element */ + $element = $event->element; + + // Attach behavior to access the status later + $element->attachBehavior('elementStatusEvents', ElementStatusBehavior::class); + + // No need to remember anything + if ($event->isNew) { + return; + } + + $element->rememberPreviousStatus(); + } + + /** + * Register event listener + * + * @param ElementEvent $event + */ + public function fireEventOnChange(ElementEvent $event) + { + /** @var Element|ElementStatusBehavior $element */ + $element = $event->element; + + // Fire ElementStatusEvents::EVENT_STATUS_CHANGED + if ($element->getBehavior('elementStatusEvents') !== null) { + $element->fireEventOnChange(); + } + } + +} diff --git a/src/behaviors/ElementStatusBehavior.php b/src/behaviors/ElementStatusBehavior.php new file mode 100644 index 0000000..3a9487f --- /dev/null +++ b/src/behaviors/ElementStatusBehavior.php @@ -0,0 +1,66 @@ +owner; + + $originalElement = Craft::$app->getElements()->getElementById( + $element->id, + get_class($element), + $element->siteId + ); + + $this->statusBeforeSave = $originalElement === null ?: $originalElement->getStatus(); + } + + /** + * Triggers an event if the status has changed + */ + public function fireEventOnChange() + { + /** @var Element $element */ + $element = $this->owner; + + // Nothing changed? + if ($this->statusBeforeSave === $element->getStatus()) { + return; + } + + if (Event::hasHandlers(ElementStatusEvents::class, ElementStatusEvents::EVENT_STATUS_CHANGED)) { + Event::trigger( + ElementStatusEvents::class, + ElementStatusEvents::EVENT_STATUS_CHANGED, + new StatusChangeEvent([ + 'element' => $element, + 'statusBeforeSave' => $this->statusBeforeSave + ]) + ); + } + } +} diff --git a/src/commands/ScheduledElements.php b/src/commands/ScheduledElements.php new file mode 100644 index 0000000..9c8e04a --- /dev/null +++ b/src/commands/ScheduledElements.php @@ -0,0 +1,182 @@ +cache = $cache; + parent::__construct($id, $module, $config); + } + + + /** + * Checks for scheduled Entries, call this command via cron + * + * @param string $forcedCheckInterval Time string of lower bound of the range, e.g. '-2 hours' + * + * @return int + */ + public function actionScheduled($forcedCheckInterval = null) + { + $lastCheck = $this->cache->exists(self::LAST_CHECK_CACHE_KEY) + ? $this->cache->get(self::LAST_CHECK_CACHE_KEY) + : Db::prepareDateForDb((new \DateTime())->modify(self::LAST_CHECK_DEFAULT_INTERVAL)); + + if ($forcedCheckInterval) { + $lastCheck = Db::prepareDateForDb((new \DateTime())->modify($forcedCheckInterval)); + } + + $now = Db::prepareDateForDb(new \DateTime()); + $published = $this->getPublishedEntries($lastCheck, $now); + $expired = $this->getExpiredEntries($lastCheck, $now); + $entries = array_merge($published, $expired); + + // Remember this check + $this->cache->set(self::LAST_CHECK_CACHE_KEY, $now); + + // Print info + ConsoleHelper::output(sprintf("> Expired Entries: %d", count($expired))); + ConsoleHelper::output(sprintf("> Published Entries: %d", count($published))); + ConsoleHelper::output(sprintf("> Range: %s to %s", $lastCheck, $now)); + + if (!count($entries)) { + return ExitCode::OK; + } + + $this->fireEvent($published, Entry::STATUS_PENDING); + $this->fireEvent($expired, Entry::STATUS_LIVE); + + $this->drawTable($entries); + + return ExitCode::OK; + } + + /** + * @param array $entries + */ + protected function drawTable(array $entries) + { + $rows = []; + + foreach ($entries as $entry) { + /** @var Entry $entry */ + $postDateString = $entry->postDate ? $entry->postDate->format(self::DATE_FORMAT) : '-'; + $expiryDateString = $entry->expiryDate ? $entry->expiryDate->format(self::DATE_FORMAT) : '-'; + $rows[] = [$entry->title, $postDateString, $expiryDateString]; + }; + + echo Table::widget([ + 'headers' => ['Title', 'PostDate', 'ExpiryDate'], + 'rows' => $rows, + ]); + + } + + /** + * @param array $elements + * @param string $previousStatus + */ + protected function fireEvent(array $elements, $previousStatus = '') + { + if (count($elements) === 0) { + return; + } + foreach ($elements as $element) { + Event::trigger( + ElementStatusEvents::class, + ElementStatusEvents::EVENT_STATUS_CHANGED, + new StatusChangeEvent([ + 'element' => $element, + 'statusBeforeSave' => $previousStatus + ]) + ); + } + } + + + /** + * @param $rangeStart + * @param $rangeEnd + * + * @return array + */ + protected function getPublishedEntries($rangeStart, $rangeEnd): array + { + // TODO: Support Product and other Elements with postDate + + // Entries published within time frame + $entries = (Entry::find() + ->where(['between', 'postDate', $rangeStart, $rangeEnd]) + ->withStructure(false) + ->orderBy(null) + ->status('live') + )->all(); + + // Exclude manually published entries (postDate ≅ dateUpdated) + return array_filter($entries, function (Entry $item) { + $diffInSeconds = abs($item->postDate->getTimestamp() - $item->dateUpdated->getTimestamp()); + return ($diffInSeconds > 60); + }); + } + + /** + * @param $rangeStart + * @param $rangeEnd + * + * @return Entry[] + */ + protected function getExpiredEntries($rangeStart, $rangeEnd): array + { + // TODO: Support Product and other Elements with expiryDate + + return (Entry::find() + ->where(['between', 'expiryDate', $rangeStart, $rangeEnd]) + ->withStructure(false) + ->orderBy(null) + ->status('expired') + )->all(); + } +} diff --git a/src/events/StatusChangeEvent.php b/src/events/StatusChangeEvent.php new file mode 100644 index 0000000..f636392 --- /dev/null +++ b/src/events/StatusChangeEvent.php @@ -0,0 +1,61 @@ +element->getStatus() === $nameOfStatus); + } + + /** + * @return bool + */ + public function changedToPublished(): bool + { + return in_array($this->element->getStatus(), [Entry::STATUS_LIVE, Element::STATUS_ENABLED]); + } + + /** + * @return bool + */ + public function changedToUnpublished(): bool + { + return !$this->changedToPublished(); + } + + /** + * @return ElementInterface|null + */ + public function getElement() + { + return $this->element; + } +}