Completed
Push — master ( 3a93f1...4a4b28 )
by Askupa
01:47
created

Form   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 245
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 245
rs 10
c 0
b 0
f 0
wmc 30
lcom 2
cbo 2

11 Methods

Rating   Name   Duplication   Size   Complexity  
A get_instance() 0 8 2
B add_field() 0 27 3
A render_edit_form() 0 12 2
A render_add_form() 0 11 2
A update_term() 0 12 3
A modify_table_columns() 0 11 2
A modify_table_content() 0 14 4
A modify_table_sortable_columns() 0 12 3
B sort_custom_column() 0 19 5
A default_props() 0 12 1
A traverse_fields() 0 10 3
1
<?php
2
3
namespace Amarkal\Taxonomy;
4
5
/**
6
 * WordPress taxonomy form utilities
7
 */
8
class Form
9
{
10
    /**
11
     * @var Singleton The reference to *Singleton* instance of this class
12
     */
13
    private static $instance;
14
    
15
    /**
16
     * @var Array Stores all the registered fields for each taxonomy
17
     */
18
    private $fields = array();
19
    
20
    /**
21
     * Returns the *Singleton* instance of this class.
22
     *
23
     * @return Singleton The *Singleton* instance.
24
     */
25
    public static function get_instance()
26
    {
27
        if( null === static::$instance ) 
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
28
        {
29
            static::$instance = new static();
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
Documentation Bug introduced by
It seems like new static() of type this<Amarkal\Taxonomy\Form> is incompatible with the declared type object<Amarkal\Taxonomy\Singleton> of property $instance.

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...
30
        }
31
        return static::$instance;
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
Bug Compatibility introduced by
The expression static::$instance; of type Amarkal\Taxonomy\Form|Amarkal\Taxonomy\Singleton adds the type Amarkal\Taxonomy\Form to the return on line 31 which is incompatible with the return type documented by Amarkal\Taxonomy\Form::get_instance of type Amarkal\Taxonomy\Singleton.
Loading history...
32
    }
33
    
34
    /**
35
     * Add a form field to both the add & edit forms for a given taxonomy.
36
     * 
37
     * @param string $taxonomy_name
38
     * @param string $field_name
39
     * @param array $field_props
40
     * @throws \RuntimeException if duplicate names are registered under the same taxonomy
41
     */
42
    public function add_field( $taxonomy_name, $field_name, $field_props )
43
    {
44
        if( !isset($this->fields[$taxonomy_name]) )
45
        {
46
            // Add fields to taxonomy add and edit forms 
47
            add_action( "{$taxonomy_name}_add_form_fields", array($this, 'render_add_form') );
48
            add_action( "{$taxonomy_name}_edit_form_fields", array($this, 'render_edit_form') );
49
            
50
            // Save the data from taxonomy add and edit forms
51
            add_action( "create_{$taxonomy_name}", array($this, 'update_term') );
52
            add_action( "edited_{$taxonomy_name}", array($this, 'update_term') );
53
            
54
            // Modify the taxonomy term table
55
            add_filter( "manage_edit-{$taxonomy_name}_columns", array($this, 'modify_table_columns') );
56
            add_filter( "manage_{$taxonomy_name}_custom_column", array($this, 'modify_table_content'), 10, 3 );
57
            add_filter( "manage_edit-{$taxonomy_name}_sortable_columns", array($this, 'modify_table_sortable_columns') );
58
            add_filter( 'terms_clauses', array($this, 'sort_custom_column'), 10, 3 );
59
            
60
            $this->fields[$taxonomy_name] = array();
61
        }
62
63
        if( !isset($this->fields[$taxonomy_name][$field_name]))
64
        {
65
            $this->fields[$taxonomy_name][$field_name] = array_merge( $this->default_props(), $field_props );
66
        }
67
        else throw new \RuntimeException("A field named '$field_name' has already been registered in '$taxonomy_name'");
68
    }
69
    
70
    /**
71
     * Render the 'edit term' form for a given taxonomy
72
     * 
73
     * @param object $term Taxonomy term
74
     */
75
    public function render_edit_form( $term )
76
    {
77
        $fields = $this->fields[$term->taxonomy];
78
        
79
        foreach( $fields as $name => $props )
80
        {
81
            $props['name'] = $name;
82
            $props['term_id'] = $term->term_id;
83
            $field = new EditField($props);
84
            echo $field->render();
85
        }
86
    }
87
    
88
    /**
89
     * Render the 'add new term' form for a given taxonomy
90
     * 
91
     * @param string $taxonomy Taxonomy name
92
     */
93
    public function render_add_form( $taxonomy )
94
    {
95
        $fields = $this->fields[$taxonomy];
96
        
97
        foreach( $fields as $name => $props )
98
        {
99
            $props['name'] = $name;
100
            $field = new AddField($props);
101
            echo $field->render();
102
        }
103
    }
104
    
105
    /**
106
     * Update the meta values for a given term. Called once one of the add/edit
107
     * forms is saved.
108
     * 
109
     * @param type $term_id
110
     */
111
    function update_term( $term_id ) 
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
update_term uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
112
    {
113
        $term = \get_term( $term_id );
114
        
115
        foreach( $this->fields[$term->taxonomy] as $name => $props )
116
        {
117
            if( isset($_POST[$name]) )
118
            {
119
                update_term_meta($term_id, $name, filter_input(INPUT_POST, $name));
120
            }
121
        }
122
    }
123
    
124
    /**
125
     * Add additional columns to the term table.
126
     * 
127
     * @param array $columns
128
     * @return array
129
     */
130
    function modify_table_columns( $columns )
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
131
    {   
132
        $this->traverse_fields(function( $taxonomy, $name, $props ) use ( &$columns ) 
0 ignored issues
show
Documentation introduced by
function ($taxonomy, $na...props['label']; } } is of type object<Closure>, but the function expects a object<Amarkal\Taxonomy\collable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
133
        {
134
            if( $props['table']['show'] )
135
            {
136
                $columns[$name] = $props['label'];
137
            }
138
        });
139
        return $columns;
140
    }
