Passed
Push — master ( aa8208...d65d07 )
by Mehmet
02:38
created

RSlim::notFound()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 10
c 1
b 1
f 0
nc 2
nop 4
dl 0
loc 14
rs 9.4285
1
<?php
2
3
namespace RSlim;
4
5
use \Psr\Http\Message\RequestInterface as Request;
6
use \Psr\Http\Message\ResponseInterface as Response;
7
8
class RSlim
9
{
10
11
    public $config = [
12
        'base_dir'  => null,
13
        'app_dir'  => 'apps/_skel',
14
        'base_url'  => null,
15
        'app_name'  => 'www',
16
        'bypass_error_handlers' => true
17
    ];
18
    public $container = null;
19
    public $app = null;
20
    private $twig = null;
21
22
    public function __construct($config)
23
    {
24
        $this->config = array_merge($this->config, $config);
25
        ini_set("default_charset", "utf-8");
26
        ini_set('date.timezone', $config['app']['timezone']);
27
        $configuration = [
28
            'settings' => [
29
                'displayErrorDetails' => $config['app']['debug'],
30
            ],
31
        ];
32
        $this->container    = new \Slim\Container($configuration);
33
        $this->app          = new \Slim\App($this->container);
34
    }
35
36
    public function runRoute($request, $response, $route, $action = 'main', $return_type = 'html', $args = [])
37
    {
38
        $controller = $this->config['base_dir'] . '/' . $this->config['app_dir'] . '/controllers/' . $route . '/' . $action . '.php';
39
        $template   = '/' . $this->config['app_dir'] . '/templates/' . $route . '/' . $action . '.html';
40
41
        if (file_exists($controller)) {
42
            require_once($controller);
43
44
            $function_name =  $route . '_' . $action;
45
            if (!function_exists($function_name)) {
46
                return $this->notFound($request, $response, $return_type, 'Controller '. $route . '/' . $action . " has not ".$function_name." function");
47
            }
48
            if ($return_type == 'json') {
49
                $status = 500;
50
                $function_output = call_user_func($function_name, $request, $args);
51
                if (!is_array($function_output)) {
52
                    $function_output = ["status" => 500, "error" => "Internal Server Error"];
53
                } else {
54
                    if (!isset($function_output['status'])) {
55
                        $function_output['status']=200;
56
                    }
57
                    $status = (int) $function_output['status'];
58
                }
59
                $response->getBody()->write(json_encode($function_output));
60
                $newResponse = $response->withHeader('Content-Type', 'application/json;charset=utf-8')->withHeader('X-Powered-By', "reformo/rslim")->withStatus($status);
61
            } else {
62 View Code Duplication
                if (!file_exists($this->config['base_dir'].$template)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
63
                    throw new \Exception("<strong>Template file not found!</strong> " . $route . '/' . $action . " needs a template file at:" . $template);
64
                }
65
                $function_output = call_user_func($function_name, $request, $args);
66
                if (!isset($function_output['data'])) {
67
                    $function_output['data'] = [];
68
                }
69
                $loader     = new \Twig_Loader_Filesystem($this->config['base_dir']);
70
                $this->twig = new \Twig_Environment($loader, [
71
                    'cache'         => '/tmp',
72
                    'debug'         => $this->config['app']['debug'],
73
                    'auto_reload'   => 1
74
                ]);
75
                $filter = new \Twig_SimpleFunction(
76
                    'rwidget_*_*',
77
                    function ($widget_name, $widget_action, $args = []) {
78
79
                        $widget_file = $this->config['base_dir'] . '/' . $this->config['app_dir'] . '/widgets/' . $widget_name . '/' . $widget_action . ".php";
80
                        $widget_template = '/' . $this->config['app_dir'] . '/templates/_widgets/' . $widget_name . '/' . $widget_action . '.html';
81
                        if (!file_exists($widget_file)) {
82
                            throw new \Exception("<strong>Widget file not found!</strong> " . $widget_name . '/' . $widget_action . "!");
83
                        }
84
                        require_once $widget_file;
85
                        $widget_content_function = "rwidget_" . $widget_name . "_" . $widget_action;
86
                        if (function_exists($widget_content_function)) {
87
                            $widget_content = call_user_func($widget_content_function, $args);
88
                            if (!file_exists($this->config['base_dir'] . $widget_template)) {
89
                                if (is_string($widget_content)) {
90
                                    return $widget_content;
91
                                } else {
92
                                    throw new \Exception("<strong>Widget should return string:</strong> " . $widget_name . '/' . $widget_action . "!");
93
                                }
94
                            } else {
95
                                return $this->twig->render($widget_template, $widget_content);
96
                            }
97
                        } else {
98
                            throw new \Exception("<strong>Widget function not found!</strong> " . $widget_name . '/' . $widget_action . "!");
99
                        }
100
                    },
101
                    array('is_safe' => array('html'))
102
                );
103
                $this->twig->addFunction($filter);
104
                $this->twig->addGlobal('runtime_config', $this->config);
105
                $this->twig->addGlobal('url_params', $request->getParams());
106
                $function_output['app_content'] = $this->twig->render($template, $function_output['data']);
107
                $main_template_name = 'default';
108
                if (isset($function_output['app_main_template'])) {
109
                    $main_template_name = $function_output['app_main_template'];
110
                }
111
                $main_template = '/' . $this->config['app_dir'] . '/templates/_' . $main_template_name . '.html';
112
113 View Code Duplication
                if (!file_exists($this->config['base_dir'] . $main_template)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
                    throw new \Exception("<strong>Main emplate file not found!</strong> ".$route . '/' . $action .
115
                                            " needs a main template file at:" . $main_template);
116
                }
117
                $app_content =  $this->twig->render($main_template, $function_output);
118
                $newResponse=$response->withHeader('X-Powered-By', "reformo/rslim");
119
                $newResponse->write($app_content);
120
            }
121
            return $newResponse;
122
        } else {
123
            return $this->notFound($request, $response, $return_type, 'Controller '. $route . '/' . $action." not found");
124
        }
125
    }
126
127
    public function notFound($request, $response, $return_type = 'html', $message = "")
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
    {
129
130
        $not_found_template =  '/apps/' . $this->config['app_name'] . '/templates/_404.html';
131
        if ($return_type == 'json') {
132
            $response->getBody()->write(json_encode(['status'=>404, 'message'=>$message]));
133
            return $response->withHeader('Content-Type', 'application/json;charset=utf-8')
134
                ->withHeader('X-Powered-By', "reformo/rslim")->withStatus(404);
135
        } else {
136
            return $response->withStatus(404)
137
                ->withHeader('Content-Type', 'text/html')->withHeader('X-Powered-By', "reformo/rslim")
138
                ->write($this->twig->render($not_found_template, ['message'=>$message]));
139
        }
140
    }
141
142
    public function register($request_method, $pattern, $controller, $return_type = 'html')
143
    {
144
        $this->app->map([strtoupper($request_method)], $pattern, function (Request $req, Response $res, $args) {
145
            list($route,$action) = explode("/", $args['controller']);
146
            return $args['RSlim']->runRoute($req, $res, $route, $action, $args['return_type'], $args);
147
        })->setArguments(['controller'=>$controller, 'return_type'=>$return_type, 'RSlim'=>$this]);
148
    }
149
150
    public function run()
151
    {
152
        $this->container['notFoundHandler'] = function ($c) {
153
            return function (Request $req, Response $res) use ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $req is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $res is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
154
                return $c['response']
155
                    ->withStatus(404)
156
                    ->withHeader('Content-Type', 'text/html')->withHeader('X-Powered-By', "reformo/rslim")
157
                    ->write('<h1>404 - Requested URL not found</h1>');
158
            };
159
        };
160
        if ($this->config['bypass_error_handlers'] === true) {
161 View Code Duplication
            $this->container['errorHandler'] = function ($container) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
                return function ($request, $response, $exception) use ($container) {
163
                    $response->getBody()->rewind();
164
                    return $response->withStatus(500)
165
                        ->withHeader('Content-Type', 'text/html')
166
                        ->write($exception->getMessage());
167
                };
168
            };
169 View Code Duplication
            $this->container['phpErrorHandler'] = function ($container) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
                return function ($request, $response, $error) use ($container) {
171
                    $response->getBody()->rewind();
172
                    return $response->withStatus(500)
173
                        ->withHeader('Content-Type', 'text/html')
174
                        ->write($error->getMessage());
175
                };
176
            };
177
        }
178
        $this->app->run();
179
    }
180
}
181