ion/src/View/HttpView.php

102 lines
2.2 KiB
PHP
Raw Normal View History

2016-10-13 13:11:22 -04:00
<?php declare(strict_types=1);
/**
* Ion
*
* Building blocks for web development
*
* PHP version 7.1
*
* @package Ion
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2018 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2018-10-05 11:44:11 -04:00
* @version 2.4.0
* @link https://git.timshomepage.net/timw4mail/ion
*/
namespace Aviat\Ion\View;
use Zend\Diactoros\Response;
use Zend\HttpHandlerRunner\Emitter\SapiEmitter;
2016-08-26 17:21:50 -04:00
use Aviat\Ion\Exception\DoubleRenderException;
use Aviat\Ion\View as BaseView;
/**
* Base view class for Http output
*/
class HttpView extends BaseView {
2016-08-26 17:21:50 -04:00
/**
* Response mime type
*
* @var string
*/
protected $contentType = '';
/**
* Do a redirect
*
* @param string $url
2016-08-26 17:21:50 -04:00
* @param int $code
* @param array $headers
2018-01-17 12:43:44 -05:00
* @throws \InvalidArgumentException
* @return void
*/
public function redirect(string $url, int $code = 302, array $headers = []): void
{
$this->response = new Response\RedirectResponse($url, $code, $headers);
}
/**
* Set the status code of the request
*
* @param int $code
2018-01-17 16:33:57 -05:00
* @throws \InvalidArgumentException
* @return HttpView
*/
public function setStatusCode(int $code): HttpView
{
$this->response = $this->response->withStatus($code)
->withProtocolVersion('1.1');
return $this;
}
/**
* Send output to client. As it renders the view,
* any attempt to call again will result in a DoubleRenderException.
*
* @throws DoubleRenderException
2018-01-17 12:43:44 -05:00
* @throws \InvalidArgumentException
* @return void
*/
2018-01-17 12:43:44 -05:00
public function send(): void
{
$this->output();
}
/**
* Send the appropriate response
*
2016-08-26 17:21:50 -04:00
* @throws DoubleRenderException
2018-01-17 16:33:57 -05:00
* @throws \InvalidArgumentException
* @return void
*/
2018-01-17 12:43:44 -05:00
protected function output(): void
{
2016-08-26 17:21:50 -04:00
if ($this->hasRendered)
{
throw new DoubleRenderException();
}
2018-01-17 12:43:44 -05:00
$this->response = $this->response
->withHeader('Content-type', "{$this->contentType};charset=utf-8")
->withHeader('X-Content-Type-Options', 'nosniff')
->withHeader('X-XSS-Protection', '1;mode=block')
->withHeader('X-Frame-Options', 'SAMEORIGIN');
2018-01-17 12:43:44 -05:00
(new SapiEmitter())->emit($this->response);
2016-08-26 17:21:50 -04:00
$this->hasRendered = TRUE;
}
}