Passed
Push — master ( f43eb5...9cfb91 )
by Andreas
10:02
created

midcom_application::get_request()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 2.0625
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_style $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
    private ?Request $request = null;
42
43
    /**
44
     * Set this variable to true during the handle phase of your component to
45
     * not show the site's style around the component output. This is mainly
46
     * targeted at XML output like RSS feeds and similar things. The output
47
     * handler of the site, excluding the style-init/-finish tags will be executed
48
     * immediately after the handle phase
49
     *
50
     * Changing this flag after the handle phase or for dynamically loaded
51
     * components won't change anything.
52
     */
53
    public bool $skip_page_style = false;
54
55
    private ?string $project_dir = null;
56
57
    private midcom_config $cfg;
58
59
    public function __construct(string $environment, bool $debug)
60
    {
61
        $this->cfg = new midcom_config;
62
        parent::__construct($environment, $debug);
63
    }
64
65 44
    private function get_request() : Request
66
    {
67 44
        if (!$this->request) {
68
            $this->request = Request::createFromGlobals();
69
        }
70 44
        return $this->request;
71
    }
72
73
    public function registerContainerConfiguration(LoaderInterface $loader)
74
    {
75
        if (file_exists($this->getProjectDir() . '/config/services.yml')) {
76
            $loader->load($this->getProjectDir() . '/config/services.yml');
77
        }
78
        if ($classes = midcom::get_registered_service_classes()) {
79
            $loader->load(function (ContainerBuilder $container) use ($classes) {
80
                foreach ($classes as $id => $class) {
81
                    $container->findDefinition($id)->setClass($class);
82
                }
83
            });
84
        }
85
    }
86
87
    protected function initializeContainer()
88
    {
89
        parent::initializeContainer();
90
        $this->container->set('config', $this->cfg);
91
    }
92
93
    protected function buildContainer()
94
    {
95
        $container = parent::buildContainer();
96
        $this->cfg->export_to($container);
97
        return $container;
98
    }
99
100
    public function registerBundles()
101
    {
102
        return [new midcomBundle];
103
    }
104
105 3
    public function getProjectDir()
106
    {
107 3
        if ($this->project_dir === null) {
108
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
109
                // this is the case where we're installed as a dependency
110
                $this->project_dir = dirname(__DIR__, 5);
111
            } else {
112
                $this->project_dir = dirname(__DIR__, 2);
113
            }
114
        }
115 3
        return $this->project_dir;
116
    }
117
118 337
    public function getCacheDir()
119
    {
120 337
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
121
    }
122
123
    /**
124
     * Magic getter for service loading
125
     */
126 726
    public function __get($key)
127
    {
128 726
        if (!$this->booted) {
129
            $this->boot();
130
        }
131 726
        return $this->getContainer()->get($key);
132
    }
133
134
    /**
135
     * Magic setter
136
     */
137
    public function __set($key, $value)
138
    {
139
        if (!$this->booted) {
140
            $this->boot();
141
        }
142
        $this->getContainer()->set($key, $value);
143
    }
144
145
    /* *************************************************************************
146
     * Control framework:
147
     * codeinit      - Handle the current request
148
     * dynamic_load   - Dynamically load and execute a URL
149
     * finish         - Cleanup Work
150
     */
151
152
    /**
153
     * Initialize the URL parser and process the request.
154
     *
155
     * This function must be called before any output starts.
156
     */
157
    public function codeinit()
158
    {
159
        $request = $this->get_request();
160
        try {
161
            $response = $this->handle($request);
162
            $response->send();
163
            $this->terminate($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 17
    public function dynamic_load(string $url, string $substyle = '')
195
    {
196 17
        debug_add("Dynamic load of URL {$url}");
197 17
        $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 17
        $oldcontext = midcom_core_context::get();
202 17
        $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 17
        if ($substyle) {
204
            $context->set_key(MIDCOM_CONTEXT_SUBSTYLE, $substyle);
205
        }
206
207 17
        $request = $this->get_request()->duplicate([], null, []);
208 17
        $request->attributes->set('context', $context);
209
210 17
        $cached = $this->cache->content->check_dl_hit($request);
211 17
        if ($cached !== false) {
212
            echo $cached;
213
            midcom_core_context::leave();
214
            return;
215
        }
216
217 17
        $backup = $this->skip_page_style;
218 17
        $this->skip_page_style = true;
219
        try {
220 17
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
221 13
        } catch (midcom_error_notfound | midcom_error_forbidden $e) {
222 13
            $e->log();
223 13
            midcom_core_context::leave();
224 13
            return;
225
        } finally {
226 17
            $this->skip_page_style = $backup;
227
        }
228
229 4
        $dl_cache_data = $response->getContent();
230 4
        echo $dl_cache_data;
231
232
        /* Cache DL the content */
233 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
234
235 4
        midcom_core_context::leave();
236
    }
237
238
    /**
239
     * Stop the PHP process
240
     *
241
     * @deprecated
242
     */
243
    public function finish()
244
    {
245
        _midcom_stop_request();
246
    }
247
248
    /* *************************************************************************
249
     * Framework Access Helper functions
250
     */
251
252
    /**
253
     * Retrieves the name of the current host, fully qualified with protocol and
254
     * port (http[s]://www.my.domain.com[:1234])
255
     */
256 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...
257
    {
258 29
        return $this->get_request()->getSchemeAndHttpHost();
259
    }
260
261
    /**
262
     * Return the prefix required to build relative links on the current site.
263
     * This includes the http[s] prefix, the hosts port (if necessary) and the
264
     * base url of the Midgard Page. Be aware, that this does *not* point to the
265
     * base host of the site.
266
     *
267
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
268
     */
269
    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...
270
    {
271
        return $this->get_host_name() . midcom_connection::get_url('self');
272
    }
273
274
    /**
275
     * Return the prefix required to build relative links on the current site.
276
     * This includes the http[s] prefix, the hosts port (if necessary) and the
277
     * base url of the main host. This is not necessarily the currently active
278
     * MidCOM Page however, use the get_page_prefix() function for that.
279
     *
280
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
281
     */
282 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...
283
    {
284 7
        $host_prefix = midcom_connection::get_url('prefix');
285 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

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

325
        /** @scrutinizer ignore-deprecated */ $this->finish();
Loading history...
326
    }
327
328
    /**
329
     * Raise some PHP limits for resource-intensive tasks
330
     */
331 8
    public function disable_limits()
332
    {
333 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

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