BaseModelDataProvider.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\DataProviders;
  3. use \ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates;
  4. use \ModulesGarden\ProxmoxAddon\Core\DependencyInjection;
  5. /**
  6. * Description of BaseModelDataProvider
  7. *
  8. * @author Sławomir Miśkowicz <slawomir@modulesgarden.com>
  9. */
  10. class BaseModelDataProvider extends BaseDataProvider
  11. {
  12. protected $model = null;
  13. public function __construct($model)
  14. {
  15. parent::__construct();
  16. $this->setModel($model);
  17. //throw exc
  18. }
  19. protected function setModel($model)
  20. {
  21. if ($this->isModelProper($model))
  22. {
  23. $this->model = DependencyInjection::create($model);
  24. }
  25. return $this;
  26. }
  27. protected function getModel()
  28. {
  29. return $this->model;
  30. }
  31. protected function isModelProper($model)
  32. {
  33. if (in_array(get_parent_class($model), [
  34. 'ModulesGarden\ProxmoxAddon\Core\Models\ExtendedEloquentModel',
  35. 'Illuminate\Database\Eloquent\Model'
  36. ]))
  37. {
  38. return true;
  39. }
  40. return false;
  41. }
  42. public function read()
  43. {
  44. if (!$this->actionElementId)
  45. {
  46. return false;
  47. }
  48. $dbData = $this->model->where('id', $this->actionElementId)->first();
  49. if ($dbData !== null)
  50. {
  51. $this->data = $dbData->toArray();
  52. }
  53. }
  54. public function create()
  55. {
  56. $this->model->fill($this->formData)->save();
  57. }
  58. public function update()
  59. {
  60. $dbData = $this->model->where('id', $this->formData['id'])->first();
  61. if ($dbData === null)
  62. {
  63. return (new ResponseTemplates\HtmlDataJsonResponse())->setMessageAndTranslate('ItemNotFound')->setStatusError()->setCallBackFunction($this->callBackFunction);
  64. ;
  65. }
  66. $dbData->fill($this->formData)->save();
  67. }
  68. public function delete()
  69. {
  70. if (!isset($this->formData['id']))
  71. {
  72. //todo return
  73. }
  74. $this->model->where('id', $this->formData['id'])->delete();
  75. }
  76. }