ResourceTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: perfectmak
  5. * Date: 2/12/16
  6. * Time: 4:01 PM
  7. */
  8. namespace Paystack\Traits;
  9. use Paystack\Interfaces\IRequest;
  10. use Paystack\Interfaces\IResponse;
  11. use Paystack\Paystack;
  12. use Paystack\Request;
  13. trait ResourceTrait
  14. {
  15. protected $_attributes = [];
  16. protected function __construct($params)
  17. {
  18. if(is_array($params))
  19. $this->_attributes = $params;
  20. else{
  21. $this->_attributes = json_decode(json_encode($params), true);
  22. }
  23. }
  24. /**
  25. * @param $url
  26. * @param array $params
  27. * @return static
  28. * @throws \Exception
  29. */
  30. protected static function _create($url, array $params)
  31. {
  32. $response = (new Request())
  33. ->setUrl(Paystack::api($url))
  34. ->setType(IRequest::TYPE_POST)
  35. ->setBody(json_encode($params))
  36. ->send();
  37. if($response->getCode() === IResponse::CODE_VALIDATION_ERROR)
  38. throw new \Exception($response->getBody()->message);
  39. return new static($response->getBody()->data);
  40. }
  41. protected static function _get($url)
  42. {
  43. $response = (new Request())
  44. ->setUrl(Paystack::api($url))
  45. ->setType(IRequest::TYPE_GET)
  46. ->send();
  47. if($response->getCode() === IResponse::CODE_VALIDATION_ERROR)
  48. throw new \Exception($response->getBody()->message);
  49. return new static($response->getBody()->data);
  50. }
  51. public function __get($key)
  52. {
  53. if(array_key_exists($key, $this->_attributes))
  54. {
  55. return $this->_attributes[$key];
  56. }
  57. else
  58. return null;
  59. }
  60. /**
  61. * @param $key
  62. * @param $value
  63. * @todo Should check in a list of properties defined in Resource class
  64. */
  65. public function __set($key, $value)
  66. {
  67. $this->_attributes[$key] = $value;
  68. }
  69. protected static function url($path = ''){
  70. return rtrim(self::$resourceUrl, '/').'/'
  71. .ltrim($path, '/');
  72. }
  73. }