PhpRenderer   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 132
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 5
dl 0
loc 132
ccs 0
cts 61
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 5
C __invoke() 0 77 11
A buildPath() 0 10 3
1
<?php
2
namespace Germania\Renderer;
3
4
use \Psr\Log\LoggerInterface;
5
use \Psr\Log\LoggerAwareTrait;
6
use \Psr\Log\LoggerAwareInterface;
7
use \Psr\Log\NullLogger;
8
use Psr\Http\Message\ResponseInterface;
9
10
11
12
class PhpRenderer implements RendererInterface, LoggerAwareInterface {
13
14
    use LoggerAwareTrait;
15
16
    /**
17
     * @var string[]
18
     */
19
    public $base_path;
20
21
22
    /**
23
     * @param string|string[]|null $base_path Optional: Base path. Defaults to PHP's getcwd()'.
24
     * @param LoggerInterface|null $logger Optional: PSR-3 Logger
25
     */
26
    public function __construct ( $base_path = null, LoggerInterface $logger = null )
27
    {
28
29
        if (is_string($base_path) or !$base_path):
30
            $this->base_path = array($base_path ?: getcwd());
0 ignored issues
show
Documentation Bug introduced by
It seems like array($base_path ?: getcwd()) of type array<integer,array<inte...teger,string>|string"}> is incompatible with the declared type array<integer,string> of property $base_path.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
31
        else:
32
            $this->base_path = $base_path;
33
        endif;
34
35
        $this->setLogger( $logger ?: new NullLogger );
36
    }
37
38
39
    /**
40
     * Returns parsed template output.
41
     *
42
     * @param  string   $template The template file
0 ignored issues
show
Bug introduced by
There is no parameter named $template. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
43
     * @param  array    $context  Associative tempalte variables array
44
     * @param  Callable $callable Optional Callback handler for output buffering
0 ignored issues
show
Bug introduced by
There is no parameter named $callable. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
45
     *
46
     * @return string|ResponseInterface   Template output or ResponseInterface instance
47
     *
48
     * @throws RuntimeException when include file is not readable somehow.
49
     */
50
    public function __invoke( $inc, array $context = array(), Callable $callback = null)
51
    {
52
        $this->logger->info("Render PHP include file: " . $inc, [
53
            'context'   => $context,
54
            'callback'  => $callback ?: "(not set)",
55
            'base_path' => $this->base_path
56
        ]);
57
58
59
        // Blank message
60
        $error_message = false;
61
62
        // Build path based on base path
63
        $path = $this->buildPath( $inc );
64
65
        if (is_readable( $path )):
66
67
            $this->logger->debug("Extract variables to include scope", $context);
68
            extract( $context );
69
70
            $this->logger->debug("Start output buffer");
71
            ob_start( $callback );
72
73
            $this->logger->debug("Include PHP file " . $inc);
74
            $result = include $path;
75
76
77
            $content_length = ob_get_length();
78
79
80
            if ($result instanceOf ResponseInterface):
81
82
                $this->logger->debug("Included PHP file returned ResponseInterface instance", [
83
                    'file' => $inc,
84
                    'ResponseInterface' => get_class( $result )
85
                ]);
86
87
                if ($echo_result = ob_get_clean()):
88
                    $this->logger->warning("Include file should not fill output buffer (echo et.al.) when returning ResponseInterface instance. To avoid data loss, content from output buffer is appended to ResponseInterface instance's body stream.", [
89
                        'file' => $inc,
90
                        'content_length' => $content_length
91
                    ]);
92
                    $result->getBody()->write( $echo_result );
93
                endif;
94
95
96
                // Return ResponseInterface
97
                $this->logger->info("Return ResponseInterface instance", [
98
                    'file' => $inc,
99
                    'ResponseInterface' => get_class( $result )
100
                ]);
101
                return $result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result; (Psr\Http\Message\ResponseInterface) is incompatible with the return type declared by the interface Germania\Renderer\RendererInterface::__invoke of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
102
            endif;
103
104
105
106
            // Return string
107
            $this->logger->info("Return include file output from output buffer", [
108
                'file' => $inc,
109
                'content_length' => $content_length
110
            ]);
111
            return ob_get_clean();
112
113
        elseif ($path === false):
114
            $error_message  = "PhpRenderer: Could not find include in any base path.";
115
        elseif (!is_file($path)):
116
            $error_message  = "PhpRenderer: Include file does not exist: " . ($path ?: "(none)");
117
        else:
118
            $error_message = "PhpRenderer: Include file not readable: " . ($path ?: "(none)");
119
        endif;
120
121
        if (!empty($error_message) and is_string( $error_message )):
122
            $this->logger->error( $error_message );
123
            throw new \RuntimeException( $error_message );
124
        endif;
125
126
    }
127
128
129
    /**
130
     * @param  string $inc The file to locate
131
     * @return string      Full path
132
     */
133
    public function buildPath( $inc )
134
    {
135
        foreach($this->base_path as $path):
136
            if ($file = realpath(join(\DIRECTORY_SEPARATOR, [$path, $inc ]))) {
137
                return $file;
138
            }
139
        endforeach;
140
141
        return false;
142
    }
143
}
144