Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

jsarnowski / jsarnowski/woocommerce-paczkomaty-inpost   php

Repository URL to install this package:

/ shipX / class-api-shipx-points.php

<?php
/**
 * ShipX Points
 *
 * @package WooCommerce Paczkomaty InPost
 */

/**
 * Can get points from API.
 */
class WPDesk_Paczkomaty_ShipX_Points {

	/**
	 * @var WPDesk_Paczkomaty_ShipX
	 */
	private $api_client;

	/**
	 * @param WPDesk_Paczkomaty_ShipX $api_client .
	 */
	public function __construct( $api_client ) {
		$this->api_client = $api_client;
	}

	/**
	 * @param stdClass $item .
	 * @param string   $field_name .
	 *
	 * @return stdClass
	 */
	private function unset_item_field( $item, $field_name ) {
		unset( $item->{$field_name} );

		return $item;
	}

	/**
	 * @param stdClass $item .
	 *
	 * @return stdClass
	 */
	private function unset_item_unnecessary_data( $item ) {
		foreach ( $item as $property => $value ) {
			if ( ! in_array( $property, array( 'name', 'type', 'address', 'payment_available' ), true ) ) {
				$item = $this->unset_item_field( $item, $property );
			}
		}

		return $item;
	}

	/**
	 * Get points from api.
	 *
	 * @param string $type .
	 *
	 * @return array
	 * @throws Exception .
	 * @throws WPDesk_Paczkomaty_ShipX_Exception .
	 */
	public function get_points_from_api( $type = 'parcel_locker' ) {
		$params = array( 'per_page' => 1000 );
		$points = array();
		if ( $type ) {
			$params['type'] = $type;
		}
		$get_points = true;
		while ( $get_points ) {
			$get_points = false;
			$api_points = $this->api_client->get_points( $params );
			foreach ( $api_points->items as $item ) {
				$points[ $item->name ] = $this->unset_item_unnecessary_data( $item );
			}
			if ( $api_points->page < $api_points->total_pages ) {
				$get_points     = true;
				$params['page'] = intval( $api_points->page ) + 1;
			}
		}

		return $points;
	}

	/**
	 * Returns point data from API.
	 *
	 * @see https://docs.inpost24.com/display/PL/%5B1.5.2%5D+Points#id-[1.5.2]Points-Informationaboutpoints
	 *
	 * @param string $point_name .
	 *
	 * @return stdClass
	 * @throws Exception .
	 * @throws WPDesk_Paczkomaty_ShipX_Exception .
	 */
	public function get_point_from_api( $point_name ) {
		return $this->api_client->get_point( $point_name );
	}

	/**
	 * @param stdClass $point .
	 *
	 * @return string
	 */
	public function get_point_label( $point ) {
		$label = $point->name;
		if ( isset( $point->address ) ) {
			if ( isset( $point->address->line1 ) ) {
				$label .= ', ';
				$label .= $point->address->line1;
			}
			if ( isset( $point->address->line2 ) ) {
				$label .= ', ';
				$label .= $point->address->line2;
			}
		}

		return $label;
	}

}