Completed
Push — develop ( bf5641...87bb83 )
by Kevin
12:46 queued 01:21
created

BuilderFactory::getRelationalAdapter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Magium\Configuration\Config;
4
5
use Magium\Configuration\Config\Storage\Mongo;
6
use Magium\Configuration\Config\Storage\RelationalDatabase;
7
use Magium\Configuration\File\Configuration\ConfigurationFileRepository;
8
use Magium\Configuration\File\Context\AbstractContextConfigurationFile;
9
use Magium\Configuration\InvalidConfigurationException;
10
use Magium\Configuration\Manager\CacheFactory;
11
use MongoDB\Client;
12
use Zend\Db\Adapter\Adapter;
13
14
class BuilderFactory implements BuilderFactoryInterface
15
{
16
    protected $configuration;
17
    protected $adapter;
18
    protected $contextFile;
19
    protected $baseDirectory;
20
21 14
    public function __construct(
22
        \SplFileInfo $baseDirectory,
23
        \SimpleXMLElement $configuration,
24
        AbstractContextConfigurationFile $contextConfigurationFile
25
    )
26
    {
27 14
        $this->configuration = $configuration;
28 14
        $this->contextFile = $contextConfigurationFile;
29 14
        if (!$baseDirectory->isDir()) {
30 1
            throw new InvalidConfigurationException('Base directory must be a directory');
31
        }
32 13
        $this->baseDirectory = $baseDirectory;
33 13
    }
34
35 3
    protected function getCache(\SimpleXMLElement $element)
36
    {
37 3
        $cacheFactory = new CacheFactory();
38 3
        return $cacheFactory->getCache($element);
39
    }
40
41 7
    public function getDatabaseConfiguration()
42
    {
43 7
        $config = json_encode($this->configuration->persistenceConfiguration);
44 7
        $config = json_decode($config, true);
45 7
        return $config;
46
    }
47
48 3
    public function getRelationalAdapter()
49
    {
50 3
        if (!$this->adapter instanceof Adapter) {
51 3
            $config = $this->getDatabaseConfiguration();
52 3
            $this->adapter = new Adapter($config);
53
        }
54 3
        return $this->adapter;
55
    }
56
57 4
    public function getMongoDsnString()
58
    {
59 4
        $config = $this->getDatabaseConfiguration();
60 4
        $dsn = 'mongodb://';  //[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]';
61 4
        $at = false;
62 4
        if (isset($config['username'])) {
63 1
            $dsn .= $config['username'];
64 1
            $at = true;
65
        }
66 4
        if (isset($config['password'])) {
67 1
            $dsn .= ':'.$config['password'];
68 1
            $at = true;
69
        }
70 4
        if ($at) {
71 1
            $dsn .= '@';
72
        }
73 4
        $dsn .= $config['hostname'];
74 4
        if (isset($config['port'])) {
75 1
            $dsn .= ':' . $config['port'];
76
        }
77 4
        return $dsn;
78
    }
79
80 2
    public function getMongoAdapter()
81
    {
82 2
        $config = $this->getDatabaseConfiguration();
83 2
        $dsn = $this->getMongoDsnString();
84 2
        $client = new Client($dsn);
85 2
        $collection = isset($config['table'])?$config['table']:Mongo::TABLE;
86 2
        return new Mongo($client->selectCollection($config['database'], $collection));
87
    }
88
89 3
    public function getPersistence()
90
    {
91 3
        if (stripos($this->configuration->persistenceConfiguration->driver, 'mongo') === 0) {
92
            return $this->getMongoAdapter();
93
        }
94 3
        $persistence = new RelationalDatabase($this->getRelationalAdapter(), $this->contextFile);
95 3
        return $persistence;
96
    }
97
98 6
    public function getSecureBaseDirectories()
99
    {
100 6
        $cwd = getcwd();
101 6
        $path = $this->baseDirectory->getRealPath();
102 6
        chdir($path);
103 6
        $config = $this->configuration->configurationDirectories;
0 ignored issues
show
Bug introduced by
The property configurationDirectories does not seem to exist in SimpleXMLElement.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
104 6
        $config = json_encode($config);
105 6
        $config = json_decode($config, true);
106 6
        $baseDirs = [];
107 6
        if (is_array($config) && isset($config['directory'])) {
108 4 View Code Duplication
            if (!is_array($config['directory'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109 3
                $config['directory'] = [$config['directory']];
110
            }
111 4
            foreach ($config['directory'] as $dir) {
112 4
                $path = realpath($dir);
113 4
                if (!is_dir($path)) {
114 1
                    throw new InvalidConfigurationLocationException('A secure configuration path cannot be determined for the directory: ' . $dir);
115
                }
116 3
                $baseDirs[] = $path;
117
            }
118
        }
119 5
        chdir($cwd);
120 5
        return $baseDirs;
121
    }
122
123 5
    public function getConfigurationFiles(array $secureBaseDirectories = [])
124
    {
125 5
        $config = json_encode($this->configuration->configurationFiles);
126 5
        $config = json_decode($config, true);
127 5
        $files = [];
128 5
        if (isset($config['file'])) {
129 3 View Code Duplication
            if (!is_array($config['file'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130 1
                $config['file'] = [$config['file']];
131
            }
132 3
            foreach ($config['file'] as $file) {
133 3
                $found = false;
134 3
                foreach ($secureBaseDirectories as $base) {
135 3
                    chdir($base);
136 3
                    $path = realpath($file);
137 3
                    if ($path) {
138 3
                        $found = true;
139 3
                        $files[] = $path;
140
                    }
141
                }
142 3
                if (!$found) {
143
                    throw new InvalidConfigurationLocationException('Could not find file: ' . $file);
144
                }
145
            }
146
        }
147 5
        return $files;
148
    }
149
150 3
    public function getBuilder()
151
    {
152
        // This method expects that chdir() has been called on the same level as the magium-configuration.xml file
153 3
        $cache = $this->getCache($this->configuration->cache);
154 3
        $persistence = $this->getPersistence();
155 3
        $secureBases = $this->getSecureBaseDirectories();
156 2
        $configurationFiles = $this->getConfigurationFiles($secureBases);
157 2
        $repository = ConfigurationFileRepository::getInstance($secureBases, $configurationFiles);
158
159
        /*
160
         * We only populate up to the secureBases because adding a DIC or service manager by configuration starts
161
         * making the configuration-based approach pay off less.  If you need a DIC or service manager for your
162
         * configuration builder (which you will if you use object/method callbacks for value filters) then you need
163
         * to wire the Builder object with your own code.
164
         */
165
166 2
        $builder = new Builder(
167 2
            $cache,
168 2
            $persistence,
169 2
            $repository
170
        );
171
172 2
        return $builder;
173
    }
174
175
}
176