Skip to content

Instantly share code, notes, and snippets.

@l0gicgate
Last active March 15, 2019 06:21
Show Gist options
  • Save l0gicgate/578bb3015b68561e7cfca9fc8bddabb1 to your computer and use it in GitHub Desktop.
Save l0gicgate/578bb3015b68561e7cfca9fc8bddabb1 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace Project\Actions;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Class Action
*
* @package Projects\Actions
*/
abstract class Action {
/**
* @var ServerRequestInterface
*/
protected $request;
/**
* @var ResponseInterface
*/
protected $response;
/**
* @var array|null
*/
protected $args;
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param array|null $args
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $args): ResponseInterface {
$this->request = $request;
$this->response = $response;
$this->args = $args;
return $this->action();
}
abstract protected function action(): ResponseInterface;
/**
* @param mixed $data
* @param bool $success
* @param bool|mixed $error
* @return ResponseInterface
*/
protected function respond($data = null, $success = true, $error = false): ResponseInterface
{
$payload = [
'success' => $success,
'error' => $error,
'data' => $data,
];
$json = json_encode($payload, JSON_PRETTY_PRINT);
$this->response->getBody()->write($json);
return $this->response->withHeader('Content-Type', 'application/json;charset=utf-8');
}
}
<?php
declare(strict_types=1);
namespace Project\Actions\Authentication;
use Project\Actions\Action;
use Project\Services\Authentication\AuthenticationService;
use Psr\Http\Message\ResponseInterface;
/**
* Class RequestAuthAction
*
* @package Projects\Actions\Authentication
*/
class RequestAuthAction extends Action
{
/**
* @var AuthenticationService
*/
private $authenticationService;
/**
* RequestAuthAction constructor.
*
* @param AuthenticationService $authenticationService
*/
public function __construct(AuthenticationService $authenticationService)
{
$this->authenticationService = $authenticationService;
}
/**
* {@inheritdoc}
*/
protected function action(): ResponseInterface
{
$username = $this->request->getParsedBodyParam('email', null);
$password = $this->request->getParsedBodyParam('password', null);
$ipAddress = $this->request->getAttribute('ip_address');
// do some validation on the data ...
try {
$this->authenticationService->authenticate($username, $password, $ipAddress);
return $this->respond(['your' => 'payload']);
} catch (AuthenticationServiceException $e) {
return $this->respond(null, false, $e->getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment