Passed
Push — develop ( 87abfc...84da8f )
by Paul
02:47
created

Settings::reset()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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