summaryrefslogtreecommitdiff
path: root/src/Client/Filesystem/CreateFile.php
blob: ce9537f00b7dde5f477b4f1602d3fadd514d2a61 (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
<?php

namespace App\Filesystem;

use App\Task\TaskInterface;

/**
 * Class to create a new file
 *
 * @author Phil Burton <phil@d3r.com>
 */
class CreateFile implements TaskInterface
{
    /**
     * Name of file to create
     *
     * @var string
     */
    protected $filename;

    /**
     * File contents to write
     *
     * @var string
     */
    protected $contents;

    /**
     * Check if the file already exists
     *
     * @param string $filename
     * @author Phil Burton <phil@d3r.com>
     */
    public function __construct(string $filename, $contents = false)
    {
        $this->filename = $filename;

        if ($contents) {
            $this->contents = $contents;
        }

        if (!is_writable(dirname($filename))) {
            throw new \Exception('Cannot create file at: ' . $filename);
        }

        if (file_exists($filename)) {
            throw new \Exception('File already exists at: ' . $filename);
        }
    }

    /**
     * Create the new file
     *
     * @author Phil Burton <phil@d3r.com>
     */
    public function execute()
    {
        touch($this->filename);

        $contents = $this->contents;
        if ($contents) {
            file_put_contents($this->filename, $contents);
        }
    }
}