Completed
Pull Request — master (#146)
by Hannes
02:12
created

Filesystem::readFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of byrokrat\giroapp.
4
 *
5
 * byrokrat\giroapp is free software: you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * byrokrat\giroapp is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with byrokrat\giroapp. If not, see <http://www.gnu.org/licenses/>.
17
 *
18
 * Copyright 2016-17 Hannes Forsgård
19
 */
20
21
declare(strict_types = 1);
22
23
namespace byrokrat\giroapp\Utils;
24
25
use byrokrat\giroapp\Exception\UnableToReadFileException;
26
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
27
28
/**
29
 * Wrapper class to access to file system
30
 */
31
class Filesystem
32
{
33
    /**
34
     * @var string
35
     */
36
    private $basePath;
37
38
    /**
39
     * @var SymfonyFilesystem
40
     */
41
    private $fs;
42
43
    public function __construct(string $basePath, SymfonyFilesystem $fs)
44
    {
45
        $this->basePath = $basePath;
46
        $this->fs = $fs;
47
    }
48
49
    public function getAbsolutePath(string $path): string
50
    {
51
        return $this->fs->isAbsolutePath($path) ? $path : $this->basePath . DIRECTORY_SEPARATOR . $path;
52
    }
53
54
    public function exists(string $path): bool
55
    {
56
        return $this->fs->exists($this->getAbsolutePath($path));
57
    }
58
59
    public function isFile(string $path): bool
60
    {
61
        $path = $this->getAbsolutePath($path);
62
        return $this->fs->exists($path) && is_file($path) && is_readable($path);
63
    }
64
65
    /**
66
     * @throws UnableToReadFileException if file does not exist
67
     */
68
    public function readFile(string $path): File
69
    {
70
        if (!$this->isFile($path)) {
71
            throw new UnableToReadFileException("Unable to read {$path}");
72
        }
73
74
        return new File(
75
            $path,
76
            (string)file_get_contents($this->getAbsolutePath($path))
77
        );
78
    }
79
80
    public function dumpFile(string $path, string $content): void
81
    {
82
        $this->fs->dumpFile($this->getAbsolutePath($path), $content);
83
    }
84
}
85