Completed
Push — master ( e090e4...18d79e )
by Damian
02:26
created

FileAccessibilityAndValidationCheck::getFiles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * Checks for the accessibility and file type validation of one or more files or folders.
5
 *
6
 * Examples:
7
 * // Checks /assets/calculator_files has .json files and all files are valid json files.
8
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/*.json",
9
 *  "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_ALL.')', 'Check a json file exist and are all valid json files'
10
 * );
11
 * 
12
 * // Checks /assets/calculator_files/calculator.json exists and is valid json file.
13
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json",
14
 *  "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_SINGLE.')', 'Check a calculator.json exists and is valid json file'
15
 * );
16
 *
17
 * // Check only existence 
18
 * EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json")',
19
 * 'Check a calculator.json exists only'
20
 * );
21
 */
22
class FileAccessibilityAndValidationCheck implements EnvironmentCheck
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
23
{
24
    /**
25
     * @var int
26
     */
27
    const CHECK_SINGLE = 1;
28
29
    /**
30
     * @var int
31
     */
32
    const CHECK_ALL = 2;
33
34
    /**
35
     * Absolute path to a file or folder, compatible with glob().
36
     *
37
     * @var string
38
     */
39
    protected $path;
40
41
    /**
42
     * Constant, check for a single file to match age criteria, or all of them.
43
     *
44
     * @var int
45
     */
46
    protected $fileTypeValidateFunc;
47
48
    /**
49
     * Constant, check for a single file to match age criteria, or all of them.
50
     *
51
     * @var int
52
     */
53
    protected $checkType;
54
55
    /**
56
     * @param string $path
57
     * @param string $fileTypeValidateFunc
58
     * @param null|int $checkType
59
     */
60
    public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
61
    {
62
        $this->path = $path;
63
        $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...
64
        $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
65
    }
66
67
    /**
68
     * @inheritdoc
69
     *
70
     * @return array
71
     */
72
    public function check()
73
    {
74
        $origStage = Versioned::get_reading_mode();
75
        Versioned::set_reading_mode('Live');
76
77
        $files = $this->getFiles();
78
        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...
79
            $fileTypeValidateFunc = $this->fileTypeValidateFunc;
80
            if (method_exists($this, $fileTypeValidateFunc)) {
81
                $invalidFiles = array();
82
                $validFiles = array();
83
84
                foreach ($files as $file) {
85
                    if ($this->$fileTypeValidateFunc($file)) {
86
                        $validFiles[] = $file;
87
                    } else {
88
                        $invalidFiles[] = $file;
89
                    }
90
                }
91
92
                // If at least one file was valid, count as passed
93
                if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
94
                    $validFileList = "\n";
95
                    foreach ($validFiles as $vf) {
96
                        $validFileList .= $vf."\n";
97
                    }
98 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...
99
                        $checkReturn = array(
100
                            EnvironmentCheck::OK,
101
                            sprintf('At least these file(s) accessible: %s', $validFileList)
102
                        );
103
                    } else {
104
                        $checkReturn = array(
105
                            EnvironmentCheck::OK,
106
                            sprintf('At least these file(s) passed file type validate function "%s": %s', $fileTypeValidateFunc, $validFileList)
107
                        );
108
                    }
109
                } else {
110
                    if (count($invalidFiles) == 0) {
111
                        $checkReturn = array(EnvironmentCheck::OK, 'All files valideted');
112
                    } else {
113
                        $invalidFileList = "\n";
114
                        foreach ($invalidFiles as $vf) {
115
                            $invalidFileList .= $vf."\n";
116
                        }
117
118 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...
119
                            $checkReturn = array(
120
                                EnvironmentCheck::ERROR,
121
                                sprintf('File(s) not accessible: %s', $invalidFileList)
122
                            );
123
                        } else {
124
                            $checkReturn = array(
125
                                EnvironmentCheck::ERROR,
126
                                sprintf('File(s) not passing the file type validate function "%s": %s', $fileTypeValidateFunc, $invalidFileList)
127
                            );
128
                        }
129
                    }
130
                }
131
            } else {
132
                $checkReturn =  array(
133
                    EnvironmentCheck::ERROR,
134
                    sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
135
                );
136
            }
137
        } else {
138
            $checkReturn = array(
139
                EnvironmentCheck::ERROR,
140
                sprintf("No files accessible at path %s", $this->path)
141
            );
142
        }
143
144
        Versioned::set_reading_mode($origStage);
145
146
        return $checkReturn;
147
    }
148
149
    /**
150
     * @param string $file
151
     *
152
     * @return bool
153
     */
154
    private function jsonValidate($file)
155
    {
156
        $json = json_decode(file_get_contents($file));
157
        if (!$json) {
158
            return false;
159
        } else {
160
            return true;
161
        }
162
    }
163
164
    /**
165
     * @param string $file
166
     *
167
     * @return bool
168
     */
169
    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...
170
    {
171
        return true;
172
    }
173
174
    /**
175
     * Gets a list of absolute file paths.
176
     *
177
     * @return array
178
     */
179
    protected function getFiles()
180
    {
181
        return glob($this->path);
182
    }
183
}
184