Completed
Pull Request — master (#3)
by Harry
07:29
created

FileNode::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * This file is part of graze/data-file
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/data-file/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/data-file
12
 */
13
14
namespace Graze\DataFile\Node;
15
16
use Graze\DataFile\Format\FormatAwareInterface;
17 14
use Graze\DataFile\Format\FormatAwareTrait;
18
use Graze\DataFile\Modify\Exception\CopyFailedException;
19 14
use League\Flysystem\File;
20
21
class FileNode extends File implements FileNodeInterface, FormatAwareInterface
22
{
23
    use FormatAwareTrait;
24
25 10
    /**
26
     * @return string
27 10
     */
28
    public function __toString()
29
    {
30
        return $this->getPath();
31
    }
32
33 18
    /**
34
     * @return mixed
35 18
     */
36
    public function getDirectory()
37
    {
38
        return pathinfo($this->path, PATHINFO_DIRNAME) . '/';
39
    }
40
41
    /**
42
     * @return string
43 21
     */
44
    public function getFilename()
45 21
    {
46 19
        return pathinfo($this->path, PATHINFO_BASENAME);
47
    }
48 2
49
    /**
50
     * Returns the contents of the file as an array.
51
     *
52
     * @return array
53
     */
54
    public function getContents()
55
    {
56
        if ($this->exists()) {
57
            return explode("\n", trim($this->read()));
58 4
        } else {
59
            return [];
60 4
        }
61 1
    }
62 1
63
    /**
64 4
     * @param string|null $newPath
65 3
     *
66
     * @return static
67 1
     * @throws CopyFailedException When it is unable to copy the file
68 1
     */
69
    public function copy($newPath = null)
70
    {
71
        if (is_null($newPath)) {
72
            $newPath = $this->path . '-copy';
73
        }
74
75
        if (@$this->filesystem->copy($this->path, $newPath)) {
76
            return $this->getClone()->setPath($newPath);
77 55
        } else {
78
            $lastError = error_get_last();
79 55
            throw new CopyFailedException($this, $newPath, $lastError['message']);
80
        }
81
    }
82
83
    /**
84
     * Return a clone of this object
85 55
     *
86
     * @return static
87 55
     */
88 1
    public function getClone()
89 1
    {
90 55
        return clone $this;
91
    }
92
93
    /**
94
     * Clone sub objects
95
     */
96
    public function __clone()
97
    {
98
        if ($this->format) {
99
            $this->format = clone $this->format;
100
        }
101
    }
102
}
103