Passed
Push — master ( ee5e63...92e6cb )
by Paul
04:58 queued 02:29
created

Settings::getValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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