Passed
Push — master ( 644e08...1c4f5c )
by Mehmet
03:13
created

RSlim::runRoute()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 5
eloc 17
c 4
b 1
f 0
nc 6
nop 6
dl 0
loc 25
rs 8.439
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_type = 'html';
47
                return $this->notFound($request, $response, $return_type, 'Controller ' . $route . '/' . $action . " has not " . $function_name . " function");
48
            }
49
            if ($return_type == 'html') {
50
                $this->useTwig($request);
51
            }
52
            if ($return_type == 'json') {
53
                return $this->returnJson($function_name, $request, $args, $response);
54
            } else {
55
                return $this->returnHtml($function_name, $request, $args, $response, $route, $action, $controller, $template);
56
            }
57
        } else {
58
            return $this->notFound($request, $response, $return_type, 'Controller ' . $route . '/' . $action . " not found");
59
        }
60
    }
61
    
62
    private function returnJson($function_name, $request, $args, $response){
63
        $status = 500;
64
        $function_output = call_user_func($function_name, $request, $args);
65
        if (!is_array($function_output)) {
66
            $function_output = ["status" => 500, "error" => "Internal Server Error"];
67
        } else {
68
            if (!isset($function_output['status'])) {
69
                $function_output['status'] = 200;
70
            }
71
            $status = (int) $function_output['status'];
72
        }
73
        $response->getBody()->write(json_encode($function_output));
74
        return $response->withHeader('Content-Type', 'application/json;charset=utf-8')->withHeader('X-Powered-By', "reformo/rslim")->withStatus($status);
75
    }
76
    
77
    private function returnHtml($function_name, $request, $args, $response, $route, $action, $controller, $template){
0 ignored issues
show
Unused Code introduced by
The parameter $controller 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...
78 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...
79
            throw new \Exception("<strong>Template file not found!</strong> " . $route . '/' . $action . " needs a template file at:" . $template);
80
        }
81
        $function_output = call_user_func($function_name, $request, $args);
82
        if (!isset($function_output['data'])) {
83
            $function_output['data'] = [];
84
        }
85
        
86
        $function_output['app_content'] = $this->twig->render($template, $function_output['data']);
87
        $main_template_name = 'default';
88
        if (isset($function_output['app_main_template'])) {
89
            $main_template_name = $function_output['app_main_template'];
90
        }
91
        $main_template = '/' . $this->config['app_dir'] . '/templates/_' . $main_template_name . '.html';
92
        
93 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...
94
            throw new \Exception("<strong>Main emplate file not found!</strong> ".$route . '/' . $action .
95
                " needs a main template file at:" . $main_template);
96
        }
97
        $app_content = $this->twig->render($main_template, $function_output);
98
        $newResponse = $response->withHeader('X-Powered-By', "reformo/rslim");
99
        $newResponse->write($app_content);
100
        
101
        return $newResponse;
102
    }
103
    
104
    private function useTwig($request)
105
    {
106
        $loader     = new \Twig_Loader_Filesystem($this->config['base_dir']);
107
        $this->twig = new \Twig_Environment($loader, [
108
            'cache'         => '/tmp',
109
            'debug'         => $this->config['app']['debug'],
110
            'auto_reload'   => 1
111
        ]);
112
        $filter = new \Twig_SimpleFunction(
113
            'rwidget_*_*',
114
            function($widget_name, $widget_action, $args = []) {
115
        
116
                $widget_file = $this->config['base_dir'] . '/' . $this->config['app_dir'] . '/widgets/' . $widget_name . '/' . $widget_action . ".php";
117
                $widget_template = '/' . $this->config['app_dir'] . '/templates/_widgets/' . $widget_name . '/' . $widget_action . '.html';
118
                if (!file_exists($widget_file)) {
119
                    throw new \Exception("<strong>Widget file not found!</strong> " . $widget_name . '/' . $widget_action . "!");
120
                }
121
                require_once $widget_file;
122
                $widget_content_function = "rwidget_" . $widget_name . "_" . $widget_action;
123
                if (function_exists($widget_content_function)) {
124
                    $widget_content = call_user_func($widget_content_function, $args);
125
                    if (!file_exists($this->config['base_dir'] . $widget_template)) {
126
                        if (is_string($widget_content)) {
127
                            return $widget_content;
128
                        } else {
129
                            throw new \Exception("<strong>Widget should return string:</strong> " . $widget_name . '/' . $widget_action . "!");
130
                        }
131
                    } else {
132
                        return $this->twig->render($widget_template, $widget_content);
133
                    }
134
                } else {
135
                    throw new \Exception("<strong>Widget function not found!</strong> " . $widget_name . '/' . $widget_action . "!");
136
                }
137
            },
138
            array('is_safe' => array('html'))
139
            );
140
        $this->twig->addFunction($filter);
141
        $this->twig->addGlobal('runtime_config', $this->config);
142
        $this->twig->addGlobal('url_params', $request->getParams());
143
    }
144
145
    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...
146
    {
147
148
        $not_found_template = '/' . $this->config['app_dir'] . '/templates/_404.html';
149
        if ($return_type == 'json') {
150
            $response->getBody()->write(json_encode(['status'=>404, 'message'=>$message]));
151
            return $response->withHeader('Content-Type', 'application/json;charset=utf-8')
152
                ->withHeader('X-Powered-By', "reformo/rslim")->withStatus(404);
153
        } else {
154
            return $response->withStatus(404)
155
                ->withHeader('Content-Type', 'text/html')->withHeader('X-Powered-By', "reformo/rslim")
156
                ->write($this->twig->render($not_found_template, ['message'=>$message]));
157
        }
158
    }
159
160
    public function register($request_method, $pattern, $controller, $return_type = 'html')
161
    {
162
        $this->app->map([strtoupper($request_method)], $pattern, function(Request $req, Response $res, $args) {
163
            list($route, $action) = explode("/", $args['controller']);
164
            return $args['RSlim']->runRoute($req, $res, $route, $action, $args['return_type'], $args);
165
        })->setArguments(['controller'=>$controller, 'return_type'=>$return_type, 'RSlim'=>$this]);
166
    }
167
168
    public function run()
169
    {
170
        $this->container['notFoundHandler'] = function($c) {
171
            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...
172
                return $c['response']
173
                    ->withStatus(404)
174
                    ->withHeader('Content-Type', 'text/html')->withHeader('X-Powered-By', "reformo/rslim")
175
                    ->write('<h1>404 - Requested URL not found</h1>');
176
            };
177
        };
178
        if ($this->config['bypass_error_handlers'] === true) {
179 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...
180
                return function($request, $response, $exception) use ($container) {
181
                    $response->getBody()->rewind();
182
                    return $response->withStatus(500)
183
                        ->withHeader('Content-Type', 'text/html')
184
                        ->write($exception->getMessage());
185
                };
186
            };
187 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...
188
                return function($request, $response, $error) use ($container) {
189
                    $response->getBody()->rewind();
190
                    return $response->withStatus(500)
191
                        ->withHeader('Content-Type', 'text/html')
192
                        ->write($error->getMessage());
193
                };
194
            };
195
        }
196
        $this->app->run();
197
    }
198
}
199