-
Notifications
You must be signed in to change notification settings - Fork 0
/
StorageFileValidatorTrait.php
107 lines (79 loc) · 2.15 KB
/
StorageFileValidatorTrait.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace denis909\yii;
use Yii;
use yii\web\UploadedFile;
trait StorageFileValidatorTrait
{
protected function preparePath($path)
{
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
$path = ltrim($path, '/');
if ($path)
{
$path = '/' . $path;
}
return $path;
}
/**
* @return yii\web\UploadedFile
*/
public function createUploadedFile(array $value) : ?UploadedFile
{
$path = realpath(Yii::getAlias('@storage/web') . '/source' . $this->preparePath($value['path']));
if (!$path)
{
return null;
}
$file = new UploadedFile;
$file->name = $value['name'];
$file->tempName = $path;
if (!$file->name)
{
$file->name = pathinfo($file->tempName, PATHINFO_BASENAME);
}
$file->type = $value['type'];
$file->size = $value['size'];
return $file;
}
/**
* {@inheritdoc}
*/
protected function validateValue($value)
{
if (is_array($value))
{
$value = $this->createUploadedFile($value);
return parent::validateValue($value);
}
return parent::validateValue($value);
}
/**
* {@inheritdoc}
*/
public function isEmpty($value, $trim = false)
{
if (is_array($value))
{
return $value ? false : true;
}
return parent::isEmpty($value, $trim);
}
/**
* {@inheritdoc}
*/
public function validateAttribute($model, $attribute)
{
$currentValue = $model->$attribute;
if ($this->maxFiles != 1 || $this->minFiles > 1)
{
$rawFiles = $model->$attribute;
foreach($rawFiles as $key => $value)
{
$model->$attribute[$key] = $this->createUploadedFile($value);
}
}
$return = parent::validateAttribute($model, $attribute);
$model->$attribute = $currentValue;
return $return;
}
}