Completed
Push — master ( 6e89de...023d00 )
by Mihail
02:41
created

App::dynamicServicePrepare()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 7.2766
cc 10
eloc 9
nc 6
nop 2

How to fix   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 Ffcms\Core;
4
5
use Ffcms\Core\Exception\ForbiddenException;
6
use Ffcms\Core\Exception\JsonException;
7
use Ffcms\Core\Exception\NativeException;
8
use Ffcms\Core\Exception\NotFoundException;
9
use Ffcms\Core\Exception\SyntaxException;
10
use Ffcms\Core\Helper\FileSystem\File;
11
use Ffcms\Core\Helper\Security;
12
use Ffcms\Core\Helper\Type\Obj;
13
use Ffcms\Core\Helper\Type\Str;
14
use Ffcms\Core\I18n\Translate;
15
use Ffcms\Core\Network\Request;
16
use Ffcms\Core\Network\Response;
17
use Ffcms\Core\Arch\View;
18
use Ffcms\Core\Debug\Manager as Debug;
19
use Ffcms\Core\Cache\MemoryObject;
20
21
/**
22
 * Class App - entry point for applications
23
 * @package Ffcms\Core
24
 */
25
class App
26
{
27
28
    /** @var \Ffcms\Core\Network\Request */
29
    public static $Request;
30
31
    /** @var \Ffcms\Core\Properties */
32
    public static $Properties;
33
34
    /** @var \Ffcms\Core\Network\Response */
35
    public static $Response;
36
37
    /** @var \Ffcms\Core\Alias */
38
    public static $Alias;
39
40
    /** @var \Ffcms\Core\Arch\View */
41
    public static $View;
42
43
    /** @var \Ffcms\Core\Debug\Manager|null */
44
    public static $Debug;
45
46
    /** @var \Ffcms\Core\Helper\Security */
47
    public static $Security;
48
49
    /** @var \Ffcms\Core\I18n\Translate */
50
    public static $Translate;
51
52
    /** @var \Ffcms\Core\Interfaces\iUser */
53
    public static $User;
54
55
    /** @var \Symfony\Component\HttpFoundation\Session\Session */
56
    public static $Session;
57
58
    /** @var \Illuminate\Database\Capsule\Manager */
59
    public static $Database;
60
61
    /** @var \Ffcms\Core\Cache\MemoryObject */
62
    public static $Memory;
63
64
    /** @var \Swift_Mailer */
65
    public static $Mailer;
66
67
    /** @var \Ffcms\Core\Interfaces\iCaptcha */
68
    public static $Captcha;
69
70
    /** @var \BasePhpFastCache */
71
    public static $Cache;
72
73
74
    /**
75
     * Prepare entry-point services
76
     * @param array|null $services
77
     * @throws NativeException
78
     */
79
    public static function init(array $services = null)
80
    {
81
        // initialize default services - used in all apps type
82
        self::$Memory = MemoryObject::instance();
83
        self::$Properties = new Properties();
84
        self::$Request = Request::createFromGlobals();
85
        self::$Security = new Security();
86
        self::$Response = new Response();
87
        self::$View = new View();
88
        self::$Translate = new Translate();
89
        self::$Alias = new Alias();
90
91
        // check if debug is enabled and available for current session
92
        if (isset($services['Debug']) && $services['Debug'] === true && Debug::isEnabled() === true) {
93
            self::$Debug = new Debug();
94
        }
95
96
        $objects = App::$Properties->getAll('object');
97
        // pass dynamic initialization
98
        self::dynamicServicePrepare($services, $objects);
99
    }
100
101
    /**
102
     * Prepare dynamic services from object anonymous functions
103
     * @param array|null $services
104
     * @param null $objects
105
     * @throws NativeException
106
     */
107
    private static function dynamicServicePrepare(array $services = null, $objects = null)
108
    {
109
        // check if object configuration is passed
110
        if (!Obj::isArray($objects)) {
111
            throw new NativeException('Object configurations is not loaded: /Private/Config/Object.php');
112
        }
113
114
        // each all objects as service_name => service_instance()
115
        foreach ($objects as $name => $instance) {
0 ignored issues
show
Bug introduced by
The expression $objects of type null is not traversable.
Loading history...
116
            // check if definition of object is exist and services list contains it or is null to auto build
117
            if (property_exists(get_called_class(), $name) && $instance instanceof \Closure && (isset($services[$name]) || $services === null)) {
118
                if ($services[$name] === true || $services === null) { // initialize from configs
119
                    self::${$name} = $instance();
120
                } elseif (is_callable($services[$name])) { // raw initialization from App::run()
121
                    self::${$name} = $services[$name]();
122
                }
123
            }
124
        }
125
    }
126
127
    /**
128
     * Run applications and display output
129
     * @throws \DebugBar\DebugBarException
130
     */
131
    public static function run()
132
    {
133
        $html = null;
134
        // lets try to get html full content to page render
135
        try {
136
            /** @var \Ffcms\Core\Arch\Controller $callClass */
137
            $callClass = null;
138
            $callMethod = 'action' . self::$Request->getAction();
139
140
            // founded callback injection alias
141
            if (self::$Request->getCallbackAlias() !== false) {
142
                $cName = self::$Request->getCallbackAlias();
143 View Code Duplication
                if (class_exists($cName)) {
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...
144
                    $callClass = new $cName;
145
                } else {
146
                    throw new NotFoundException('Callback alias of class "' . App::$Security->strip_tags($cName) . '" is not founded');
0 ignored issues
show
Documentation introduced by
$cName is of type boolean, but the function expects a string|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
147
                }
148
            } else { // typical parsing of native apps
149
                $cName = '\Apps\Controller\\' . env_name . '\\' . self::$Request->getController();
150
151
                // try to initialize class object
152 View Code Duplication
                if (class_exists($cName)) {
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...
153
                    $callClass = new $cName;
154
                } else {
155
                    throw new NotFoundException('Application can not be runned. Initialized class not founded: ' . App::$Security->strip_tags($cName));
156
                }
157
            }
158
159
            // try to call method of founded callback class
160
            if (method_exists($callClass, $callMethod)) {
161
                $actionQuery = [];
162
                // prepare action params for callback
163
                if (!Str::likeEmpty(self::$Request->getID())) {
164
                    $actionQuery[] = self::$Request->getID();
165
                    if (!Str::likeEmpty(self::$Request->getAdd())) {
166
                        $actionQuery[] = self::$Request->getAdd();
167
                    }
168
                }
169
                // make callback call to action in controller and get response
170
                $actionResponse = @call_user_func_array([$callClass, $callMethod], $actionQuery);
171
                if ($actionResponse !== null && !Str::likeEmpty($actionResponse)) {
172
                    // set response to controller property object
173
                    $callClass->setResponse($actionResponse);
174
                }
175
176
                $html = $callClass->getOutput();
177
            } else {
178
                throw new NotFoundException('Method "' . App::$Security->strip_tags($callMethod) . '()" not founded in "' . get_class($callClass) . '"');
179
            }
180
        } catch (NotFoundException $e) { // catch exceptions and set output
181
            $html = $e->display();
182
        } catch (ForbiddenException $e) {
183
            $html = $e->display();
184
        } catch (SyntaxException $e) {
185
            $html = $e->display();
186
        } catch (JsonException $e) {
187
            $html = $e->display();
188
        } catch (NativeException $e) {
189
            $html = $e->display();
190
        } catch (\Exception $e) { // catch all other exceptions
191
            $html = (new NativeException($e->getMessage()))->display();
192
        }
193
194
        // set full rendered content to response builder
195
        self::$Response->setContent($html);
196
        // echo full response to user via http foundation
197
        self::$Response->send();
198
    }
199
200
}