Completed
Push — master ( 6a1fad...afb84c )
by Sebastian
05:39
created

Tar::validatePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
crap 6
1
<?php
2
namespace phpbu\App\Backup\Source;
3
4
use phpbu\App\Backup\Target;
5
use phpbu\App\Cli\Executable;
6
use phpbu\App\Cli\Result as CliResult;
7
use phpbu\App\Exception;
8
use phpbu\App\Result;
9
use phpbu\App\Util;
10
11
/**
12
 * Tar source class.
13
 *
14
 * @package    phpbu
15
 * @subpackage Backup
16
 * @author     Sebastian Feldmann <[email protected]>
17
 * @copyright  Sebastian Feldmann <[email protected]>
18
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
19
 * @link       http://phpbu.de/
20
 * @since      Class available since Release 1.0.0
21
 */
22
class Tar extends SimulatorExecutable implements Simulator
23
{
24
    /**
25
     * Tar Executable
26
     *
27
     * @var \phpbu\App\Cli\Executable\Tar
28
     */
29
    protected $executable;
30
31
    /**
32
     * Path to executable.
33
     *
34
     * @var string
35
     */
36
    private $pathToTar;
37
38
    /**
39
     * Path to backup
40
     *
41
     * @var string
42
     */
43
    private $path;
44
45
    /**
46
     * Tar should ignore failed reads
47
     * --ignore-failed-read
48
     *
49
     * @var boolean
50
     */
51
    private $ignoreFailedRead;
52
53
    /**
54
     * Remove the packed data
55
     *
56
     * @var boolean
57
     */
58
    private $removeSourceDir;
59
60
    /**
61
     * Compression to use.
62
     *
63
     * @var string
64
     */
65
    private $compression = '';
66
67
    /**
68
     * Path where to store the archive.
69
     *
70
     * @var string
71
     */
72
    private $pathToArchive;
73
74
    /**
75
     * Setup.
76
     *
77
     * @see    \phpbu\App\Backup\Source
78
     * @param  array $conf
79
     * @throws \phpbu\App\Exception
80
     */
81 7
    public function setup(array $conf = [])
82
    {
83 7
        $this->pathToTar        = Util\Arr::getValue($conf, 'pathToTar', '');
84 7
        $this->path             = Util\Arr::getValue($conf, 'path', '');
85 7
        $this->ignoreFailedRead = Util\Str::toBoolean(Util\Arr::getValue($conf, 'ignoreFailedRead', ''), false);
86 7
        $this->removeSourceDir  = Util\Str::toBoolean(Util\Arr::getValue($conf, 'removeSourceDir', ''), false);
87
88 7
        if (empty($this->path)) {
89 1
            throw new Exception('path option is mandatory');
90
        }
91 6
    }
92
93
    /**
94
     * Execute the backup.
95
     *
96
     * @see    \phpbu\App\Backup\Source
97
     * @param  \phpbu\App\Backup\Target $target
98
     * @param  \phpbu\App\Result        $result
99
     * @return \phpbu\App\Backup\Source\Status
100
     * @throws \phpbu\App\Exception
101
     */
102 3 View Code Duplication
    public function backup(Target $target, Result $result) : Status
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
    {
104
        // make sure source path is a directory
105 3
        $this->validatePath();
106 3
        // set uncompressed default MIME type
107 3
        $target->setMimeType('application/x-tar');
108
        $tar = $this->execute($target);
109
110 3
        $result->debug($tar->getCmdPrintable());
111 1
112 1
        if ($this->tarFailed($tar)) {
113
            throw new Exception('tar failed: ' . $tar->getStdErr());
114 3
        }
115
116 3
        return $this->createStatus($target);
117 1
    }
118
119
    /**
120 2
     * Check if tar failed.
121
     *
122
     * @param  \phpbu\App\Cli\Result
123
     * @return bool
124
     */
125
    public function tarFailed(CliResult $tar) : bool
126
    {
127
        $ignoreFail = $this->ignoreFailedRead && $tar->getCode() == 1;
0 ignored issues
show
Bug introduced by
The method getCode() does not seem to exist on object<phpbu\App\Cli\Result>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
128
        return !$tar->isSuccessful() && !$ignoreFail;
129 6
    }
130
131 6
    /**
132
     * Setup the Executable to run the 'tar' command.
133 3
     *
134 2
     * @param  \phpbu\App\Backup\Target
135 1
     * @return \phpbu\App\Cli\Executable
136 1
     */
137
    protected function createExecutable(Target $target) : Executable
138 1
    {
139 1
        // check if tar supports requested compression
140
        if ($target->shouldBeCompressed()) {
141 2
            if (!Executable\Tar::isCompressionValid($target->getCompression()->getCommand())) {
142
                $this->pathToArchive = $target->getPathnamePlain();
143 1
            } else {
144
                // compression could be handled by the tar command
145 3
                $this->pathToArchive = $target->getPathname();
146 3
                $this->compression   = $target->getCompression()->getCommand();
147 3
            }
148 3
        } else {
149 3
            // no compression at all
150 3
            $this->pathToArchive = $target->getPathname();
151 6
        }
152
153
        $executable = new Executable\Tar($this->pathToTar);
154
        $executable->archiveDirectory($this->path)
155
                   ->useCompression($this->compression)
156
                   ->ignoreFailedRead($this->ignoreFailedRead)
157
                   ->removeSourceDirectory($this->removeSourceDir)
158
                   ->archiveTo($this->pathToArchive);
159
        return $executable;
160
    }
161
162
    /**
163
     * Check the source to compress.
164
     *
165
     * @throws \phpbu\App\Exception
166
     */
167
    private function validatePath()
168
    {
169
        if (!is_dir($this->path)) {
170
            throw new Exception('path to compress has to be a directory');
171
        }
172
    }
173
174
    /**
175
     * Create backup status.
176
     *
177
     * @param  \phpbu\App\Backup\Target
178
     * @return \phpbu\App\Backup\Source\Status
179
     */
180
    protected function createStatus(Target $target) : Status
181
    {
182
        $status = Status::create();
183
        // if tar doesn't handle the compression mark status uncompressed so the app can take care of compression
184
        if (!$this->getExecutable($target)->handlesCompression()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface phpbu\App\Cli\Executable as the method handlesCompression() does only exist in the following implementations of said interface: phpbu\App\Cli\Executable\Tar.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
185
            $status->uncompressedFile($target->getPathnamePlain());
186
        }
187
        return $status;
188
    }
189
}
190