From 98d168517214e2fadf4218b66327ccd17b83eef6 Mon Sep 17 00:00:00 2001 From: Dave M Date: Mon, 7 Dec 2020 17:28:05 +0000 Subject: [PATCH] - Added some utilities methods from Growlogs --- src/ControllerTrait.php | 53 ++++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/src/ControllerTrait.php b/src/ControllerTrait.php index 6fcd553..33684ea 100644 --- a/src/ControllerTrait.php +++ b/src/ControllerTrait.php @@ -28,21 +28,14 @@ use function file_get_contents; * @RouteParam("methods" => [ "GET", "POST", "DELETE" ]) */ trait ControllerTrait { - - public Session $session; - + public ? Session $session; + public ? Picea\Picea $picea; public ? MailerInterface $mailer; public array $contextList = []; - public function __construct(? Picea\Picea $picea = null, ? Session $session = null, ? MailerInterface $mailer = null) { - $this->picea = $picea; - $this->session = $session; - $this->mailer = $mailer; - } - public function exportJson(ServerRequestInterface $request, string $entityClass, bool $includeRelations = true, ? callable $callback = null) : ResponseInterface { foreach($entityClass::repository()->filterServerRequest( $entityClass::searchRequest()->fromRequest($request->withQueryParams($request->getQueryParams() + ['limit' => PHP_INT_MAX,])) )->loadAll() as $entity) { @@ -83,6 +76,48 @@ trait ControllerTrait { return new JsonResponse($data, $code, $headers); } + public function fromResponse(ResponseInterface $response) + { + if ( $response->getStatusCode() === 200 ) { + if ( $response instanceof \Zend\Diactoros\Response\JsonResponse) { + return $response->getPayload(); + } + } + + return null; + } + + public function asset(string $url, array $parameters = []) : string + { + if (! $this->picea ) { + throw new \Exception("A picea object must be provided on class initialization to use this method."); + } + + return $this->picea->compiler->getExtensionFromToken('asset')->buildAssetUrl($url, $parameters); + } + + public function url(string $url, array $parameters = []) : string + { + if (! $this->picea ) { + throw new \Exception("A picea object must be provided on class initialization to use this method."); + } + + return $this->picea->compiler->getExtensionFromToken('url')->buildUrl($url, $parameters); + } + + public function route(string $name, array $parameters = []) : string + { + if (! $this->picea ) { + throw new \Exception("A picea object must be provided on class initialization to use this method."); + } + + return $this->picea->compiler->getExtensionFromToken('route')->buildRouteUrl($name, $parameters); + } + + public function json($data, int $flags = 0) { + return htmlentities(json_encode($data, $flags), ENT_QUOTES, 'UTF-8'); + } + public function pushContext(FormContext $context) : FormContext { $this->contextList[$context->formName ?? uniqid("context_")] = $context;