141
    
142
    /**
143
     * Retrieve the data for a given column in the term table.
144
     * 
145
     * @see https://developer.wordpress.org/reference/hooks/manage_this-screen-taxonomy_custom_column/
146
     * 
147
     * @param type $content
148
     * @param type $column_name
149
     * @param type $term_id
150
     * @return type
151
     */
152
    function modify_table_content( $content, $column_name, $term_id )
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
153
    {   
154
        $term = \get_term($term_id);
155
        $this->traverse_fields(function( $taxonomy, $name, $props ) use ( &$content, $column_name, $term ) 
0 ignored issues
show
Documentation introduced by
function ($taxonomy, $na..., $name, true); } } is of type object<Closure>, but the function expects a object<Amarkal\Taxonomy\collable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
156
        {
157
            if( $props['table']['show'] && 
158
                $term->taxonomy === $taxonomy &&
159
                $name === $column_name
160
            ) {
161
                $content = \get_term_meta($term->term_id, $name, true);
162
            }
163
        });
164
        return $content;
165
    }
166
    
167
    /**
168
     * Make custom table columns sortable.
169
     * 
170
     * @param array $columns
171
     * @return string
172
     */
173
    function modify_table_sortable_columns( $columns )
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
174
    {
175
        $this->traverse_fields(function( $taxonomy, $name, $props ) use ( &$columns ) 
0 ignored issues
show
Documentation introduced by
function ($taxonomy, $na...$name] = $name; } } is of type object<Closure>, but the function expects a object<Amarkal\Taxonomy\collable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
176
        {
177
            if( $props['table']['show'] && 
178
                $props['table']['sortable']
179
            ) {
180
                $columns[$name] = $name;
181
            }
182
        });
183
        return $columns;
184
    }
185
    
186
    /**
187
     * Modify terms_clauses to allow sorting custom WordPress Admin Table Columns by a custom Taxonomy Term meta
188
     * 
189
     * @see https://developer.wordpress.org/reference/hooks/terms_clauses/
190
     * 
191
     * @global type $wpdb
192
     * @param type $clauses
193
     * @param type $taxonomies
194
     * @param type $args
195
     * @return string
196
     */
197
    function sort_custom_column( $clauses, $taxonomies, $args )
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
198
    {
199
        $this->traverse_fields(function( $taxonomy, $name, $props ) use ( &$clauses, $args ) 
0 ignored issues
show
Documentation introduced by
function ($taxonomy, $na...tm.meta_value'; } } is of type object<Closure>, but the function expects a object<Amarkal\Taxonomy\collable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
200
        {
201
            if( in_array($taxonomy, $args['taxonomy']) && 
202
                $props['table']['show'] && 
203
                $props['table']['sortable'] &&
204
                $name === $args['orderby']
205
            )
206
            {
207
                global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
208
                // tt refers to the $wpdb->term_taxonomy table
209
                $clauses['join'] .= " LEFT JOIN {$wpdb->termmeta} AS tm ON t.term_id = tm.term_id";
210
                $clauses['where'] = "tt.taxonomy = '{$taxonomy}' AND (tm.meta_key = '{$name}' OR tm.meta_key IS NULL)";
211
                $clauses['orderby'] = "ORDER BY tm.meta_value";
212
            }
213
        });
214
        return $clauses;
215
    }
216
    
217
    /**
218
     * The default form field properties. This is merged with the user given 
219
     * properties. When the component is rendered, this will be merged with the
220
     * component's properties as well.
221
     * 
222
     * @return array
223
     */
224
    private function default_props()
225
    {
226
        return array(
227
            'type'          => null,
228
            'label'         => null,
229
            'description'   => null,
230
            'table'         => array(
231
                'show'      => false,
232
                'sortable'  => false
233
            )
234
        );
235
    }
236
    
237
    /**
238
     * Treverse the $fields array.
239
     * 
240
     * @param collable $callback Called on each iteration
241
     */
242
    private function traverse_fields( $callback )
243
    {
244
        foreach( $this->fields as $taxonomy => $fields )
245
        {
246
            foreach( $fields as $name => $props )
247
            {
248
                $callback( $taxonomy, $name, $props );
249
            }
250
        }
251
    }
252
}