Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NEW: Event-driven snapshot actions #3

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
376 changes: 145 additions & 231 deletions README.md

Large diffs are not rendered by default.

73 changes: 42 additions & 31 deletions _config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,55 +27,66 @@ Name: snapshot-listeners
---
SilverStripe\CMS\Controllers\CMSMain:
extensions:
- SilverStripe\Snapshots\Listener\Page\CMSMainAction
- SilverStripe\Snapshots\Listener\CMSMain\Listener

SilverStripe\Forms\GridField\GridField:
extensions:
- SilverStripe\Snapshots\Listener\GridField\AlterAction
- SilverStripe\Snapshots\Listener\GridField\UrlHandlerAction
- SilverStripe\Snapshots\Listener\GridField\Alteration\Listener
- SilverStripe\Snapshots\Listener\GridField\Action\Listener

SilverStripe\Forms\FormRequestHandler:
extensions:
- SilverStripe\Snapshots\Listener\Form\Submission
- SilverStripe\Snapshots\Listener\Form\Listener

SilverStripe\GraphQL\Scaffolding\Scaffolders\CRUD\Create:
extensions:
- SilverStripe\Snapshots\Listener\GraphQL\GenericAction
- SilverStripe\Snapshots\Listener\GraphQL\Mutation\Listener

SilverStripe\GraphQL\Scaffolding\Scaffolders\CRUD\Delete:
extensions:
- SilverStripe\Snapshots\Listener\GraphQL\GenericAction
- SilverStripe\Snapshots\Listener\GraphQL\Mutation\Listener

SilverStripe\GraphQL\Scaffolding\Scaffolders\CRUD\Update:
extensions:
- SilverStripe\Snapshots\Listener\GraphQL\GenericAction
- SilverStripe\Snapshots\Listener\GraphQL\Mutation\Listener

SilverStripe\GraphQL\Manager:
extensions:
- SilverStripe\Snapshots\Listener\GraphQL\CustomAction
- SilverStripe\Snapshots\Listener\GraphQL\Middleware\Listener

---
Name: snapshot-actions
Name: snapshot-events
---
SilverStripe\Snapshots\Snapshot:
actions:
# page edit form
'save': 'Save page'
'publish': 'Publish'
'unpublish': 'Unpublish'
# site tree
'savetreenode': 'Changed site tree position'
# grid field item edit form
'doSave': 'Save item'
'doDelete': 'Delete item'
# grid field actions (via standard action)
'deleterecord': 'Delete item'
# grid field actions (via form submission)
'handleReorder': 'Changed items order'
# linkable edit form
'doSaveLink': 'Link Edit'
'doRemoveLink': 'Link Delete'
# GraphQL CRUD
'graphql_crud_create': 'GraphQL create'
'graphql_crud_delete': 'GraphQL delete'
'graphql_crud_update': 'GraphQL update'
SilverStripe\Core\Injector\Injector:
SilverStripe\Snapshots\Dispatch\Dispatcher:
properties:
handlers:
formGeneric:
on:
'formSubmitted.unpublish': true
'formSubmitted.doSave': true
'formSubmitted.doDelete': true
handler: %$SilverStripe\Snapshots\Handler\Form\Handler
save:
on:
'formSubmitted.save': true
handler: %$SilverStripe\Snapshots\Handler\Form\SaveHandler
publish:
on:
'formSubmitted.publish': true
handler: %$SilverStripe\Snapshots\Handler\Form\PublishHandler
cmsMain:
on:
'cmsAction.savetreenode': true
handler: %$SilverStripe\Snapshots\Handler\CMSMain\Handler
gridFieldAction:
on:
'gridFieldAlteration.deleterecord': true
'gridFieldAlteration.archiverecord': true
handler: %$SilverStripe\Snapshots\Handler\GridField\Action\Handler
graphqlMutation:
on:
'graphqlMutation.create': true
'graphqlMutation.update': true
'graphqlMutation.delete': true
handler: %$SilverStripe\Snapshots\Handler\GraphQL\Mutation\Handler
18 changes: 18 additions & 0 deletions lang/en.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
en:
SilverStripe\Snapshots\Handler\Form\FormSubmissionHandler:
HANDLER_unpublish: 'Unpublish page'
HANDLER_doSave: 'Save item'
HANDLER_doDelete: 'Delete item'
SilverStripe\Snapshots\Handler\Form\SaveHandler:
HANDLER_save: 'Save page'
SilverStripe\Snapshots\Handler\Form\PublishHandler:
HANDLER_publish: 'Publish page'
SilverStripe\Snapshots\Handler\CMSMain\ActionHandler:
HANDLER_savetreenode: 'Reordered site tree'
SilverStripe\Snapshots\Handler\GraphQL\MutationHandler:
HANDLER_graphql_crud_create: 'GraphQL create'
HANDLER_graphql_crud_update: 'GraphQL update'
HANDLER_graphql_crud_delete: 'GraphQL delete'
SilverStripe\Snapshots\Handler\GridField\URLActionHandler:
HANDLER_deleterecord: 'Delete record'
HANDLER_archiverecord: 'Archive record'
11 changes: 10 additions & 1 deletion src/ActivityEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use SilverStripe\Versioned\Versioned;
use SilverStripe\View\ArrayData;
use Exception;

