Passed
Push — develop ( 9b346b...48f539 )
by Paul
12:10
created

Settings::filterInstruction()   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 3
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\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( $settings, $this->getSettings() ));
122
	}
123
124
	/**
125
	 * @return void
126
	 * @action current_screen
127
	 */
128
	public function register()
129
	{
130
		if(( new Helper )->getCurrentScreen()->id != $this->hook )return;
131
		foreach( parent::register() as $metabox ) {
132
			new RWMetaBox( $metabox, static::ID, $this->hook );
133
		}
134
		add_screen_option( 'layout_columns', [
135
			'max' => 2,
136
			'default' => 2,
137
		]);
138
		$this->action( 'init' );
139
	}
140
141
	/**
142
	 * @return void
143
	 * @action admin_menu
144
	 */
145
	public function registerSetting()
146
	{
147
		register_setting( static::id(), static::id(), [$this, 'filterSavedSettings'] );
148
	}
149
150
	/**
151
	 * @return void
152
	 * @action admin_print_footer_scripts
153
	 */
154
	public function renderFooterScript()
155
	{
156
		if(( new Helper )->getCurrentScreen()->id != $this->hook )return;
157
		$this->render( 'settings/script', [
158
			'confirm' => __( 'Are you sure want to do this?', 'pollux' ),
159
			'hook' => $this->hook,
160
			'id' => static::id(),
161
		]);
162
	}
163
164
	/**
165
	 * @return void
166
	 * @callback add_menu_page
167
	 */
168
	public function renderPage()
169
	{
170
		$this->render( 'settings/index', [
171
			'columns' => get_current_screen()->get_columns(),
172
			'heading' => __( 'Site Settings', 'pollux' ),
173
			'id' => static::id(),
174
		]);
175
	}
176
177
	/**
178
	 * @return void
179
	 * @callback add_meta_box
180
	 */
181
	public function renderSubmitMetaBox()
182
	{
183
		global $pagenow;
184
		$query = [
185
			'_wpnonce' => wp_create_nonce( $this->hook ),
186
			'action' => 'reset',
187
			'page' => static::id(),
188
		];
189
		$this->render( 'settings/submit', [
190
			'reset' => __( 'Reset all', 'pollux' ),
191
			'reset_url' => esc_url( add_query_arg( $query, admin_url( $pagenow ))),
192
			'submit' => get_submit_button( __( 'Save', 'pollux' ), 'primary', 'submit', false ),
193
		]);
194
	}
195
196
	/**
197
	 * @return void
198
	 * @action pollux/{static::ID}/init
199
	 */
200
	public function reset()
201
	{
202
		if( filter_input( INPUT_GET, 'page' ) !== static::id()
203
			|| filter_input( INPUT_GET, 'action' ) !== 'reset'
204
		)return;
205
		if( wp_verify_nonce( filter_input( INPUT_GET, '_wpnonce' ), $this->hook )) {
206
			update_option( static::id(), $this->getDefaults() );
207
			add_settings_error( static::id(), 'reset', __( 'Reset successful.', 'pollux' ), 'updated' );
208
		}
209
		else {
210
			add_settings_error( static::id(), 'failed', __( 'Failed to reset. Please try again.', 'pollux' ));
211
		}
212
		set_transient( 'settings_errors', get_settings_errors(), 30 );
213
		wp_safe_redirect( add_query_arg( 'settings-updated', 'true',  wp_get_referer() ));
214
		exit;
215
	}
216
217
	/**
218
	 * @param string $key
219
	 * @return array
220
	 */
221
	protected function filterArrayByKey( array $array, $key )
222
	{
223
		return array_filter( $array, function( $value ) use( $key ) {
224
			return !empty( $value[$key] );
225
		});
226
	}
227
228
	/**
229
	 * @return array
230
	 */
231
	protected function getDefaults()
232
	{
233
		$metaboxes = $this->filterArrayByKey( $this->metaboxes, 'slug' );
234
235
		array_walk( $metaboxes, function( &$metabox ) {
236
			$fields = array_map( function( $field ) {
237
				$field = wp_parse_args( $field, ['std' => ''] );
238
				return [$field['slug'] => $field['std']];
239
			}, $this->filterArrayByKey( $metabox['fields'], 'slug' ));
240
			$metabox = [
241
				$metabox['slug'] => call_user_func_array( 'array_merge', $fields ),
242
			];
243
		});
244
		return call_user_func_array( 'array_merge', $metaboxes );
245
	}
246
247
	protected function getSettings()
248
	{
249
		return (array) SiteMeta::all();
250
	}
251
252
	/**
253
	 * @return string|array
254
	 */
255
	protected function getValue( $key, $group )
256
	{
257
		return SiteMeta::get( $group, $key, false );
258
	}
259
260
	/**
261
	 * @param string $name
262
	 * @param string $parentId
263
	 * @return string
264
	 */
265
	protected function normalizeFieldName( $name, array $data, $parentId )
266
	{
267
		return sprintf( '%s[%s][%s]', static::id(), $parentId, $data['slug'] );
268
	}
269
270
	/**
271
	 * @param string $id
272
	 * @param string $parentId
273
	 * @return string
274
	 */
275
	protected function normalizeId( $id, array $data, $parentId )
276
	{
277
		return $parentId == $id
278
			? sprintf( '%s-%s', static::id(), $id )
279
			: sprintf( '%s-%s-%s', static::id(), $parentId, $id );
280
	}
281
}
282