GetAction.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace common\modules\attachment\actions;
  3. use common\modules\attachment\models\Attachment;
  4. use common\modules\attachment\models\MediaItem;
  5. use Yii;
  6. use yii\base\Action;
  7. use yii\web\Response;
  8. class GetAction extends Action
  9. {
  10. public $userId;
  11. /**
  12. *
  13. * @var int return type (images or files)
  14. */
  15. public $type = MediaItem::FILE_TYPE_IMAGE;
  16. /**
  17. * @inheritdoc
  18. */
  19. public function init()
  20. {
  21. if(!$this->userId) {
  22. $this->userId = \Yii::$app->user->id;
  23. }
  24. }
  25. /**
  26. * @inheritdoc
  27. */
  28. public function run()
  29. {
  30. Yii::$app->response->format = Response::FORMAT_JSON;
  31. $attachments = Attachment::findAll(["user_id" => $this->userId]);
  32. $list = [];
  33. foreach ($attachments as $attachment) {
  34. $mediaItem = MediaItem::createFromAttachment($attachment);
  35. if ($mediaItem->getFileType() === MediaItem::FILE_TYPE_IMAGE) {
  36. $list[] = [
  37. 'title' => $attachment->title,
  38. 'thumb' => $attachment->getUrl() ,
  39. 'image' => $attachment->getUrl() ,
  40. ];
  41. } elseif ($mediaItem->getFileType() === MediaItem::FILE_TYPE_DOCUMENT) {
  42. $list[] = [
  43. 'title' => $attachment->title,
  44. 'name' => $attachment->title,
  45. 'link' =>$attachment->getUrl(),
  46. 'size' => $attachment->size
  47. ];
  48. } else {
  49. $list[] = $url;
  50. }
  51. }
  52. return $list;
  53. }
  54. }