Completed
Branch master (9dcfc4)
by Daniel
24:32
created

FileAccessibilityAndValidationCheck::check()   C

Complexity

Conditions 12
Paths 7

Size

Total Lines 84
Code Lines 57

Duplication

Lines 30
Ratio 35.71 %

Importance

Changes 0
Metric Value
dl 30
loc 84
rs 5.034
c 0
b 0
f 0
cc 12
eloc 57
nc 7
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\EnvironmentCheck\Checks;
4
5
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
6
use SilverStripe\ORM\Versioning\Versioned;
7
8
/**
9
 * Checks for the accessibility and file type validation of one or more files or folders.
10
 *
11
 * Examples:
12
 * // Checks /assets/calculator_files has .json files and all files are valid json files.
13
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/*.json",
14
 *  "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_ALL.')', 'Check a json file exist and are all valid json files'
15
 * );
16
 *
17
 * // Checks /assets/calculator_files/calculator.json exists and is valid json file.
18
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json",
19
 *  "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_SINGLE.')', 'Check a calculator.json exists and is valid json file'
20
 * );
21
 *
22
 * // Check only existence
23
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json")',
24
 * 'Check a calculator.json exists only'
25
 * );
26
 *
27
 * @package environmentcheck
28
 */
29
class FileAccessibilityAndValidationCheck implements EnvironmentCheck
30
{
31
    /**
32
     * @var int
33
     */
34
    const CHECK_SINGLE = 1;
35
36
    /**
37
     * @var int
38
     */
39
    const CHECK_ALL = 2;
40
41
    /**
42
     * Absolute path to a file or folder, compatible with glob().
43
     *
44
     * @var string
45
     */
46
    protected $path;
47
48
    /**
49
     * Constant, check for a single file to match age criteria, or all of them.
50
     *
51
     * @var int
52
     */
53
    protected $fileTypeValidateFunc;
54
55
    /**
56
     * Constant, check for a single file to match age criteria, or all of them.
57
     *
58
     * @var int
59
     */
60
    protected $checkType;
61
62
    /**
63
     * @param string $path
64
     * @param string $fileTypeValidateFunc
65
     * @param null|int $checkType
66
     */
67
    public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
68
    {
69
        $this->path = $path;
70
        $this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation';
0 ignored issues
show
Documentation Bug introduced by
The property $fileTypeValidateFunc was declared of type integer, but $fileTypeValidateFunc ? ...dateFunc : 'noVidation' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
71
        $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
72
    }
73
74
    /**
75
     * {@inheritDoc}
76
     *
77
     * @return array
78
     */
79
    public function check()
80
    {
81
        $origStage = Versioned::get_reading_mode();
82
        Versioned::set_reading_mode(Versioned::LIVE);
83
84
        $files = $this->getFiles();
85
        if ($files) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $files of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
86
            $fileTypeValidateFunc = $this->fileTypeValidateFunc;
87
            if (method_exists($this, $fileTypeValidateFunc)) {
88
                $invalidFiles = [];
89
                $validFiles = [];
90
91
                foreach ($files as $file) {
92
                    if ($this->$fileTypeValidateFunc($file)) {
93
                        $validFiles[] = $file;
94
                    } else {
95
                        $invalidFiles[] = $file;
96
                    }
97
                }
98
99
                // If at least one file was valid, count as passed
100
                if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
101
                    $validFileList = PHP_EOL;
102
                    foreach ($validFiles as $vf) {
103
                        $validFileList .= $vf . PHP_EOL;
104
                    }
105 View Code Duplication
                    if ($fileTypeValidateFunc == 'noVidation') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
106
                        $checkReturn = [
107
                            EnvironmentCheck::OK,
108
                            sprintf('At least these file(s) accessible: %s', $validFileList)
109
                        ];
110
                    } else {
111
                        $checkReturn = [
112
                            EnvironmentCheck::OK,
113
                            sprintf(
114
                                'At least these file(s) passed file type validate function "%s": %s',
115
                                $fileTypeValidateFunc,
116
                                $validFileList
117
                            )
118
                        ];
119
                    }
120
                } else {
121
                    if (count($invalidFiles) == 0) {
122
                        $checkReturn = [EnvironmentCheck::OK, 'All files valideted'];
123
                    } else {
124
                        $invalidFileList = PHP_EOL;
125
                        foreach ($invalidFiles as $vf) {
126
                            $invalidFileList .= $vf . PHP_EOL;
127
                        }
128
129 View Code Duplication
                        if ($fileTypeValidateFunc == 'noVidation') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
130
                            $checkReturn = [
131
                                EnvironmentCheck::ERROR,
132
                                sprintf('File(s) not accessible: %s', $invalidFileList)
133
                            ];
134
                        } else {
135
                            $checkReturn = [
136
                                EnvironmentCheck::ERROR,
137
                                sprintf(
138
                                    'File(s) not passing the file type validate function "%s": %s',
139
                                    $fileTypeValidateFunc,
140
                                    $invalidFileList
141
                                )
142
                            ];
143
                        }
144
                    }
145
                }
146
            } else {
147
                $checkReturn =  array(
148
                    EnvironmentCheck::ERROR,
149
                    sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
150
                );
151
            }
152
        } else {
153
            $checkReturn = array(
154
                EnvironmentCheck::ERROR,
155
                sprintf("No files accessible at path %s", $this->path)
156
            );
157
        }
158
159
        Versioned::set_reading_mode($origStage);
160
161
        return $checkReturn;
162
    }
163
164
    /**
165
     * @param string $file
166
     *
167
     * @return bool
168
     */
169
    private function jsonValidate($file)
170
    {
171
        $json = json_decode(file_get_contents($file));
172
        if (!$json) {
173
            return false;
174
        }
175
        return true;
176
    }
177
178
    /**
179
     * @param string $file
180
     *
181
     * @return bool
182
     */
183
    protected function noVidation($file)
0 ignored issues
show
Unused Code introduced by
The parameter $file is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
184
    {
185
        return true;
186
    }
187
188
    /**
189
     * Gets a list of absolute file paths.
190
     *
191
     * @return array
192
     */
193
    protected function getFiles()
194
    {
195
        return glob($this->path);
196
    }
197
}
198