9
9
10
10
namespace Tinywan \Storage \Adapter ;
11
11
12
+ use Tinywan \Storage \Exception \StorageException ;
13
+
12
14
class LocalAdapter extends AdapterAbstract
13
15
{
14
16
/**
@@ -20,19 +22,28 @@ public function uploadFile(array $options = []): array
20
22
{
21
23
$ result = [];
22
24
$ config = config ('plugin.tinywan.storage.app.storage.local ' );
23
- if (is_callable ($ config ['root ' ])) {
24
- $ config ['root ' ] = (string ) $ config ['root ' ]();
25
+ $ dirname = $ config ['dirname ' ];
26
+ if (is_callable ($ dirname )) {
27
+ $ dirname = (string ) $ dirname () ?: '' ;
28
+ }
29
+ if (!empty ($ dirname )){
30
+ $ dirname = DIRECTORY_SEPARATOR .ltrim ($ dirname , DIRECTORY_SEPARATOR ); // 避免没有加前置 “/”
31
+ }
32
+ $ basePath = $ config ['root ' ].$ dirname .DIRECTORY_SEPARATOR ;
33
+ if (!$ this ->createDir ($ basePath )) {
34
+ throw new StorageException ('文件夹创建失败,请核查是否有对应权限。 ' );
25
35
}
36
+ $ baseUrl = $ config ['domain ' ].$ config ['uri ' ].str_replace (DIRECTORY_SEPARATOR , '/ ' , $ dirname ).'/ ' ;
26
37
foreach ($ this ->files as $ key => $ file ) {
27
38
$ uniqueId = hash_file ('sha1 ' , $ file ->getPathname ());
28
39
$ saveFilename = $ uniqueId .'. ' .$ file ->getUploadExtension ();
29
- $ savePath = $ config [ ' root ' ]. $ this -> dirSeparator .$ saveFilename ;
40
+ $ savePath = $ basePath .$ saveFilename ;
30
41
$ temp = [
31
42
'key ' => $ key ,
32
43
'origin_name ' => $ file ->getUploadName (),
33
44
'save_name ' => $ saveFilename ,
34
45
'save_path ' => $ savePath ,
35
- 'url ' => $ config [ ' domain ' ]. $ config [ ' dirname ' ]. $ this -> dirSeparator .$ saveFilename ,
46
+ 'url ' => $ baseUrl .$ saveFilename ,
36
47
'unique_id ' => $ uniqueId ,
37
48
'size ' => $ file ->getSize (),
38
49
'mime_type ' => $ file ->getUploadMineType (),
@@ -44,4 +55,25 @@ public function uploadFile(array $options = []): array
44
55
45
56
return $ result ;
46
57
}
58
+
59
+
60
+ protected function createDir (string $ path ): bool
61
+ {
62
+ // 判断传过来的$path是否已是目录,若是,则直接返回true
63
+ if (is_dir ($ path )) {
64
+ return true ;
65
+ }
66
+
67
+ // 走到这步,说明传过来的$path不是目录
68
+ // 判断其上级是否为目录,是,则直接创建$path目录
69
+ if (is_dir (dirname ($ path ))) {
70
+ return mkdir ($ path );
71
+ }
72
+
73
+ // 走到这说明其上级目录也不是目录,则继续判断其上上...级目录
74
+ $ this ->createDir (dirname ($ path ));
75
+
76
+ // 走到这步,说明上级目录已创建成功,则直接接着创建当前目录,并把创建的结果返回
77
+ return mkdir ($ path );
78
+ }
47
79
}
0 commit comments