HummingBirdAnimeClient/src/AnimeClient/Controller.php

368 lines
8.2 KiB
PHP
Raw Normal View History

2016-10-20 22:09:36 -04:00
<?php declare(strict_types=1);
/**
* Hummingbird Anime List Client
2015-11-16 11:40:01 -05:00
*
2018-08-22 13:48:27 -04:00
* An API client for Kitsu to manage anime and manga watch lists
2015-11-16 11:40:01 -05:00
*
2023-07-13 11:08:05 -04:00
* PHP version 8.1
2016-08-30 10:01:18 -04:00
*
2023-07-13 11:08:05 -04:00
* @copyright 2015 - 2023 Timothy J. Warren <tim@timshome.page>
2016-08-30 10:01:18 -04:00
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-12-10 17:06:50 -05:00
* @version 5.2
2023-07-13 11:08:05 -04:00
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
2016-10-20 22:09:36 -04:00
2015-09-15 13:19:29 -04:00
namespace Aviat\AnimeClient;
2019-12-09 13:13:31 -05:00
use Aura\Router\Generator;
2019-12-09 13:13:31 -05:00
use Aura\Session\Segment;
use Aviat\AnimeClient\API\Kitsu\Auth;
use Aviat\AnimeClient\Enum\EventType;
2018-01-16 14:58:07 -05:00
use Aviat\Ion\Di\{
ContainerAware,
2019-12-09 13:13:31 -05:00
ContainerInterface,
Exception\ContainerException,
Exception\NotFoundException
2018-01-16 14:58:07 -05:00
};
2017-12-06 14:40:13 -05:00
use Aviat\Ion\Exception\DoubleRenderException;
2016-12-20 12:58:37 -05:00
use Aviat\Ion\View\{HtmlView, HttpView, JsonView};
use Aviat\Ion\{ConfigInterface, Event};
2016-10-20 22:09:36 -04:00
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\SimpleCache\CacheInterface;
use function Aviat\Ion\_dir;
use function is_array;
2015-09-17 23:11:18 -04:00
/**
2015-09-17 23:11:18 -04:00
* Controller base, defines output methods
*/
class Controller
{
2017-03-31 13:37:53 -04:00
use ContainerAware;
2023-05-09 12:52:11 -04:00
/**
* The global configuration object
*/
public ConfigInterface $config;
/**
* The authentication object
*/
2020-04-10 20:01:46 -04:00
protected Auth $auth;
2017-03-31 13:37:53 -04:00
/**
* Cache manager
*/
2020-05-08 19:15:21 -04:00
protected CacheInterface $cache;
2017-03-31 13:37:53 -04:00
/**
* Request object
*/
2020-04-10 20:01:46 -04:00
protected ServerRequestInterface $request;
2017-03-31 13:37:53 -04:00
/**
* Url generation class
*/
2020-04-10 20:01:46 -04:00
protected UrlGenerator $urlGenerator;
2017-03-31 13:37:53 -04:00
/**
* Aura url generator
*/
2020-04-10 20:01:46 -04:00
protected Generator $url;
2017-03-31 13:37:53 -04:00
/**
* Session segment
*/
2020-04-10 20:01:46 -04:00
protected Segment $session;
2017-03-31 13:37:53 -04:00
/**
* Common data to be sent to views
*/
2020-04-10 20:01:46 -04:00
protected array $baseData = [];
2015-06-26 16:39:10 -04:00
/**
* Controller constructor.
*
2019-12-09 13:13:31 -05:00
* @throws ContainerException
* @throws NotFoundException
*/
2015-09-17 23:11:18 -04:00
public function __construct(ContainerInterface $container)
2015-05-22 12:36:26 -04:00
{
2015-09-17 23:11:18 -04:00
$this->setContainer($container);
2018-12-21 15:52:34 -05:00
2016-03-03 16:53:17 -05:00
$auraUrlGenerator = $container->get('aura-router')->getGenerator();
2018-12-21 15:52:34 -05:00
$session = $container->get('session');
2015-09-17 23:11:18 -04:00
$urlGenerator = $container->get('url-generator');
2018-12-21 15:52:34 -05:00
$this->auth = $container->get('auth');
$this->cache = $container->get('cache');
$this->config = $container->get('config');
$this->request = $container->get('request');
2018-12-21 15:52:34 -05:00
$this->session = $session->getSegment(SESSION_SEGMENT);
2017-03-30 16:16:40 -04:00
$this->url = $auraUrlGenerator;
2015-09-17 23:11:18 -04:00
$this->urlGenerator = $urlGenerator;
2016-01-04 10:53:03 -05:00
2018-12-21 15:52:34 -05:00
$this->baseData = [
'auth' => $container->get('auth'),
'config' => $this->config,
'menu_name' => '',
'message' => $this->session->getFlash('message'), // Get message box data if it exists
'other_type' => 'manga',
'url' => $auraUrlGenerator,
'url_type' => 'anime',
'urlGenerator' => $urlGenerator,
];
2020-05-08 19:15:21 -04:00
// Set up 'global' events
Event::on(EventType::CLEAR_CACHE, fn () => clearCache($this->cache));
Event::on(EventType::RESET_CACHE_KEY, fn (string $key) => $this->cache->delete($key));
2017-03-08 12:55:49 -05:00
}
2023-07-13 11:06:52 -04:00
/**
* Set the current url in the session as the target of a future redirect
*
* @throws ContainerException
* @throws NotFoundException
*/
public function setSessionRedirect(?string $url = NULL): void
{
$serverParams = $this->request->getServerParams();
if ( ! array_key_exists('HTTP_REFERER', $serverParams))
{
return;
}
$util = $this->container->get('util');
$doubleFormPage = $serverParams['HTTP_REFERER'] === $this->request->getUri();
$isLoginPage = str_contains($serverParams['HTTP_REFERER'], 'login');
// Don't attempt to set the redirect url if
// the page is one of the form type pages,
// and the previous page is also a form type
if ($doubleFormPage || $isLoginPage)
{
return;
}
if (NULL === $url)
{
$url = $util->isViewPage()
? (string) $this->request->getUri()
: $serverParams['HTTP_REFERER'];
}
$this->session->set('redirect_url', $url);
}
/**
* Redirect to the url previously set in the session
*
* If one is not set, redirect to default url
*
* @throws InvalidArgumentException
*/
public function sessionRedirect(): void
{
$target = $this->session->get('redirect_url') ?? '/';
$this->redirect($target, 303);
$this->session->set('redirect_url', NULL);
}
/**
* Check if the current user is authenticated, else error and exit
*/
protected function checkAuth(): void
{
if ( ! $this->auth->isAuthenticated())
{
$this->errorPage(
403,
'Forbidden',
'You must <a href="/login">log in</a> to perform this action.'
);
}
}
/**
* Get the string output of a partial template
*/
protected function loadPartial(HtmlView $view, string $template, array $data = []): string
{
$router = $this->container->get('dispatcher');
if (isset($this->baseData))
{
$data = array_merge($this->baseData, $data);
}
$route = $router->getRoute();
$data['route_path'] = $route !== FALSE ? $route->path : '';
$templatePath = _dir($this->config->get('view_path'), "{$template}.php");
if ( ! is_file($templatePath))
{
throw new InvalidArgumentException("Invalid template : {$template}");
}
return $view->renderTemplate($templatePath, $data);
}
/**
* Render a template with header and footer
*/
protected function renderFullPage(HtmlView $view, string $template, array $data): HtmlView
{
$csp = [
"default-src 'self' media.kitsu.io kitsu-production-media.s3.us-west-002.backblazeb2.com",
"object-src 'none'",
"child-src 'self' *.youtube.com polyfill.io",
];
$view->addHeader('Content-Security-Policy', implode('; ', $csp));
$view->appendOutput($this->loadPartial($view, 'header', $data));
if (array_key_exists('message', $data) && is_array($data['message']))
{
$view->appendOutput($this->loadPartial($view, 'message', $data['message']));
}
$view->appendOutput($this->loadPartial($view, $template, $data));
$view->appendOutput($this->loadPartial($view, 'footer', $data));
return $view;
}
/**
* 404 action
*
* @throws InvalidArgumentException
*/
public function notFound(
string $title = 'Sorry, page not found',
string $message = 'Page Not Found'
): never {
$this->outputHTML('404', [
'title' => $title,
'message' => $message,
], NULL, 404);
exit();
}
/**
* Display a generic error page
*
* @throws InvalidArgumentException
*/
public function errorPage(int $httpCode, string $title, string $message, string $longMessage = ''): void
{
$this->outputHTML('error', [
'title' => $title,
'message' => $message,
'long_message' => $longMessage,
], NULL, $httpCode);
}
/**
* Redirect to the default controller/url from an empty path
*
* @throws InvalidArgumentException
*/
public function redirectToDefaultRoute(): void
{
$defaultType = $this->config->get('default_list');
$this->redirect($this->urlGenerator->defaultUrl($defaultType), 303);
}
/**
* Set a session flash variable to display a message on
* next page load
*/
public function setFlashMessage(string $message, string $type = 'info'): void
{
static $messages;
if ( ! $messages)
{
$messages = [];
}
$messages[] = [
'message_type' => $type,
'message' => $message,
];
$this->session->setFlash('message', $messages);
}
2017-03-31 13:37:53 -04:00
/**
* Helper for consistent page titles
*
2019-12-09 13:13:31 -05:00
* @param string ...$parts Title segments
2017-03-31 13:37:53 -04:00
*/
public function formatTitle(string ...$parts): string
2017-03-31 13:37:53 -04:00
{
return implode(' &middot; ', $parts);
}
2023-07-13 11:06:52 -04:00
/**
* Add a message box to the page
*
* @throws InvalidArgumentException
*/
protected function showMessage(HtmlView $view, string $type, string $message): string
{
return $this->loadPartial($view, 'message', [
'message_type' => $type,
'message' => $message,
]);
}
/**
* Output a template to HTML, using the provided data
*
* @throws InvalidArgumentException
*/
protected function outputHTML(string $template, array $data = [], ?HtmlView $view = NULL, int $code = 200): void
{
if (NULL === $view)
{
$view = new HtmlView($this->container);
}
$view->setStatusCode($code);
$this->renderFullPage($view, $template, $data)->send();
}
/**
* Output a JSON Response
*
* @param int $code - the http status code
* @throws DoubleRenderException
*/
protected function outputJSON(mixed $data, int $code): void
{
JsonView::new()
->setOutput($data)
->setStatusCode($code)
->send();
}
/**
* Redirect to the selected page
*/
protected function redirect(string $url, int $code): void
{
HttpView::new()
->redirect($url, $code)
->send();
}
}
// End of BaseController.php