-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathImageAttachmentAction.php
73 lines (63 loc) · 1.89 KB
/
ImageAttachmentAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace zxbodya\yii2\imageAttachment;
use Yii;
use yii\base\Action;
use yii\db\ActiveRecord;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\web\UploadedFile;
/**
* Action to handle calls from ImageAttachmentWidget,
* and apply changes to model with ImageAttachmentBehavior
*
* @example
*
* public function actions()
* {
* return array(
* 'saveImageAttachment' => 'ext.imageAttachment.ImageAttachmentAction',
* );
* }
*
* @author Bogdan Savluk <[email protected]>
*
*/
class ImageAttachmentAction extends Action
{
/**
* Glue used to implode composite primary keys
* @var string
*/
public $pkGlue = '_';
/**
* @var array Mapping between types and model class names
*/
public $types = [];
public function run($type, $behavior, $id)
{
$remove = Yii::$app->request->post('remove', false);
if (!isset($this->types[$type])) {
throw new BadRequestHttpException('Specified model not found');
}
/** @var ActiveRecord $targetModel */
$pkNames = call_user_func([$this->types[$type], 'primaryKey']);
$pkValues = explode($this->pkGlue, $id);
$pk = array_combine($pkNames, $pkValues);
$targetModel = call_user_func([$this->types[$type], 'findOne'], $pk);
/** @var ImageAttachmentBehavior $behavior */
$behavior = $targetModel->getBehavior($behavior);
if ($remove) {
$behavior->removeImages();
return Json::encode(array());
} else {
/** @var UploadedFile $imageFile */
$imageFile = UploadedFile::getInstanceByName('image');
$behavior->setImage($imageFile->tempName);
return Json::encode(
array(
'previewUrl' => $behavior->getUrl('preview'),
)
);
}
}
}