Passed
Push — master ( cfaae5...9b930a )
by Paul
02:25
created

Settings::onSave()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
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 here instead to check dependencies and capability
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;
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_' . self::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
			self::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', self::ID )) === false ) {
95
			return $location;
96
		}
97
		return add_query_arg([
98
			'page' => self::ID,
99
			'settings-updated' => 'true',
100
		], admin_url( 'admin.php' ));
101
	}
102
103
	/**
104
	 * @return void
105
	 */
106
	public function register( $metaboxes = [] )
107
	{
108
		if( get_current_screen()->id != $this->hook )return;
109
		foreach( parent::register() as $metabox ) {
110
			new SettingsMetaBox( $metabox );
111
		}
112
		add_screen_option( 'layout_columns', [
113
			'max' => 2,
114
			'default' => 2,
115
		]);
116
		do_action( 'pollux/settings/init' );
117
	}
118
119
	/**
120
	 * @return void
121
	 */
122
	public function registerSetting()
123
	{
124
		register_setting( self::ID, self::ID, [$this, 'onSave'] );
125
	}
126
127
	public function onSave( $settings )
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
128
	{
129
		// error_log( print_r( $settings, 1 ));
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
130
		return $settings;
131
	}
132
133
	/**
134
	 * @return void
135
	 */
136
	public function renderFooterScript()
137
	{
138
		$this->render( 'settings/script', [
139
			'confirm' => __( 'Are you sure want to do this?', 'pollux' ),
140
			'hook' => $this->hook,
141
			'id' => self::ID,
142
		]);
143
	}
144
145
	/**
146
	 * @return void
147
	 */
148
	public function renderPage()
149
	{
150
		$this->render( 'settings/index', [
151
			'columns' => get_current_screen()->get_columns(),
152
			'id' => self::ID,
153
			'title' => __( 'Site Settings', 'pollux' ),
154
		]);
155
	}
156
157
	/**
158
	 * @return void
159
	 */
160
	public function renderSubmitMetaBox()
161
	{
162
		$query = [
163
			'_wpnonce' => wp_create_nonce( $this->hook ),
164
			'action' => 'reset',
165
			'page' => self::ID,
166
		];
167
		$this->render( 'settings/submit', [
168
			'reset' => __( 'Reset Settings', 'pollux' ),
169
			'reset_url' => esc_url( add_query_arg( $query, admin_url( 'admin.php' ))),
170
			'submit' => get_submit_button( __( 'Save', 'pollux' ), 'primary', 'submit', false ),
171
		]);
172
	}
173
174
	/**
175
	 * @return void
176
	 */
177
	public function reset()
178
	{
179
		if( filter_input( INPUT_GET, 'page' ) !== self::ID
180
			|| filter_input( INPUT_GET, 'action' ) !== 'reset'
181
		)return;
182
		if( wp_verify_nonce( filter_input( INPUT_GET, '_wpnonce' ), $this->hook )) {
183
			delete_option( self::ID );
184
			// @todo: now trigger save to restore defaults
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...
185
			return add_settings_error( self::ID, 'reset', __( 'Settings reset to defaults.', 'pollux' ), 'updated' );
186
		}
187
		add_settings_error( self::ID, 'reset', __( 'Failed to reset settings. Please refresh the page and try again.', 'pollux' ));
188
	}
189
190
	/**
191
	 * @return array
192
	 */
193
	protected function getInstructions()
194
	{
195
		return array_filter( $this->metaboxes, function( $metabox ) {
196
			return $this->verifyMetaBoxCondition( $metabox['condition'] );
197
		});
198
	}
199
200
	/**
201
	 * @return array
202
	 */
203
	protected function getPostTypes()
204
	{
205
		return [];
206
	}
207
208
	/**
209
	 * {@inheritdoc}
210
	 */
211 View Code Duplication
	protected function normalize()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212
	{
213
		$this->metaboxes = [];
214
		foreach( $this->app->config['settings'] as $id => $metabox ) {
215
			$defaults = [
216
				'condition' => [],
217
				'fields' => [],
218
				'id' => $id,
219
				'slug' => $id,
220
			];
221
			$this->metaboxes[] = $this->normalizeThis( $metabox, $defaults, $id );
222
		}
223
	}
224
225
	/**
226
	 * @param string $name
227
	 * @param string $parentId
228
	 * @return string
229
	 */
230
	protected function normalizeFieldName( $name, array $data, $parentId )
231
	{
232
		if( !empty( $name )) {
233
			return $name;
234
		}
235
		$name = str_replace( sprintf( '%s-%s-', self::ID, $parentId ), '', $data['id'] );
236
		return sprintf( '%s[%s][%s]', self::ID, $parentId, $name );
237
	}
238
239
	/**
240
	 * @param string $id
241
	 * @param string $parentId
242
	 * @return string
243
	 */
244
	protected function normalizeId( $id, array $data, $parentId )
245
	{
246
		return $parentId == $id
247
			? sprintf( '%s-%s', self::ID, $id )
248
			: sprintf( '%s-%s-%s', self::ID, $parentId, $id );
249
	}
250
}
251