Completed
Pull Request — master (#460)
by Bram
36:05
created

EditableFileField::getValueFromData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * Allows a user to add a field that can be used to upload a file.
5
 *
6
 * @package userforms
7
 */
8
9
class EditableFileField extends EditableFormField {
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...
10
11
	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...
12
13
	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...
14
15
	private static $has_one = array(
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...
16
		'Folder' => 'Folder' // From CustomFields
17
	);
18
19
	/**
20
	 * Further limit uploadable file extensions in addition to the restrictions
21
	 * imposed by the File.allowed_extensions global configuration.
22
	 * @config
23
	 */
24
	private static $allowed_extensions_blacklist = array(
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...
25
		'htm', 'html', 'xhtml', 'swf', 'xml'
26
	);
27
28
	/**
29
	 * @return FieldList
30
	 */
31
	public function getCMSFields() {
32
		$fields = parent::getCMSFields();
33
34
		$fields->addFieldToTab(
35
			'Root.Main',
36
			TreeDropdownField::create(
37
				'FolderID',
38
				_t('EditableUploadField.SELECTUPLOADFOLDER', 'Select upload folder'),
39
				'Folder'
40
			)
41
		);
42
43
		$fields->addFieldToTab("Root.Main", new LiteralField("FileUploadWarning",
44
				"<p class=\"message notice\">" . _t("UserDefinedForm.FileUploadWarning",
45
				"Files uploaded through this field could be publicly accessible if the exact URL is known")
46
				. "</p>"), "Type");
47
48
		return $fields;
49
	}
50
51
	public function getFormField() {
52
		if(isset(Config::inst()->get('EditableFileField', 'use_uploadfield')) && Config::inst()->get('EditableFileField', 'use_uploadfield')) {
53
			$field = Upload::create($this->Name, $this->EscapedTitle);
0 ignored issues
show
Documentation introduced by
The property EscapedTitle does not exist on object<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...
Bug Compatibility introduced by
The expression \Upload::create($this->N..., $this->EscapedTitle); of type Upload adds the type Upload to the return on line 78 which is incompatible with the return type of the parent method EditableFormField::getFormField of type FormField|null.
Loading history...
54
		} else {
55
			$field = FileField::create($this->Name, $this->EscapedTitle);
0 ignored issues
show
Documentation introduced by
The property EscapedTitle does not exist on object<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...
56
		}
57
	
58
		$field->setFieldHolderTemplate('UserFormsField_holder')
0 ignored issues
show
Bug introduced by
The method setFieldHolderTemplate does only exist in FileField, but not in Upload.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
59
				->setTemplate('UserFormsFileField');
60
61
		$field->getValidator()->setAllowedExtensions(
62
			array_diff(
63
				// filter out '' since this would be a regex problem on JS end
64
				array_filter(Config::inst()->get('File', 'allowed_extensions')),
65
				$this->config()->allowed_extensions_blacklist
66
			)
67
		);
68
69
		$folder = $this->Folder();
0 ignored issues
show
Documentation Bug introduced by
The method Folder does not exist on object<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...
70
		if($folder && $folder->exists()) {
71
			$field->setFolderName(
0 ignored issues
show
Bug introduced by
The method setFolderName does only exist in FileField, but not in Upload.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
72
				preg_replace("/^assets\//","", $folder->Filename)
73
			);
74
		}
75
76
		$this->doUpdateFormField($field);
0 ignored issues
show
Bug introduced by
It seems like $field defined by \Upload::create($this->Name, $this->EscapedTitle) on line 53 can also be of type object<Upload>; however, EditableFormField::doUpdateFormField() does only seem to accept object<FormField>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
77
78
		return $field;
79
	}
80
81
82
	/**
83
	 * Return the value for the database, link to the file is stored as a
84
	 * relation so value for the field can be null.
85
	 *
86
	 * @return string
87
	 */
88
	public function getValueFromData() {
89
		return null;
90
	}
91
92
	public function getSubmittedFormField() {
93
		return new SubmittedFileField();
94
	}
95
96
97
	public function migrateSettings($data) {
98
		// Migrate 'Folder' setting to 'FolderID'
99
		if(isset($data['Folder'])) {
100
			$this->FolderID = $data['Folder'];
0 ignored issues
show
Documentation introduced by
The property FolderID does not exist on object<EditableFileField>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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
			unset($data['Folder']);
102
		}
103
104
		parent::migrateSettings($data);
105
	}
106
}
107