Completed
Push — master ( 38192e...3b3b09 )
by Joschi
04:50
created

App::getServiceService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * Toggl Dashboard
5
 *
6
 * @category    Tollwerk
7
 * @package     Tollwerk\Admin
8
 * @subpackage  Tollwerk\Admin\Ports
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Tollwerk\Admin\Infrastructure;
38
39
use Doctrine\DBAL\Types\Type;
40
use Doctrine\ORM\EntityManager;
41
use Doctrine\ORM\Tools\Setup;
42
use Symfony\Component\Yaml\Yaml;
43
use Tollwerk\Admin\Application\Contract\PersistenceAdapterFactoryInterface;
44
use Tollwerk\Admin\Application\Contract\PersistenceServiceInterface;
45
use Tollwerk\Admin\Application\Contract\ServiceServiceInterface;
46
use Tollwerk\Admin\Application\Contract\StorageAdapterStrategyInterface;
47
use Tollwerk\Admin\Application\Service\AccountService;
48
use Tollwerk\Admin\Application\Service\DomainService;
49
use Tollwerk\Admin\Application\Service\VirtualHostService;
50
use Tollwerk\Admin\Infrastructure\Doctrine\EnumVhosttypeType;
51
use Tollwerk\Admin\Infrastructure\Factory\PersistenceAdapterFactory;
52
use Tollwerk\Admin\Infrastructure\Service\PersistenceService;
53
use Tollwerk\Admin\Infrastructure\Service\ServiceService;
54
use Tollwerk\Admin\Infrastructure\Strategy\DoctrineStorageAdapterStrategy;
55
56
/**
57
 * App
58
 *
59
 * @package Tollwerk\Admin
60
 * @subpackage Tollwerk\Admin\Ports
61
 */
