Passed
Push — master ( 964e1c...49cc4f )
by Florian
01:49 queued 12s
created

DomainModelAwareTrait::loadService()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 3
dl 0
loc 17
ccs 0
cts 9
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright (c) Florian Krämer
4
 *
5
 * Licensed under The MIT License
6
 * For full copyright and license information, please see the LICENSE.txt
7
 * Redistributions of files must retain the above copyright notice.
8
 *
9
 * @copyright     Copyright (c) Florian Krämer
10
 * @link          https://github.com/burzum/cakephp-service-layer
11
 * @since         1.0.0
12
 * @license       https://opensource.org/licenses/mit-license.php MIT License
13
 */
14
declare(strict_types = 1);
15
16
namespace Burzum\CakeServiceLayer\DomainModel;
17
18
use Cake\Core\ObjectRegistry;
19
20
/**
21
 * Domain Model Aware Trait
22
 *
23
 * CakePHP style locator to load domain model classes
24
 */
25
trait DomainModelAwareTrait
26
{
27
    /**
28
     * Service Locator Registry
29
     *
30
     * @var \Cake\Core\ObjectRegistry
31
     */
32
    protected $domainModelLocator;
33
34
    /**
35
     * Default Domain Model Locator Class
36
     *
37
     * @var string
38
     */
39
    protected $defaultDomainModelLocator = DomainModelLocator::class;
40
41
    /**
42
     * Load a Domain Model
43
     *
44
     * @param string $model Domain Model Name
45
     * @param array $constructorArgs Constructor Args
46
     * @param bool $assignProperty Assigns the domain model to a class property of the same name
47
     * @return \stdClass
48
     */
49
    public function loadService($model, array $constructorArgs = [], $assignProperty = false)
50
    {
51
        $domainModel = $this->getDomainModelLocator()->load($model, $constructorArgs);
52
53
        if (!$assignProperty) {
54
            return $domainModel;
55
        }
56
57
        list(, $name) = pluginSplit($model);
58
59
        if (isset($this->{$name})) {
60
            trigger_error(__CLASS__ . '::$%s is already in use.', E_USER_WARNING);
61
        }
62
63
        $this->{$name} = $domainModel;
64
65
        return $domainModel;
66
    }
67
68
    /**
69
     * Get the service locator
70
     *
71
     * @return \Cake\Core\ObjectRegistry
72
     */
73
    public function getDomainModelLocator()
74
    {
75
        if (empty($this->serviceLocator)) {
76
            $class = $this->defaultDomainModelLocator;
77
            $this->domainModelLocator = new $class();
78
        }
79
80
        return $this->domainModelLocator;
81
    }
82
83
    /**
84
     * Sets the Domain model locator
85
     *
86
     * @param \Cake\Core\ObjectRegistry $locator Locator
87
     * @return void
88
     */
89
    public function setDomainModelLocator(ObjectRegistry $locator)
90
    {
91
        $this->domainModelLocator = $locator;
92
    }
93
}
94