RedirectResponse::to()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 2
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * @package   WPEmerge
4
 * @author    Atanas Angelov <[email protected]>
5
 * @copyright 2017-2019 Atanas Angelov
6
 * @license   https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
7
 * @link      https://wpemerge.com/
8
 */
9
10
namespace WPEmerge\Responses;
11
12
use GuzzleHttp\Psr7\Response as Psr7Response;
13
use Psr\Http\Message\ResponseInterface;
14
use WPEmerge\Requests\RequestInterface;
15
16
/**
17
 * A collection of tools for the creation of responses
18
 */
19
class RedirectResponse extends Psr7Response {
20
	/**
21
	 * Current request.
22
	 *
23
	 * @var RequestInterface
24
	 */
25
	protected $request = null;
26
27
	/**
28
	 * Constructor.
29
	 *
30
	 * @codeCoverageIgnore
31
	 * @param RequestInterface $request
32
	 */
33
	public function __construct( RequestInterface $request ) {
34
		parent::__construct();
35
		$this->request = $request;
36
	}
37
38
	/**
39
	 * Get a response redirecting to a specific url.
40
	 *
41
	 * @param  string            $url
42
	 * @param  integer           $status
43
	 * @return ResponseInterface
44
	 */
45 2
	public function to( $url, $status = 302 ) {
46
		return $this
47 2
			->withHeader( 'Location', $url )
48 2
			->withStatus( $status );
49
	}
50
51
	/**
52
	 * Get a response redirecting back to the referrer or a fallback.
53
	 *
54
	 * @param  string            $fallback
55
	 * @param  integer           $status
56
	 * @return ResponseInterface
57
	 */
58 4
	public function back( $fallback = '', $status = 302 ) {
59 4
		$url = $this->request->getHeaderLine( 'Referer' );
60
61 4
		if ( empty( $url ) ) {
62 2
			$url = $fallback;
63
		}
64
65 4
		if ( empty( $url ) ) {
66 1
			$url = $this->request->getUrl();
67
		}
68
69 4
		return $this->to( $url, $status );
70
	}
71
}
72