Completed
Pull Request — master (#29)
by satoru
02:06
created

ContentsFileValidation::checkExtension()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 8.8571
cc 5
eloc 9
nc 4
nop 2
1
<?php
2
3
namespace ContentsFile\Validation;
4
5
use Cake\Validation\Validation;
6
7
class ContentsFileValidation extends Validation
8
{
9
    /**
10
     * checkMaxSize
11
     *
12
     */
13
    public static function checkMaxSize($value, $max, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context 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...
14
    {
15
        $maxValue = self::calcFileSizeUnit($max);
16
        return $maxValue >= $value['size'];
17
    }
18
19
    /**
20
     * uploadMaxSizeCheck
21
     *
22
     */
23
    public static function uploadMaxSizeCheck($value, $context)
0 ignored issues
show
Unused Code introduced by
The parameter $context 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...
24
    {
25
        return $value['error'] != UPLOAD_ERR_INI_SIZE;
26
    }
27
28
    /**
29
     * Calculate file size by unit
30
     *
31
     * e.g.) 100KB -> 1024000
32
     *
33
     * @param $size mixed
34
     * @return int file size
35
     */
36
    private static function calcFileSizeUnit($size)
37
    {
38
        $units = ['K', 'M', 'G', 'T'];
39
        $byte = 1024;
40
41
        if (is_numeric($size) || is_int($size)) {
42
            return $size;
43
        } else if (is_string($size) && preg_match('/^([0-9]+(?:\.[0-9]+)?)(' . implode('|', $units) . ')B?$/i', $size, $matches)) {
44
            return $matches[1] * pow($byte, array_search($matches[2], $units) + 1);
45
        }
46
        return false;
47
    }
48
49
    /**
50
     * checkExtension
51
     * 拡張子のチェック
52
     *
53
     * @param $value mixed
54
     * @return bool
55
     */
56
    public static function checkExtension($value, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
57
    {
58
        // データがない場合はチェックしない
59
        if (!is_array($value) || !array_key_exists('name', $value)) {
60
            return true;
61
        }
62
        $check = $value['name'];
63
64
        $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
65
        foreach ($extensions as $value) {
66
            if ($extension === strtolower($value)) {
67
                return true;
68
            }
69
        }
70
71
        return false;
72
    }
73
}
74