| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Api\Classes; |
| 4 |
|
| 5 |
use FluentSupport\App\Models\Product; |
| 6 |
|
| 7 |
/** |
| 8 |
* Products PHP API. |
| 9 |
* |
| 10 |
* Example Usage: $productApi = FluentSupportApi('products'); |
| 11 |
*/ |
| 12 |
class Products |
| 13 |
{ |
| 14 |
private $instance = null; |
| 15 |
|
| 16 |
private $allowedInstanceMethods = [ |
| 17 |
'all', |
| 18 |
'get', |
| 19 |
'find', |
| 20 |
'first', |
| 21 |
'paginate' |
| 22 |
]; |
| 23 |
|
| 24 |
public function __construct(Product $instance) |
| 25 |
{ |
| 26 |
$this->instance = $instance; |
| 27 |
} |
| 28 |
|
| 29 |
public function getProducts() |
| 30 |
{ |
| 31 |
return Product::paginate(); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @param int $id |
| 36 |
*/ |
| 37 |
public function getProduct(int $id) |
| 38 |
{ |
| 39 |
if (!$id) { |
| 40 |
return; |
| 41 |
} |
| 42 |
|
| 43 |
return Product::findOrFail($id); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @param array $data |
| 48 |
*/ |
| 49 |
public function createProduct(array $data) |
| 50 |
{ |
| 51 |
if (empty($data['title'])) { |
| 52 |
return; |
| 53 |
} |
| 54 |
return Product::create(wp_unslash($data)); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* @param int $id |
| 59 |
* @param array $data |
| 60 |
*/ |
| 61 |
public function updateProduct(int $id, array $data) |
| 62 |
{ |
| 63 |
if (!$id || !$data) { |
| 64 |
return; |
| 65 |
} |
| 66 |
return Product::findOrFail($id)->update($data); |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* @param int $id |
| 71 |
*/ |
| 72 |
public function deleteProduct(int $id) |
| 73 |
{ |
| 74 |
if (!$id) { |
| 75 |
return; |
| 76 |
} |
| 77 |
return Product::findOrFail($id)->delete(); |
| 78 |
} |
| 79 |
|
| 80 |
public function getInstance() |
| 81 |
{ |
| 82 |
return $this->instance; |
| 83 |
} |
| 84 |
|
| 85 |
public function __call($method, $params) |
| 86 |
{ |
| 87 |
if (in_array($method, $this->allowedInstanceMethods)) { |
| 88 |
return call_user_func_array([$this->instance, $method], $params); |
| 89 |
} |
| 90 |
|
| 91 |
throw new \Exception(sprintf('Method %s does not exist.', esc_html($method))); |
| 92 |
} |
| 93 |
} |
| 94 |
|