-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathJsModelAbstract.php
More file actions
111 lines (100 loc) · 2.8 KB
/
JsModelAbstract.php
File metadata and controls
111 lines (100 loc) · 2.8 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
<?php
namespace Fp\JsFormValidatorBundle\Model;
use Symfony\Component\Validator\Constraint;
/**
* All the models inherited from this class converted to a similar Javascript model by printing them as a string
*
* Class PhpToJsModel
*
* @package Fp\JsFormValidatorBundle\Model
*/
abstract class JsModelAbstract
{
/**
* This function converts the model to the related JavaScript model
*
* @return string
*/
public function toJsString()
{
return self::phpValueToJs($this->toArray());
}
/**
* @return string
*/
public function __toString()
{
return $this->toJsString();
}
/**
* Convert php value to the Javascript formatted string
*
* @param mixed $value
*
* @return string
*/
public static function phpValueToJs($value)
{
// Initialize "groups" option if it is not set
if ($value instanceof Constraint) {
$value->groups;
}
// For object which has own __toString method
if ($value instanceof JsModelAbstract) {
return $value->toJsString();
}
// For object which has own __toString method
elseif (is_object($value) && method_exists($value, '__toString')) {
return self::phpValueToJs($value->__toString());
}
// For an object or associative array
elseif (is_object($value) || (is_array($value) && array_values($value) !== $value)) {
$jsObject = array();
foreach ($value as $paramName => $paramValue) {
$paramName = addcslashes($paramName, '\'\\');
$jsObject[] = "'$paramName':" . self::phpValueToJs($paramValue);
}
return sprintf('{%1$s}', implode($jsObject, ','));
}
// For a sequential array
elseif (is_array($value)) {
$jsArray = array();
foreach ($value as $item) {
$jsArray[] = self::phpValueToJs($item);
}
return sprintf('[%1$s]', implode($jsArray, ','));
}
// For string
elseif (is_string($value)) {
$value = addcslashes($value, '\'\\');
return "'$value'";
}
// For boolean
elseif (is_bool($value)) {
return true === $value ? 'true' : 'false';
}
// For numbers
elseif (is_numeric($value)) {
return $value;
}
// For null
elseif (is_null($value)) {
return 'null';
}
// Otherwise
else {
return 'undefined';
}
}
/**
* @return array
*/
public function toArray()
{
$result = array();
foreach ($this as $key => $value) {
$result[$key] = $value;
}
return $result;
}
}