| 1 |
<?php |
| 2 |
|
| 3 |
declare( strict_types=1 ); |
| 4 |
|
| 5 |
namespace Packetery\Module\Checkout; |
| 6 |
|
| 7 |
use Packetery\Module\Framework\WcAdapter; |
| 8 |
|
| 9 |
class SessionService { |
| 10 |
|
| 11 |
/** |
| 12 |
* @var WcAdapter |
| 13 |
*/ |
| 14 |
private $wcAdapter; |
| 15 |
|
| 16 |
public function __construct( |
| 17 |
WcAdapter $wcAdapter |
| 18 |
) { |
| 19 |
$this->wcAdapter = $wcAdapter; |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Gets shipping method from session without calculation. |
| 24 |
* |
| 25 |
* @return string |
| 26 |
*/ |
| 27 |
public function getChosenMethodFromSession(): string { |
| 28 |
$chosenShippingRate = null; |
| 29 |
if ( $this->wcAdapter->session() !== null ) { |
| 30 |
$chosenShippingRates = $this->wcAdapter->sessionGetArray( 'chosen_shipping_methods' ); |
| 31 |
if ( isset( $chosenShippingRates[0] ) && is_string( $chosenShippingRates[0] ) ) { |
| 32 |
$chosenShippingRate = $chosenShippingRates[0]; |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
return $chosenShippingRate ?? ''; |
| 37 |
} |
| 38 |
|
| 39 |
public function getChosenPaymentMethod(): ?string { |
| 40 |
return $this->wcAdapter->sessionGetString( 'chosen_payment_method' ); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Updates shipping rates cost based on cart properties. |
| 45 |
* To test, change the shipping price during the transition from the first to the second step of the cart. |
| 46 |
*/ |
| 47 |
public function actionUpdateShippingRates(): void { |
| 48 |
$packages = $this->wcAdapter->shippingGetPackages(); |
| 49 |
foreach ( $packages as $index => $package ) { |
| 50 |
$this->wcAdapter->sessionSet( 'shipping_for_package_' . $index, false ); |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Updates shipping packages to make WooCommerce caching system work correctly. |
| 56 |
* Package values are used in WooCommerce method \WC_Shipping::calculate_shipping_for_package(). |
| 57 |
* In order to generate package cache hash correctly by WooCommerce |
| 58 |
* the package must contain all relevant information related to pricing. |
| 59 |
* |
| 60 |
* @param array $packages Packages. |
| 61 |
* |
| 62 |
* @return array |
| 63 |
*/ |
| 64 |
public function filterUpdateShippingPackages( array $packages ): array { |
| 65 |
foreach ( $packages as $key => $package ) { |
| 66 |
$package['packetery_payment_method'] = $this->getChosenPaymentMethod(); |
| 67 |
$packages[ $key ] = $package; |
| 68 |
} |
| 69 |
|
| 70 |
return $packages; |
| 71 |
} |
| 72 |
} |
| 73 |
|