62
class App
63
{
64
    /**
65
     * Configuration
66
     *
67
     * @var array
68
     */
69
    protected static $config;
70
    /**
71
     * Root directory
72
     *
73
     * @var string
74
     */
75
    protected static $rootDirectory;
76
    /**
77
     * Entity manager
78
     *
79
     * @var EntityManager
80
     */
81
    protected static $entityManager;
82
    /**
83
     * Developer mode
84
     *
85
     * @var boolean
86
     */
87
    protected static $devMode;
88
    /**
89
     * Account service
90
     *
91
     * @var AccountService
92
     */
93
    protected static $accountService = null;
94
    /**
95
     * Virtual host service
96
     *
97
     * @var VirtualHostService
98
     */
99
    protected static $vhostService = null;
100
    /**
101
     * Domain service
102
     *
103
     * @var DomainService
104
     */
105
    protected static $domainService = null;
106
    /**
107
     * Active Storage adapter
108
     *
109
     * @var StorageAdapterStrategyInterface
110
     */
111
    protected static $storageAdapter;
112
    /**
113
     * Persistence adapter factory
114
     *
115
     * @var PersistenceAdapterFactoryInterface
116
     */
117
    protected static $persistenceAdapterFactory;
118
    /**
119
     * Persistence service
120
     *
121
     * @var PersistenceServiceInterface
122
     */
123
    protected static $persistenceService;
124
    /**
125
     * Service service
126
     *
127
     * @var ServiceServiceInterface
128
     */
129
    protected static $serviceService;
130
    /**
131
     * App domain
132
     *
133
     * @var string
134
     */
135
    const DOMAIN = 'admin';
136
137
    /**
138
     * Bootstrap
139
     *
140
     * @see https://github.com/toggl/toggl_api_docs/blob/master/reports.md
141
     * @see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html
142
     *
143
     * @param bool $devMode Developer mode
144
     */
145
    public static function bootstrap($devMode = false)
146
    {
147
        self::$devMode = !!$devMode;
148
        self::$rootDirectory = dirname(dirname(dirname(__DIR__))).DIRECTORY_SEPARATOR;
149
150
        // Initialize the configuration
151
        $config = file_get_contents(self::$rootDirectory.'config'.DIRECTORY_SEPARATOR.'config.yml');
152
        self::$config = Yaml::parse($config);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Symfony\Component\Yaml\Yaml::parse($config) can also be of type string or object<stdClass>. However, the property $config is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
153
154
        // Initialize doctrine
155
        self::initializeDoctrine();
156
157
        // Register the Doctrine storage adapter and persistence adapter factory
158
        self::$storageAdapter = new DoctrineStorageAdapterStrategy();
159
        self::$persistenceAdapterFactory = new PersistenceAdapterFactory();
160
        self::$serviceService = new ServiceService();
161
        self::$persistenceService = new PersistenceService(self::$persistenceAdapterFactory, self::$serviceService);
162
    }
163
164
    /**
165
     * Initialize Doctrine
166
     */
167
    protected static function initializeDoctrine()
168
    {
169
        // If the Doctrine parameters don't exist
170
        if (empty(self::$config['doctrine'])
171
            || !is_array(self::$config['doctrine'])
172
            || empty(self::$config['doctrine']['dbparams'])
173
        ) {
174
            throw new \InvalidArgumentException('Invalid Doctrine database parameters', 1466175889);
175
        }
176
177
        $modelPaths = [
178
            self::$rootDirectory.'src'.DIRECTORY_SEPARATOR.'Admin'
179
            .DIRECTORY_SEPARATOR.'Infrastructure'.DIRECTORY_SEPARATOR.'Model'
180
        ];
181
        $dbParams = self::$config['doctrine']['dbparams'];
182
        $config = Setup::createAnnotationMetadataConfiguration($modelPaths, self::$devMode);
183
184
        self::$entityManager = EntityManager::create($dbParams, $config);
185
        $platform = self::$entityManager->getConnection()->getDatabasePlatform();
186
        $platform->registerDoctrineTypeMapping('enum', 'string');
187
188
        // Register the virtual host type declaration
189
        Type::addType(EnumVhosttypeType::ENUM_TYPE, EnumVhosttypeType::class);
190
191
        // Set the locale
192
        $locale = self::getConfig('general.locale');
193
        putenv('LC_ALL='.$locale);
194
        setlocale(LC_ALL, $locale);
195
196
        \bindtextdomain(self::DOMAIN, self::$rootDirectory.'src'.DIRECTORY_SEPARATOR.'Admin'
197
            .DIRECTORY_SEPARATOR.'Infrastructure'.DIRECTORY_SEPARATOR.'Lang');
198
        \bind_textdomain_codeset(self::DOMAIN, 'UTF-8');
199
        \textdomain(self::DOMAIN);
200
    }
201
202
    /**
203
     * Return the entity manager
204
     *
205
     * @return EntityManager
206
     */
207
    public static function getEntityManager()
208
    {
209
        return self::$entityManager;
210
    }
211
212
    /**
213
     * Get a configuration value
214
     *
215
     * @param null $key Optional: config value key
216
     * @return mixed Configuration value(s)
217
     */
218 3
    public static function getConfig($key = null)
219
    {
220 3
        if ($key === null) {
221
            return self::$config;
222
        }
223 3
        $keyParts = explode('.', $key);
224 3
        $config =& self::$config;
225 3
        foreach ($keyParts as $keyPart) {
226 3
            if (!array_key_exists($keyPart, $config)) {
227
                throw new \InvalidArgumentException(sprintf('Invalid config key "%s"', $key), 1466179561);
228
            }
229 3
            $config =& $config[$keyPart];
230 3
        }
231 3
        return $config;
232
    }
233
234
    /**
235
     * Return the contents of a particular template
236
     *
237
     * @param string $template Template name
238
     * @return string template contents
239
     */
240
    public static function getTemplate($template)
241
    {
242
        $templateFile = self::$rootDirectory.'src'.DIRECTORY_SEPARATOR.'Admin'
243
            .DIRECTORY_SEPARATOR.'Infrastructure'.DIRECTORY_SEPARATOR.'Templates'.DIRECTORY_SEPARATOR.$template;
244
        if (!file_exists($templateFile)) {
245
            throw new \RuntimeException(sprintf('Unknown template "%s"', $template), 1475503926);
246
        }
247
        return file_get_contents($templateFile);
248
    }
249
250
    /**
251
     * Return the account service
252
     *
253
     * @return AccountService Account service
254
     */
255
    public static function getAccountService()
256
    {
257
        if (self::$accountService === null) {
258
            self::$accountService = new AccountService(self::$storageAdapter, self::$persistenceService);
259
        }
260
261
        return self::$accountService;
262
    }
263
264
    /**
265
     * Return the virtual host service
266
     *
267
     * @return VirtualHostService Virtual host service
268
     */
269
    public static function getVirtualHostService()
270
    {
271
        if (self::$vhostService === null) {
272
            self::$vhostService = new VirtualHostService(self::$storageAdapter, self::$persistenceService);
273
        }
274
275
        return self::$vhostService;
276
    }
277
278
    /**
279
     * Return the domain service
280
     *
281
     * @return DomainService Domain service
282
     */
283
    public static function getDomainService()
284
    {
285
        if (self::$domainService === null) {
286
            self::$domainService = new DomainService(self::$storageAdapter, self::$persistenceService);
287
        }
288
289
        return self::$domainService;
290
    }
291
292
    /**
293
     * Return the shell service service
294
     *
295
     * @return ServiceServiceInterface Service service
296
     */
297
    public static function getServiceService()
298
    {
299
        return self::$serviceService;
300
    }
301
}
302