Completed
Pull Request — master (#3)
by Harry
05:31
created

FileProcessTrait::processFile()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 8.8571
cc 5
eloc 13
nc 3
nop 4
crap 5
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\Modify;
15
16
use Graze\DataFile\Helper\Process\ProcessTrait;
17
use Graze\DataFile\Node\LocalFileNodeInterface;
18
use Psr\Log\LogLevel;
19
use Symfony\Component\Process\Exception\ProcessFailedException;
20
21
trait FileProcessTrait
22
{
23
    use ProcessTrait;
24
25
    /**
26
     * @param LocalFileNodeInterface $file
27
     * @param LocalFileNodeInterface $output
28
     * @param string                 $cmd
29
     * @param bool                   $deleteOld
30
     *
31
     * @return LocalFileNodeInterface
32
     */
33 52
    protected function processFile(
34
        LocalFileNodeInterface $file,
35
        LocalFileNodeInterface $output,
36
        $cmd,
37
        $deleteOld = true
38
    ) {
39 52
        $process = $this->getProcess($cmd);
40 52
        $process->run();
41
42 52
        if (!$process->isSuccessful() || !$output->exists()) {
43 8
            throw new ProcessFailedException($process);
44
        }
45
46 44
        if ($file->exists() && !$deleteOld) {
47 9
            $this->log(LogLevel::DEBUG, "Deleting old file: '{file}'", ['file' => $file]);
48 9
            $file->delete();
49 9
        }
50
51 44
        return $output;
52
    }
53
54
    /**
55
     * Create a target file from a source file and postfix
56
     *
57
     * @param LocalFileNodeInterface $file
58
     * @param string                 $postfix
59
     *
60
     * @return LocalFileNodeInterface
61
     */
62 34
    protected function getTargetFile(LocalFileNodeInterface $file, $postfix)
63
    {
64 34
        if (strlen($postfix) > 0) {
65 31
            $postfix = '-' . $postfix;
66 31
        }
67
68 34
        $pathInfo = pathinfo($file->getPath());
69 34
        $extension = isset($pathInfo['extension']) ? '.' . $pathInfo['extension'] : '';
70
71 34
        $path = sprintf('%s/%s%s%s', $pathInfo['dirname'], $pathInfo['filename'], $postfix, $extension);
72
73 34
        return $file->getClone()
74 34
                    ->setPath($path);
75
    }
76
}
77