Passed
Push — master ( 0c08dd...2d3809 )
by Andreas
17:26
created

midcom_application::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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\dependencyInjection\loggerPass;
15
use midcom\dependencyInjection\componentPass;
16
use midcom\dependencyInjection\indexerPass;
17
18
/**
19
 * Main controlling instance of the MidCOM Framework
20
 *
21
 * @property midcom_services_i18n $i18n
22
 * @property midcom_helper__componentloader $componentloader
23
 * @property midcom_services_dbclassloader $dbclassloader
24
 * @property midcom_helper__dbfactory $dbfactory
25
 * @property midcom_helper_head $head
26
 * @property midcom_helper__styleloader $style
27
 * @property midcom_services_auth $auth
28
 * @property midcom_services_permalinks $permalinks
29
 * @property midcom_services_toolbars $toolbars
30
 * @property midcom_services_uimessages $uimessages
31
 * @property midcom_services_metadata $metadata
32
 * @property midcom_services_rcs $rcs
33
 * @property midcom_services__sessioning $session
34
 * @property midcom_services_indexer $indexer
35
 * @property midcom_config $config
36
 * @property midcom_services_cache $cache
37
 * @property Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
38
 * @property midcom_debug $debug
39
 * @package midcom
40
 */
41
class midcom_application extends Kernel
42
{
43
    /**
44
     * Host prefix cache to avoid computing it each time.
45
     *
46
     * @var string
47
     * @see get_host_prefix()
48
     */
49
    private $_cached_host_prefix = '';
50
51
    /**
52
     * Page prefix cache to avoid computing it each time.
53
     *
54
     * @var string
55
     * @see get_page_prefix()
56
     */
57
    private $_cached_page_prefix = '';
58
59
    /**
60
     * @var Request
61
     */
62
    private $request;
63
64
    /**
65
     * Set this variable to true during the handle phase of your component to
66
     * not show the site's style around the component output. This is mainly
67
     * targeted at XML output like RSS feeds and similar things. The output
68
     * handler of the site, excluding the style-init/-finish tags will be executed
69
     * immediately after the handle phase
70
     *
71
     * Changing this flag after the handle phase or for dynamically loaded
72
     * components won't change anything.
73
     *
74
     * @var boolean
75
     */
76
    public $skip_page_style = false;
77
78
    private $project_dir;
79
80
    /**
81
     * @var midcom_config
82
     */
83
    private $cfg;
84
85
    public function __construct(string $environment, bool $debug)
86
    {
87
        midcom_compat_environment::initialize();
88
        $this->request = Request::createFromGlobals();
89
        $this->cfg = new midcom_config;
90
        parent::__construct($environment, $debug);
91
    }
92
93
    public function registerContainerConfiguration(LoaderInterface $loader)
94
    {
95
        $loader->load(__DIR__ . '/config/services.yml');
96
        if (file_exists($this->getProjectDir() . '/config/services.yml')) {
97
            $loader->load($this->getProjectDir() . '/config/services.yml');
98
        }
99
        if ($classes = midcom::get_registered_service_classes()) {
100
            $loader->load(function (ContainerBuilder $container) use ($classes) {
101
                foreach ($classes as $id => $class) {
102
                    $container->findDefinition($id)->setClass($class);
103
                }
104
            });
105
        }
106
    }
107
108
    protected function initializeContainer()
109
    {
110
        parent::initializeContainer();
111
        $this->container->set('config', $this->cfg);
112
    }
113
114
    protected function build(ContainerBuilder $container)
115
    {
116
        parent::build($container);
117
        $container->addCompilerPass(new loggerPass($this->cfg));
118
        $container->addCompilerPass(new componentPass($this->cfg));
119
        $container->addCompilerPass(new indexerPass($this->cfg));
120
    }
121
122
    public function registerBundles()
123
    {
124
        return [];
125
    }
126
127
    public function getProjectDir()
128
    {
129
        if ($this->project_dir === null) {
130
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
131
                // this is the case where we're installed as a dependency
132
                $this->project_dir = dirname(__DIR__, 5);
133
            } else {
134
                $this->project_dir = dirname(__DIR__, 2);
135
            }
136
        }
137
        return $this->project_dir;
138
    }
