Completed
Push — master ( 52433d...0053cc )
by Carsten
04:59 queued 02:17
created

WebsiteMiddleware::__invoke()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 67
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 67
ccs 28
cts 28
cp 1
rs 7.0237
c 0
b 0
f 0
cc 7
eloc 26
nc 16
nop 3
crap 7

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Germania\PsrWebsites;
3
4
use Psr\Log\LoggerInterface;
5
use Psr\Log\NullLogger;
6
use Psr\Http\Message\ServerRequestInterface as Request;
7
use Psr\Http\Message\ResponseInterface as Response;
8
use Interop\Container\ContainerInterface;
9
use Slim\Http\Body as ResponseBody;
10
11
class WebsiteMiddleware
12
{
13
14
    /**
15
     * @var ContainerInterface
16
     */
17
    public $websites;
18
19
    /**
20
     * @var Callable
21
     */
22
    public $render;
23
24
    /**
25
     * @var string
26
     */
27
    public $template;
28
29
    /**
30
     * @var array
31
     */
32
    public $defaults = array();
33
34
    /**
35
     * @var LoggerInterface
36
     */
37
    public $logger;
38
39
40
41
42
    /**
43
     * @param ContainerInterface  $websites   A ContainerInterface instance that returns a website for the current route name
44
     * @param Callable            $render     Rendering callable that receives template file and variables context
45
     * @param string              $template   Template file
46
     * @param array               $defaults   Default variables context
47
     * @param LoggerInterface     $logger     Optional: PSR-3 Logger
48
     */
49 2
    public function __construct( ContainerInterface $websites, Callable $render, $template, array $defaults, LoggerInterface $logger = null)
50
    {
51 2
        $this->websites  = $websites;
52 2
        $this->render    = $render;
53 2
        $this->template  = $template;
54 2
        $this->defaults  = $defaults;
55
56 2
        $this->logger    = $logger ?: new NullLogger;
57 2
    }
58
59
60
    /**
61
     * @param  Psr\Http\Message\ServerRequestInterface  $request  PSR7 request
62
     * @param  Psr\Http\Message\ResponseInterface       $response PSR7 response
63
     * @param  callable                                 $next     Next middleware
64
     *
65
     * @return Psr\Http\Message\ResponseInterface
66
     */
67 1
    public function __invoke(Request $request, Response $response, $next)
68
    {
69
        // ---------------------------------------
70
        //  1. Get current Website object,
71
        //     add as attribute to Request.
72
        //     The website will be available within route controllers.
73
        // ---------------------------------------
74 1
        $website_factory = $this->websites;
75 1
        $current_route_name = $request->getAttribute('route')->getName();
76 1
        $website = $website_factory->get( $current_route_name );
77
78 1
        $request = $request->withAttribute('website', $website);
79
80
81
        // ---------------------------------------
82
        //  2. Call next middleware.
83
        //     Page content (not HTML head and stuff!)
84
        //     should be created there...
85
        // ---------------------------------------
86 1
        $content_response = $next($request, $response);
87
88
89
        // ---------------------------------------
90
        // 3. Create template variables
91
        // ---------------------------------------
92
93 1
        $vars = array_merge(
94 1
            $this->defaults, [
95 1
                'title'    =>  $website->getTitle(),
96 1
                'id'       =>  $website->getDomId(),
97 1
                'base_url' =>  $request->getUri()->getBaseUrl(),
98 1
                'content'  =>  (string) $content_response->getBody()
99 1
            ]
100 1
        );
101
102 1
        $vars['javascripts'] = isset($vars['javascripts'])
103 1
        ? array_merge($vars['javascripts'], $website->getJavascripts() ?: array())
104 1
        : ($website->getJavascripts() ?: array());
105
106 1
        $vars['stylesheets'] = isset($vars['stylesheets'])
107 1
        ? array_merge($vars['stylesheets'], $website->getStylesheets() ?: array())
108 1
        : ($website->getStylesheets() ?: array());
109
110
111
        // ---------------------------------------
112
        // 5. After that, render 'full page' template
113
        // ---------------------------------------
114
115
        // Output global website template
116 1
        $this->logger->debug("Render page template…");
117
118 1
        $render    = $this->render;
119 1
        $full_page_html = $render( $this->template, $vars);
120
121 1
        $this->logger->debug("Finish page template render; write response");
122
123
124
        // ---------------------------------------
125
        // 6. Write response
126
        // ---------------------------------------
127
128 1
        $full_html_response_body = new ResponseBody(fopen('php://temp', 'r+'));
129 1
        $full_html_response_body->write($full_page_html);
130
131 1
        return $response->withHeader('Content-Type', 'text/html')
132 1
                        ->withBody($full_html_response_body);
133
    }
134
135
136
137
}
138