hal-platform / hal

:shipit: Hal Deployment Platform - Web UI/API
MIT License
18 stars 4 forks source link

Cleanup removal confirmation middleware #11

Closed skluck closed 7 years ago

skluck commented 7 years ago

To allow more targeted and user-friendly messages before making destructive actions. This allows a template to better curate its content for the entity being removed (or maybe use different templates).

See the following psr-7 middleware for an example

class DeleteConfirmationMiddleware implements MiddlewareInterface
{
    use EntityLoaderTrait;
    use HTTPMessageTrait;

    /**
     * @var TemplateInterface
     */
    private $template;

    public function __construct(TemplateInterface $template)
    {
        $this->template = $template;
    }

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param MiddlewareInterface|callable $next
     *
     * @return ResponseInterface
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
    {
        if ($request->getMethod() === 'POST') {
            return $next($request, $response);
        }

        $entities = [];

        foreach ($this->entityMappings() as $uriKey => $type) {
            try {
                $entity = $this->getEntity($request, $uriKey, $type);
                $entities[$uriKey] = $entity;
            } catch (InvalidArgumentException $e) {}
        }

        $rendered = $this->template->render([
            'delete' => $entities
        ]);

        return $this->withBody($response, $rendered);
    }
}