PluginProbe
Packeta / 1.2.2
Packeta v1.2.2
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / src / Packetery / Module / Options / Page.php

Page.php in Packeta 1.2.2, at src/Packetery/Module/Options/Page.php

395 lines 11.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Class Page
4 *
5 * @package Packetery\Options
6 */
7
8 declare( strict_types=1 );
9
10 namespace Packetery\Module\Options;
11
12 use Packetery\Core\Api\Soap\Request\SenderGetReturnRouting;
13 use Packetery\Core\Log;
14 use Packetery\Module\FormFactory;
15 use Packetery\Module\MessageManager;
16 use PacketeryLatte\Engine;
17 use PacketeryNette\Forms\Form;
18
19 /**
20 * Class Page
21 *
22 * @package Packetery\Options
23 */
24 class Page {
25
26 private const FORM_FIELDS_CONTAINER = 'packetery';
27 private const FORM_FIELD_PACKETA_LABEL_FORMAT = 'packeta_label_format';
28 private const FORM_FIELD_CARRIER_LABEL_FORMAT = 'carrier_label_format';
29
30 private const DEFAULT_VALUE_PACKETA_LABEL_FORMAT = 'A6 on A4';
31 private const DEFAULT_VALUE_CARRIER_LABEL_FORMAT = self::DEFAULT_VALUE_PACKETA_LABEL_FORMAT;
32
33 public const ACTION_VALIDATE_SENDER = 'validate-sender';
34
35 public const SLUG = 'packeta-options';
36
37 /**
38 * PacketeryLatte_engine.
39 *
40 * @var Engine PacketeryLatte engine.
41 */
42 private $latte_engine;
43
44 /**
45 * Options Provider
46 *
47 * @var Provider
48 */
49 private $optionsProvider;
50
51 /**
52 * Form factory.
53 *
54 * @var FormFactory Form factory.
55 */
56 private $formFactory;
57
58 /**
59 * Packeta client.
60 *
61 * @var \Packetery\Core\Api\Soap\Client
62 */
63 private $packetaClient;
64
65 /**
66 * Logger
67 *
68 * @var Log\ILogger
69 */
70 private $logger;
71
72 /**
73 * Message manager.
74 *
75 * @var MessageManager
76 */
77 private $messageManager;
78
79 /**
80 * HTTP request.
81 *
82 * @var \PacketeryNette\Http\Request
83 */
84 private $httpRequest;
85
86 /**
87 * Plugin constructor.
88 *
89 * @param Engine $latte_engine PacketeryLatte_engine.
90 * @param Provider $optionsProvider Options provider.
91 * @param FormFactory $formFactory Form factory.
92 * @param \Packetery\Core\Api\Soap\Client $packetaClient Packeta Client.
93 * @param Log\ILogger $logger Logger.
94 * @param MessageManager $messageManager Message manager.
95 * @param \PacketeryNette\Http\Request $httpRequest HTTP request.
96 */
97 public function __construct( Engine $latte_engine, Provider $optionsProvider, FormFactory $formFactory, \Packetery\Core\Api\Soap\Client $packetaClient, Log\ILogger $logger, MessageManager $messageManager, \PacketeryNette\Http\Request $httpRequest ) {
98 $this->latte_engine = $latte_engine;
99 $this->optionsProvider = $optionsProvider;
100 $this->formFactory = $formFactory;
101 $this->packetaClient = $packetaClient;
102 $this->logger = $logger;
103 $this->messageManager = $messageManager;
104 $this->httpRequest = $httpRequest;
105 }
106
107 /**
108 * Registers WP callbacks.
109 */
110 public function register(): void {
111 add_action( 'admin_init', array( $this, 'admin_init' ) );
112 add_menu_page(
113 __( 'Packeta', 'packetery' ),
114 __( 'Packeta', 'packetery' ),
115 'manage_options',
116 self::SLUG,
117 '',
118 'dashicons-schedule',
119 55 // todo Move item to last position in menu.
120 );
121 add_submenu_page(
122 self::SLUG,
123 __( 'Settings', 'packetery' ),
124 __( 'Settings', 'packetery' ),
125 'manage_options',
126 self::SLUG,
127 array(
128 $this,
129 'render',
130 ),
131 1
132 );
133 add_action( 'admin_init', [ $this, 'processActions' ] );
134 }
135
136 /**
137 * Sets default values.
138 */
139 public function setDefaultValues(): void {
140 $value = get_option( self::FORM_FIELDS_CONTAINER );
141 $value[ self::FORM_FIELD_PACKETA_LABEL_FORMAT ] = self::DEFAULT_VALUE_PACKETA_LABEL_FORMAT;
142 $value[ self::FORM_FIELD_CARRIER_LABEL_FORMAT ] = self::DEFAULT_VALUE_CARRIER_LABEL_FORMAT;
143 update_option( self::FORM_FIELDS_CONTAINER, $value );
144 }
145
146 /**
147 * Creates settings form.
148 *
149 * @return Form
150 */
151 private function create_form(): Form {
152 $form = $this->formFactory->create();
153 $form->setAction( 'options.php' );
154
155 $container = $form->addContainer( self::FORM_FIELDS_CONTAINER );
156 $container->addText( 'api_password', __( 'API password', 'packetery' ) )
157 ->setRequired()
158 ->addRule( $form::PATTERN, __( 'API password must be 32 characters long and must contain valid characters!', 'packetery' ), '[a-z\d]{32}' );
159 $container->addText( 'sender', __( 'Sender', 'packetery' ) )
160 ->setRequired();
161
162 $packetaLabelFormats = $this->optionsProvider->getPacketaLabelFormats();
163 $container->addSelect(
164 self::FORM_FIELD_PACKETA_LABEL_FORMAT,
165 __( 'Packeta Label Format', 'packetery' ),
166 $packetaLabelFormats
167 )->checkDefaultValue( false )->setDefaultValue( self::DEFAULT_VALUE_PACKETA_LABEL_FORMAT );
168
169 $carrierLabelFormats = $this->optionsProvider->getCarrierLabelFormat();
170 $container->addSelect(
171 self::FORM_FIELD_CARRIER_LABEL_FORMAT,
172 __( 'Carrier Label Format', 'packetery' ),
173 $carrierLabelFormats
174 )->checkDefaultValue( false )->setDefaultValue( self::DEFAULT_VALUE_CARRIER_LABEL_FORMAT );
175
176 $gateways = $this->getAvailablePaymentGateways();
177 $enabledGateways = [];
178 foreach ( $gateways as $gateway ) {
179 $enabledGateways[ $gateway->id ] = $gateway->get_method_title();
180 }
181 $container->addSelect(
182 'cod_payment_method',
183 __( 'Payment method that represents cash on delivery', 'packetery' ),
184 $enabledGateways
185 )->setPrompt( '--' )->checkDefaultValue( false );
186
187 $container->addText( 'packaging_weight', __( 'packagingWeight', 'packetery' ) . ' (kg)' )
188 ->setRequired( true )
189 ->addRule( Form::FLOAT )
190 ->addRule( Form::MIN, null, 0 )
191 ->setDefaultValue( 0 );
192
193 // TODO: Packet status sync.
194
195 if ( $this->optionsProvider->has_any() ) {
196 $container->setDefaults( $this->optionsProvider->data_to_array() );
197 }
198
199 return $form;
200 }
201
202 /**
203 * Get available gateways.
204 *
205 * @return \WC_Payment_Gateway[]
206 */
207 public function getAvailablePaymentGateways(): array {
208 $availableGateways = [];
209
210 foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) {
211 if ( 'yes' === $gateway->enabled ) {
212 $availableGateways[ $gateway->id ] = $gateway;
213 }
214 }
215
216 return array_filter( (array) apply_filters( 'woocommerce_available_payment_gateways', $availableGateways ), [ $this, 'filterValidGatewayClass' ] );
217 }
218
219 /**
220 * Callback for array filter. Returns true if gateway is of correct type.
221 *
222 * @param object $gateway Gateway to check.
223 * @return bool
224 */
225 protected function filterValidGatewayClass( $gateway ): bool {
226 return $gateway && is_a( $gateway, 'WC_Payment_Gateway' );
227 }
228
229 /**
230 * Admin_init callback.
231 */
232 public function admin_init(): void {
233 register_setting( self::FORM_FIELDS_CONTAINER, self::FORM_FIELDS_CONTAINER, array( $this, 'options_validate' ) );
234 add_settings_section( 'packetery_main', __( 'Main Settings', 'packetery' ), '', self::SLUG );
235 }
236
237 /**
238 * Validates options.
239 *
240 * @param array $options Packetery_options.
241 *
242 * @return array
243 */
244 public function options_validate( $options ): array {
245 $form = $this->create_form();
246 $form[ self::FORM_FIELDS_CONTAINER ]->setValues( $options );
247 if ( $form->isValid() === false ) {
248 foreach ( $form[ self::FORM_FIELDS_CONTAINER ]->getControls() as $control ) {
249 if ( $control->hasErrors() === false ) {
250 continue;
251 }
252
253 add_settings_error( $control->getCaption(), esc_attr( $control->getName() ), $control->getError() );
254 $options[ $control->getName() ] = '';
255 }
256 }
257
258 $api_password = $form[ self::FORM_FIELDS_CONTAINER ]['api_password'];
259 if ( $api_password->hasErrors() === false ) {
260 $api_pass = $api_password->getValue();
261 $options['api_key'] = substr( $api_pass, 0, 16 );
262 $this->packetaClient->setApiPassword( $api_pass );
263 } else {
264 $options['api_key'] = '';
265 }
266
267 $this->validateSender( $options['sender'] );
268
269 return $options;
270 }
271
272 /**
273 * Validates sender.
274 *
275 * @param string $senderLabel Sender lbel.
276 *
277 * @return bool|null
278 */
279 private function validateSender( string $senderLabel ): ?bool {
280 $senderValidationRequest = new SenderGetReturnRouting( $senderLabel );
281 $senderValidationResponse = $this->packetaClient->senderGetReturnRouting( $senderValidationRequest );
282
283 $senderValidationLog = new Log\Record();
284 $senderValidationLog->action = Log\Record::ACTION_SENDER_VALIDATION;
285
286 $senderValidationLog->status = Log\Record::STATUS_SUCCESS;
287 $senderValidationLog->title = __( 'senderValidationSuccessLogTitle', 'packetery' );
288
289 if ( $senderValidationResponse->hasFault() ) {
290 $senderValidationLog->status = Log\Record::STATUS_ERROR;
291 $senderValidationLog->params = [
292 'errorMessage' => $senderValidationResponse->getFaultString(),
293 ];
294 $senderValidationLog->title = __( 'senderValidationErrorLogTitle', 'packetery' );
295 }
296
297 $this->logger->add( $senderValidationLog );
298
299 $senderExists = $senderValidationResponse->senderExists();
300
301 if ( false === $senderExists ) {
302 $this->messageManager->flash_message( __( 'specifiedSenderDoesNotExist', 'packetery' ), MessageManager::TYPE_INFO, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
303 }
304
305 if ( null === $senderExists ) {
306 $this->messageManager->flash_message( __( 'unableToCheckSpecifiedSender', 'packetery' ), MessageManager::TYPE_INFO, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
307 }
308
309 return $senderExists;
310 }
311
312 /**
313 * Process actions.
314 *
315 * @return void
316 */
317 public function processActions(): void {
318 $action = $this->httpRequest->getQuery( 'action' );
319 if ( self::ACTION_VALIDATE_SENDER === $action ) {
320 $result = $this->validateSender( $this->optionsProvider->get_sender() );
321
322 if ( true === $result ) {
323 $this->messageManager->flash_message( __( 'specifiedSenderIsOk', 'packetery' ), MessageManager::TYPE_SUCCESS, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
324 }
325
326 $doRedirect = wp_safe_redirect(
327 add_query_arg(
328 [
329 'page' => self::SLUG,
330 ],
331 get_admin_url( null, 'admin.php' )
332 )
333 );
334
335 if ( $doRedirect ) {
336 exit;
337 }
338 }
339 }
340
341 /**
342 * Renders page.
343 */
344 public function render(): void {
345 $latteParams = [ 'form' => $this->create_form() ];
346 if ( ! extension_loaded( 'soap' ) ) {
347 $latteParams['error'] = __( 'This plugin requires an active SOAP library for proper operation. Contact your web hosting administrator.', 'packetery' );
348 }
349
350 $latteParams['apiPasswordLink'] = trim( $this->latte_engine->renderToString( PACKETERY_PLUGIN_DIR . '/template/options/help-block-link.latte', [ 'href' => 'https://client.packeta.com/support' ] ) );
351
352 $latteParams['senderDescription'] = sprintf(
353 /* translators: 1: emphasis start 2: emphasis end 3: client section link start 4: client section link end */
354 esc_html__( 'senderDescription', 'packetery' ),
355 '<strong>',
356 '</strong>',
357 '<a href="https://client.packeta.com/senders" target="_blank">',
358 '</a>'
359 );
360
361 $latteParams['exportLink'] = add_query_arg(
362 [
363 'page' => self::SLUG,
364 'action' => Exporter::ACTION_EXPORT_SETTINGS,
365 ],
366 get_admin_url( null, 'admin.php' )
367 );
368
369 $latteParams['canValidateSender'] = (bool) $this->optionsProvider->get_sender();
370 $latteParams['senderValidationLink'] = add_query_arg(
371 [
372 'page' => self::SLUG,
373 'action' => self::ACTION_VALIDATE_SENDER,
374 ],
375 get_admin_url( null, 'admin.php' )
376 );
377
378 $lastExport = null;
379 $lastExportOption = get_option( Exporter::OPTION_LAST_SETTINGS_EXPORT );
380 if ( false !== $lastExportOption ) {
381 $date = \DateTime::createFromFormat( DATE_ATOM, $lastExportOption );
382 if ( false !== $date ) {
383 $date->setTimezone( wp_timezone() );
384 $lastExport = $date->format( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) );
385 }
386 }
387 if ( $lastExport ) {
388 $latteParams['lastExport'] = $lastExport;
389 }
390
391 $latteParams['messages'] = $this->messageManager->renderToString( MessageManager::RENDERER_PACKETERY, 'plugin-options' );
392 $this->latte_engine->render( PACKETERY_PLUGIN_DIR . '/template/options/page.latte', $latteParams );
393 }
394 }
395