Passed
Push — master ( 0900bd...eba4df )
by Andreas
29:39
created

midcom_application::get_host_prefix()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.2098

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 10
ccs 5
cts 7
cp 0.7143
crap 3.2098
rs 10
1
<?php
2
/**
3
 * @package midcom
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\HttpKernelInterface;
11
use Symfony\Component\HttpKernel\Kernel;
12
use Symfony\Component\Config\Loader\LoaderInterface;
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
14
use midcom\bundle\midcomBundle;
15
16
/**
17
 * Main controlling instance of the MidCOM Framework
18
 *
19
 * @property midcom_services_i18n $i18n
20
 * @property midcom_helper__componentloader $componentloader
21
 * @property midcom_services_dbclassloader $dbclassloader
22
 * @property midcom_helper__dbfactory $dbfactory
23
 * @property midcom_helper_head $head
24
 * @property midcom_helper__styleloader $style
25
 * @property midcom_services_auth $auth
26
 * @property midcom_services_permalinks $permalinks
27
 * @property midcom_services_toolbars $toolbars
28
 * @property midcom_services_uimessages $uimessages
29
 * @property midcom_services_metadata $metadata
30
 * @property midcom_services_rcs $rcs
31
 * @property midcom_services__sessioning $session
32
 * @property midcom_services_indexer $indexer
33
 * @property midcom_config $config
34
 * @property midcom_services_cache $cache
35
 * @property Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
36
 * @property midcom_debug $debug
37
 * @package midcom
38
 */
39
class midcom_application extends Kernel
40
{
41
    /**
42
     * @var Request
43
     */
44
    private $request;
45
46
    /**
47
     * Set this variable to true during the handle phase of your component to
48
     * not show the site's style around the component output. This is mainly
49
     * targeted at XML output like RSS feeds and similar things. The output
50
     * handler of the site, excluding the style-init/-finish tags will be executed
51
     * immediately after the handle phase
52
     *
53
     * Changing this flag after the handle phase or for dynamically loaded
54
     * components won't change anything.
55
     *
56
     * @var boolean
57
     */
58
    public $skip_page_style = false;
59
60
    private $project_dir;
61
62
    /**
63
     * @var midcom_config
64
     */
65
    private $cfg;
66
67
    public function __construct(string $environment, bool $debug)
68
    {
69
        $this->request = Request::createFromGlobals();
70
        $this->cfg = new midcom_config;
71
        parent::__construct($environment, $debug);
72
    }
73
74
    public function registerContainerConfiguration(LoaderInterface $loader)
75
    {
76
        if (file_exists($this->getProjectDir() . '/config/services.yml')) {
77
            $loader->load($this->getProjectDir() . '/config/services.yml');
78
        }
79
        if ($classes = midcom::get_registered_service_classes()) {
80
            $loader->load(function (ContainerBuilder $container) use ($classes) {
81
                foreach ($classes as $id => $class) {
82
                    $container->findDefinition($id)->setClass($class);
83
                }
84
            });
85
        }
86
    }
87
88
    protected function initializeContainer()
89
    {
90
        parent::initializeContainer();
91
        $this->container->set('config', $this->cfg);
92
    }
93
94
    protected function buildContainer()
95
    {
96
        $container = parent::buildContainer();
97
        $this->cfg->export_to($container);
98
        return $container;
99
    }
100
101
    public function registerBundles()
102
    {
103
        return [new midcomBundle];
104
    }
105
106
    public function getProjectDir()
107
    {
108
        if ($this->project_dir === null) {
109
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
110
                // this is the case where we're installed as a dependency
111
                $this->project_dir = dirname(__DIR__, 5);
112
            } else {
113
                $this->project_dir = dirname(__DIR__, 2);
114
            }
115
        }
116
        return $this->project_dir;
117
    }
118
119 327
    public function getCacheDir()
120
    {
121 327
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
122
    }
123
124
    /**
125
     * Magic getter for service loading
126
     */
127 683
    public function __get($key)
128
    {
129 683
        if (!$this->booted) {
130
            $this->boot();
131
        }
132 683
        return $this->getContainer()->get($key);
133
    }
134
135
    /**
136
     * Magic setter
137
     */
138
    public function __set($key, $value)
