Completed
Pull Request — master (#647)
by Robbie
20:35 queued 18:30
created

EditableLiteralField::getFormField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\UserForms\Model\EditableFormField;
4
5
use SilverStripe\Core\Injector\Injector;
6
use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig;
7
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
8
use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser;
9
use SilverStripe\Forms\CheckboxField;
10
use SilverStripe\Forms\CompositeField;
11
use SilverStripe\Forms\LiteralField;
12
use SilverStripe\UserForms\Model\EditableFormField;
13
14
/**
15
 * Editable Literal Field. A literal field is just a blank slate where
16
 * you can add your own HTML / Images / Flash
17
 *
18
 * @package userforms
19
 */
20
class EditableLiteralField extends EditableFormField
21
{
22
    private static $singular_name = 'HTML Block';
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...
23
24
    private static $plural_name = 'HTML Blocks';
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 $plural_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...
25
26
    private static $table_name = 'EditableLiteralField';
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...
27
28
    /**
29
     * Mark as literal only
30
     *
31
     * @config
32
     * @var bool
33
     */
34
    private static $literal = true;
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 $literal 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...
35
36
    /**
37
     * Get the name of the editor config to use for HTML sanitisation. Defaults to the active config.
38
     *
39
     * @var string
40
     * @config
41
     */
42
    private static $editor_config = null;
0 ignored issues
show
Unused Code introduced by
The property $editor_config 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
44
    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...
45
        'Content' => 'HTMLText', // From CustomSettings
46
        'HideFromReports' => 'Boolean(0)', // from CustomSettings
47
        'HideLabel' => 'Boolean(0)'
48
    ];
49
50
    private static $defaults = [
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 $defaults 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...
51
        'HideFromReports' => false
52
    ];
53
54
    /**
55
     * Returns the {@see HTMLEditorConfig} instance to use for sanitisation
56
     *
57
     * @return HTMLEditorConfig
58
     */
59
    protected function getEditorConfig()
60
    {
61
        $editorConfig = $this->config()->get('editor_config');
62
        if ($editorConfig) {
63
            return HTMLEditorConfig::get($editorConfig);
64
        }
65
        return HTMLEditorConfig::get_active();
66
    }
67
68
    /**
69
     * Safely sanitise html content, if enabled
70
     *
71
     * @param string $content Raw html
72
     * @return string Safely sanitised html
73
     */
74
    protected function sanitiseContent($content)
75
    {
76
        // Check if sanitisation is enabled
77
        if (!HTMLEditorField::config()->get('sanitise_server_side')) {
78
            return $content;
79
        }
80
81
        // Perform sanitisation
82
        $htmlValue = Injector::inst()->create('HTMLValue', $content);
83
        $santiser = Injector::inst()->create(HTMLEditorSanitiser::class, $this->getEditorConfig());
84
        $santiser->sanitise($htmlValue);
85
        return $htmlValue->getContent();
86
    }
87
88
    /**
89
     * Get HTML Content of this literal field
90
     *
91
     * @return string
92
     */
93
    public function getContent()
94
    {
95
        // Apply html editor sanitisation rules
96
        $content = $this->getField('Content');
97
        return $this->sanitiseContent($content);
98
    }
99
100
    /**
101
     * Set the content with the given value
102
     *
103
     * @param string $content
104
     */
105
    public function setContent($content)
106
    {
107
        // Apply html editor sanitisation rules
108
        $content = $this->sanitiseContent($content);
109
        $this->setField('Content', $content);
110
    }
111
112
    /**
113
     * @return FieldList
114
     */
115
    public function getCMSFields()
116
    {
117
        $fields = parent::getCMSFields();
118
119
        $fields->removeByName(['Default', 'Validation', 'RightTitle']);
120
121
        $fields->addFieldsToTab('Root.Main', [
122
            HTMLEditorField::create('Content', _t(__CLASS__.'.CONTENT', 'HTML'))
123
                ->setRows(4)
124
                ->setColumns(20),
125
            CheckboxField::create(
126
                'HideFromReports',
127
                _t(__CLASS__.'.HIDEFROMREPORT', 'Hide from reports?')
128
            ),
129
            CheckboxField::create(
130
                'HideLabel',
131
                _t(__CLASS__.'.HIDELABEL', "Hide 'Title' label on frontend?")
132
            )
133
        ]);
134
135
        return $fields;
136
    }
137
138
    public function getFormField()
139
    {
140
        $content = LiteralField::create(
141
            "LiteralFieldContent-{$this->ID}]",
142
            $this->dbObject('Content')->forTemplate()
143
        );
144
145
        $field = CompositeField::create($content)
146
            ->setName($this->Name)
147
            // ->setID($this->Name) // @todo
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
148
            ->setFieldHolderTemplate(__CLASS__ . '_holder');
149
150
        $this->doUpdateFormField($field);
0 ignored issues
show
Documentation introduced by
$field is of type object<SilverStripe\Forms\CompositeField>, 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...
151
152
        return $field;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $field; (SilverStripe\Forms\CompositeField) 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...
153
    }
154
155
    protected function updateFormField($field)
156
    {
157
        parent::updateFormField($field);
158
159
        if ($this->HideLabel) {
0 ignored issues
show
Documentation introduced by
The property HideLabel does not exist on object<SilverStripe\User...d\EditableLiteralField>. 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...
160
            $this->ExtraClass .= ' nolabel';
0 ignored issues
show
Documentation introduced by
The property ExtraClass does not exist on object<SilverStripe\User...d\EditableLiteralField>. 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...
161
        } else {
162
            $field->setTitle($this->Title);
163
        }
164
    }
165
166
    public function showInReports()
167
    {
168
        return !$this->HideFromReports;
0 ignored issues
show
Documentation introduced by
The property HideFromReports does not exist on object<SilverStripe\User...d\EditableLiteralField>. 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...
169
    }
170
}
171