Completed
Pull Request — staging (#840)
by
unknown
15:23
created

EasyFormsShortcode::get_default_atts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
/**
3
 * YIKES Inc. Easy Forms.
4
 *
5
 * @package   YIKES\EasyForms
6
 * @author    Freddie Mixell
7
 * @license   GPL2
8
 */
9
10
namespace YIKES\EasyForms\Shortcode;
11
12
use YIKES\EasyForms\Asset;
13
use YIKES\EasyForms\AssetAware;
14
use YIKES\EasyForms\ScriptAsset;
15
use YIKES\EasyForms\StyleAsset;
16
use YIKES\EasyForms\Exception;
17
use YIKES\EasyForms\View\FormEscapedView;
18
use YIKES\EasyForms\View\NoOverrideLocationView;
19
use YIKES\EasyForms\Form\OptinForm as EasyForm;
20
use YIKES\EasyForms\Model\Subscriber;
21
use YIKES\EasyForms\Model\SubscriberRepository;
22
use YIKES\EasyForms\Model\OptinForm as EasyFormsModel;
23
use YIkes\EasyForms\Model\OptinFormRepository;
24
25
/**
26
 * Class EasyFormsShortcode
27
 *
28
 * @since %VERSION%
29
 * @package YIKES\EasyForms
30
 */
31
32
final class EasyFormsShortcode extends BaseShortcode {
33
34
    const TAG           = 'yikes-mailchimp';
35
	const VIEW_URI      = 'views/easy-forms-shortcode';
36
	const SUBMITTED_URI = 'views/easy-forms-shortcode-completed';
37
38
	/**
39
	 * Whether a form has been submitted.
40
	 *
41
	 * @since %VERSION%
42
	 * @var bool
43
	 */
44
	private $is_submitted = false;
45
46
	/**
47
	 * The view URI to use.
48
	 *
49
	 * This property is used so that the view can be switched dynamically
50
	 * as needed.
51
	 *
52
	 * @since %VERSION%
53
	 * @var string
54
	 */
55
    private $view_uri = self::VIEW_URI;
56
    
57
    /**
58
	 * Register the Shortcode.
59
	 *
60
	 * @since %VERSION%
61
	 */
62
	public function register() {
63
		parent::register();
64
		add_action( 'easy_forms_do_shortcode', function( $atts ) {
65
			echo $this->process_shortcode( $atts ); // phpcs:ignore WordPress.Security.EscapeOutput
66
		} );
67
    }
68
    
69
    /**
70
	 * Get the default array of attributes for the shortcode.
71
	 *
72
	 * @since %VERSION%
73
	 * @return array
74
	 */
75
	public function get_default_atts() {
76
		return [
77
			'form'                       => '',
78
			'submit'                     => '',
79
			'title'                      => '0',
80
			'custom_title'               => '',
81
			'description'                => '0',
82
			'custom_description'         => '',
83
			'ajax'                       => '',
84
			'recaptcha'                  => '', // manually set googles recptcha state
85
			'recaptcha_lang'             => '', // manually set the recaptcha language in the shortcode - also available is the yikes-mailchimp-recaptcha-language filter
86
			'recaptcha_type'             => '', // manually set the recaptcha type - audio/image - default image
87
			'recaptcha_theme'            => '', // manually set the recaptcha theme - light/dark - default light
88
			'recaptcha_size'             => '', // set the recaptcha size - normal/compact - default normal
89
			'recaptcha_data_callback'    => '', // set a custom js callback function to run after a successful recaptcha response - default none
90
			'recaptcha_expired_callback' => '', // set a custom js callback function to run after the recaptcha has expired - default none
91
			'inline'                     => '0',
92
		];
93
	}
94
95
	/**
96
	 * Get the context to pass onto the view.
97
	 *
98
	 * Override to provide data to the view that is not part of the shortcode
99
	 * attributes.
100
	 *
101
	 * @since %VERSION%
102
	 *
103
	 * @param array $atts Array of shortcode attributes.
104
	 *
105
	 * @return array Context to pass onto view.
106
	 * @throws InvalidPostID When the post ID is not valid.
107
	 */
108
	protected function get_context( array $atts ) {
109
		$optin_form = ( new OptinFormRepository() )->find( $atts['form'] );
110
		/** @todo Recaptcha Settings. */
111
		$this->is_submitted = $this->is_submitting_form();
112
		// Set up the classes we'll use for the form and the individual fields.
113
		$form_classes = $optin_form['form_settings']['yikes-easy-mc-form-class-names'];
114
115
		// Set up the form object.
116
		$form = $this->get_optin_form( $optin_form->get_id(), $optin_form, $field_classes );
0 ignored issues
show
Bug introduced by
The variable $field_classes does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
$form is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
117
		return [
118
			'form_settings' => $optin_form['form_settings'],
119
			'optin_form'    => $optin_form,
120
			'form_id'       => $optin_form->get_id(),
121
			'form_classes'  => $form_classes,
122
			'submitted'     => $this->is_submitted,
123
		];
124
	}
125
126
	/**
127
	 * Process the shortcode attributes and prepare rendering.
128
	 *
129
	 * @since %VERSION%
130
	 *
131
	 * @param array|string $atts Attributes as passed to the shortcode.
132
	 *
133
	 * @return string Rendered HTML of the shortcode.
134
	 */
135
	public function process_shortcode( $atts ) {
136
		try {
137
			// Determine if the form has been submitted.
138
			$this->is_submitted = $this->is_submitting_form();
139
			// Process the shortcode attributes.
140
			$atts    = $this->process_attributes( $atts );
141
			$context = $this->get_context( $atts );
142
			return $this->render( $context );
143
		} catch ( Exception $e ) {
0 ignored issues
show
Bug introduced by
The class YIKES\EasyForms\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
144
			return $this->exception_to_string( $e );
145
		}
146
	}
147
    
148
   /**
149
	 * Get the View URI to use for rendering the shortcode.
150
	 *
151
	 * @since %VERSION%
152
	 *
153
	 * @return string View URI.
154
	 */
155
	protected function get_view_uri() {
156
		if ( self::VIEW_URI !== $uri && self::SUBMITTED_URI !== $uri ) {
0 ignored issues
show
Bug introduced by
The variable $uri does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
157
			throw InvalidURI::from_list( $uri, [ self::VIEW_URI, self::SUBMITTED_URI ] );
158
		}
159
160
		return $this->view_uri;
161
    }
162
    
163
    /**
164
	 * Set the view URI.
165
	 *
166
	 * @since %VERSION%
167
	 *
168
	 * @param string $uri The URI to use.
169
	 */
170
	private function set_view_uri( $uri ) {
171
		$this->view_uri = $uri;
172
	}
173
	
174
	/**
175
	 * Determine whether a form is currently being submitted.
176
	 *
177
	 * @since %VERSION%
178
	 * @return bool
179
	 */
180
	private function is_submitting_form() {
181
		return ! empty( $_POST );
182
	}
183
    
184
    /**
185
	 * Render the current Renderable.
186
	 *
187
	 * @since %VERSION%
188
	 *
189
	 * @param array $context Context in which to render.
190
	 *
191
	 * @return string Rendered HTML.
192
	 */
193
	public function render( array $context = [] ) {
194
		try {
195
			$this->enqueue_assets();
196
			$view = new FormEscapedView( new NoOverrideLocationView( $this->get_view_uri() ) );
197
			return $view->render( $context );
198
		} catch ( \Exception $e ) {
199
			return $this->exception_to_string( $e );
200
		}
201
	}
202
	
203
	/**
204
	 * Get the form object.
205
	 *
206
	 * @since %VERSION%
207
	 *
208
	 * @param int              $form_id       The ID for the form.
209
	 * @param EasyFormsModel   $form   The form Object.
210
	 * @param array            $field_classes The classes for fields in the form.
211
	 *
212
	 * @return EasyForm
213
	 */
214
	private function get_optin_form( $form_id, $form, $field_classes ) {
215
		$form = new EasyForm( $form_id, $form, $field_classes );
216
		if ( $this->is_submitted ) {
217
			$this->handle_submission( $form );
218
		}
219
		return $form;
220
	}
221
222
	/**
223
	 * Handle the form submission.
224
	 *
225
	 * @since %VERSION%
226
	 *
227
	 * @param EasyForm $form The form object.
228
	 *
229
	 * @return Subscriber|null Returns a new Subscriber object, or null if one was not created.
230
	 * @throws InvalidURI When an invalid URI is set for the view.
231
	 */
232
	private function handle_submission( EasyForm $form ) {
233
		$form->set_submission( $_POST );
234
		$form->validate_submission();
235
		// Maybe update the view URI.
236
		if ( ! $form->has_errors() ) {
237
			$this->set_view_uri( self::SUBMITTED_URI );
238
			$subscriber = ( new SubscriberRepository() )->create_from_form( $form );
239
		}
240
		return isset( $subscriber ) ? $subscriber : null;
241
	}
242
    
243
    /**
244
	 * Convert an exception to a string.
245
	 *
246
	 * @since %VERSION%
247
	 *
248
	 * @param \Exception $e The exception object.
249
	 *
250
	 * @return string
251
	 */
252
	private function exception_to_string( \Exception $e ) {
253
		return sprintf(
254
			/* translators: %s refers to the error message */
255
			esc_html__( 'There was an error displaying the form: %s', 'easy-forms-text-domain' ),
256
			$e->getMessage()
257
		);
258
	}
259
}
260