1
1
<?php
2
2
3
- namespace GM \ ImageFile ;
3
+ namespace GM ;
4
4
5
5
use \Exception ;
6
- use \Error ;
7
6
8
7
class ImageFile {
9
8
10
- private $ base64String ;
11
- private $ imageFileString ;
12
- private $ defaultPath ;
13
- private $ type ;
9
+ protected $ base64String ;
10
+ protected $ imageFileString ;
11
+ protected $ defaultPath ;
12
+ protected $ type ;
14
13
15
14
/**
16
15
* ImageFile constructor.
@@ -27,18 +26,18 @@ public function __construct(string $base64String) {
27
26
$ content = explode (';base64, ' , $ base64WithoutDataType [1 ]);
28
27
29
28
if ($ content === false ) {
30
- throw new Exception (Error::WRONG_IMAGE_FORMAT );
29
+ throw new Exception (Error::WRONG_FORMAT );
31
30
}
32
31
33
32
$ this ->type = $ content [0 ];
34
33
$ this ->base64String = $ content [1 ];
35
34
$ this ->imageFileString = base64_decode ($ this ->base64String );
36
35
37
36
if ($ this ->imageFileString === false ) {
38
- throw new Exception (Error::WRONG_IMAGE_FORMAT );
37
+ throw new Exception (Error::WRONG_FORMAT );
39
38
}
40
39
41
- $ this ->defaultPath = '/images ' ;
40
+ $ this ->defaultPath = '' ;
42
41
}
43
42
44
43
/**
@@ -53,12 +52,17 @@ public function getImageString() : string {
53
52
/**
54
53
* Store the image to the storage given by $path and give him a random name started by $prefix.
55
54
*
56
- * @param null|string $path format: 'path/to/the/folder', default path: '/images'
55
+ * @param null|string $path
56
+ * format: 'path/to/my/folder/', default: ''
57
57
* @param null|string $prefix
58
+ * @param null|string $storageUrl
59
+ * format: 'http{s}://mysite.com/storage/'
60
+ * The function returns url to the image if this parameter is set.
61
+ * Otherwise, it returns the full path to the image.
58
62
* @return null|string
59
63
* @throws Exception
60
64
*/
61
- public function store (?string $ path , ?string $ prefix ) : ?string {
65
+ public function store (?string $ path = null , ?string $ prefix = null , ? string $ storageUrl = null ) : ?string {
62
66
63
67
$ fileName = uniqid ($ prefix ?? 'IM ' ) . '. ' . $ this ->type ;
64
68
$ fullPath = ($ path ?? $ this ->defaultPath ) . $ fileName ;
@@ -75,15 +79,23 @@ public function store(?string $path, ?string $prefix) : ?string {
75
79
76
80
fclose ($ fileStream );
77
81
82
+ if ($ storageUrl ) {
83
+ return $ storageUrl . $ fileName ;
84
+ }
85
+
78
86
return $ fullPath ;
79
87
}
80
88
81
- private function validateBase64String (string $ base64String ) : void {
89
+ /**
90
+ * @param string $base64String
91
+ * @throws Exception
92
+ */
93
+ protected function validateBase64String (string $ base64String ) : void {
82
94
83
95
if (strpos ($ base64String , 'data:image/ ' ) === false ||
84
96
strpos ($ base64String , ';base64, ' ) === false ) {
85
97
86
- throw new Exception (Error::WRONG_IMAGE_FORMAT );
98
+ throw new Exception (Error::WRONG_FORMAT );
87
99
}
88
100
}
89
101
0 commit comments