Completed
Pull Request — master (#21)
by Daniel
06:05
created

RowData::getObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid;
6
7
use Symfony\Component\Form\FormInterface;
8
use Symfony\Component\Form\FormView;
9
10
/**
11
 * TODO: Tests for this class.
12
 */
13
final class RowData
14
{
15
    private $object;
16
    private $form;
17
18
    private function __construct()
19
    {
20
    }
21
22
    public static function fromObject($object): RowData
23
    {
24
        if (!is_object($object)) {
25
            throw new \InvalidArgumentException(sprintf(
26
                'Object must be an object, got: "%s"',
27
                gettype($object)
28
            ));
29
        }
30
31
        $instance = new self();
32
        $instance->object = $object;
33
34
        return $instance;
35
    }
36
37
    public static function fromForm(FormView $form): RowData
38
    {
39
        $instance = new self();
40
        $instance->object = $this->getFormObject();
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
41
        $instance->form = $form;
42
43
        return $instance;
44
    }
45
46
    public function getForm(): FormView
47
    {
48
        if (!$this->form) {
49
            throw new \InvalidArgumentException(
50
                'No form was set on row data.'
51
            );
52
        }
53
54
        return $this->form;
55
    }
56
57
    public function getObject()
58
    {
59
        return $this->object;
60
    }
61
62
    private function getFormObject()
63
    {
64
        if (!isset($this->form->vars['data'])) {
65
            throw new \RuntimeException(sprintf(
66
                'Expected "data" to be set on the form view. Actual view variables: "%s"',
67
                implode('", "', array_keys($this->form->vars))
68
            ));
69
        }
70
71
        return $this->form->vars['data'];
72
    }
73
}
74