Passed
Push — master ( 4f6cf9...8debd5 )
by Mikael
02:03
created

FlatFileContentController::catchAll()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 0
cts 26
cp 0
rs 9.0168
c 0
b 0
f 0
cc 5
nc 12
nop 0
crap 30
1
<?php
2
3
namespace Anax\Controller;
4
5
use Anax\Commons\ContainerInjectableInterface;
6
use Anax\Commons\ContainerInjectableTrait;
7
8
/**
9
 * A controller for flat file markdown content.
10
 */
11
class FlatFileContentController implements ContainerInjectableInterface
12
{
13
    use ContainerInjectableTrait;
14
15
16
17
    /**
18
     * Render a page using flat file content.
19
     *
20
     * @return mixed as null when flat file is not found and otherwise a 
21
     *               complete response object with content to render.
22
     */
23
    public function catchAll()
24
    {
25
        // Get the current route and see if it matches a content/file
26
        $path = $this->di->get("request")->getRoute();
27
        $file1 = ANAX_INSTALL_PATH . "/content/${path}.md";
28
        $file2 = ANAX_INSTALL_PATH . "/content/${path}/index.md";
29
30
        $file = is_file($file1) ? $file1 : null;
31
        $file = is_file($file2) ? $file2 : $file;
32
        
33
        if (!$file) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $file of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
34
            return;
35
        }
36
37
        // Check that file is really in the right place
38
        $real = realpath($file);
39
        $base = realpath(ANAX_INSTALL_PATH . "/content/");
40
        if (strncmp($base, $real, strlen($base))) {
41
            return;
42
        }
43
44
        // Get content from markdown file
45
        $content = file_get_contents($file);
46
        $content = $this->di->get("textfilter")->parse(
47
            $content,
48
            ["frontmatter", "variable", "shortcode", "markdown", "titlefromheader"]
49
        );
50
51
        // Add content as a view and then render the page
52
        $page = $this->di->get("page");
53
        $page->add("anax/v2/article/default", [
54
            "content" => $content->text,
55
            "frontmatter" => $content->frontmatter,
56
        ]);
57
58
        return $page->render($content->frontmatter); 
59
    }
60
}
61