11<?php
22
3- namespace GM \ ImageFile ;
3+ namespace GM ;
44
55use \Exception ;
6- use \Error ;
76
87class ImageFile {
98
10- private $ base64String ;
11- private $ imageFileString ;
12- private $ defaultPath ;
13- private $ type ;
9+ protected $ base64String ;
10+ protected $ imageFileString ;
11+ protected $ defaultPath ;
12+ protected $ type ;
1413
1514 /**
1615 * ImageFile constructor.
@@ -27,18 +26,18 @@ public function __construct(string $base64String) {
2726 $ content = explode (';base64, ' , $ base64WithoutDataType [1 ]);
2827
2928 if ($ content === false ) {
30- throw new Exception (Error::WRONG_IMAGE_FORMAT );
29+ throw new Exception (Error::WRONG_FORMAT );
3130 }
3231
3332 $ this ->type = $ content [0 ];
3433 $ this ->base64String = $ content [1 ];
3534 $ this ->imageFileString = base64_decode ($ this ->base64String );
3635
3736 if ($ this ->imageFileString === false ) {
38- throw new Exception (Error::WRONG_IMAGE_FORMAT );
37+ throw new Exception (Error::WRONG_FORMAT );
3938 }
4039
41- $ this ->defaultPath = '/images ' ;
40+ $ this ->defaultPath = '' ;
4241 }
4342
4443 /**
@@ -53,12 +52,17 @@ public function getImageString() : string {
5352 /**
5453 * Store the image to the storage given by $path and give him a random name started by $prefix.
5554 *
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: ''
5757 * @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.
5862 * @return null|string
5963 * @throws Exception
6064 */
61- public function store (?string $ path , ?string $ prefix ) : ?string {
65+ public function store (?string $ path = null , ?string $ prefix = null , ? string $ storageUrl = null ) : ?string {
6266
6367 $ fileName = uniqid ($ prefix ?? 'IM ' ) . '. ' . $ this ->type ;
6468 $ fullPath = ($ path ?? $ this ->defaultPath ) . $ fileName ;
@@ -75,15 +79,23 @@ public function store(?string $path, ?string $prefix) : ?string {
7579
7680 fclose ($ fileStream );
7781
82+ if ($ storageUrl ) {
83+ return $ storageUrl . $ fileName ;
84+ }
85+
7886 return $ fullPath ;
7987 }
8088
81- private function validateBase64String (string $ base64String ) : void {
89+ /**
90+ * @param string $base64String
91+ * @throws Exception
92+ */
93+ protected function validateBase64String (string $ base64String ) : void {
8294
8395 if (strpos ($ base64String , 'data:image/ ' ) === false ||
8496 strpos ($ base64String , ';base64, ' ) === false ) {
8597
86- throw new Exception (Error::WRONG_IMAGE_FORMAT );
98+ throw new Exception (Error::WRONG_FORMAT );
8799 }
88100 }
89101
0 commit comments