Completed
Push — master ( a94534...362609 )
by Maciej
13s
created

RuleCollection::remove_params()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 1
nop 0
dl 0
loc 10
rs 9.2
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 12 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
namespace WFV\Collection;
3
defined( 'ABSPATH' ) || die();
4
5
use WFV\Abstraction\Collectable;
6
7
/**
8
 *
9
 *
10
 * @since 0.10.0
11
 */
12
class RuleCollection extends Collectable {
13
14
	/**
15
	 *
16
	 *
17
	 * @since 0.10.0
18
	 *
19
	 * @param array $rules
20
	 */
21
	public function __construct( array $rules ) {
22
		$this->data = $this->parse_rules( $rules );
23
	}
24
25
26
	/**
27
	 * Get rules array
28
	 * When $flat is true, returns array without params
29
	 *
30
	 * @since 0.10.0
31
	 *
32
	 * @param bool (optional) $flat
33
	 * @return array
34
	 */
35
	public function get_array( $flat = false ) {
36
		return ( $flat ) ? $this->remove_params() : $this->data;
37
	}
38
39
	/**
40
	 * Return a rule's parameters or false if none
41
	 *
42
	 * @since 0.11.0
43
	 *
44
	 * @param string $field
45
	 * @param int $index
46
	 * @return array|bool
47
	 */
48
	public function get_params( $field, $index ) {
49
		return ( $this-> has_params( $field, $index ) )
50
			? $this->data[ $field ][ $index ]['params']
51
			: false;
52
	}
53
54
	/**
55
	 * Returns true if field is optional
56
	 *
57
	 * @since 0.11.0
58
	 *
59
	 * @param string $field
60
	 * @return bool
61
	 */
62
	public function is_optional( $field ) {
63
		return in_array('optional', $this->data[ $field ] );
64
	}
65
66
	/**
67
	 * Get array of unique rule types
68
	 *
69
	 * @since 0.11.0
70
	 *
71
	 * @return array
72
	 */
73
	public function unique() {
74
		$flat = $this->flatten( $this->remove_params() );
75
		return array_values( array_unique( $flat ) );
76
	}
77
78
	/**
79
	 * Extract rule name from a rule string
80
	 *
81
	 * @since 0.11.0
82
	 * @access protected
83
	 *
84
	 * @param string $rule
85
	 * @return string
86
	 */
87
	protected function extract_name( $rule ) {
88
		return strstr( $rule, ':', true );
89
	}
90
91
	/**
92
	 * Extract rule parameters from a rule string
93
	 *
94
	 * @since 0.11.0
95
	 * @access protected
96
	 *
97
	 * @param string $rule
98
	 * @return string
99
	 */
100
	protected function extract_params( $rule ) {
101
		return ltrim( strstr($rule, ':'), ':');
102
	}
103
104
	/**
105
	 * Returns a flat index array of rules
106
	 *
107
	 * @since 0.11.0
108
	 * @access protected
109
	 *
110
	 * @param array $array
111
	 * @return array
112
	 */
113
	protected function flatten( array $array ) {
114
		$flat = array();
115
		foreach( $array as $rule ) {
116
			if( is_array( $rule ) ){
117
				$flat = array_merge( $flat, $this->flatten( $rule ) );
118
			} else {
119
				$flat[] = $rule;
120
			}
121
		}
122
		return $flat;
123
	}
124
125
	/**
126
	 * Returns true when a rule has parameters
127
	 *
128
	 * @since 0.11.0
129
	 * @access protected
130
	 *
131
	 * @param string $field
132
	 * @param int $index
133
	 * @return bool
134
	 */
135
	protected function has_params( $field, $index ) {
136
		return is_array( $this->data[ $field ][ $index ] );
137
	}
138
139
	/**
140
	 * Checks if a rule string has parameters
141
	 *
142
	 * @since 0.11.0
143
	 * @access protected
144
	 *
145
	 * @param string $rule
146
	 * @return bool
147
	 */
148
	protected function string_has_params( $rule ) {
149
		return strpos( $rule, ':' );
150
	}
151
152
	/**
153
	 * Split each string ruleset from config array
154
	 *  into a machine friendly multi-dimensional array
155
	 *
156
	 * @since 0.11.0
157
	 * @access protected
158
	 *
159
	 * @param array $rules
160
	 * @return array
161
	 */
162
	protected function parse_rules( array $rules ) {
163
		// WIP - works, but confusing - simplify or breakdown into small methods
164
		$parsed = array();
165
		$this->split_rules( $rules );
166
		foreach( $rules as $field => $ruleset ) {
167
			$parsed[ $field ] = array_map( function( $rule ) {
168
				if ( $this->string_has_params( $rule ) ) {
169
					return array(
170
						'rule' => $this->extract_name( $rule ),
171
						'params' => explode( ',', $this->extract_params( $rule ) )
172
					);
173
				}
174
				return $rule;
175
			}, $ruleset );
176
		}
177
		return $parsed;
178
	}
179
180
	/**
181
	 * Flatens rules with parameters in the collection
182
	 *  and returns the new array.
183
	 *
184
	 * @since 0.11.0
185
	 * @access protected
186
	 *
187
	 * @return array
188
	 */
189
	protected function remove_params() {
190
		return array_map( function( $item ) {
191
			foreach( $item as $rule ) {
192
				if( $rule !== 'optional' ) {
193
					$rules[] = ( is_string( $rule ) ) ? $rule : $rule['rule'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rules was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rules = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
194
				}
195
			}
196
			return $rules;
0 ignored issues
show
Bug introduced by
The variable $rules does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
197
		}, $this->data );
198
	}
199
200
	/**
201
	 * Converts string ruleset to index array
202
	 *
203
	 * @since 0.11.0
204
	 * @access protected
205
	 *
206
	 * @param array $rules
207
	 */
208
	protected function split_rules( array &$rules ) {
209
		// perhaps the $rules array structure should be validated here?...
210
		$rules = array_map( function( $item ) {
211
			return explode( '|', $item );
212
		}, $rules );
213
	}
214
}
215