139
140 325
    public function getCacheDir()
141
    {
142 325
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
143
    }
144
145
    /**
146
     * Magic getter for service loading
147
     */
148 735
    public function __get($key)
149
    {
150 735
        return $this->getContainer()->get($key);
151
    }
152
153
    /**
154
     * Magic setter
155
     */
156
    public function __set($key, $value)
157
    {
158
        $this->getContainer()->set($key, $value);
159
    }
160
161
    /* *************************************************************************
162
     * Control framework:
163
     * codeinit      - Handle the current request
164
     * dynamic_load   - Dynamically load and execute a URL
165
     * finish         - Cleanup Work
166
     */
167
168
    /**
169
     * Initialize the URL parser and process the request.
170
     *
171
     * This function must be called before any output starts.
172
     */
173
    public function codeinit()
174
    {
175
        try {
176
            $this->handle($this->request)->send();
177
        } catch (Error $e) {
178
            $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

178
            $this->getHttpKernel()->/** @scrutinizer ignore-call */ terminateWithException($e);
Loading history...
179
        }
180
    }
181
182
    /**
183
     * Dynamically execute a subrequest and insert its output in place of the
184
     * function call.
185
     *
186
     * It tries to load the component referenced with the URL $url and executes
187
     * it as if it was used as primary component.
188
     *
189
     * This is only possible if the system is in the Page-Style output phase. It
190
     * cannot be used within code-init or during the output phase of another
191
     * component.
192
     *
193
     * Example code, executed on a site's homepage, it will load the news listing from
194
     * the given URL and display it using a substyle of the node style that is assigned
195
     * to the loaded one:
196
     *
197
     * <code>
198
     * $blog = '/blog/latest/3/';
199
     * $substyle = 'homepage';
200
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
201
     * </code>
202
     *
203
     * Results of dynamic_loads are cached with the system cache strategy
204
     *
205
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
206
     */
207 16
    public function dynamic_load(string $url, string $substyle = '')
