Passed
Push — master ( 0634b8...886ef2 )
by Mehmet
02:47
created

RSlim::run_route()   D

Complexity

Conditions 14
Paths 14

Size

Total Lines 93
Code Lines 66

Duplication

Lines 12
Ratio 12.9 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
cc 14
eloc 66
c 5
b 0
f 1
nc 14
nop 6
dl 12
loc 93
rs 4.9516

How to fix   Long Method    Complexity   

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
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
    public $config = [
11
        'base_dir'  => null,
12
        'base_url'  => null,
13
        'app_name'  => 'www',
14
        'bypass_error_handlers' => true
15
    ];
16
    public $container = null;
17
    public $app = null;
18
    private $twig = null;
19
20
    public function __construct($config)
21
    {
22
        $this->config = array_merge($this->config, $config);
23
        ini_set("default_charset", "utf-8");
24
        ini_set('date.timezone', $config['app']['timezone']);
25
        $configuration = [
26
            'settings' => [
27
                'displayErrorDetails' => $config['app']['debug'],
28
            ],
29
        ];
30
        $this->container    = new \Slim\Container($configuration);
31
        $this->app          = new \Slim\App($this->container);
32
    }
33
34
    public function run_route($request, $response, $route, $action='main', $return_type='html', $args = [])
35
    {
36
        $controller = $this->config['base_dir'] . '/apps/' . $this->config['app_name'] .'/controllers/'. $route . '/' . $action . '.php';
37
        $template   = '/apps/' . $this->config['app_name'] . '/templates/' . $route . '/' . $action . '.html';
38
39
        if(file_exists($controller)){
40
41
            require_once($controller);
42
43 View Code Duplication
            if(!function_exists('app_content')){
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...
44
                return $this->not_found($request, $response, $return_type, 'Controller '. $route . '/' . $action." has not app_content function");
45
            }
46
            if( $return_type == 'json' ){
47
                $status = 500;
48
                $function_output = app_content($request, $args);
49
                if(!is_array( $function_output) ){
50
                    $function_output = ["status" => 500, "error" => "Internal Server Error"];
51
                }
52
                else{
53
                    if(!isset($function_output['status'])){
54
                        $function_output['status']=200;
55
                    }
56
                    $status = (int) $function_output['status'];
57
                }
58
                $response->getBody()->write( json_encode( $function_output ) );
59
                $newResponse = $response->withHeader('Content-Type', 'application/json;charset=utf-8')->withHeader('X-Powered-By',"reformo/rslim")->withStatus($status);
60
            }
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 = app_content($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'] . '/apps/' . $this->config['app_name'] . '/widgets/' . $widget_name . '/' . $widget_action . ".php";
80
                        $widget_template = '/apps/' . $this->config['app_name'] . '/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
                                }
92
                                else{
93
                                    throw new \Exception("<strong>Widget should return string:</strong> " . $widget_name . '/' . $widget_action . "!");
94
                                }
95
                            } else {
96
                                return $this->twig->render($widget_template, $widget_content);
97
                            }
98
                        }
99
                        else {
100
                            throw new \Exception("<strong>Widget function not found!</strong> " . $widget_name . '/' . $widget_action . "!");
101
                        }
102
                    },
103
                    array('is_safe' => array('html')));
104
                $this->twig->addFunction($filter);
105
                $this->twig->addGlobal('runtime_config', $this->config);
106
                $this->twig->addGlobal('url_params', $request->getParams());
107
                $function_output['app_content']=$this->twig->render($template, $function_output['data']);
108
                $main_template_name = 'default';
109
                if (isset($function_output['app_main_template'])) {
110
                    $main_template_name = $function_output['app_main_template'];
111
                }
112
                $main_template =  '/apps/'.$this->config['app_name'] . '/templates/_' . $main_template_name . '.html';
113
114 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...
115
                    throw new \Exception("<strong>Main emplate file not found!</strong> ".$route.'/'.$action." 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
        }
123 View Code Duplication
        else{
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...
124
            return $this->not_found($request, $response, $return_type, 'Controller '. $route . '/' . $action." not found");
125
        }
126
    }
127
128
    public function not_found($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...
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')->withHeader('X-Powered-By',"reformo/rslim")->withStatus(404);
134
        }
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']->run_route($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
}