| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class Product\ProductEntityFactory. |
| 4 |
* |
| 5 |
* @package Packetery\Module\Product |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace Packetery\Module\Product; |
| 11 |
|
| 12 |
use Packetery\Module\Exception\ProductNotFoundException; |
| 13 |
use Packetery\Module\Framework\WcAdapter; |
| 14 |
|
| 15 |
/** |
| 16 |
* Class Product\ProductEntityFactory. |
| 17 |
* |
| 18 |
* @package Packetery\Module\Product |
| 19 |
*/ |
| 20 |
class ProductEntityFactory { |
| 21 |
|
| 22 |
/** |
| 23 |
* WP adapter. |
| 24 |
* |
| 25 |
* @var WcAdapter |
| 26 |
*/ |
| 27 |
private $wcAdapter; |
| 28 |
|
| 29 |
/** |
| 30 |
* Constructor. |
| 31 |
* |
| 32 |
* @param WcAdapter $wcAdapter WC adapter. |
| 33 |
*/ |
| 34 |
public function __construct( WcAdapter $wcAdapter ) { |
| 35 |
$this->wcAdapter = $wcAdapter; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Create instance from post ID. |
| 40 |
* |
| 41 |
* @param int|string $postId Post ID. |
| 42 |
* |
| 43 |
* @return Entity |
| 44 |
* @throws ProductNotFoundException Product not found. |
| 45 |
*/ |
| 46 |
public function fromPostId( $postId ): Entity { |
| 47 |
$product = $this->wcAdapter->getProduct( $postId ); |
| 48 |
if ( ! ( $product instanceof \WC_Product ) ) { |
| 49 |
throw new ProductNotFoundException( "Product $postId not found." ); |
| 50 |
} |
| 51 |
|
| 52 |
return new Entity( $product ); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Creates instance using global variables. |
| 57 |
* |
| 58 |
* @return Entity |
| 59 |
*/ |
| 60 |
public function fromGlobals(): Entity { |
| 61 |
global $post; |
| 62 |
|
| 63 |
return $this->fromPostId( $post->ID ); |
| 64 |
} |
| 65 |
} |
| 66 |
|