139
    {
140
        if (!$this->booted) {
141
            $this->boot();
142
        }
143
        $this->getContainer()->set($key, $value);
144
    }
145
146
    /* *************************************************************************
147
     * Control framework:
148
     * codeinit      - Handle the current request
149
     * dynamic_load   - Dynamically load and execute a URL
150
     * finish         - Cleanup Work
151
     */
152
153
    /**
154
     * Initialize the URL parser and process the request.
155
     *
156
     * This function must be called before any output starts.
157
     */
158
    public function codeinit()
159
    {
160
        try {
161
            $response = $this->handle($this->request);
162
            $response->send();
163
            $this->terminate($this->request, $response);
164
        } catch (Error $e) {
165
            $this->getHttpKernel()->terminateWithException($e);
0 ignored issues
show
Bug introduced by
The method terminateWithException() does not exist on Symfony\Component\HttpKernel\HttpKernelInterface. It seems like you code against a sub-type of Symfony\Component\HttpKernel\HttpKernelInterface such as Symfony\Component\HttpKernel\HttpKernel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

165
            $this->getHttpKernel()->/** @scrutinizer ignore-call */ terminateWithException($e);
Loading history...
166
        }
167
    }
168
169
    /**
170
     * Dynamically execute a subrequest and insert its output in place of the
171
     * function call.
172
     *
173
     * It tries to load the component referenced with the URL $url and executes
174
     * it as if it was used as primary component.
175
     *
176
     * This is only possible if the system is in the Page-Style output phase. It
177
     * cannot be used within code-init or during the output phase of another
178
     * component.
179
     *
180
     * Example code, executed on a site's homepage, it will load the news listing from
181
     * the given URL and display it using a substyle of the node style that is assigned
182
     * to the loaded one:
183
     *
184
     * <code>
185
     * $blog = '/blog/latest/3/';
186
     * $substyle = 'homepage';
187
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
188
     * </code>
189
     *
190
     * Results of dynamic_loads are cached with the system cache strategy
191
     *
192
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
193
     */
194 16
    public function dynamic_load(string $url, string $substyle = '')
