Completed
Push — master ( 48d67a...18cae0 )
by Massimiliano
02:43
created

Config::getBowerFileContent()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
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 RuntimeException;
17
18
/**
19
 * Config
20
 */
21
class Config implements ConfigInterface
22
{
23
    protected $cacheDir;
24
    protected $installDir;
25
    protected $filesystem;
26
    protected $basePackagesUrl = 'http://registry.bower.io/packages/';
27
    protected $saveToBowerJsonFile = false;
28
    protected $bowerFileNames = ['bower.json', 'package.json'];
29
    protected $stdBowerFileName = 'bower.json';
30
31
    /**
32
     * @param Filesystem $filesystem
33
     */
34
    public function __construct(Filesystem $filesystem)
35
    {
36
        $this->filesystem = $filesystem;
37
        $this->cacheDir = $this->getHomeDir() . '/.cache/bowerphp';
38
        $this->installDir = getcwd() . '/bower_components';
39
        $rc = getcwd() . '/.bowerrc';
40
41
        if ($this->filesystem->exists($rc)) {
42
            $json = json_decode($this->filesystem->read($rc), true);
43
            if (is_null($json)) {
44
                throw new RuntimeException('Invalid .bowerrc file.');
45
            }
46
            if (isset($json['directory'])) {
47
                $this->installDir = getcwd() . '/' . $json['directory'];
48
            }
49
            if (isset($json['storage']) && isset($json['storage']['packages'])) {
50
                $this->cacheDir = $json['storage']['packages'];
51
            }
52
        }
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getBasePackagesUrl()
59
    {
60
        return $this->basePackagesUrl;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function getCacheDir()
67
    {
68
        return $this->cacheDir;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function getInstallDir()
75
    {
76
        return $this->installDir;
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function isSaveToBowerJsonFile()
83
    {
84
        return $this->saveToBowerJsonFile;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function setSaveToBowerJsonFile($flag = true)
91
    {
92
        $this->saveToBowerJsonFile = $flag;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function initBowerJsonFile(array $params)
99
    {
100
        $file = getcwd() . '/' . $this->stdBowerFileName;
101
        $json = json_encode($this->createAClearBowerFile($params), JSON_PRETTY_PRINT);
102
103
        return $this->filesystem->write($file, $json);
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function updateBowerJsonFile(PackageInterface $package)
110
    {
111
        if (!$this->isSaveToBowerJsonFile()) {
112
            return 0;
113
        }
114
115
        $decode = $this->getBowerFileContent();
116
        $decode['dependencies'][$package->getName()] = $package->getRequiredVersion();
117
        $file = getcwd() . '/' . $this->stdBowerFileName;
118
        $json = json_encode($decode, JSON_PRETTY_PRINT);
119
120
        return $this->filesystem->write($file, $json);
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function updateBowerJsonFile2(array $old, array $new)
127
    {
128
        $json = json_encode(array_merge($old, $new), JSON_PRETTY_PRINT);
129
        $file = getcwd() . '/' . $this->stdBowerFileName;
130
131
        return $this->filesystem->write($file, $json);
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function getBowerFileContent()
138
    {
139
        if (!$this->bowerFileExists()) {
140
            throw new RuntimeException('No ' . $this->stdBowerFileName . ' found. You can run "init" command to create it.');
141
        }
142
        $bowerJson = $this->filesystem->read(getcwd() . '/' . $this->stdBowerFileName);
143
        if (empty($bowerJson) || !is_array($decode = json_decode($bowerJson, true))) {
144
            throw new RuntimeException(sprintf('Malformed JSON in %s: %s.', $this->stdBowerFileName, $bowerJson));
145
        }
146
147
        return $decode;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function getOverridesSection()
154
    {
155
        if ($this->bowerFileExists()) {
156
            $bowerData = $this->getBowerFileContent();
157
            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...
158
                return $bowerData['overrides'];
159
            }
160
        }
161
162
        return [];
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function getOverrideFor($packageName)
169
    {
170
        $overrides = $this->getOverridesSection();
171
        if (array_key_exists($packageName, $overrides)) {
172
            return $overrides[$packageName];
173
        }
174
175
        return [];
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     */
181
    public function getPackageBowerFileContent(PackageInterface $package)
182
    {
183
        $file = $this->getInstallDir() . '/' . $package->getName() . '/.bower.json';
184
        if (!$this->filesystem->exists($file)) {
185
            throw new RuntimeException(sprintf('Could not find .bower.json file for package %s.', $package->getName()));
186
        }
187
        $bowerJson = $this->filesystem->read($file);
188
        $bower = json_decode($bowerJson, true);
189
        if (is_null($bower)) {
190
            throw new RuntimeException(sprintf('Invalid content in .bower.json for package %s.', $package->getName()));
191
        }
192
193
        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...
194
    }
195
196
    /**
197
     * {@inheritdoc}
198
     */
199
    public function bowerFileExists()
200
    {
201
        return $this->filesystem->exists(getcwd() . '/' . $this->stdBowerFileName);
202
    }
203
204
    /**
205
     * @param  array $params
206
     * @return array
207
     */
208
    protected function createAClearBowerFile(array $params)
209
    {
210
        $structure = [
211
            'name'    => $params['name'],
212
            'authors' => [
213
                0 => 'Beelab <[email protected]>',
214
                1 => $params['author'],
215
            ],
216
            'private'      => true,
217
            'dependencies' => new \StdClass(),
218
        ];
219
220
        return $structure;
221
    }
222
223
    /**
224
     * @return string
225
     */
226
    protected function getHomeDir()
227
    {
228
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
229
            $appData = getenv('APPDATA');
230
            if (empty($appData)) {
231
                throw new \RuntimeException('The APPDATA environment variable must be set for bowerphp to run correctly');
232
            }
233
234
            return strtr($appData, '\\', '/');
235
        }
236
        $home = getenv('HOME');
237
        if (empty($home)) {
238
            throw new \RuntimeException('The HOME environment variable must be set for bowerphp to run correctly');
239
        }
240
241
        return rtrim($home, '/');
242
    }
243
}
244