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