Passed
Push — develop ( f91847...084281 )
by Paul
03:07
created

Settings::filterArrayByKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\Pollux\Settings;
4
5
use GeminiLabs\Pollux\Application;
6
use GeminiLabs\Pollux\Facades\SiteMeta;
7
use GeminiLabs\Pollux\Helper;
8
use GeminiLabs\Pollux\MetaBox\MetaBox;
9
use GeminiLabs\Pollux\Settings\RWMetaBox;
10
11
class Settings extends MetaBox
12
{
13
	/**
14
	 * @var string
15
	 */
16
	const ID = 'settings';
17
18
	/**
19
	 * @var array
20
	 */
21
	public static $conditions = [
22
		'class_exists', 'defined', 'function_exists', 'hook', 'is_plugin_active',
23
		'is_plugin_inactive',
24
	];
25
26
	/**
27
	 * @var string
28
	 */
29
	public $hook;
30
31
	/**
32
	 * @return string
33
	 */
34
	public static function id()
35
	{
36
		return apply_filters( sprintf( 'pollux/%s/id', static::ID ), Application::prefix() . static::ID );
37
	}
38
39
	/**
40
	 * {@inheritdoc}
41
	 */
42
	public function init()
43
	{
44
		// @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...
45
		// 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...
46
47
		$this->normalize( $this->app->config[static::ID] );
48
49
		add_action( 'admin_menu',                                [$this, 'addPage'] );
50
		add_action( 'pollux/'.static::ID.'/init',                [$this, 'addSubmitMetaBox'] );
51
		add_action( 'current_screen',                            [$this, 'register'] );
52
		add_action( 'admin_menu',                                [$this, 'registerSetting'] );
53
		add_action( 'pollux/'.static::ID.'/init',                [$this, 'reset'] );
54
		add_action( 'admin_print_footer_scripts',                [$this, 'renderFooterScript'] );
55
		add_filter( 'pollux/'.static::ID.'/instruction',         [$this, 'filterInstruction'], 10, 3 );
56
		add_filter( 'pollux/'.static::ID.'/before/instructions', [$this, 'filterBeforeInstructions'] );
57
	}
58
59
	/**
60
	 * @return void
61
	 * @action admin_menu
62
	 */
63
	public function addPage()
64
	{
65
		$this->hook = call_user_func_array( 'add_menu_page', $this->filter( 'page', [
66
			__( 'Site Settings', 'pollux' ),
67
			__( 'Site Settings', 'pollux' ),
68
			'edit_theme_options',
69
			static::id(),
70
			[$this, 'renderPage'],
71
			'dashicons-screenoptions',
72
			1313
73
		]));
74
	}
75
76
	/**
77
	 * @return void
78
	 * @action pollux/{static::ID}/init
79
	 */
80
	public function addSubmitMetaBox()
81
	{
82
		call_user_func_array( 'add_meta_box', $this->filter( 'metabox/submit', [
83
			'submitdiv',
84
			__( 'Save Settings', 'pollux' ),
85
			[$this, 'renderSubmitMetaBox'],
86
			$this->hook,
87
			'side',
88
			'high',
89
		]));
90
	}
91
92
	/**
93
	 * @return string
94
	 * @filter pollux/{static::ID}/before/instructions
95
	 */
96
	public function filterBeforeInstructions()
97
	{
98
		return '<pre class="my-sites nav-tab-active misc-pub-section">SiteMeta::all();</pre>';
99
	}
100
101
	/**
102
	 * @param string $instruction
103
	 * @return string
104
	 * @action pollux/{static::ID}/instruction
105
	 */
106
	public function filterInstruction( $instruction, array $field, array $metabox )
107
	{
108
		return sprintf( "SiteMeta::%s('%s');", $metabox['slug'], $field['slug'] );
109
	}
110
111
	/**
112
	 * @param null|array $settings
113
	 * @return array
114
	 * @callback register_setting
115
	 */
116
	public function filterSavedSettings( $settings )
117
	{
118
		if( is_null( $settings )) {
119
			$settings = [];
120
		}
121
		return $this->filter( 'save', array_merge( $this->getSettings(), $settings ));
122
	}
123
124
	/**
125
	 * @param string $key
126
	 * @param mixed $fallback
127
	 * @param string $group
128
	 * @return string|array
129
	 */
130
	public function getMetaValue( $key, $fallback = '', $group = '' )
131
	{
132
		return SiteMeta::get( $group, $key, $fallback );
133
	}
134
135
	/**
136
	 * @return void
137
	 * @action current_screen
138
	 */
139
	public function register()
140
	{
141
		if(( new Helper )->getCurrentScreen()->id != $this->hook )return;
142
		foreach( parent::register() as $metabox ) {
143
			new RWMetaBox( $metabox, static::ID, $this );
144
		}
145
		add_screen_option( 'layout_columns', [
146
			'max' => 2,
147
			'default' => 2,
148
		]);
149
		$this->action( 'init' );
150
	}
151
152
	/**
153
	 * @return void
154
	 * @action admin_menu
155
	 */
156
	public function registerSetting()
157
	{
158
		register_setting( static::id(), static::id(), [$this, 'filterSavedSettings'] );
159
	}
160
161
	/**
162
	 * @return void
163
	 * @action admin_print_footer_scripts
164
	 */
165
	public function renderFooterScript()
166
	{
167
		if(( new Helper )->getCurrentScreen()->id != $this->hook )return;
168
		$this->render( 'settings/script', [
169
			'confirm' => __( 'Are you sure want to do this?', 'pollux' ),
170
			'hook' => $this->hook,
171
			'id' => static::id(),
172
		]);
173
	}
174
175
	/**
176
	 * @return void
177
	 * @callback add_menu_page
178
	 */
179
	public function renderPage()
180
	{
181
		$this->render( 'settings/index', [
182
			'columns' => get_current_screen()->get_columns(),
183
			'heading' => __( 'Site Settings', 'pollux' ),
184
			'id' => static::id(),
185
		]);
186
	}
187
188
	/**
189
	 * @return void
190
	 * @callback add_meta_box
191
	 */
192
	public function renderSubmitMetaBox()
193
	{
194
		global $pagenow;
195
		$query = [
196
			'_wpnonce' => wp_create_nonce( $this->hook ),
197
			'action' => 'reset',
198
			'page' => static::id(),
199
		];
200
		$this->render( 'settings/submit', [
201
			'reset' => __( 'Reset all', 'pollux' ),
202
			'reset_url' => esc_url( add_query_arg( $query, admin_url( $pagenow ))),
203
			'submit' => get_submit_button( __( 'Save', 'pollux' ), 'primary', 'submit', false ),
204
		]);
205
	}
206
207
	/**
208
	 * @return void
209
	 * @action pollux/{static::ID}/init
210
	 */
211
	public function reset()
212
	{
213
		if( filter_input( INPUT_GET, 'page' ) !== static::id()
214
			|| filter_input( INPUT_GET, 'action' ) !== 'reset'
215
		)return;
216
		if( wp_verify_nonce( filter_input( INPUT_GET, '_wpnonce' ), $this->hook )) {
217
			update_option( static::id(), $this->getDefaults() );
218
			add_settings_error( static::id(), 'reset', __( 'Reset successful.', 'pollux' ), 'updated' );
219
		}
220
		else {
221
			add_settings_error( static::id(), 'failed', __( 'Failed to reset. Please try again.', 'pollux' ));
222
		}
223
		set_transient( 'settings_errors', get_settings_errors(), 30 );
224
		wp_safe_redirect( add_query_arg( 'settings-updated', 'true',  wp_get_referer() ));
225
		exit;
226
	}
227
228
	/**
229
	 * @param string $key
230
	 * @return array
231
	 */
232
	protected function filterArrayByKey( array $array, $key )
233
	{
234
		return array_filter( $array, function( $value ) use( $key ) {
235
			return !empty( $value[$key] );
236
		});
237
	}
238
239
	/**
240
	 * @return array
241
	 */
242
	protected function getDefaults()
243
	{
244
		$metaboxes = $this->filterArrayByKey( $this->metaboxes, 'slug' );
245
246
		array_walk( $metaboxes, function( &$metabox ) {
247
			$fields = array_map( function( $field ) {
248
				$field = wp_parse_args( $field, ['std' => ''] );
249
				return [$field['slug'] => $field['std']];
250
			}, $this->filterArrayByKey( $metabox['fields'], 'slug' ));
251
			$metabox = [
252
				$metabox['slug'] => call_user_func_array( 'array_merge', $fields ),
253
			];
254
		});
255
		return call_user_func_array( 'array_merge', $metaboxes );
256
	}
257
258
	protected function getSettings()
259
	{
260
		return (array) SiteMeta::all();
261
	}
262
263
	/**
264
	 * @param string $name
265
	 * @param string $parentId
266
	 * @return string
267
	 */
268
	protected function normalizeFieldName( $name, array $data, $parentId )
269
	{
270
		return sprintf( '%s[%s][%s]', static::id(), $parentId, $data['slug'] );
271
	}
272
273
	/**
274
	 * @param string $id
275
	 * @param string $parentId
276
	 * @return string
277
	 */
278
	protected function normalizeId( $id, array $data, $parentId )
279
	{
280
		return $parentId == $id
281
			? sprintf( '%s-%s', static::id(), $id )
282
			: sprintf( '%s-%s-%s', static::id(), $parentId, $id );
283
	}
284
}
285