aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/DIContainer.php
blob: 0b288bb67a635e8039eaa07ae86df779967073c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

namespace Studip;

use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;

class DIContainer
{
    /**
     * The current globally available container.
     *
     * @var static
     */
    protected static $instance;

    /**
     * Get the globally available instance of the container.
     *
     * @return ContainerInterface
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            $builder = static::createBuilder();
            static::$instance = $builder->build();
        }

        return static::$instance;
    }

    /**
     * Set the instance of the container.
     *
     * @param  \Psr\Container\ContainerInterface|null  $container
     * @return \Psr\Container\ContainerInterface|static
     */
    public static function setInstance(ContainerInterface $container = null)
    {
        return static::$instance = $container;
    }

    /**
     * Set up the ContainerBuilder.
     */
    protected static function createBuilder(): ContainerBuilder
    {
        $builder = new ContainerBuilder();
        if (\Studip\ENV == 'production') {
            $builder->enableCompilation(
                self::getCompilationPath(),
                self::getCompilationClass()
            );
        }
        $builder->useAttributes(true);
        $builder->addDefinitions('lib/bootstrap-definitions.php');

        $jsonapiSettings = require 'lib/classes/JsonApi/settings.php';
        $jsonapiSettings($builder);

        $jsonapiDependencies = require 'lib/classes/JsonApi/dependencies.php';
        $jsonapiDependencies($builder);

        return $builder;
    }

    public static function getCompilationPath(): string
    {
        return $GLOBALS['TMP_PATH'];
    }

    public static function getCompilationClass(): string
    {
        return 'CompiledContainer';
    }
}