Passed
Push — develop ( 2969a7...df24bb )
by Felipe
05:41 queued 11s
created

ContainerUtils::maybeRenderIframes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 18
rs 9.9332
1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-RC6
5
 */
6
7
namespace PHPPgAdmin;
8
9
/**
10
 * @file
11
 * A class that adds convenience methods to the container
12
 */
13
14
/**
15
 * A class that adds convenience methods to the container.
16
 *
17
 * @package PHPPgAdmin
18
 */
19
class ContainerUtils
20
{
21
    use \PHPPgAdmin\Traits\HelperTrait;
22
23
    protected $container;
24
    /** @var Connector */
0 ignored issues
show
Bug introduced by
The type PHPPgAdmin\Connector was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
25
    protected static $instance;
26
27
    /**
28
     * Constructor of the ContainerUtils class.
29
     *
30
     * @param \Slim\Container $container The app container
31
     */
32
    public function __construct()
33
    {
34
        $composerinfo = json_decode(file_get_contents(BASE_PATH.'/composer.json'));
35
        $appVersion   = $composerinfo->version;
36
37
        $phpMinVer = (str_replace(['<', '>', '='], '', $composerinfo->require->php));
38
        //$this->prtrace($appVersion);
39
        //$this->dump($composerinfo);
40
41
        $config = [
42
            'msg'       => '',
43
            'appThemes' => [
44
                'default'    => 'Default',
45
                'cappuccino' => 'Cappuccino',
46
                'gotar'      => 'Blue/Green',
47
                'bootstrap'  => 'Bootstrap3',
48
            ],
49
            'settings'  => [
50
                'displayErrorDetails'               => DEBUGMODE,
51
                'determineRouteBeforeAppMiddleware' => true,
52
                'base_path'                         => BASE_PATH,
53
                'debug'                             => DEBUGMODE,
54
55
                // 'routerCacheFile'                   => BASE_PATH . '/temp/route.cache.php',
56
57
                // Configuration file version.  If this is greater than that in config.inc.php, then
58
                // the app will refuse to run.  This and $conf['version'] should be incremented whenever
59
                // backwards incompatible changes are made to config.inc.php-dist.
60
                'base_version'                      => 60,
61
                // Application version
62
                'appVersion'                        => 'v'.$appVersion,
63
                // Application name
64
                'appName'                           => 'phpPgAdmin6',
65
66
                // PostgreSQL and PHP minimum version
67
                'postgresqlMinVer'                  => '9.3',
68
                'phpMinVer'                         => $phpMinVer,
69
                'displayErrorDetails'               => DEBUGMODE,
70
                'addContentLengthHeader'            => false,
71
            ],
72
        ];
73
74
        $this->app = new \Slim\App($config);
75
76
        // Fetch DI Container
77
        $container            = $this->app->getContainer();
78
        $container['utils']   = $this;
79
        $container['version'] = 'v'.$appVersion;
80
        $container['errors']  = [];
81
82
        $this->container = $container;
83
    }
84
85
    public static function createContainer()
86
    {
87
        if (!self::$instance) {
88
            self::$instance = new self();
0 ignored issues
show
Documentation Bug introduced by
It seems like new self() of type PHPPgAdmin\ContainerUtils is incompatible with the declared type PHPPgAdmin\Connector of property $instance.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
89
        }
90
91
        return [self::$instance->container, self::$instance->app];
92
    }
93
94
    public function maybeRenderIframes($response, $subject, $query_string)
95
    {
96
        $c       = $this->container;
97
        $in_test = $c->view->offsetGet('in_test');
0 ignored issues
show
Bug introduced by
Accessing view on the interface Psr\Container\ContainerInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
98
99
        if ($in_test === '1') {
100
            $className  = '\PHPPgAdmin\Controller\\'.ucfirst($subject).'Controller';
101
            $controller = new $className($c);
102
103
            return $controller->render();
104
        }
105
106
        $viewVars = [
107
            'url'            => '/src/views/'.$subject.($query_string ? '?'.$query_string : ''),
108
            'headertemplate' => 'header.twig',
109
        ];
110
111
        return $c->view->render($response, 'iframe_view.twig', $viewVars);
112
    }
113
114
    /**
115
     * Gets the theme from
116
     * 1. The $_REQUEST global (when it's chosen from start screen)
117
     * 2. Server specific config theme
118
     * 3.- $_SESSION global (subsequent requests after 1.)
119
     * 4.- $_COOKIE global (mostly fallback for $_SESSION after 1.- and 3.-)
120
     * 5.- theme as set in config
121
     * 6.- 'default' theme.
122
     *
123
     * @param <type>     $conf         The conf
0 ignored issues
show
Documentation Bug introduced by
The doc comment <type> at position 0 could not be parsed: Unknown type name '<' at position 0 in <type>.
Loading history...
124
     * @param null|mixed $_server_info
125
     *
126
     * @return string the theme
127
     */
128
    public function getTheme(array $conf, $_server_info = null)
129
    {
130
        $_theme = null;
131
        // List of themes
132
        $themefolders = $this->getThemeFolders();
133
        // Check if theme is in $_REQUEST, $_SESSION or $_COOKIE
134
        // 1.- First priority: $_REQUEST, this happens when you use the selector
135
        if (array_key_exists('theme', $_REQUEST) &&
136
            array_key_exists($_REQUEST['theme'], $themefolders)) {
137
            $_theme = $_REQUEST['theme'];
138
        } elseif ( // otherwise, see if there's a theme associated with this particular server
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
139
            !is_null($_server_info) &&
140
            array_key_exists('theme', $_server_info) &&
141
            is_string($_server_info['theme']) &&
142
            array_key_exists($_COOKIE['ppaTheme'], $themefolders)) {
143
            $_theme = $_server_info['theme'];
144
        } elseif (array_key_exists('ppaTheme', $_SESSION) &&
145
            array_key_exists($_SESSION['ppaTheme'], $themefolders)) {
146
            // otherwise check $_SESSION
147
            $_theme = $_SESSION['ppaTheme'];
148
        } elseif (array_key_exists('ppaTheme', $_SESSION) &&
149
            array_key_exists($_COOKIE['ppaTheme'], $themefolders)) {
150
            // oterwise check $_COOKIE
151
            $_theme = $_COOKIE['ppaTheme'];
152
        } elseif ( // see if there's a valid theme set in config file
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
153
            array_key_exists('theme', $conf) &&
154
            is_string($conf['theme']) &&
155
            array_key_exists($conf['theme'], $themefolders)) {
156
            $_theme = $conf['theme'];
157
        } else {
158
            // okay then, use default theme
159
            $_theme = 'default';
160
        }
161
162
        return $_theme;
163
    }
164
165
    /**
166
     * Traverse THEME_PATH, consider as theme folders those which
167
     * contain a `global.css` stylesheet.
168
     *
169
     * @return array the theme folders
170
     */
171
    private function getThemeFolders()
172
    {
173
        // no THEME_PATH (how?) then return empty array
174
        if (!$gestor = opendir(THEME_PATH)) {
175
            closedir($gestor);
0 ignored issues
show
Bug introduced by
It seems like $gestor can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, 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

175
            closedir(/** @scrutinizer ignore-type */ $gestor);
Loading history...
176
177
            return [];
178
        }
179
        $themefolders = [];
180
181
        /* This is the right way to iterate on a folder */
182
        while (false !== ($foldername = readdir($gestor))) {
183
            if ($foldername == '.' || $foldername == '..') {
184
                continue;
185
            }
186
187
            $folderpath = sprintf('%s%s%s', THEME_PATH, DIRECTORY_SEPARATOR, $foldername);
188
            $stylesheet = sprintf('%s%s%s', $folderpath, DIRECTORY_SEPARATOR, 'global.css');
189
            // if $folderpath if indeed a folder and contains a global.css file, then it's a theme
190
            if (is_dir($folderpath) &&
191
                is_file($stylesheet)) {
192
                $themefolders[$foldername] = $folderpath;
193
            }
194
        }
195
196
        closedir($gestor);
197
198
        return $themefolders;
199
    }
200
201
    /**
202
     * Determines the redirection url according to query string.
203
     *
204
     * @return string the redirect url
205
     */
206
    public function getRedirectUrl()
207
    {
208
        $query_string = $this->container->requestobj->getUri()->getQuery();
0 ignored issues
show
Bug introduced by
Accessing requestobj on the interface Psr\Container\ContainerInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
209
210
        // if server_id isn't set, then you will be redirected to intro
211
        if ($this->container->requestobj->getQueryParam('server') === null) {
212
            $destinationurl = \SUBFOLDER.'/src/views/intro';
213
        } else {
214
            // otherwise, you'll be redirected to the login page for that server;
215
            $destinationurl = \SUBFOLDER.'/src/views/login'.($query_string ? '?'.$query_string : '');
216
        }
217
218
        return $destinationurl;
219
    }
220
221
    /**
222
     * Gets the destination with the last active tab selected for that controller
223
     * Usually used after going through a redirect route.
224
     *
225
     * @param string $subject The subject, usually a view name like 'server' or 'table'
226
     *
227
     * @return string The destination url with last tab set in the query string
228
     */
229
    public function getDestinationWithLastTab($subject)
230
    {
231
        $_server_info = $this->container->misc->getServerInfo();
0 ignored issues
show
Bug introduced by
Accessing misc on the interface Psr\Container\ContainerInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
232
        $this->addFlash($subject, 'getDestinationWithLastTab');
233
        //$this->prtrace('$_server_info', $_server_info);
234
        // If username isn't set in server_info, you should login
235
        if (!isset($_server_info['username'])) {
236
            $destinationurl = $this->getRedirectUrl();
237
        } else {
238
            $url = $this->container->misc->getLastTabURL($subject);
239
            $this->addFlash($url, 'getLastTabURL for '.$subject);
240
            // Load query vars into superglobal arrays
241
            if (isset($url['urlvars'])) {
242
                $urlvars = [];
243
                foreach ($url['urlvars'] as $key => $urlvar) {
244
                    //$this->prtrace($key, $urlvar);
245
                    $urlvars[$key] = \PHPPgAdmin\Decorators\Decorator::get_sanitized_value($urlvar, $_REQUEST);
246
                }
247
                $_REQUEST = array_merge($_REQUEST, $urlvars);
248
                $_GET     = array_merge($_GET, $urlvars);
249
            }
250
251
            $actionurl      = \PHPPgAdmin\Decorators\Decorator::actionurl($url['url'], $_GET);
252
            $destinationurl = $actionurl->value($_GET);
253
        }
254
        $destinationurl = str_replace('views/?', "views/{$subject}?", $destinationurl);
255
        // $this->prtrace('destinationurl for ' . $subject, $destinationurl);
256
        return $destinationurl;
257
    }
258
259
    /**
260
     * Adds an error to the errors array property of the container.
261
     *
262
     * @param string $errormsg The error msg
263
     *
264
     * @return \Slim\Container The app container
265
     */
266
    public function addError($errormsg)
267
    {
268
        $errors   = $this->container->get('errors');
269
        $errors[] = $errormsg;
270
        $this->container->offsetSet('errors', $errors);
271
272
        return $this->container;
273
    }
274
}
275