Completed
Pull Request — master (#21)
by Daniel
02:09
created

RowData::fromObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
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->form = $form;
41
        $instance->object = $instance->getFormObject();
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