alltube/classes/Factory/ViewFactory.php

91 lines
2.6 KiB
PHP
Raw Normal View History

<?php
/**
* ViewFactory class.
*/
2017-04-25 22:52:05 +00:00
2020-10-20 21:29:50 +00:00
namespace Alltube\Factory;
2020-10-20 21:29:50 +00:00
use Alltube\LocaleManager;
use Psr\Container\ContainerInterface;
use Slim\Http\Request;
2020-10-19 20:24:59 +00:00
use Slim\Http\Uri;
use Slim\Views\Smarty;
use Slim\Views\SmartyPlugins;
2020-05-13 19:18:32 +00:00
use SmartyException;
/**
* Create Smarty view object.
*/
class ViewFactory
{
2020-10-21 22:45:09 +00:00
/**
* Generate the canonical URL of the current page.
*
* @param Request $request PSR-7 Request
*
* @return string URL
*/
2020-12-17 21:43:05 +00:00
private static function getCanonicalUrl(Request $request): string
2020-10-21 22:45:09 +00:00
{
/** @var Uri $uri */
$uri = $request->getUri();
return $uri->withBasePath('')
->withHost('alltubedownload.net')
->withScheme('https');
}
/**
* Create Smarty view object.
*
2017-11-12 15:36:44 +00:00
* @param ContainerInterface $container Slim dependency container
2020-09-27 13:53:53 +00:00
* @param Request|null $request PSR-7 request
*
* @return Smarty
2020-05-13 19:18:32 +00:00
* @throws SmartyException
*/
2020-12-17 21:43:05 +00:00
public static function create(ContainerInterface $container, Request $request = null): Smarty
{
if (!isset($request)) {
2020-05-13 20:28:05 +00:00
$request = $container->get('request');
}
2020-10-20 21:29:50 +00:00
$view = new Smarty(__DIR__ . '/../../templates/');
2020-10-19 20:24:59 +00:00
/** @var Uri $uri */
$uri = $request->getUri();
if (in_array('https', $request->getHeader('X-Forwarded-Proto'))) {
$uri = $uri->withScheme('https')->withPort(443);
}
// set values from X-Forwarded-* headers
2020-10-19 20:24:59 +00:00
if ($host = current($request->getHeader('X-Forwarded-Host'))) {
$uri = $uri->withHost($host);
}
2020-10-19 20:24:59 +00:00
if ($port = current($request->getHeader('X-Forwarded-Port'))) {
$uri = $uri->withPort(intVal($port));
}
2020-10-19 20:24:59 +00:00
if ($path = current($request->getHeader('X-Forwarded-Path'))) {
$uri = $uri->withBasePath($path);
}
2020-05-13 20:28:05 +00:00
/** @var LocaleManager $localeManager */
$localeManager = $container->get('locale');
2020-10-19 20:24:59 +00:00
$smartyPlugins = new SmartyPlugins($container->get('router'), $uri->withUserInfo(''));
$view->registerPlugin('function', 'path_for', [$smartyPlugins, 'pathFor']);
$view->registerPlugin('function', 'base_url', [$smartyPlugins, 'baseUrl']);
$view->registerPlugin('block', 't', [$localeManager, 'smartyTranslate']);
2020-10-21 22:45:09 +00:00
$view->offsetSet('canonical', self::getCanonicalUrl($request));
$view->offsetSet('locale', $container->get('locale'));
2020-10-21 22:45:09 +00:00
$view->offsetSet('config', $container->get('config'));
2020-10-22 19:40:20 +00:00
$view->offsetSet('domain', $uri->withBasePath('')->getBaseUrl());
2020-10-21 22:45:09 +00:00
return $view;
}
}