getToplevelController()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\GridFieldAddOns;
4
5
use SilverStripe\Forms\Form;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\Forms\FormAction;
8
use SilverStripe\Control\Controller;
9
use SilverStripe\Control\RequestHandler;
10
use SilverStripe\ORM\ValidationException;
11
use SilverStripe\Control\PjaxResponseNegotiator;
12
use SilverStripe\GridFieldAddOns\GridFieldExpandableForm;
13
14
class GridFieldExpandableForm_ItemRequest extends RequestHandler
15
{
16
17
    private static $url_handlers = 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...
18
        '$Action!' => '$Action',
19
        '' => 'edit',
20
    );
21
22
    private static $allowed_actions = 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...
23
        'edit',
24
        'ExpandableForm'
25
    );
26
27
    protected $gridfield;
28
    protected $component;
29
    protected $record;
30
    protected $controller;
31
    protected $name;
32
    protected $formorfields;
33
    protected $template = GridFieldExpandableForm::class;
34
35
    public function __construct($gridfield, $component, $record, $controller, $name, $formorfields)
36
    {
37
        $this->gridfield = $gridfield;
38
        $this->component = $component;
39
        $this->record = $record;
40
        $this->controller = $controller;
41
        $this->name = $name;
42
        $this->formorfields = $formorfields;
43
        parent::__construct();
44
    }
45
46
    public function edit($request)
47
    {
48
        $form = $this->ExpandableForm($this->gridField, $request);
0 ignored issues
show
Bug introduced by
The property gridField does not seem to exist. Did you mean gridfield?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Unused Code introduced by
The call to GridFieldExpandableForm_...quest::ExpandableForm() has too many arguments starting with $this->gridField.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
49
50
        return $this
51
            ->customise(['ExpandableForm' => $form])
52
            ->renderWith($this->template);
53
    }
54
55
    /**
56
     * Generate a form to allow editing of a reord
57
     *
58
     * @return \SilverStripe\Forms\Form
59
     */
60
    public function ExpandableForm()
61
    {
62
        $record = $this->record;
63
64
        if (!$record->canView()) {
65
            $controller = $this->getToplevelController();
66
            return $controller->httpError(403);
67
        }
68
69
        if ($this->formorfields instanceof FieldList) {
70
            $fields = $this->formorfields;
71
        } elseif ($this->formorfields instanceof ViewableData) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\GridFieldAddOns\ViewableData does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
72
            $form = $this->formorfields;
73
        } elseif ($this->record->hasMethod('getExandableForm')) {
74
            $form = $this->record->getExandableForm($this, __FUNCTION__);
75
            $this->record->extend('updateExandableForm', $form);
76
        } elseif ($this->record->hasMethod('getExandableFormFields')) {
77
            $fields = $this->record->getExandableFormFields();
78
            $this->record->extend('updateExandableFormFields', $fields);
79
        } else {
80
            $fields = $this->record->scaffoldFormFields();
81
            $this->record->extend('updateExandableFormFields', $fields);
82
        }
83
84
        if (empty($form)) {
85
            $actions = new FieldList();
86
            $actions->push(
87
                FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save'))
88
                    ->setUseButtonTag(true)
89
                    ->addExtraClass('ss-ui-action-constructive btn-primary font-icon-save')
90
                    ->setAttribute('data-icon', 'accept')
91
                    ->setAttribute('data-action-type', 'default')
92
            );
93
94
            $form = new Form(
95
                $this,
96
                'ExpandableForm',
97
                $fields,
0 ignored issues
show
Bug introduced by
The variable $fields does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
98
                $actions
99
            );
100
        }
101
102
        if ($this->validator) {
0 ignored issues
show
Documentation introduced by
The property validator does not exist on object<SilverStripe\Grid...ndableForm_ItemRequest>. 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...
103
            $form->setValidator($this->validator);
0 ignored issues
show
Documentation introduced by
The property validator does not exist on object<SilverStripe\Grid...ndableForm_ItemRequest>. 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...
104
        }
105
106
        $form->loadDataFrom($this->record, Form::MERGE_DEFAULT);
107
108
        $form->IncludeFormTag = false;
109
110
        // Ensure form is made readonly if editing not allowed
111
        if (!$record->canEdit()) {
112
            $form->makeReadonly();
113
        }
114
115
        return $form;
116
    }
117
118
    public function doSave($data, $form)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
119
    {
120
        // Check permission
121
        if (!$this->record->canEdit()) {
122
            $controller = $this->getToplevelController();
123
            return $controller->httpError(403);
124
        }
125
126
        try {
127
            $form->saveInto($this->record);
128
            $this->record->write();
129
            $list = $this->gridfield->getList();
130
            if ($list instanceof ManyManyList) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\GridFieldAddOns\ManyManyList does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
131
                $extradata = array_intersect_key($data, $list->getField('extraFields'));
132
                $list->add($this->record, $extradata);
133
            } else {
134
                $list->add($this->record);
135
            }
136
        } catch (ValidationException $e) {
137
            $form->sessionMessage($e->getResult()->message(), 'bad');
0 ignored issues
show
Bug introduced by
The method message() does not exist on SilverStripe\ORM\ValidationResult. Did you maybe mean addFieldMessage()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
138
            $responseNegotiator = new PjaxResponseNegotiator(array(
139
                'CurrentForm' => function () use (&$form) {
140
                    return $form->forTemplate();
141
                },
142
                'default' => function () use (&$controller) {
143
                    return $controller->redirectBack();
144
                }
145
            ));
146
            if ($controller->getRequest()->isAjax()) {
147
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
148
            }
149
            return $responseNegotiator->respond($controller->getRequest());
150
        }
151
        return $this->customise(array('ExpandableForm' => $form))->renderWith($this->template);
152
    }
153
154
    public function doDelete($data, $form)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Unused Code introduced by
The parameter $data 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...
155
    {
156
        try {
157
            if (!$this->record->canDelete()) {
158
                throw new ValidationException(
159
                    _t('GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions"),
160
                    0
161
                );
162
            }
163
164
            $this->record->delete();
165
        } catch (ValidationException $e) {
166
            $form->sessionMessage($e->getResult()->message(), 'bad');
0 ignored issues
show
Bug introduced by
The method message() does not exist on SilverStripe\ORM\ValidationResult. Did you maybe mean addFieldMessage()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
167
            return Controller::curr()->redirectBack();
168
        }
169
        return 'deleted';
170
    }
171
172
    protected function getToplevelController()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
173
    {
174
        $c = $this->popupController;
0 ignored issues
show
Bug introduced by
The property popupController does not seem to exist. Did you mean controller?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
175
        while ($c && $c instanceof GridFieldExpandableForm_ItemRequest) {
176
            $c = $c->getController();
0 ignored issues
show
Documentation Bug introduced by
The method getController does not exist on object<SilverStripe\Grid...ndableForm_ItemRequest>? 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...
177
        }
178
        return $c;
179
    }
180
    
181
    public function Link($action = null)
182
    {
183
        return Controller::join_links(
184
            $this->gridfield->Link('expand'),
185
            $this->record->ID ? $this->record->ID : 'new',
186
            $action
187
        );
188
    }
189
}
190