208
    {
209 16
        debug_add("Dynamic load of URL {$url}");
210 16
        $url = midcom_connection::get_url('prefix') . $url;
211
212
        // Determine new Context ID and set current context,
213
        // enter that context and prepare its data structure.
214 16
        $oldcontext = midcom_core_context::get();
215 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

215
        $context = midcom_core_context::enter($url, /** @scrutinizer ignore-type */ $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
Loading history...
216 16
        if ($substyle) {
217
            $context->set_key(MIDCOM_CONTEXT_SUBSTYLE, $substyle);
218
        }
219
220 16
        $request = $this->request->duplicate([], null, []);
221 16
        $request->attributes->set('context', $context);
222
223 16
        $cached = $this->cache->content->check_dl_hit($request);
224 16
        if ($cached !== false) {
225
            echo $cached;
226
            midcom_core_context::leave();
227
            return;
228
        }
229
230 16
        $backup = $this->skip_page_style;
231 16
        $this->skip_page_style = true;
232
        try {
233 16
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
234 12
        } catch (midcom_error $e) {
235 12
            if ($e instanceof midcom_error_notfound || $e instanceof midcom_error_forbidden) {
236 12
                $e->log();
237 12
                midcom_core_context::leave();
238 12
                return;
239
            }
240
            throw $e;
241 4
        } finally {
242 16
            $this->skip_page_style = $backup;
243
        }
244
245 4
        $dl_cache_data = $response->getContent();
246 4
        echo $dl_cache_data;
247
248
        /* Cache DL the content */
249 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
250
251 4
        midcom_core_context::leave();
252 4
    }
253
254
    /**
255
     * Exit from the framework, execute after all output has been made.
256
     *
257
     * <b>WARNING:</b> Anything done after calling this method will be lost.
258
     */
259
    public function finish()
260
    {
261
        debug_add("End of MidCOM run: " . $this->request->server->get('REQUEST_URI'));
262
        _midcom_stop_request();
263
    }
264
265
    /* *************************************************************************
266
     * Framework Access Helper functions
267
     */
268
269
    /**
270
     * Retrieves the name of the current host, fully qualified with protocol and
271
     * port (http[s]://www.my.domain.com[:1234])
272
     */
273 37
    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...
274
    {
275 37
        return $this->request->getSchemeAndHttpHost();
276
    }
277
278
    /**
279
     * Return the prefix required to build relative links on the current site.
280
     * This includes the http[s] prefix, the hosts port (if necessary) and the
281
     * base url of the Midgard Page. Be aware, that this does *not* point to the
282
     * base host of the site.
283
     *
284
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
285
     */
286
    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...
287
    {
288
        if (!$this->_cached_page_prefix) {
289
            $host_name = $this->get_host_name();
290
            $this->_cached_page_prefix = $host_name . midcom_connection::get_url('self');
291
        }
292
293
        return $this->_cached_page_prefix;
294
    }
295
296
    /**
297
     * Return the prefix required to build relative links on the current site.
298
     * This includes the http[s] prefix, the hosts port (if necessary) and the
299
     * base url of the main host. This is not necessarily the currently active
300
     * MidCOM Page however, use the get_page_prefix() function for that.
301
     *
302
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
303
     */
304 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...
305
    {
306 7
        if (!$this->_cached_host_prefix) {
307 1
            $host_name = $this->get_host_name();
308 1
            $host_prefix = midcom_connection::get_url('prefix');
309 1
            if (substr($host_prefix, 0, 1) != '/') {
310
                $host_prefix = "/{$host_prefix}";
311
            }
312 1
            if (substr($host_prefix, -1, 1) != '/') {
313
                $host_prefix .= '/';
314
            }
315 1
            $this->_cached_host_prefix = "{$host_name}{$host_prefix}";
316
        }
317
318 7
        return $this->_cached_host_prefix;
319
    }
320
321
    /* *************************************************************************
322
     * Generic Helper Functions not directly related with MidCOM:
323
     *
324
     * relocate           - executes a HTTP relocation to the given URL
325
     */
326
327
    /**
328
     * Sends a header out to the client.
329
     *
330
     * This function is syntactically identical to
331
     * the regular PHP header() function, but is integrated into the framework. Every
332
     * Header you sent must go through this function or it might be lost later on;
333
     * this is especially important with caching.
334
     *
335
     * @param string $header    The header to send.
336
     * @param integer $response_code HTTP response code to send with the header
337
     */
338 17
    public function header($header, $response_code = null)
339
    {
340 17
        $this->cache->content->register_sent_header($header);
341 17
        midcom_compat_environment::get()->header($header, true, $response_code);
342 17
    }
343
344
    /**
345
     * Relocate to another URL.
346
     *
347
     * Note, that this function automatically makes the page uncacheable, calls
348
     * midcom_finish and exit, so it will never return. If the headers have already
349
     * been sent, this will leave you with a partially completed page, so beware.
350
     *
351
     * @param string $url    The URL to redirect to, will be preprocessed as outlined above.
352
     * @param int $response_code HTTP response code to send with the relocation, from 3xx series
353
     */
354
    public function relocate($url, $response_code = 302)
355
    {
356
        $response = new midcom_response_relocate($url, $response_code);
357
        $response->send();
358
        $this->finish();
359
    }
360
361
    /**
362
     * Raise some PHP limits for resource-intensive tasks
363
     */
364 8
    public function disable_limits()
365
    {
366 8
        $stat = @ini_set('max_execution_time', $this->config->get('midcom_max_execution_time'));
367 8
        if (false === $stat) {
368
            debug_add('ini_set("max_execution_time", ' . $this->config->get('midcom_max_execution_time') . ') returned false', MIDCOM_LOG_WARN);
369
        }
370 8
        $stat = @ini_set('memory_limit', $this->config->get('midcom_max_memory'));
371 8
        if (false === $stat) {
372
            debug_add('ini_set("memory_limit", ' . $this->config->get('midcom_max_memory') . ') returned false', MIDCOM_LOG_WARN);
373
        }
374 8
    }
375
}
376