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 4 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
365 changes: 131 additions & 234 deletions README.md

Large diffs are not rendered by default.

65 changes: 34 additions & 31 deletions _config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,55 +27,58 @@ Name: snapshot-listeners
---
SilverStripe\CMS\Controllers\CMSMain:
extensions:
- SilverStripe\Snapshots\Listener\Page\CMSMainAction
- SilverStripe\Snapshots\Listener\CMSMain\CMSMainActionListener
unclecheese marked this conversation as resolved.
Show resolved Hide resolved

SilverStripe\Forms\GridField\GridField:
extensions:
- SilverStripe\Snapshots\Listener\GridField\AlterAction
- SilverStripe\Snapshots\Listener\GridField\UrlHandlerAction
- SilverStripe\Snapshots\Listener\GridField\GridFieldAlterationListener
- SilverStripe\Snapshots\Listener\GridField\GridFieldURLListener

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

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

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

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

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

---
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:
-
on: [ formSubmitted.unpublish, formSubmitted.doSave, formSubmitted.doDelete]
handler: %$SilverStripe\Snapshots\Handler\Form\FormSubmissionHandler
-
on: [ formSubmitted.save ]
handler: %$SilverStripe\Snapshots\Handler\Form\SaveHandler
-
on: [ formSubmitted.publish ]
handler: %$SilverStripe\Snapshots\Handler\Form\PublishHandler
-
on: [ cmsAction.savetreenode ]
handler: %$SilverStripe\Snapshots\Handler\CMSMain\ActionHandler
-
on: [ gridFieldAlteration.deleterecord, gridFieldAlteration.archiverecord ]
handler: %$SilverStripe\Snapshots\Handler\GridField\URLActionHandler
-
on: [ gridFieldAction.handleReorder ]
handler: %$SilverStripe\Snapshots\Handler\GridField\URLActionHandler
-
on: [ graphqlMutation.create, graphqlMutation.update, graphqlMutation.delete ]
handler: %$SilverStripe\Snapshots\Handler\GraphQL\MutationHandler
20 changes: 20 additions & 0 deletions lang/en.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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'
SilverStripe\Snapshots\Handler\GridField\AlterationHandler:
unclecheese marked this conversation as resolved.
Show resolved Hide resolved
HANDLER_handleReorder: 'Reorder items'
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
138 changes: 138 additions & 0 deletions src/Dispatch/Dispatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?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 array HandlerInterface[]
*/
private $handlers = [];

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

$loader->addToDispatcher($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) {
$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
{
$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.

// 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);
}
}
}
}
10 changes: 10 additions & 0 deletions src/Dispatch/EventHandlerLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php


namespace SilverStripe\Snapshots\Dispatch;


interface EventHandlerLoader
{
public function addToDispatcher(Dispatcher $dispatcher): void;
}
54 changes: 54 additions & 0 deletions src/Handler/CMSMain/ActionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?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\CMSMain\CMSMainContext;
use SilverStripe\Snapshots\Listener\EventContext;
use SilverStripe\Snapshots\Snapshot;

class ActionHandler extends HandlerAbstract
{
/**
* @param EventContext $context
* @return Snapshot|null
* @throws ValidationException
*/
protected function createSnapshot(EventContext $context): ?Snapshot
{
/* @var CMSMainContext $context */
$action = $context->getAction();
unclecheese marked this conversation as resolved.
Show resolved Hide resolved
/* @var HTTPResponse $result */
$result = $context->getResult();
if (!$result instanceof HTTPResponse) {
return null;
}
if ((int) $result->getStatusCode() !== 200) {
return null;
}

$className = $context->getTreeClass();
$id = (int) $context->getId();

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);
}
}
46 changes: 46 additions & 0 deletions src/Handler/Form/FormSubmissionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php


namespace SilverStripe\Snapshots\Handler\Form;


use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Snapshots\Handler\HandlerAbstract;
use SilverStripe\Snapshots\Listener\Form\FormContext;
use SilverStripe\Snapshots\Listener\EventContext;
use SilverStripe\Snapshots\Snapshot;

class FormSubmissionHandler extends HandlerAbstract
{
/**
* @param EventContext $context
* @return Snapshot|null
* @throws ValidationException
*/
protected function createSnapshot(EventContext $context): ?Snapshot
{
/* @var FormContext $context */
$action = $context->getAction();
unclecheese marked this conversation as resolved.
Show resolved Hide resolved
$page = $this->getPage($context);
$record = $context->getForm()->getRecord();

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

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

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

/**
* @param FormContext $context
* @return SiteTree|null
*/
protected function getPage(FormContext $context): ?SiteTree
{
$url = $context->getRequest()->getURL();
return $this->getCurrentPageFromRequestUrl($url);
}
}
Loading