class ActivityEntry extends ArrayData
{
Expand Down Expand Up @@ -49,7 +50,7 @@ public static function createFromSnapshotItem(SnapshotItem $item)
$previousVersion = Versioned::get_all_versions($item->ObjectClass, $item->ObjectID)
->sort('Version', 'DESC')
->first();
if ($previousVersion->exists()) {
if ($previousVersion && $previousVersion->exists()) {
$itemObj = $item->getItem($previousVersion->Version);
// This is to deal with the case in which there is no previous version
// it's better to give a faulty snapshot point than break the app
Expand All @@ -58,6 +59,14 @@ public static function createFromSnapshotItem(SnapshotItem $item)
}
}

if (!$itemObj) {
throw new Exception(sprintf(
'Could not resolve SnapshotItem %s to a previous %s version',
$item->ID,
$item->ObjectClass
));
}

return new static([
'Subject' => $itemObj,
'Action' => $flag,
Expand Down
171 changes: 171 additions & 0 deletions src/Dispatch/Dispatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<?php

namespace SilverStripe\Snapshots\Dispatch;

use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Snapshots\Handler\HandlerInterface;
use InvalidArgumentException;
use Exception;
use SilverStripe\Snapshots\Listener\EventContext;

class Dispatcher
{
use Injectable;

/**
* @var EventHandlerLoader[]
*/
private $loaders = [];

/**
* @var array HandlerInterface[]
*/
private $handlers = [];

/**
* @var bool
*/
private $initialised = false;

/**
* @param EventHandlerLoader[] $loaders
* @return $this
*/
public function setLoaders($loaders = [])
{
foreach ($loaders as $loader) {
if (!$loader instanceof EventHandlerLoader) {
throw new InvalidArgumentException(sprintf(
'%s not passed an instance of %s',
__CLASS__,
EventHandlerLoader::class
));
}
}
$this->loaders = $loaders;

return $this;
}

/**
* @param array $handlers
* @throws Exception
*/
public function setHandlers(array $handlers)
{
foreach ($handlers as $spec) {
if (!isset($spec['handler']) || !isset($spec['on'])) {
throw new InvalidArgumentException('Event handlers must have a "on" and "handler" nodes');
}
$on = is_array($spec['on']) ? $spec['on'] : [$spec['on']];
$handler = $spec['handler'];

if (!$handler instanceof HandlerInterface) {
throw new InvalidArgumentException(sprintf(
'Handler for %s is not an instance of %s',
implode(', ', $on),
HandlerInterface::class
));
}

foreach ($on as $eventName => $shouldInclude) {
if ($shouldInclude) {
$this->addListener($eventName, $handler);
}
}
}
}

/**
* @param string $event
* @param HandlerInterface $handler
* @return $this
* @throws Exception
*/
public function addListener(string $event, HandlerInterface $handler): self
{
if (!isset($this->handlers[$event])) {
$this->handlers[$event] = [];
}

foreach ($this->handlers[$event] as $existing) {
if ($existing === $handler) {
throw new Exception(sprintf(
'Handler for %s has already been added',
$event
));
}
}
$this->handlers[$event][] = $handler;

return $this;
}

/**
* @param string $event
* @param HandlerInterface $handler
* @return $this
*/
public function removeListener(string $event, HandlerInterface $handler): self
{
$handlers = $this->handlers[$event] ?? [];
$this->handlers = array_filter($handlers, function ($existing) use ($handler) {
return $existing !== $handler;
});

return $this;
}

/**
* @param string $event
* @param string $className
* @return $this
*/
public function removeListenerByClassName(string $event, string $className): self
{
$handlers = $this->handlers[$event] ?? [];
$this->handlers = array_filter($handlers, function ($existing) use ($className) {
return get_class($existing) !== $className;
});

return $this;
}

/**
* @param string $event
* @param EventContext $context
*/
public function trigger(string $event, EventContext $context): void
{
// TODO: This could be moved to procedural code in something like _config.php,
// or add a new class that bootstraps the dispatcher.
$this->initialise();

$action = $context->getAction();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$action = $context->getAction();
$action = $context->getAction();
if ($action === null) {
return;
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're going to do an early exit at the trigger level, why not leave action as a required param for EventContext? Then the handlers an guarantee they have action on the context objects. We shouldn't be firing events in the first place if the action is indeterminate.

Copy link

@mfendeksilverstripe mfendeksilverstripe Jan 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not all contexts get an action as an input param. Some of them (for example Graph QL) have to determine action from context data. This is the place where we currently attempt to determine action from data which may fail. This is a valid case and needs to be supported as we can't guarantee that we can determine action from data in all cases.

I think we can move this check to listeners.

if ($action === null) {
return;
}

// First fire listeners to <eventName.actionName>, then just fire generic <eventName> listeners
$eventsToFire = [ $event . '.' . $action, $event];
foreach ($eventsToFire as $event) {
$handlers = $this->handlers[$event] ?? [];
/* @var HandlerInterface $handler */
foreach ($handlers as $handler) {
$handler->fire($context);
}
}
}

private function initialise(): void
{
if ($this->initialised) {
return;
}

foreach ($this->loaders as $loader) {
$loader->addToDispatcher($this);
}
$this->initialised = true;
}
}
9 changes: 9 additions & 0 deletions src/Dispatch/EventHandlerLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php


namespace SilverStripe\Snapshots\Dispatch;

interface EventHandlerLoader
{
public function addToDispatcher(Dispatcher $dispatcher): void;
}
55 changes: 55 additions & 0 deletions src/Handler/CMSMain/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php


namespace SilverStripe\Snapshots\Handler\CMSMain;

use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Snapshots\Handler\HandlerAbstract;
use SilverStripe\Snapshots\Listener\EventContext;
use SilverStripe\Snapshots\Snapshot;

class Handler extends HandlerAbstract
{
/**
* @param EventContext $context
* @return Snapshot|null
* @throws ValidationException
*/
protected function createSnapshot(EventContext $context): ?Snapshot
{
$action = $context->getAction();
if ($action === null) {
return null;
}

/* @var HTTPResponse $result */
$result = $context->get('result');
if (!$result instanceof HTTPResponse) {
return null;
}
if ((int) $result->getStatusCode() !== 200) {
return null;
}

$className = $context->get('treeClass');
$id = (int) $context->get('id');

if (!$id) {
return null;
}

/** @var SiteTree $page */
$page = DataObject::get_by_id($className, $id);

if ($page === null) {
return null;
}

$message = $this->getMessage($action);

return Snapshot::singleton()->createSnapshotFromAction($page, null, $message);
}
}
Loading