22
33namespace Differ ;
44
5+ use Symfony \Component \Yaml \Yaml ;
6+
57class FileReader implements FileReaderInterface
68{
79 private const MAX_FILE_SIZE = 4096 ;
810 private string $ fileFormat ;
911
12+ private function normalizeFilename (string $ filename )
13+ {
14+ return strtolower ($ filename );
15+ }
16+
1017 public function __construct (string $ fileFormat = 'json ' )
1118 {
1219 $ this ->fileFormat = $ fileFormat ;
@@ -15,14 +22,31 @@ public function __construct(string $fileFormat = 'json')
1522 public function readFile (string $ filename , bool $ isArray = null ): ?array
1623 {
1724 if (file_exists ($ filename )) {
18- $ handle = fopen ($ filename , "r " );
19- $ result = json_decode (fread ($ handle , self ::MAX_FILE_SIZE ), $ isArray );
20- fclose ($ handle );
21- $ type = gettype ($ result );
22- if ($ type === 'object ' ) {
23- return get_object_vars ($ result );
24- } elseif ($ type === 'array ' ) {
25- return $ result ;
25+ $ fileNameParts = explode (". " , $ this ->normalizeFilename ($ filename ));
26+ $ fileFormat = end ($ fileNameParts );
27+ if ($ fileFormat === 'json ' ) {
28+ $ handle = fopen ($ filename , "r " );
29+ $ result = json_decode (fread ($ handle , self ::MAX_FILE_SIZE ), $ isArray );
30+ fclose ($ handle );
31+ $ type = gettype ($ result );
32+ if ($ type === 'object ' ) {
33+ return get_object_vars ($ result );
34+ } elseif ($ type === 'array ' ) {
35+ return $ result ;
36+ }
37+ } else if ($ fileFormat === 'yaml ' || $ fileFormat === 'yml ' ) {
38+ $ handle = fopen ($ filename , "r " );
39+ $ result = Yaml::parse (fread ($ handle , self ::MAX_FILE_SIZE ), Yaml::PARSE_OBJECT_FOR_MAP );
40+ fclose ($ handle );
41+ $ type = gettype ($ result );
42+ if ($ type === 'object ' ) {
43+ return get_object_vars ($ result );
44+ } elseif ($ type === 'array ' ) {
45+ return $ result ;
46+ }
47+ } else {
48+ throw new \Exception ("Unknown files format: \n" .
49+ "use .json, .yaml (.yml) enstead \n" );
2650 }
2751 } else {
2852 return null ;
0 commit comments