Completed
Push — master ( d41cf1...36fce9 )
by Javi
23:31
created

AbstractController   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 6
dl 0
loc 53
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A url() 0 4 1
A redirect() 0 4 2
A response() 0 15 3
1
<?php
2
3
namespace Philae;
4
5
use League\Container\ContainerAwareInterface;
6
use League\Container\ContainerAwareTrait;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * @method Application getContainer()
11
 */
12
abstract class AbstractController implements ContainerAwareInterface
13
{
14
    use ContainerAwareTrait;
15
16
    /**
17
     * Create a new URL
18
     *
19
     * @param string|null $to
20
     * @param array|null $query
21
     * @return string
22
     */
23
    protected function url(string $to = null, array $query = null): string
24
    {
25
        return $this->getContainer()->getUriResolver()->uri($to, $query)->__toString();
26
    }
27
28
    /**
29
     * Create a new redirect response
30
     *
31
     * @param string $to
32
     * @param array|null $query
33
     * @param bool $permanent
34
     * @return ResponseInterface
35
     */
36
    protected function redirect(string $to, array $query = null, bool $permanent = false): ResponseInterface
37
    {
38
        return $this->response(null, $permanent ? 301 : 302, ['Location' => $this->url($to, $query)]);
39
    }
40
41
    /**
42
     * Create a new response
43
     *
44
     * @param string|mixed $content
45
     * @param int $code
46
     * @param array $headers
47
     * @return ResponseInterface
48
     */
49
    protected function response($content, int $code = 200, array $headers = []): ResponseInterface
50
    {
51
        $response = $this->getContainer()->getResponse()->withStatus($code);
52
53
        if ($content) {
54
            $headers['Content-Length'] = strlen($content);
55
            $response->getBody()->write($content);
56
        }
57
58
        foreach ($headers as $k => $v) {
59
            $response = $response->withHeader(strtolower($k), $v);
60
        }
61
62
        return $response;
63
    }
64
}
65