1 2 //+ Jonas Raoni Soares Silva 3 //@ http://jsfromhell.com 4 5 class JS{ 6 //generic and maybe not the desired results xD 7 function value($o){ 8 if($o === null) 9 return 'null'; 10 $t = strtolower(gettype($o)); 11 if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer'))) 12 $t = 'number'; 13 elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x') 14 $t = 'date'; 15 elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1)) 16 $t = 'object'; 17 elseif(!in_array($t, array('boolean', 'string', 'array', 'object'))) 18 $t = 'string'; 19 $t = 'from' . $t; 20 return self::$t($o); 21 } 22 function fromNumber($o){ 23 return +$o . ''; 24 } 25 function fromObject($o){ 26 $r = array(); 27 foreach($o as $n => $v) 28 $r[] = self::fromString($n) . ':' . self::value($v); 29 return '{' . implode(',', $r) . '}'; 30 } 31 function fromBoolean($o){ 32 return $o ? 'true' : 'false'; 33 } 34 //$q = should quote? 35 //$c = char that will be used to quote 36 function fromString($o, $q = true, $c = '"'){ 37 return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p; 38 } 39 function fromArray($o){ 40 $s = ''; 41 foreach($o as $v) 42 $s .= ($s ? ',' : '') . self::value($v); 43 return '[' . $s . ']'; 44 } 45 function fromDate($o){ 46 (is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime()); 47 $o = explode(',', date('Y,n,j,G,i,s', $o)); 48 foreach($o as $i => $v) 49 $o[$i] = +$v; 50 return 'new Date(' . implode(',', $o) . ')'; 51 } 52 }
Example
1 2 $o = new stdClass; 3 $o->abc = 123; 4 echo implode("\n<br />", array( 5 JS::value('1984-07-22 11:30:12'), 6 JS::value('Test'), 7 JS::value(1234), 8 JS::value(true), 9 JS::value(array(1,2,3)), 10 JS::value(array('lala' => 'x')), 11 JS::value($o) 12 ));