1<?php
2
3
4namespace ComboStrap;
5
6
7use DateTime;
8
9class LocalFs implements FileSystem
10{
11
12    // same as java
13    public const SCHEME = "file";
14
15    /**
16     * @var LocalFs
17     */
18    private static $localFs;
19
20    public static function getOrCreate(): LocalFs
21    {
22        if(self::$localFs === null){
23            self::$localFs = new LocalFs();
24        }
25        return self::$localFs;
26    }
27
28    function exists(Path $path): bool
29    {
30        return file_exists($path->toAbsolutePath()->toString());
31    }
32
33    /**
34     * @return string
35     */
36    public function getContent($path): ?string
37    {
38        $mime = $path->getMime();
39        if($mime === null){
40            throw new ExceptionComboRuntime("The mime is unknown for the path ($path)");
41        }
42        if ($mime->isTextBased()) {
43            $content = @file_get_contents($path->toAbsolutePath()->toString());
44            if($content===false){
45                // file does not exists
46                return null;
47            }
48            return $content;
49        }
50        throw new ExceptionComboRuntime("This mime content ($mime) can not yet be retrieved for the path ($path)");
51    }
52
53    public function getModifiedTime($path): ?DateTime
54    {
55        if(!self::exists($path)){
56            return null;
57        }
58        return Iso8601Date::createFromTimestamp(filemtime($path->toAbsolutePath()->toString()))->getDateTime();
59    }
60
61    public function getCreationTime(Path $path)
62    {
63        if(!$this->exists($path)){
64            return null;
65        }
66        $filePath = $path->toAbsolutePath()->toString();
67        $timestamp = filectime($filePath);
68        return Iso8601Date::createFromTimestamp($timestamp)->getDateTime();
69    }
70
71    public function delete(Path $path)
72    {
73        unlink($path->toAbsolutePath()->toString());
74    }
75
76    /**
77     * @return false|int
78     */
79    public function getSize($path)
80    {
81        return filesize($path->toAbsolutePath()->toString());
82    }
83
84    /**
85     * @throws ExceptionCombo
86     */
87    public function createDirectory(Path $dirPath)
88    {
89        $result = mkdir($dirPath->toAbsolutePath()->toString(), $mode = 0770, $recursive = true);
90        if($result===false){
91            throw new ExceptionCombo("Unable to create the directory path ($dirPath)");
92        }
93    }
94
95}
96