195
    {
196 16
        debug_add("Dynamic load of URL {$url}");
197 16
        $url = midcom_connection::get_url('prefix') . $url;
198
199
        // Determine new Context ID and set current context,
200
        // enter that context and prepare its data structure.
201 16
        $oldcontext = midcom_core_context::get();
202 16
        $context = midcom_core_context::enter($url, $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
0 ignored issues
show
Bug introduced by
It seems like $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC) can also be of type false; however, parameter $topic of midcom_core_context::enter() does only seem to accept midcom_db_topic|null, 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

202
        $context = midcom_core_context::enter($url, /** @scrutinizer ignore-type */ $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
Loading history...
203 16
        if ($substyle) {
204
            $context->set_key(MIDCOM_CONTEXT_SUBSTYLE, $substyle);
205
        }
206
207 16
        $request = $this->request->duplicate([], null, []);
208 16
        $request->attributes->set('context', $context);
209
210 16
        $cached = $this->cache->content->check_dl_hit($request);
211 16
        if ($cached !== false) {
212
            echo $cached;
213
            midcom_core_context::leave();
214
            return;
215
        }
216
217 16
        $backup = $this->skip_page_style;
218 16
        $this->skip_page_style = true;
219
        try {
220 16
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
221 12
        } catch (midcom_error $e) {
222 12
            if ($e instanceof midcom_error_notfound || $e instanceof midcom_error_forbidden) {
223 12
                $e->log();
224 12
                midcom_core_context::leave();
225 12
                return;
226
            }
227
            throw $e;
228 4
        } finally {
229 16
            $this->skip_page_style = $backup;
230
        }
231
232 4
        $dl_cache_data = $response->getContent();
233 4
        echo $dl_cache_data;
234
235
        /* Cache DL the content */
236 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
237
238 4
        midcom_core_context::leave();
239 4
    }
240
241
    /**
242
     * Stop the PHP process
243
     *
244
     * @deprecated
245
     */
246
    public function finish()
247
    {
248
        _midcom_stop_request();
249
    }
250
251
    /* *************************************************************************
252
     * Framework Access Helper functions
253
     */
254
255
    /**
256
     * Retrieves the name of the current host, fully qualified with protocol and
257
     * port (http[s]://www.my.domain.com[:1234])
258
     */
259 29
    function get_host_name() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
260
    {
261 29
        return $this->request->getSchemeAndHttpHost();
262
    }
263
264
    /**
265
     * Return the prefix required to build relative links on the current site.
266
     * This includes the http[s] prefix, the hosts port (if necessary) and the
267
     * base url of the Midgard Page. Be aware, that this does *not* point to the
268
     * base host of the site.
269
     *
270
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
271
     */
272
    function get_page_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
273
    {
274
        return $this->get_host_name() . midcom_connection::get_url('self');
275
    }
276
277
    /**
278
     * Return the prefix required to build relative links on the current site.
279
     * This includes the http[s] prefix, the hosts port (if necessary) and the
280
     * base url of the main host. This is not necessarily the currently active
281
     * MidCOM Page however, use the get_page_prefix() function for that.
282
     *
283
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
284
     */
285 7
    function get_host_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
286
    {
287 7
        $host_prefix = midcom_connection::get_url('prefix');
288 7
        if (!str_starts_with($host_prefix, '/')) {
0 ignored issues
show
Bug introduced by
It seems like $host_prefix can also be of type null; however, parameter $haystack of str_starts_with() does only seem to accept string, 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

288
        if (!str_starts_with(/** @scrutinizer ignore-type */ $host_prefix, '/')) {
Loading history...
289
            $host_prefix = '/' . $host_prefix;
290
        }
291 7
        if (!str_ends_with($host_prefix, '/')) {
292
            $host_prefix .= '/';
293
        }
294 7
        return $this->get_host_name() . $host_prefix;
295
    }
296
297
    /* *************************************************************************
298
     * Generic Helper Functions not directly related with MidCOM:
299
     *
300
     * relocate           - executes a HTTP relocation to the given URL
301
     */
302
303
    /**
304
     * Sends a header out to the client.
305
     *
306
     * This function is syntactically identical to
307
     * the regular PHP header() function, but is integrated into the framework. Every
308
     * Header you sent must go through this function or it might be lost later on;
309
     * this is especially important with caching.
310
     */
311 17
    public function header(string $header, int $response_code = 0)
312
    {
313 17
        $this->cache->content->register_sent_header($header);
314 17
        midcom_compat_environment::header($header, true, $response_code);
315 17
    }
316
317
    /**
318
     * Relocate to another URL.
319
     *
320
     * Note, that this function automatically makes the page uncacheable, calls
321
     * midcom_finish and exit, so it will never return. If the headers have already
322
     * been sent, this will leave you with a partially completed page, so beware.
323
     */
324
    public function relocate(string $url, int $response_code = 302)
325
    {
326
        $response = new midcom_response_relocate($url, $response_code);
327
        $response->send();
328
        $this->finish();
0 ignored issues
show
Deprecated Code introduced by
The function midcom_application::finish() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

328
        /** @scrutinizer ignore-deprecated */ $this->finish();
Loading history...
329
    }
330
331
    /**
332
     * Raise some PHP limits for resource-intensive tasks
333
     */
334 8
    public function disable_limits()
335
    {
336 8
        $stat = @ini_set('max_execution_time', $this->config->get('midcom_max_execution_time'));
0 ignored issues
show
Bug introduced by
It seems like $this->config->get('midcom_max_execution_time') can also be of type null; however, parameter $value of ini_set() does only seem to accept string, 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

336
        $stat = @ini_set('max_execution_time', /** @scrutinizer ignore-type */ $this->config->get('midcom_max_execution_time'));
Loading history...
337 8
        if (false === $stat) {
338
            debug_add('ini_set("max_execution_time", ' . $this->config->get('midcom_max_execution_time') . ') returned false', MIDCOM_LOG_WARN);
339
        }
340 8
        $stat = @ini_set('memory_limit', $this->config->get('midcom_max_memory'));
341 8
        if (false === $stat) {
342
            debug_add('ini_set("memory_limit", ' . $this->config->get('midcom_max_memory') . ') returned false', MIDCOM_LOG_WARN);
343
        }
344 8
    }
345
}
346