Config   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 2

Importance

Changes 0
Metric Value
wmc 34
cbo 2
dl 0
loc 229
rs 9.68
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 20 6
A getBasePackagesUrl() 0 4 1
A getCacheDir() 0 4 1
A getInstallDir() 0 4 1
A isSaveToBowerJsonFile() 0 4 1
A setSaveToBowerJsonFile() 0 4 1
A initBowerJsonFile() 0 7 1
A updateBowerJsonFile() 0 13 2
A updateBowerJsonFile2() 0 7 1
A getBowerFileContent() 0 12 4
A getOverridesSection() 0 11 4
A getOverrideFor() 0 9 2
A getPackageBowerFileContent() 0 14 3
A bowerFileExists() 0 4 1
A createAClearBowerFile() 0 14 1
A getHomeDir() 0 17 4
1
<?php
2
3
/*
4
 * This file is part of Bowerphp.
5
 *
6
 * (c) Massimiliano Arione <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Bowerphp\Config;
13
14
use Bowerphp\Package\PackageInterface;
15
use Bowerphp\Util\Filesystem;
16
use RuntimeException;
17
18
/**
19
 * Config
20
 */
21
class Config implements ConfigInterface
22
{
23
    protected $cacheDir;
24
25
    protected $installDir;
26
27
    protected $filesystem;
28
29
    protected $basePackagesUrl = 'http://registry.bower.io/packages/';
30
31
    protected $saveToBowerJsonFile = false;
32
33
    protected $bowerFileNames = ['bower.json', 'package.json'];
34
35
    protected $stdBowerFileName = 'bower.json';
36
37
    /**
38
     * @param Filesystem $filesystem
39
     */
40
    public function __construct(Filesystem $filesystem)
41
    {
42
        $this->filesystem = $filesystem;
43
        $this->cacheDir = $this->getHomeDir() . '/.cache/bowerphp';
44
        $this->installDir = getcwd() . '/bower_components';
45
        $rc = getcwd() . '/.bowerrc';
46
47
        if ($this->filesystem->exists($rc)) {
48
            $json = json_decode($this->filesystem->read($rc), true);
49
            if (is_null($json)) {
50
                throw new RuntimeException('Invalid .bowerrc file.');
51
            }
52
            if (isset($json['directory'])) {
53
                $this->installDir = getcwd() . '/' . $json['directory'];
54
            }
55
            if (isset($json['storage']) && isset($json['storage']['packages'])) {
56
                $this->cacheDir = $json['storage']['packages'];
57
            }
58
        }
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getBasePackagesUrl()
65
    {
66
        return $this->basePackagesUrl;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getCacheDir()
73
    {
74
        return $this->cacheDir;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getInstallDir()
81
    {
82
        return $this->installDir;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function isSaveToBowerJsonFile()
89
    {
90
        return $this->saveToBowerJsonFile;
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function setSaveToBowerJsonFile($flag = true)
97
    {
98
        $this->saveToBowerJsonFile = $flag;
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    public function initBowerJsonFile(array $params)
105
    {
106
        $file = getcwd() . '/' . $this->stdBowerFileName;
107
        $json = json_encode($this->createAClearBowerFile($params), JSON_PRETTY_PRINT);
108
109
        return $this->filesystem->write($file, $json);
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function updateBowerJsonFile(PackageInterface $package)
116
    {
117
        if (!$this->isSaveToBowerJsonFile()) {
118
            return 0;
119
        }
120
121
        $decode = $this->getBowerFileContent();
122
        $decode['dependencies'][$package->getName()] = $package->getRequiredVersion();
123
        $file = getcwd() . '/' . $this->stdBowerFileName;
124
        $json = json_encode($decode, JSON_PRETTY_PRINT);
125
126
        return $this->filesystem->write($file, $json);
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function updateBowerJsonFile2(array $old, array $new)
133
    {
134
        $json = json_encode(array_merge($old, $new), JSON_PRETTY_PRINT);
135
        $file = getcwd() . '/' . $this->stdBowerFileName;
136
137
        return $this->filesystem->write($file, $json);
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    public function getBowerFileContent()
144
    {
145
        if (!$this->bowerFileExists()) {
146
            throw new RuntimeException('No ' . $this->stdBowerFileName . ' found. You can run "init" command to create it.');
147
        }
148
        $bowerJson = $this->filesystem->read(getcwd() . '/' . $this->stdBowerFileName);
149
        if (empty($bowerJson) || !is_array($decode = json_decode($bowerJson, true))) {
150
            throw new RuntimeException(sprintf('Malformed JSON in %s: %s.', $this->stdBowerFileName, $bowerJson));
151
        }
152
153
        return $decode;
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function getOverridesSection()
160
    {
161
        if ($this->bowerFileExists()) {
162
            $bowerData = $this->getBowerFileContent();
163
            if ($bowerData && array_key_exists('overrides', $bowerData)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $bowerData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
164
                return $bowerData['overrides'];
165
            }
166
        }
167
168
        return [];
169
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174
    public function getOverrideFor($packageName)
175
    {
176
        $overrides = $this->getOverridesSection();
177
        if (array_key_exists($packageName, $overrides)) {
178
            return $overrides[$packageName];
179
        }
180
181
        return [];
182
    }
183
184
    /**
185
     * {@inheritdoc}
186
     */
187
    public function getPackageBowerFileContent(PackageInterface $package)
188
    {
189
        $file = $this->getInstallDir() . '/' . $package->getName() . '/.bower.json';
190
        if (!$this->filesystem->exists($file)) {
191
            throw new RuntimeException(sprintf('Could not find .bower.json file for package %s.', $package->getName()));
192
        }
193
        $bowerJson = $this->filesystem->read($file);
194
        $bower = json_decode($bowerJson, true);
195
        if (is_null($bower)) {
196
            throw new RuntimeException(sprintf('Invalid content in .bower.json for package %s.', $package->getName()));
197
        }
198
199
        return $bower;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $bower; (object|integer|double|string|array|boolean) is incompatible with the return type declared by the interface Bowerphp\Config\ConfigIn...PackageBowerFileContent of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205
    public function bowerFileExists()
206
    {
207
        return $this->filesystem->exists(getcwd() . '/' . $this->stdBowerFileName);
208
    }
209
210
    /**
211
     * @param  array $params
212
     * @return array
213
     */
214
    protected function createAClearBowerFile(array $params)
215
    {
216
        $structure = [
217
            'name'    => $params['name'],
218
            'authors' => [
219
                0 => 'Beelab <[email protected]>',
220
                1 => $params['author'],
221
            ],
222
            'private'      => true,
223
            'dependencies' => new \StdClass(),
224
        ];
225
226
        return $structure;
227
    }
228
229
    /**
230
     * @return string
231
     */
232
    protected function getHomeDir()
233
    {
234
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
235
            $appData = getenv('APPDATA');
236
            if (empty($appData)) {
237
                throw new \RuntimeException('The APPDATA environment variable must be set for bowerphp to run correctly');
238
            }
239
240
            return strtr($appData, '\\', '/');
241
        }
242
        $home = getenv('HOME');
243
        if (empty($home)) {
244
            throw new \RuntimeException('The HOME environment variable must be set for bowerphp to run correctly');
245
        }
246
247
        return rtrim($home, '/');
248
    }
249
}
250