Completed
Push — master ( a77268...4f25b6 )
by Joao
02:36
created

Setting   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 24
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 172
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A path() 0 5 1
A filename() 0 5 1
B get() 0 17 5
A set() 0 6 1
A forget() 0 6 1
A has() 0 9 3
A load() 0 14 4
A save() 0 12 4
A clear() 0 6 1
A setArray() 0 9 2
1
<?php namespace jlourenco\support;
2
3
/*
4
 * This is a Laravel package that is not being used on the
5
 * vendors folder because it does not support Laravel 5
6
 */
7
8
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
9
 * ---------------------------------------------
10
 * | Do not remove!!!!                         |
11
 * |                                           |
12
 * | @package   PhoenixCore                    |
13
 * | @version   2.0                            |
14
 * | @develper  Phil F (http://www.Weztec.com) |
15
 * | @author    Phoenix Development Team       |
16
 * | @license   Free to all                    |
17
 * | @copyright 2013 Phoenix Group             |
18
 * | @link      http://www.phoenix-core.com    |
19
 * ---------------------------------------------
20
 *
21
 * Example syntax:
22
 * use Setting (If you are using namespaces)
23
 *
24
 * Single dimension
25
 * set:         Setting::set('name', 'Phil'))
26
 * get:         Setting::get('name')
27
 * forget:      Setting::forget('name')
28
 * has:         Setting::has('name')
29
 *
30
 * Multi dimensional
31
 * set:         Setting::set('names' , array('firstName' => 'Phil', 'surname' => 'F'))
32
 * setArray:    Setting::setArray(array('firstName' => 'Phil', 'surname' => 'F'))
33
 * get:         Setting::get('names.firstName')
34
 * forget:      Setting::forget('names.surname'))
35
 * has:         Setting::has('names.firstName')
36
 *
37
 * Clear:
38
 * clear:        Setting::clear()
39
 *
40
 * Using a different path (make sure the path exists and is writable) *
41
 * Setting::path('setting2.json')->set(array('names2' => array('firstName' => 'Phil', 'surname' => 'F')));
42
 *
43
 * Using a different filename
44
 * Setting::filename('setting2.json')->set(array('names2' => array('firstName' => 'Phil', 'surname' => 'F')));
45
 *
46
 * Using both a different path and filename (make sure the path exists and is writable)
47
 * Setting::path(app_path().'/storage/meta/sub')->filename('dummy.json')->set(array('names2' => array('firstName' => 'Phil', 'surname' => 'F')));
48
 */
49
50
/**
51
 * Class Setting
52
 * @package Philf\Setting
53
 */
