44
55use Rcsofttech85 \FileHandler \DependencyInjection \ServiceContainer ;
66use Rcsofttech85 \FileHandler \Exception \FileHandlerException ;
7+ use Symfony \Component \DependencyInjection \ContainerBuilder ;
78
89trait FileValidatorTrait
910{
@@ -30,10 +31,6 @@ public function validateFileName(string $filename, string|null $path = null): st
3031 $ filename = $ absolutePath . DIRECTORY_SEPARATOR . $ filename ;
3132 }
3233
33-
34- if (!file_exists ($ filename )) {
35- throw new FileHandlerException ('file not found ' );
36- }
3734 return $ filename ;
3835 }
3936
@@ -51,44 +48,72 @@ public function sanitize(string $filename): string
5148 }
5249
5350 /**
51+ * @param string $filename
52+ * @param string $envVariable
53+ * @return bool
5454 * @throws FileHandlerException
5555 */
5656 private function isFileSafe (string $ filename , string $ envVariable ): bool
5757 {
5858 $ safeFile = $ this ->getParameter ($ envVariable );
5959
60+
6061 if ($ safeFile !== $ filename ) {
6162 return false ;
6263 }
63- if (!file_exists ($ safeFile )) {
64- throw new FileHandlerException ('env variable does not contain a valid file path ' );
65- }
66-
6764
6865 return true ;
6966 }
7067
7168 /**
72- * @throws FileHandlerException
69+ * @param string $filename
70+ * @param string $envVariable
71+ * @return bool
7372 */
7473 public function isFileRestricted (string $ filename , string $ envVariable ): bool
7574 {
7675 return $ this ->isFileSafe ($ filename , $ envVariable );
7776 }
7877
7978 /**
79+ * @param string $param
80+ * @return string
8081 * @throws FileHandlerException
8182 */
8283 private function getParameter (string $ param ): string
8384 {
8485 $ container = (new ServiceContainer ())->getContainerBuilder ();
86+ return $ this ->getParam ($ container , $ param );
87+ }
8588
86- $ parameter = $ container ->getParameter ($ param );
87-
88- if (!is_string ($ parameter )) {
89- throw new FileHandlerException ("{$ param } is expected to be string " );
89+ /**
90+ * @param ContainerBuilder $container
91+ * @param string $parameter
92+ * @return string
93+ * @throws FileHandlerException
94+ */
95+ public function getParam (ContainerBuilder $ container , string $ parameter ): string
96+ {
97+ $ param = $ container ->getParameter ($ parameter );
98+ if (!is_string ($ param )) {
99+ throw new FileHandlerException ("{$ parameter } is not string type " );
90100 }
91101
92- return $ parameter ;
102+ return $ param ;
103+ }
104+
105+ /**
106+ * @param string $filename
107+ * @param string $mode
108+ * @return mixed
109+ * @throws FileHandlerException
110+ */
111+ public function openFileAndReturnResource (string $ filename , string $ mode = 'w ' ): mixed
112+ {
113+ $ file = fopen ($ filename , $ mode );
114+ if (!$ file ) {
115+ throw new FileHandlerException ('file is not valid ' );
116+ }
117+ return $ file ;
93118 }
94119}
0 commit comments