Completed
Pull Request — master (#135)
by
unknown
05:49
created

Config::getCurrentDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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 Bowerphp\Util\Json;
17
use RuntimeException;
18
19
/**
20
 * Config
21
 */
22
class Config implements ConfigInterface
23
{
24
    protected $currentDir;
25
    protected $cacheDir;
26
    protected $installDir;
27
    protected $filesystem;
28
    protected $basePackagesUrl = 'http://bower.herokuapp.com/packages/';
29
    protected $allPackagesUrl = 'https://bower-component-list.herokuapp.com/';
30
    protected $saveToBowerJsonFile = false;
31
    protected $bowerFileNames = array('bower.json', 'package.json');
32
    protected $stdBowerFileName = 'bower.json';
33
    protected $rcFileName = '.bowerrc';
34
35
    /**
36
     * @param Filesystem $filesystem
37
     */
38
    public function __construct(Filesystem $filesystem)
39
    {
40
        $this->currentDir = getcwd();
41
        $this->filesystem = $filesystem;
42
        $this->cacheDir = $this->getHomeDir() . '/.cache/bowerphp';
43
        $this->installDir = $this->currentDir . '/bower_components';
44
        $rcPath = $this->getBowerrcPath();
45
46
        if ($rcPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rcPath of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
47
            $rc = $rcPath . '/' . $this->rcFileName;
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['cwd'])) {
53
              $this->currentDir = $rcPath . '/' . $json['cwd'];
54
            }
55
            if (isset($json['directory'])) {
56
              $this->installDir = $rcPath . '/' . $json['directory'];
57
            }
58
            if (isset($json['storage']) && isset($json['storage']['packages'])) {
59
              $this->cacheDir = $json['storage']['packages'];
60
            }
61
        }
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getCurrentDir() 
68
    {
69
        return $this->currentDir;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function getBasePackagesUrl()
76
    {
77
        return $this->basePackagesUrl;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function getAllPackagesUrl()
84
    {
85
        return $this->allPackagesUrl;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function getCacheDir()
92
    {
93
        return $this->cacheDir;
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function getInstallDir()
100
    {
101
        return $this->installDir;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function isSaveToBowerJsonFile()
108
    {
109
        return $this->saveToBowerJsonFile;
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function setSaveToBowerJsonFile($flag = true)
116
    {
117
        $this->saveToBowerJsonFile = $flag;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function initBowerJsonFile(array $params)
124
    {
125
        $file = $this->currentDir . '/' . $this->stdBowerFileName;
126
        $json = Json::encode($this->createAClearBowerFile($params));
127
128
        return $this->filesystem->write($file, $json);
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function updateBowerJsonFile(PackageInterface $package)
135
    {
136
        if (!$this->isSaveToBowerJsonFile()) {
137
            return 0;
138
        }
139
140
        $decode = $this->getBowerFileContent();
141
        $decode['dependencies'][$package->getName()] = $package->getRequiredVersion();
142
        $file = $this->currentDir . '/' . $this->stdBowerFileName;
143
        $json = Json::encode($decode);
144
145
        return $this->filesystem->write($file, $json);
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function updateBowerJsonFile2(array $old, array $new)
152
    {
153
        $json = Json::encode(array_merge($old, $new));
154
        $file = $this->currentDir . '/' . $this->stdBowerFileName;
155
156
        return $this->filesystem->write($file, $json);
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function getBowerFileContent()
163
    {
164
        if (!$this->bowerFileExists()) {
165
            throw new RuntimeException('No ' . $this->stdBowerFileName . ' found. You can run "init" command to create it.');
166
        }
167
        $bowerJson = $this->filesystem->read($this->currentDir . '/' . $this->stdBowerFileName);
168
        if (empty($bowerJson) || !is_array($decode = json_decode($bowerJson, true))) {
169
            throw new RuntimeException(sprintf('Malformed JSON in %s: %s.', $this->stdBowerFileName, $bowerJson));
170
        }
171
172
        return $decode;
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     */
178
    public function getOverridesSection()
179
    {
180
        if ($this->bowerFileExists()) {
181
            $bowerData = $this->getBowerFileContent();
182
            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...
183
                return $bowerData['overrides'];
184
            }
185
        }
186
187
        return array();
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function getOverrideFor($packageName)
194
    {
195
        $overrides = $this->getOverridesSection();
196
        if (array_key_exists($packageName, $overrides)) {
197
            return $overrides[$packageName];
198
        }
199
200
        return array();
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function getPackageBowerFileContent(PackageInterface $package)
207
    {
208
        $file = $this->getInstallDir() . '/' . $package->getName() . '/.bower.json';
209
        if (!$this->filesystem->exists($file)) {
210
            throw new RuntimeException(sprintf('Could not find .bower.json file for package %s.', $package->getName()));
211
        }
212
        $bowerJson = $this->filesystem->read($file);
213
        $bower = json_decode($bowerJson, true);
214
        if (is_null($bower)) {
215
            throw new RuntimeException(sprintf('Invalid content in .bower.json for package %s.', $package->getName()));
216
        }
217
218
        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...
219
    }
220
221
    /**
222
     * {@inheritdoc}
223
     */
224
    public function bowerFileExists()
225
    {
226
        return $this->filesystem->exists($this->currentDir . '/' . $this->stdBowerFileName);
227
    }
228
229
    /**
230
     * @param  array $params
231
     * @return array
232
     */
233
    protected function createAClearBowerFile(array $params)
234
    {
235
        $structure = array(
236
            'name'    => $params['name'],
237
            'authors' => array(
238
                0 => 'Beelab <[email protected]>',
239
                1 => $params['author'],
240
            ),
241
            'private'      => true,
242
            'dependencies' => new \StdClass(),
243
        );
244
245
        return $structure;
246
    }
247
248
    /**
249
     * @return string
250
     */
251
    protected function getHomeDir()
252
    {
253
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
254
            $appData = getenv('APPDATA');
255
            if (empty($appData)) {
256
                throw new \RuntimeException('The APPDATA environment variable must be set for bowerphp to run correctly');
257
            }
258
259
            return strtr($appData, '\\', '/');
260
        }
261
        $home = getenv('HOME');
262
        if (empty($home)) {
263
            throw new \RuntimeException('The HOME environment variable must be set for bowerphp to run correctly');
264
        }
265
266
        return rtrim($home, '/');
267
    }
268
269
    protected function getBowerrcPath()
270
    {
271
      do {
272
        if ($this->filesystem->exists(getcwd() . '/' . $this->rcFileName)) {
273
          return getcwd();
274
        }
275
        chdir('..');
276
      }
277
      while(getcwd() !== '/');
278
      return false;
279
    }
280
}
281