Passed
Push — master ( 58283b...9d21ea )
by Paul
02:29
created

Settings::normalizeId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\Pollux;
4
5
use GeminiLabs\Pollux\Application;
6
use GeminiLabs\Pollux\MetaBox;
7
use GeminiLabs\Pollux\SettingsMetaBox;
8
9
class Settings extends MetaBox
10
{
11
	const CONDITIONS = [
12
		'hook', 'is_plugin_active', 'is_plugin_inactive',
13
	];
14
15
	/**
16
	 * @var string
17
	 */
18
	CONST ID = 'pollux-settings';
19
20
	/**
21
	 * @var string
22
	 */
23
	public $hook;
24
25
	/**
26
	 * {@inheritdoc}
27
	 */
28
	public function init()
29
	{
30
		// @todo: run GateKeeper to check dependencies and capability (make sure it it run on the correct hook!)
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
31
		// if( !is_plugin_active( 'meta-box/meta-box.php' ))return;
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
32
33
		$this->normalize();
34
35
		add_action( 'admin_menu',                               [$this, 'addPage'] );
36
		add_action( 'pollux/settings/init',                     [$this, 'addSubmitMetaBox'] );
37
		add_filter( 'pollux/settings/instruction',              [$this, 'filterInstruction'], 10, 3 );
38
		add_filter( 'wp_redirect',                              [$this, 'filterRedirectOnSave'] );
39
		add_action( 'current_screen',                           [$this, 'register'] );
40
		add_action( 'admin_menu',                               [$this, 'registerSetting'] );
41
		add_action( 'pollux/settings/init',                     [$this, 'reset'] );
42
		add_action( 'admin_footer-toplevel_page_' . static::ID, [$this, 'renderFooterScript'] );
43
	}
44
45
	/**
46
	 * @return void
47
	 */
48
	public function addPage()
49
	{
50
		$this->hook = call_user_func_array( 'add_menu_page', apply_filters( 'pollux/settings/page', [
51
			__( 'Site Settings', 'pollux' ),
52
			__( 'Site Settings', 'pollux' ),
53
			'edit_theme_options',
54
			static::ID,
55
			[$this, 'renderPage'],
56
			'dashicons-screenoptions',
57
			1313
58
		]));
59
	}
60
61
	/**
62
	 * @return void
63
	 */
64
	public function addSubmitMetaBox()
65
	{
66
		call_user_func_array( 'add_meta_box', apply_filters( 'pollux/settings/metabox/submit', [
67
			'submitdiv',
68
			__( 'Save Settings', 'pollux' ),
69
			[ $this, 'renderSubmitMetaBox'],
70
			$this->hook,
71
			'side',
72
			'high',
73
		]));
74
	}
75
76
	/**
77
	 * @param string $instruction
78
	 * @param string $fieldId
79
	 * @param string $metaboxId
80
	 * @return string
81
	 */
82
	public function filterInstruction( $instruction, $fieldId, $metaboxId )
83
	{
84
		return sprintf( "SiteMeta::get('%s', '%s');", $metaboxId, $fieldId );
85
	}
86
87
	/**
88
	 * @param string $location
89
	 * @return string
90
	 */
91
	public function filterRedirectOnSave( $location )
92
	{
93
		if( strpos( $location, 'settings-updated=true' ) === false
94
			|| strpos( $location, sprintf( 'page=%s', static::ID )) === false ) {
95
			return $location;
96
		}
97
		return add_query_arg([
98
			'page' => static::ID,
99
			'settings-updated' => 'true',
100
		], admin_url( 'admin.php' ));
101
	}
102
103
	/**
104
	 * @return array
105
	 */
106
	public function filterSavedSettings( array $settings )
107
	{
108
		return apply_filters( 'pollux/settings/save', $settings );
109
	}
110
111
	/**
112
	 * @return void
113
	 */
114
	public function register( $metaboxes = [] )
115
	{
116
		if( $this->app->screen()->id != $this->hook )return;
117
		foreach( parent::register() as $metabox ) {
118
			new SettingsMetaBox( $metabox );
119
		}
120
		add_screen_option( 'layout_columns', [
121
			'max' => 2,
122
			'default' => 2,
123
		]);
124
		do_action( 'pollux/settings/init' );
125
	}
126
127
	/**
128
	 * @return void
129
	 */
130
	public function registerSetting()
131
	{
132
		register_setting( static::ID, static::ID, [$this, 'filterSavedSettings'] );
133
	}
134
135
	/**
136
	 * @return void
137
	 */
138
	public function renderFooterScript()
139
	{
140
		$this->render( 'settings/script', [
141
			'confirm' => __( 'Are you sure want to do this?', 'pollux' ),
142
			'hook' => $this->hook,
143
			'id' => static::ID,
144
		]);
145
	}
146
147
	/**
148
	 * @return void
149
	 */
150
	public function renderPage()
151
	{
152
		$this->render( 'settings/index', [
153
			'columns' => get_current_screen()->get_columns(),
154
			'id' => static::ID,
155
			'title' => __( 'Site Settings', 'pollux' ),
156
		]);
157
	}
158
159
	/**
160
	 * @return void
161
	 */
162
	public function renderSubmitMetaBox()
163
	{
164
		$query = [
165
			'_wpnonce' => wp_create_nonce( $this->hook ),
166
			'action' => 'reset',
167
			'page' => static::ID,
168
		];
169
		$this->render( 'settings/submit', [
170
			'reset' => __( 'Reset Settings', 'pollux' ),
171
			'reset_url' => esc_url( add_query_arg( $query, admin_url( 'admin.php' ))),
172
			'submit' => get_submit_button( __( 'Save', 'pollux' ), 'primary', 'submit', false ),
173
		]);
174
	}
175
176
	/**
177
	 * @return void
178
	 */
179
	public function reset()
180
	{
181
		if( filter_input( INPUT_GET, 'page' ) !== static::ID
182
			|| filter_input( INPUT_GET, 'action' ) !== 'reset'
183
		)return;
184
		if( wp_verify_nonce( filter_input( INPUT_GET, '_wpnonce' ), $this->hook )) {
185
			update_option( static::ID, $this->getDefaults() );
186
			return add_settings_error( static::ID, 'reset', __( 'Settings reset to defaults.', 'pollux' ), 'updated' );
187
		}
188
		add_settings_error( static::ID, 'reset', __( 'Failed to reset settings. Please refresh the page and try again.', 'pollux' ));
189
	}
190
191
	/**
192
	 * @param string $key
193
	 * @return array
194
	 */
195
	protected function filterArrayByKey( array $array, $key )
196
	{
197
		return array_filter( $array, function( $value ) use( $key ) {
198
			return !empty( $value[$key] );
199
		});
200
	}
201
202
	/**
203
	 * @return array
204
	 */
205
	protected function getDefaults()
206
	{
207
		$metaboxes = $this->filterArrayByKey( $this->metaboxes, 'slug' );
208
209
		array_walk( $metaboxes, function( &$metabox ) {
210
			$fields = array_map( function( $field ) {
211
				$field = wp_parse_args( $field, ['std' => ''] );
212
				return [$field['slug'] => $field['std']];
213
			}, $this->filterArrayByKey( $metabox['fields'], 'slug' ));
214
			$metabox = [
215
				$metabox['slug'] => call_user_func_array( 'array_merge', $fields ),
216
			];
217
		});
218
		return call_user_func_array( 'array_merge', $metaboxes );
219
	}
220
221
	/**
222
	 * {@inheritdoc}
223
	 */
224 View Code Duplication
	protected function normalize()
225
	{
226
		foreach( $this->app->config['settings'] as $id => $metabox ) {
227
			$defaults = [
228
				'condition' => [],
229
				'fields' => [],
230
				'id' => $id,
231
				'slug' => $id,
232
			];
233
			$this->metaboxes[] = $this->normalizeThis( $metabox, $defaults, $id );
234
		}
235
	}
236
237
	/**
238
	 * @param string $name
239
	 * @param string $parentId
240
	 * @return string
241
	 */
242
	protected function normalizeFieldName( $name, array $data, $parentId )
243
	{
244
		if( !empty( $name )) {
245
			return $name;
246
		}
247
		$name = str_replace( sprintf( '%s-%s-', static::ID, $parentId ), '', $data['id'] );
248
		return sprintf( '%s[%s][%s]', static::ID, $parentId, $name );
249
	}
250
251
	/**
252
	 * @param string $id
253
	 * @param string $parentId
254
	 * @return string
255
	 */
256
	protected function normalizeId( $id, array $data, $parentId )
257
	{
258
		return $parentId == $id
259
			? sprintf( '%s-%s', static::ID, $id )
260
			: sprintf( '%s-%s-%s', static::ID, $parentId, $id );
261
	}
262
}
263