54
class Setting {
55
    /**
56
     * The path to the file
57
     * @var string
58
     */
59
    protected $path;
60
    /**
61
     * The filename used to store the config
62
     * @var string
63
     */
64
    protected $filename;
65
    /**
66
     * The class working array
67
     * @var array
68
     */
69
    protected $settings;
70
    /**
71
     * Create the Setting instance
72
     * @param string $path      The path to the file
73
     * @param string $filename  The filename
74
     * @param interfaces\FallbackInterface $fallback
75
     */
76
    public function __construct($path, $filename, $fallback = null)
77
    {
78
        $this->path     = $path;
79
        $this->filename = $filename;
80
        $this->fallback = $fallback;
0 ignored issues
show
Bug introduced by
The property fallback does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
81
        // Load the file and store the contents in $this->settings
82
        $this->load($this->path, $this->filename);
83
    }
84
    /**
85
     * Set the path to the file to use
86
     * @param  string $path The path to the file
87
     * @return \Philf\Setting\Setting
88
     */
89
    public function path($path)
90
    {
91
        $this->path = $path;
92
        return $this;
93
    }
94
    /**
95
     * Set the filename to use
96
     * @param  string $filename The filename
97
     * @return \Philf\Setting\Setting
98
     */
99
    public function filename($filename)
100
    {
101
        $this->filename = $filename;
102
        return $this;
103
    }
104
    /**
105
     * Get a value and return it
106
     * @param string $key String using dot notation
107
     * @param Mixed $default
108
     * @return Mixed             The value(s) found
109
     */
110
    public function get($key = null, $default = null)
111
    {
112
        if (empty($key))
113
        {
114
            return $this->settings;
115
        }
116
        $ts = microtime(true);
117
        if($ts !== array_get($this->settings, $key, $ts))
118
        {
119
            return array_get($this->settings, $key);
120
        }
121
        if ( ! is_null($this->fallback) and $this->fallback->fallbackHas($key))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
122
        {
123
            return $this->fallback->fallbackGet($key, $default);
124
        }
125
        return $default;
126
    }
127
    /**
128
     * Store the passed value in to the json file
129
     * @param $key
130
     * @param  mixed $value The value(s) to be stored
131
     * @return void
132
     */
133
    public function set($key, $value)
134
    {
135
        array_set($this->settings,$key,$value);
136
        $this->save($this->path, $this->filename);
137
        $this->load($this->path, $this->filename);
138
    }
139
    /**
140
     * Forget the value(s) currently stored
141
     * @param  mixed $deleteKey The value(s) to be removed (dot notation)
142
     * @return void
143
     */
144
    public function forget($deleteKey)
145
    {
146
        array_forget($this->settings,$deleteKey);
147
        $this->save($this->path, $this->filename);
148
        $this->load($this->path, $this->filename);
149
    }
150
    /**
151
     * Check to see if the value exists
152
     * @param  string  $searchKey The key to search for
153
     * @return boolean            True: found - False not found
154
     */
155
    public function has($searchKey)
156
    {
157
        $default = microtime(true);
158
        if($default == array_get($this->settings, $searchKey, $default) and !is_null($this->fallback))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
159
        {
160
            return $this->fallback->fallbackHas($searchKey);
161
        }
162
        return $default !== array_get($this->settings, $searchKey, $default);
163
    }
164
    /**
165
     * Load the file in to $this->settings so values can be used immediately
166
     * @param  string $path     The path to be used
167
     * @param  string $filename The filename to be used
168
     * @return \Philf\Setting\Setting
169
     */
170
    public function load($path = null, $filename = null)
171
    {
172
        $this->path     = isset($path) ? $path : $this->path;
173
        $this->filename = isset($filename) ? $filename : $this->filename;
174
        if (is_file($this->path.'/'.$this->filename))
175
        {
176
            $this->settings = json_decode(file_get_contents($this->path.'/'.$this->filename), true);
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode(file_get_con...$this->filename), true) of type * is incompatible with the declared type array of property $settings.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
177
        }
178
        else
179
        {
180
            $this->settings = array();
181
        }
182
        return $this;
183
    }
184
    /**
185
     * Save the file
186
     * @param  string $path     The path to be used
187
     * @param  string $filename The filename to be used
188
     * @return void
189
     */
190
    public function save($path = null, $filename = null)
191
    {
192
        $this->path     = isset($path) ? $path : $this->path;
193
        $this->filename = isset($filename) ? $filename : $this->filename;
194
        if ( ! file_exists($this->path))
195
        {
196
            mkdir($this->path, 0755, true);
197
        }
198
        $fh = fopen($this->path.'/'.$this->filename, 'w+');
199
        fwrite($fh, json_encode($this->settings));
200
        fclose($fh);
201
    }
202
    /**
203
     * Clears the JSON Config file
204
     */
205
    public function clear()
206
    {
207
        $this->settings = array();
208
        $this->save($this->path, $this->filename);
209
        $this->load($this->path, $this->filename);
210
    }
211
    /**
212
     * This will mass assign data to the Setting
213
     * @param array $data
214
     */
215
    public function setArray(array $data)
216
    {
217
        foreach ($data as $key => $value)
218
        {
219
            array_set($this->settings,$key,$value);
220
        }
221
        $this->save($this->path, $this->filename);
222
        $this->load($this->path, $this->filename);
223
    }
224
225
}