-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathObjectForm.php
More file actions
117 lines (94 loc) · 2.72 KB
/
ObjectForm.php
File metadata and controls
117 lines (94 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace Icinga\Module\Vspheredb\Web\Form;
use gipfl\ZfDbStore\Store;
use Icinga\Authentication\Auth;
use Ramsey\Uuid\Uuid;
use RuntimeException;
use ipl\I18n\Translation;
use gipfl\Web\Form;
use gipfl\ZfDbStore\StorableInterface;
abstract class ObjectForm extends Form
{
use Translation;
/** @var Store */
protected $store;
/** @var StorableInterface */
protected $object;
protected $class;
protected $wasNew = true;
public function __construct(Store $store)
{
$this->store = $store;
$this->setMethod('POST');
}
public function setObject(StorableInterface $object)
{
$this->object = $object;
$this->populate($object->getProperties());
$this->wasNew = $object->isNew();
return $this;
}
/**
* @return ?StorableInterface
*/
public function getObject()
{
return $this->object;
}
public function wasNew()
{
return $this->wasNew;
}
public function isNew()
{
return $this->object === null || $this->object->isNew();
}
protected function getObjectClass()
{
if ($this->class === null) {
throw new RuntimeException(sprintf(
'ObjectForm %s defined no $class',
get_class($this)
));
}
return $this->class;
}
protected static function now()
{
$time = explode(' ', microtime());
return round(1000 * ((int)$time[1] + (float)$time[0]));
}
public function onSuccess()
{
if ($this->object) {
$object = $this->object;
$object->setProperties($this->getValues());
} else {
$object = $this->createObject();
}
if ($object->hasProperty('ts_modified') && $object->isModified()) {
$object->set('ts_modified', static::now());
}
if ($object->hasProperty('modified_by')) {
$object->set('modified_by', Auth::getInstance()->getUser()->getUsername());
}
$this->store->store($object);
}
protected function createObject()
{
/** @var StorableInterface $class Not really an object, it's a class name */
$class = $this->getObjectClass();
$object = $class::create($this->getValues());
$this->object = $object;
if ($object->getKeyProperty() === 'uuid') {
$object->set('uuid', Uuid::uuid4()->getBytes());
}
if ($object->hasProperty('ts_created')) {
$object->set('ts_created', static::now());
}
if ($object->hasProperty('created_by')) {
$object->set('created_by', Auth::getInstance()->getUser()->getUsername());
}
return $object;
}
}