Completed
Push — development ( 381f0e...33ac70 )
by
unknown
05:34
created

Nav_Menu_Container::to_json()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Meta_Datastore;
6
use Carbon_Fields\Datastore\Nav_Menu_Datastore;
7
use Carbon_Fields\Walker\Nav_Menu_Edit_Walker;
8
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
9
10
/**
11
 * Nav menu item fields container class.
12
 */
13
class Nav_Menu_Container extends Container {
14
	/**
15
	 * Array of container clones for every menu item
16
	 *
17
	 * @see init()
18
	 * @var int
19
	 */
20
	protected $menu_item_instances = array();
21
22
	/**
23
	 * Create a new nav menu item fields container
24
	 *
25
	 * @param string $id ID of the container
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
26
	 **/
27
	public function __construct( $title ) {
28
		parent::__construct( $title );
29
30
		if ( ! $this->get_datastore() ) {
31
			$this->set_datastore( new Nav_Menu_Datastore(), $this->has_default_datastore() );
0 ignored issues
show
Documentation introduced by
$this->has_default_datastore() is of type object<Carbon_Fields\Dat...re\Datastore_Interface>, but the function expects a boolean.

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...
32
		}
33
34
		// Register the custom edit walker only once
35
		$callable = array( get_class(), 'edit_walker' );
36
		if ( !has_filter( 'wp_edit_nav_menu_walker', $callable ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
37
			add_filter( 'wp_edit_nav_menu_walker', $callable, 10, 2 );
38
		}
39
	}
40
41
	/**
42
	 * Perform instance initialization after calling setup()
43
	 *
44
	 * @param int $menu_item_id Used to pass the correct menu_item_id to the Container object
45
	 * @param bool $render Whether the container will render the fields.
0 ignored issues
show
Bug introduced by
There is no parameter named $render. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
46
	 */
47
	public function init( $menu_item_id = 0 ) {
48
		$this->get_datastore()->set_id( $menu_item_id );
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Carbon_Fields\Datastore\Datastore_Interface as the method set_id() does only exist in the following implementations of said interface: Carbon_Fields\Datastore\Comment_Meta_Datastore, Carbon_Fields\Datastore\Meta_Datastore, Carbon_Fields\Datastore\Nav_Menu_Datastore, Carbon_Fields\Datastore\Post_Meta_Datastore, Carbon_Fields\Datastore\Term_Meta_Datastore, Carbon_Fields\Datastore\User_Meta_Datastore.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
49
		$this->load();
50
		$this->_attach();
51
52
		// Only the base container should register for updating/rendering
53
		if ( $menu_item_id === 0 ) {
54
			add_action( 'wp_update_nav_menu_item', array( $this, 'update' ), 10, 3 );
55
			add_action( 'crb_print_carbon_container_nav_menu_fields_html', array( $this, 'form' ), 10, 5 );
56
		}
57
58
		return $this;
59
	}
60
61
	/**
62
	 * Checks whether the current request is valid
63
	 *
64
	 * @return bool
65
	 **/
66
	public function is_valid_save() {
67
		// rely on wp_update_nav_menu_item action not being called unless WP's nonce is not valid
68
		return true;
69
	}
70
71
	/**
72
	 * Perform checks whether the container should be attached during the current request
73
	 *
74
	 * @return bool True if the container is allowed to be attached
75
	 **/
76
	public function is_valid_attach() {
77
		global $pagenow;
78
79
		if ( $pagenow === 'nav-menus.php' ) {
80
			return true;
81
		} elseif ( defined( 'DOING_AJAX' ) && DOING_AJAX && $_REQUEST['action'] === 'add-menu-item' ) {
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_REQUEST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
82
			return true;
83
		}
84
85
		return false;
86
	}
87
88
	/**
89
	 * Perform save operation after successful is_valid_save() check.
90
	 * The call is propagated to all fields in the container.
91
	 **/
92
	public function save( $data = null ) {
93
		foreach ( $this->fields as $field ) {
94
			$field->set_value_from_input();
95
			$field->save();
96
		}
97
98
		do_action( 'carbon_after_save_nav_menu', $this );
99
	}
100
101
	/**
102
	 * Output the container markup
103
	 **/
104
	public function render() {
105
		include \Carbon_Fields\DIR . '/templates/Container/nav_menu.php';
106
	}
107
108
	/**
109
	 * Trigger Save for all instances
110
	 */
111
	public function update( $menu_id, $current_menu_item_id ) {
112
		if ( !$this->is_valid_attach() ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
113
			return;
114
		}
115
		
116
		$clone = $this->get_clone_for_menu_item( $current_menu_item_id );
117
		$clone->_save();
118
	}
119
120
	/**
121
	 * Render custom fields inside each Nav Menu entry
122
	 */
123
	public function form( $item ) {
124
		if ( !$this->is_valid_attach() ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
125
			return;
126
		}
127
128
		$clone = $this->get_clone_for_menu_item( $item->ID );
129
		$clone->render();
130
	}
131
132
	/**
133
	 * Create a clone of this container with it's own datastore for every menu item
134
	 */
135
	protected function get_clone_for_menu_item( $menu_item_id ) {
136
		if ( !isset( $this->menu_item_instances[ $menu_item_id ] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
137
			$menu_item_datastore = new Nav_Menu_Datastore();
138
			$menu_item_datastore->set_id( $menu_item_id );
139
			$menu_item_field_prefix = $menu_item_datastore->get_garbage_prefix();
1 ignored issue
show
Comprehensibility Naming introduced by
The variable name $menu_item_field_prefix exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
140
141
			$custom_fields = array();
142
			$fields = $this->get_fields();
143
			foreach ( $fields as $field ) {
144
				$tmp_field = clone $field;
145
146
				$tmp_field->set_id( $menu_item_field_prefix . $tmp_field->get_id() );
147
				$tmp_field->set_name( $menu_item_field_prefix . $tmp_field->get_name() );
148
				$tmp_field->set_datastore( $menu_item_datastore, true );
149
150
				$custom_fields[] = $tmp_field;
151
			}
152
153
			$this->menu_item_instances[ $menu_item_id ] = Container::factory( $this->type, $menu_item_field_prefix . $this->id )
154
				->set_datastore( $menu_item_datastore, true )
155
				->add_fields( $custom_fields )
156
				->init( $menu_item_id );
157
			
158
		}
159
160
		return $this->menu_item_instances[ $menu_item_id ];
161
	}
162
163
	/**
164
	 * Setup custom walker for the Nav Menu entries
165
	 */
166
	public static function edit_walker() {
167
		return '\Carbon_Fields\Walker\Nav_Menu_Edit_Walker';
168
	}
169
}
170