Passed
Push — master ( 69774c...de7969 )
by Sebastian
02:46
created

IsEmpty   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 50
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isEmpty() 0 7 2
A execute() 0 23 5
1
<?php
2
3
/**
4
 * This file is part of CaptainHook
5
 *
6
 * (c) Sebastian Feldmann <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CaptainHook\App\Hook\File\Action;
13
14
use CaptainHook\App\Config;
15
use CaptainHook\App\Console\IO;
16
use CaptainHook\App\Exception\ActionFailed;
17
use CaptainHook\App\Hook\Action;
18
use Exception;
19
use SebastianFeldmann\Git\Repository;
20
21
/**
22
 * Class IsEmpty
23
 *
24
 * @package CaptainHook
25
 * @author  Felix Edelmann <[email protected]>
26
 * @link    https://github.com/captainhookphp/captainhook
27
 * @since   Class available since Release 5.4.0
28
 */
29
class IsEmpty implements Action
30
{
31
    /**
32
     * Executes the action
33
     *
34
     * @param  \CaptainHook\App\Config           $config
35
     * @param  \CaptainHook\App\Console\IO       $io
36
     * @param  \SebastianFeldmann\Git\Repository $repository
37
     * @param  \CaptainHook\App\Config\Action    $action
38
     * @return void
39
     * @throws \Exception
40
     */
41
    public function execute(Config $config, IO $io, Repository $repository, Config\Action $action): void
42
    {
43
        $options = $action->getOptions();
44
        $files = $options->get('files');
45
        if ($files === null) {
46
            throw new Exception('Missing option "files" for IsEmpty action');
47
        }
48
49
        $failedFiles = 0;
50
        foreach ($files as $file) {
0 ignored issues
show
Bug introduced by
The expression $files of type string is not traversable.
Loading history...
51
            if (!$this->isEmpty($file)) {
52
                $io->write('- <error>FAIL</error> ' . $file, true);
53
                $failedFiles++;
54
            } else {
55
                $io->write('- <info>OK</info> ' . $file, true, IO::VERBOSE);
56
            }
57
        }
58
59
        if ($failedFiles > 0) {
60
            throw new ActionFailed('<error>Error: ' . $failedFiles . ' non-empty file(s)</error>');
61
        }
62
63
        $io->write('<info>All files are empty or don\'t exist</info>');
64
    }
65
66
    /**
67
     * Returns true when the file is empty or doesn't exist
68
     *
69
     * @param  string $file
70
     * @return bool
71
     */
72
    protected function isEmpty($file): bool
73
    {
74
        if (!file_exists($file)) {
75
            return true;
76
        }
77
78
        return filesize($file) === 0;
79
    }
80
}
81