| 1 |
<?php |
| 2 |
|
| 3 |
namespace Moloni\Controllers; |
| 4 |
|
| 5 |
use Moloni\Curl; |
| 6 |
use Moloni\Exceptions\APIException; |
| 7 |
use Moloni\Exceptions\GenericException; |
| 8 |
|
| 9 |
/** |
| 10 |
* Class Product Category |
| 11 |
* @package Moloni\Controllers |
| 12 |
*/ |
| 13 |
class ProductCategory |
| 14 |
{ |
| 15 |
|
| 16 |
public $name; |
| 17 |
public $category_id; |
| 18 |
public $parent_id = 0; |
| 19 |
|
| 20 |
/** |
| 21 |
* Product Category constructor. |
| 22 |
* @param string $name |
| 23 |
* @param int $parentId |
| 24 |
*/ |
| 25 |
public function __construct($name, $parentId = 0) |
| 26 |
{ |
| 27 |
$this->name = wp_specialchars_decode(trim($name)); |
| 28 |
$this->parent_id = $parentId; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* This method SHOULD be replaced by a productCategories/getBySearch |
| 33 |
* |
| 34 |
* @throws APIException |
| 35 |
*/ |
| 36 |
public function loadByName() |
| 37 |
{ |
| 38 |
$categoriesList = Curl::simple('productCategories/getByName', [ |
| 39 |
'parent_id' => $this->parent_id, |
| 40 |
'name' => $this->name, |
| 41 |
'exact' => 1 |
| 42 |
]); |
| 43 |
|
| 44 |
if (!empty($categoriesList) && is_array($categoriesList)) { |
| 45 |
$this->category_id = $categoriesList[0]['category_id']; |
| 46 |
return $this; |
| 47 |
} |
| 48 |
|
| 49 |
return false; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Create a product based on a WooCommerce Product |
| 54 |
* |
| 55 |
* @return ProductCategory |
| 56 |
* @throws GenericException |
| 57 |
*/ |
| 58 |
public function create(): ProductCategory |
| 59 |
{ |
| 60 |
try { |
| 61 |
$insert = Curl::simple('productCategories/insert', $this->mapPropsToValues()); |
| 62 |
} catch (APIException $e) { |
| 63 |
throw new GenericException(__('Erro ao inserir a categoria') . ' ' . $this->name, $e->getData()); |
| 64 |
} |
| 65 |
|
| 66 |
if (!isset($insert['category_id'])) { |
| 67 |
throw new GenericException(__('Erro ao inserir a categoria') . ' ' . $this->name); |
| 68 |
} |
| 69 |
|
| 70 |
$this->category_id = $insert['category_id']; |
| 71 |
|
| 72 |
return $this; |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
/** |
| 77 |
* Map this object properties to an array to insert/update a moloni product category |
| 78 |
* @return array |
| 79 |
*/ |
| 80 |
private function mapPropsToValues() |
| 81 |
{ |
| 82 |
$values = []; |
| 83 |
|
| 84 |
$values['name'] = $this->name; |
| 85 |
$values['parent_id'] = $this->parent_id; |
| 86 |
|
| 87 |
return $values; |
| 88 |
} |
| 89 |
} |
| 90 |
|