Completed
Push — master ( 3eba7c...0a67a0 )
by Simon
15s queued 11s
created

PartialUserFormController::savePartialSubmission()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 42
rs 8.3146
c 0
b 0
f 0
cc 7
nc 9
nop 1
1
<?php
2
3
namespace Firesphere\PartialUserforms\Controllers;
4
5
use Page;
6
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
9
use SilverStripe\ORM\DataObject;
10
use SilverStripe\ORM\FieldType\DBField;
11
use SilverStripe\UserForms\Control\UserDefinedFormController;
12
13
/**
14
 * Class PartialUserFormController
15
 * @package Firesphere\PartialUserforms\Controllers
16
 */
17
class PartialUserFormController extends UserDefinedFormController
18
{
19
20
    /**
21
     * @var array
22
     */
23
    private static $url_handlers = [
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...
24
        '$Key/$Token' => 'partial',
25
    ];
26
27
    /**
28
     * @var array
29
     */
30
    private static $allowed_actions = [
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...
31
        'partial',
32
    ];
33
34
    /**
35
     * Partial form
36
     *
37
     * @param HTTPRequest $request
38
     * @return \SilverStripe\ORM\FieldType\DBHTMLText|void
39
     * @throws \SilverStripe\Control\HTTPResponse_Exception
40
     */
41
    public function partial(HTTPRequest $request)
42
    {
43
        // Ensure this URL doesn't get picked up by HTTP caches
44
        HTTPCacheControlMiddleware::singleton()->disableCache();
45
46
        $key = $request->param('Key');
47
        $token = $request->param('Token');
48
49
        $partial = PartialFormSubmission::get()->find('Token', $token);
50
        if (!$token || !$partial || !$partial->UserDefinedFormID) {
51
            return $this->httpError(404);
52
        }
53
54
        // TODO: Recognize visitor with the password
55
        if ($partial->generateKey($token) === $key) {
56
            // Set the session if the last session has expired
57
            if (!$request->getSession()->get(PartialSubmissionController::SESSION_KEY)) {
58
                $request->getSession()->set(PartialSubmissionController::SESSION_KEY, $partial->ID);
59
            }
60
61
            // Set data record and load the form
62
            $this->dataRecord = DataObject::get_by_id($partial->UserDefinedFormClass, $partial->UserDefinedFormID);
0 ignored issues
show
Documentation Bug introduced by
It seems like \SilverStripe\ORM\DataOb...ial->UserDefinedFormID) can also be of type object<SilverStripe\ORM\DataObject>. However, the property $dataRecord is declared as type object<SilverStripe\CMS\Model\SiteTree>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
63
            $this->setFailover($this->dataRecord);
0 ignored issues
show
Bug introduced by
It seems like $this->dataRecord can be null; however, setFailover() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
64
65
            $form = $this->Form();
66
            $fields = $partial->PartialFields()->map('Name', 'Value')->toArray();
67
            $form->loadDataFrom($fields);
0 ignored issues
show
Documentation Bug introduced by
The method loadDataFrom does not exist on object<Firesphere\Partia...tialUserFormController>? 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...
68
69
            // Copied from {@link UserDefinedFormController}
70
            if ($this->Content && $form && !$this->config()->disable_form_content_shortcode) {
0 ignored issues
show
Documentation introduced by
The property Content does not exist on object<Firesphere\Partia...tialUserFormController>. 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...
71
                $hasLocation = stristr($this->Content, '$UserDefinedForm');
0 ignored issues
show
Documentation introduced by
The property Content does not exist on object<Firesphere\Partia...tialUserFormController>. 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...
72
                if ($hasLocation) {
73
                    /** @see Requirements_Backend::escapeReplacement */
74
                    $formEscapedForRegex = addcslashes($form->forTemplate(), '\\$');
0 ignored issues
show
Documentation Bug introduced by
The method forTemplate does not exist on object<Firesphere\Partia...tialUserFormController>? 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...
75
                    $content = preg_replace(
76
                        '/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i',
77
                        $formEscapedForRegex,
78
                        $this->Content
0 ignored issues
show
Documentation introduced by
The property Content does not exist on object<Firesphere\Partia...tialUserFormController>. 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...
79
                    );
80
81
                    return $this->customise([
82
                        'Content' => DBField::create_field('HTMLText', $content),
83
                        'Form' => '',
84
                        'PartialLink' => $partial->getPartialLink()
85
                    ])->renderWith([static::class, Page::class]);
86
                }
87
            }
88
89
            return $this->customise([
90
                'Content' => DBField::create_field('HTMLText', $this->Content),
0 ignored issues
show
Documentation introduced by
The property Content does not exist on object<Firesphere\Partia...tialUserFormController>. 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...
91
                'Form' => $form,
92
                'PartialLink' => $partial->getPartialLink()
93
            ])->renderWith([static::class, Page::class]);
94
        } else {
95
            return $this->httpError(404);
96
        }
97
    }
98
}
99