Completed
Push — master ( 96c1cc...0890c5 )
by Franco
13s
created

EditableFileField::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\UserForms\Model\EditableFormField;
4
5
use SilverStripe\Assets\File;
6
use SilverStripe\Assets\Folder;
7
use SilverStripe\Core\Config\Config;
8
use SilverStripe\Forms\FileField;
9
use SilverStripe\Forms\LiteralField;
10
use SilverStripe\Forms\NumericField;
11
use SilverStripe\Forms\TreeDropdownField;
12
use SilverStripe\UserForms\Model\EditableFormField;
13
use SilverStripe\UserForms\Model\Submission\SubmittedFileField;
14
15
/**
16
 * Allows a user to add a field that can be used to upload a file.
17
 *
18
 * @package userforms
19
 */
20
class EditableFileField extends EditableFormField
21
{
22
23
    private static $singular_name = 'File Upload Field';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $singular_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
24
25
    private static $plural_names = 'File Fields';
0 ignored issues
show
Unused Code introduced by
The property $plural_names is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
26
27
    private static $db = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        'MaxFileSizeMB' => 'Float',
29
    ];
30
31
    private static $has_one = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
32
        'Folder' => Folder::class // From CustomFields
33
    ];
34
35
    private static $table_name = 'EditableFileField';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $table_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
36
37
    /**
38
     * Further limit uploadable file extensions in addition to the restrictions
39
     * imposed by the File.allowed_extensions global configuration.
40
     * @config
41
     */
42
    private static $allowed_extensions_blacklist = [
0 ignored issues
show
Unused Code introduced by
The property $allowed_extensions_blacklist is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
43
        'htm', 'html', 'xhtml', 'swf', 'xml'
44
    ];
45
46
    /**
47
     * @return FieldList
48
     */
49
    public function getCMSFields()
50
    {
51
        $fields = parent::getCMSFields();
52
53
        $fields->addFieldToTab(
54
            'Root.Main',
55
            TreeDropdownField::create(
56
                'FolderID',
57
                _t('EditableUploadField.SELECTUPLOADFOLDER', 'Select upload folder'),
58
                Folder::class
59
            )
60
        );
61
62
        $fields->addFieldToTab("Root.Main", LiteralField::create(
63
            'FileUploadWarning',
64
            '<p class="message notice">' . _t(
65
                'SilverStripe\\UserForms\\Model\\UserDefinedForm.FileUploadWarning',
66
                'Files uploaded through this field could be publicly accessible if the exact URL is known'
67
            )
68
            . '</p>'
69
        ), 'Type');
70
71
        $fields->addFieldToTab(
72
            'Root.Main',
73
            NumericField::create('MaxFileSizeMB')
74
                ->setTitle('Max File Size MB')
75
                ->setDescription("Note: Maximum php allowed size is {$this->getPHPMaxFileSizeMB()} MB")
76
        );
77
78
        $fields->removeByName('Default');
79
80
        return $fields;
81
    }
82
83
    /**
84
     * @return ValidationResult
85
     */
86
    public function validate()
87
    {
88
        $result = parent::validate();
89
90
        $max = static::get_php_max_file_size();
91
        if ($this->MaxFileSizeMB * 1024 > $max) {
0 ignored issues
show
Documentation introduced by
The property MaxFileSizeMB does not exist on object<SilverStripe\User...ield\EditableFileField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
92
            $result->addError("Your max file size limit can't be larger than the server's limit of {$this->getPHPMaxFileSizeMB()}.");
93
        }
94
95
        return $result;
96
    }
97
98
    public function getFormField()
99
    {
100
        $field = FileField::create($this->Name, $this->EscapedTitle)
0 ignored issues
show
Documentation introduced by
The property EscapedTitle does not exist on object<SilverStripe\User...ield\EditableFileField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
101
            ->setFieldHolderTemplate('UserFormsField_holder')
102
            ->setTemplate(__CLASS__);
103
104
        $field->setFieldHolderTemplate('UserFormsField_holder')
105
            ->setTemplate(__CLASS__);
106
107
        $field->getValidator()->setAllowedExtensions(
108
            array_diff(
109
                // filter out '' since this would be a regex problem on JS end
110
                array_filter(Config::inst()->get(File::class, 'allowed_extensions')),
111
                $this->config()->get('allowed_extensions_blacklist')
112
            )
113
        );
114
115
        if ($this->MaxFileSizeMB > 0) {
0 ignored issues
show
Documentation introduced by
The property MaxFileSizeMB does not exist on object<SilverStripe\User...ield\EditableFileField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
116
            $field->getValidator()->setAllowedMaxFileSize($this->MaxFileSizeMB * 1024 * 1024);
0 ignored issues
show
Documentation introduced by
The property MaxFileSizeMB does not exist on object<SilverStripe\User...ield\EditableFileField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
117
        } else {
118
            $field->getValidator()->setAllowedMaxFileSize(static::get_php_max_file_size());
119
        }
120
121
        $folder = $this->Folder();
0 ignored issues
show
Documentation Bug introduced by
The method Folder does not exist on object<SilverStripe\User...ield\EditableFileField>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
122
        if ($folder && $folder->exists()) {
123
            $field->setFolderName(
124
                preg_replace("/^assets\//", "", $folder->Filename)
125
            );
126
        }
127
128
        $this->doUpdateFormField($field);
0 ignored issues
show
Documentation introduced by
$field is of type object<SilverStripe\Forms\FileField>, but the function expects a object<SilverStripe\UserForms\Model\FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
129
130
        return $field;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $field; (SilverStripe\Forms\FileField) is incompatible with the return type of the parent method SilverStripe\UserForms\M...FormField::getFormField of type SilverStripe\UserForms\Model\FormField|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
131
    }
132
133
134
    /**
135
     * Return the value for the database, link to the file is stored as a
136
     * relation so value for the field can be null.
137
     *
138
     * @return string
139
     */
140
    public function getValueFromData()
141
    {
142
        return null;
143
    }
144
145
    public function getSubmittedFormField()
146
    {
147
        return SubmittedFileField::create();
148
    }
149
150
    /**
151
     * @return float
152
     */
153
    public static function get_php_max_file_size()
154
    {
155
        $maxUpload = File::ini2bytes(ini_get('upload_max_filesize'));
156
        $maxPost = File::ini2bytes(ini_get('post_max_size'));
157
        return min($maxUpload, $maxPost);
158
    }
159
160
    public function getPHPMaxFileSizeMB()
161
    {
162
        return round(static::get_php_max_file_size() / 1024.0, 1);
163
    }
164
}
165