summaryrefslogtreecommitdiffstats
path: root/source/File.php
blob: 076592ca49345811868ffd10bbdfe209a4a6b308 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
/**
 * @author stev leibelt <artodeto@bazzline.net>
 * @since 2014-08-13 
 */

/**
 * Class File
 */
class File
{
    /**
     * @var string
     */
    private $path;

    /**
     * @param null|string $path
     */
    public function __construct($path = null)
    {
        if (!is_null($path)) {
            $this->setPath($path);
        }
    }

    /**
     * @param string|array $content
     * @throws Exception
     */
    public function append($content)
    {
        if (is_array($content)) {
            $content = implode(PHP_EOL, $content);
        } else {
            $content .= PHP_EOL;
        }

        $numberOfBytes = file_put_contents($this->getPath(), $content, FILE_APPEND);

        if ($numberOfBytes === false) {
            throw new Exception(
                'can not append content to file "' . $this->getPath() . '"'
            );
        }
    }

    /**
     * @param string $path
     * @throws Exception
     */
    public function copy($path)
    {
        $couldBeCopied = copy($this->getPath(), $path);

        if ($couldBeCopied === false) {
            throw new Exception(
                'could not copy file from path "' . $this->getPath() . '" to "' . $path . '"'
            );
        }
    }

    /**
     * @return bool
     * @throws Exception
     */
    public function exists()
    {
        return (is_file($this->getPath()));
    }

    /**
     * @return string
     * @throws Exception
     */
    public function getPath()
    {
        if (is_null($this->path)) {
            throw new Exception(
                'no path set'
            );
        }

        return $this->path;
    }

    /**
     * @return array
     * @throws Exception
     */
    public function read()
    {
        return explode("\n", file_get_contents($this->getPath()));
    }

    /**
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = (string) $path;
    }

    /**
     * @param string|array $content
     * @throws Exception
     */
    public function write($content)
    {
        if (is_array($content)) {
            $content = implode("\n", $content);
        }

        $numberOfBytes = file_put_contents($this->getPath(), $content);

        if ($numberOfBytes === false) {
            throw new Exception(
                'can not append content to file "' . $this->getPath() . '"'
            );
        }
    }
}