Passed
Push — master ( 2b832f...d7a7e9 )
by Florent
02:41
created

PagesController::adminSavePage()   B

Complexity

Conditions 8
Paths 36

Size

Total Lines 59
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 39
nc 36
nop 2
dl 0
loc 59
rs 8.0515
c 0
b 0
f 0

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
3
/**
4
 *  * Pages controller
5
 *  *
6
 * The file contains all the functions used for off-chain pages.
7
 * Display / Save / update / ...
8
 *
9
 *  * @category   Controllers
10
 *  * @package    SuperHive
11
 *  * @author     Florent Kosmala <[email protected]>
12
 *  * @license    https://www.gnu.org/licenses/gpl-3.0.txt GPL-3.0
13
 *  */
14
15
declare(strict_types=1);
16
17
namespace App\Controllers;
18
19
use Psr\Container\ContainerInterface;
20
use Psr\Http\Message\ResponseInterface as Response;
21
use Psr\Http\Message\ServerRequestInterface as Request;
22
23
final class PagesController
24
{
25
    private ContainerInterface $app;
26
27
    public function __construct(ContainerInterface $app)
28
    {
29
        $this->app = $app;
30
    }
31
32
    /**
33
     *  * Admin pages function
34
     *  *
35
     * This function display the already written pages and a button to create one.
36
     *
37
     * @param Response $response
38
     */
39
    public function adminPages(Response $response): Response
40
    {
41
        $pagesDir = $this->app->get('pagesdir');
42
        $settings = $this->app->get('settings');
43
        $pages = [];
44
45
        $allPages = preg_grep('~\.(html)$~', scandir($pagesDir));
46
        foreach ($allPages as $page) {
47
            $pages[] = substr($page, 0, strrpos($page, '.'));
48
        }
49
50
        return $this->app->get('view')->render($response, '/admin/admin-pages.html', [
51
            'settings' => $settings,
52
            'pages' => $pages,
53
        ]);
54
    }
55
56
    /**
57
     *  * Administration new page function
58
     *  *
59
     * This function just display editor to write new page.
60
     *
61
     * @param Response $response
62
     */
63
    public function adminNewPage(Response $response): Response
64
    {
65
        $settings = $this->app->get('settings');
66
67
        return $this->app->get('view')->render($response, '/admin/admin-newpage.html', [
68
            'settings' => $settings,
69
        ]);
70
    }
71
72
    /**
73
     *  * Administration edit page function
74
     *  *
75
     * Same as adminNewPage but with already written content from already written page.
76
     *
77
     * @param string $file
78
     * @param Response $response
79
     */
80
    public function adminEditPage(string $file, Response $response): Response
81
    {
82
        $pageTitle = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $pageTitle is dead and can be removed.
Loading history...
83
84
        $pagesDir = $this->app->get('pagesdir');
85
        $settings = $this->app->get('settings');
86
87
        $content = file_get_contents($pagesDir . $file . '.html');
88
89
        $pageTitle = preg_match('/\{% block title %\}(.*?)\{% endblock %\}/s', $content, $match);
90
        $pageTitle = $match[1];
91
        $pageContent = strstr($content, '{% block page %}');
92
        $pageContent = preg_replace("/\{%(.*?)%\}/", '', $pageContent);
93
94
        return $this->app->get('view')->render($response, '/admin/admin-newpage.html', [
95
            'pageTitle' => $pageTitle,
96
            'pageFile' => $file,
97
            'pageContent' => $pageContent,
98
            'settings' => $settings,
99
        ]);
100
    }
101
102
    /**
103
     *  * Administration delete page function
104
     *  *
105
     * called to delete fpage and return to administration Pages section
106
     *
107
     * @param string $file
108
     * @param Response $response
109
     * @param array<string, string> $args
110
     */
111
    public function adminDelPage(string $file, Response $response): Response
112
    {
113
        $name = $file;
114
        $pagesDir = $this->app->get('pagesdir');
115
        $filePath = $pagesDir . $name . '.html';
116
117
        if (unlink($filePath)) {
118
            $response->getBody()->write('OK');
119
        } else {
120
            $response->getBody()->write('Error');
121
        }
122
123
        return $response;
124
    }
125
126
    /**
127
     *  * Administration save page function
128
     *  *
129
     * Used to generate slug, html code and save page in file.
130
     *
131
     * @param Request $request
132
     * @param Response $response
133
     */
134
    public function adminSavePage(Request $request, Response $response): Response
135
    {
136
        $data = $request->getParsedBody();
137
        $pagesDir = $this->app->get('pagesdir');
138
139
        if (!empty($data['title'])) {
140
            $pageTitle = $data['title'];
141
        } else {
142
            $pageTitle = "No Title";
143
        }
144
        
145
        if (!empty($data['mde'])) {
146
            $pageContent = $data['mde'];
147
        } else {
148
            $pageContent = 'No content in this page';
149
        }
150
        
151
152
        // Some functions to slugify title to create very cool URL
153
        $acc = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ';
154
        $noAcc = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';
155
        $title = mb_convert_encoding($pageTitle, 'UTF-8', mb_list_encodings());
156
        $acc = mb_convert_encoding($acc, 'UTF-8', mb_list_encodings());
157
        $slug = mb_strtolower(strtr($title, $acc, $noAcc));
0 ignored issues
show
Bug introduced by
It seems like $acc can also be of type array; however, parameter $from of strtr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

157
        $slug = mb_strtolower(strtr($title, /** @scrutinizer ignore-type */ $acc, $noAcc));
Loading history...
Bug introduced by
It seems like $title can also be of type array; however, parameter $str of strtr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

157
        $slug = mb_strtolower(strtr(/** @scrutinizer ignore-type */ $title, $acc, $noAcc));
Loading history...
158
        $slug = preg_replace('~[^\pL\d]+~u', '-', $slug);
159
        $slug = preg_replace('~[^-\w]+~', '', $slug);
160
        $slug = strtolower($slug);
161
        $slug = preg_replace('~-+~', '-', $slug);
162
163
        // apply Twig to the page to display with selected theme
164
        $page = '{% extends settings.theme ~ "/page.html" %}';
165
        $page .= "\n{% block title %}" . $title . "{% endblock %}\n";
0 ignored issues
show
Bug introduced by
Are you sure $title of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
        $page .= "\n{% block title %}" . /** @scrutinizer ignore-type */ $title . "{% endblock %}\n";
Loading history...
166
        $page .= "\n{% block page %}\n" . $pageContent . "\n{% endblock %}\n";
167
168
        $file = $pagesDir . $slug . '.html';
169
170
        if (file_put_contents($file, $page)) {
171
            if (isset($_SERVER['HTTPS'])) {
172
                $isSecure = $_SERVER['HTTPS'];
173
            }
174
            if (isset($isSecure) && $isSecure === 'on') {
175
                $scheme = 'https';
176
            } else {
177
                $scheme = 'http';
178
            }
179
180
            if (isset($_SERVER['HTTP_HOST'])) {
181
                $host = $_SERVER['HTTP_HOST'];
182
            } else {
183
                $host = "unknown_host.com";
184
            }
185
186
187
            $pageUrl = $scheme . '://' . $host . '/pages/' . $slug;
188
            $response->getBody()->write($pageUrl);
189
        } else {
190
            $response->getBody()->write('Error');
191
        }
192
        return $response;
193
    }
194
}
195