Test Block Top

The Blog...
Articles, Tips & Trick and Other Interesting Information...
Tampilkan postingan dengan label Converter. Tampilkan semua postingan
Tampilkan postingan dengan label Converter. Tampilkan semua postingan
06 Mei 2012

PHP To JavaScript Converter

Tidak sengaja saya baru saja menemukan script unik di google code, script PHP yang dapat convert File PHP ke JavaScript. Penasaran! Langsung saja ke TKP. Berikut cara sederhana convert file PHP ke JavaScript.

Pertama, persyaratan untuk dapat menjalankan script PHP to JavaScript Converter ini adalah Webserver (Setidaknya Apache Webserver harus terinstall di server). Jika anda punya account hosting, anda bisa langsung melanjutkan tutorial ini. Namun jika tidak ada, tidak masalah. Script ini bisa juga dijalankan oleh Apache yang terinstall pada sistem operasi Windows (menggunakan WAMP Server).

Kedua, code simple PHP to JavaScript Converter. Copy code PHP di bawah ini kemudian simpan dengan nama terserah (bebas). Misal, php2js.php:



<?php
error_reporting(E_ALL);
class PHP2js {
/** @var array holds tokens of the php file being converted */
private $_tokens;
/** @var int number of tokens */
private $count;
/** @var int the current token */
private $current = 0;
/** @var javascript gets collected here */
private $js;

/** @var array these token keys will be converted to their values */
private $_convert = array (
'T_IS_EQUAL'=>'==',
'T_IS_GREATER_OR_EQUAL'=>'>=',
'T_IS_SMALLER_OR_EQUAL'=>'<=',
'T_IS_IDENTICAL'=>'===',
'T_IS_NOT_EQUAL'=>'!=',
'T_IS_NOT_IDENTICAL'=>'!==',
'T_IS_SMALLER_OR_EQUA'=>'<=',
'T_BOOLEAN_AND'=>'&&',
'T_BOOLEAN_OR'=>'||',
'T_CONCAT_EQUAL'=>'+= ',
'T_DIV_EQUAL'=>'/=',
'T_DOUBLE_COLON'=>'.',
'T_INC'=>'++',
'T_MINUS_EQUAL'=>'-=',
'T_MOD_EQUAL'=>'%=',
'T_MUL_EQUAL'=>'*=',
'T_OBJECT_OPERATOR'=>'.',
'T_OR_EQUAL'=>'|=',
'T_PLUS_EQUAL'=>'+=',
'T_SL'=>'<<',
'T_SL_EQUAL'=>'<<=',
'T_SR'=>'>>',
'T_SR_EQUAL'=>'>>=',
'T_START_HEREDOC'=>'<<<',
'T_XOR_EQUAL'=>'^=',
'T_NEW'=>'new',
'T_ELSE'=>'else',
'.'=>'+',
'T_IF'=>'if',
'T_RETURN'=>'return',
'T_AS'=>'in',
'T_WHILE'=>'while',
'T_LOGICAL_AND' => 'AND',
'T_LOGICAL_OR' => 'OR',
'T_LOGICAL_XOR' => 'XOR',
'T_EVAL' => 'eval',
'T_ELSEIF' => 'else if',
'T_BREAK' => 'break',
'T_DOUBLE_ARROW' => ':',
);

/** @var array these tokens stays the same */
private $_keep = array(
'=', ',', '}', '{', ';', '(', ')', '*', '/', '+', '-', '>', '<', '[', ']',
);

/** @var array these tokens keeps their value */
private $_keepValue = array (
'T_CONSTANT_ENCAPSED_STRING', 'T_STRING', 'T_COMMENT', 'T_ML_COMMENT', 'T_DOC_COMMENT', 'T_LNUMBER',
'T_WHITESPACE',
);

/**
* constructor, runs the show
*
* @param string $file path (relative or absolute) to the php file that is converted to js
*/
public function __construct ($file) {
$this->file = $file;
$this->_tokens = $this->getTokens($file);
$this->count = count($this->_tokens)-1;
$this->compileJs();

}

/**
* gets tokens from file. Remove the meta PHP2js stuff.
*
* @param string $file path (relative or absolute) to the php file that is converted to js
* @return array
*/
private function getTokens($file) {
$src = file_get_contents($this->file);
$src = preg_replace ("/\n([\t ]*)require.*PHP2js\.php.*\'.*;/Uis", "", $src);
$src = preg_replace ("/\n([\t ]*)new.*PHP2js.*;/Uis", "", $src);
$this->src = $src;
return token_get_all($src);
}

/**
* loops through tokens and convert to js
*
*/
private function compileJs() {
foreach ($this->_tokens as $_) {
$this->next ($name, $value);
$this->parseToken($name, $value, $this->js);
}
}

/**
* output the js and die
*/
private function renderJs () {
echo "<script>$this->js</script>";
die();
}

/**
* changed referenced args to name and value of next token
*
* @param string $name
* @param string $value
* @param unknown_type $i, the amount of nexts to skip
*/
private function next(& $name, & $value, $i=1) {
for ($j=0; $j<$i; $j++) {
$this->current++;
if ($this->current > $this->count) $this->renderJs();
$_token = $this->_tokens[$this->current];
$this->getToken ($name, $value, $_token);
}
}

/**
* find and return first name matching argument
*
* @param mixed $_tokenNames
* @return string
*/
private function findFirst ($_needles) {
$name = $value = '';
for ($i=$this->current+1; $i<$this->count; $i++) {
$this->getToken($name, $value, $this->_tokens[$i]);
if (in_array($name, (array)$_needles)) {
return $name;
}
}
}

/**
* return javascript until match, match not included
*
* @param array $_needles
* @return string
*/
private function parseUntil ($_needles, $_schema=array(), $includeMatch = false) {
$name = $value = $js = $tmp = '';
while (true) {
$this->next ($name, $value);
$this->parseToken($name, $value, $tmp, $_schema);
if (in_array($name, (array)$_needles)) {
if ($includeMatch === true) {
return $tmp;
} else {
return $js;
}
}
$js = $tmp;
}
}

/**
* tries to find the token in $this->_convert, $this->_keep and $this->_keepValue
* if it fails it tries to find a method named as the token. If fails here also it throws away the token.
*
* @param string $name
* @param string $value
* @param string $js store js here by reference
*/
private function parseToken ($name, $value, & $js, $_schema=array()) {
//custom changes
if (in_array($name, array_keys ((array)$_schema))) {
$js .= $_schema[$name];
//change name to other value
} else if (in_array($name, array_keys ($this->_convert))) {
$js .= (!empty($this->_convert[$name])) ? $this->_convert[$name]: $name;
//keep key
} elseif (in_array($name, $this->_keep)) {
$js .= $name;
//keep value
} elseif (in_array($name, $this->_keepValue)) {
$js .= $value;
//call method
} else {
if (method_exists($this, $name)) {
$js .= $this->$name($value);
}
}
//ignore
}

/**
* converters
*
* These guys are equivalents to tokens.
*/

/**
* class definition
*
* @param sting $value
* @return string
*/
private function T_CLASS($value) {
$this->next ($name, $value, 2);
return "function $value() ";
}

/**
* define function
*
* @param string $value
* @return string
*/
private function T_FUNCTION($value) {
$this->next ($name, $value, 2);
return "this.$value = function";
}

/**
* echo is replaced with document.write
*
* @param string $value
* @return string
*/
private function T_ECHO($value) {
return 'document.write('.$this->parseUntil(';').');';
}

/**
* array. Supports both single and associative
*
* @param string $value
* @return string
*/
private function T_ARRAY($value) {
$_convert = array('('=>'{',     ')'=>'}',);
$js = $this->parseUntil(array(';'), $_convert, true);
if (strpos($js, ':') === false) {
$this->tmp = -1;
$js = preg_replace_callback ('/([{, \t\n])(\'.*\')(|.*:(.*))([,} \t\n])/Uis', array($this, 'cb_T_ARRAY'), $js);
}
return $js;
}

private function cb_T_ARRAY($_matches) {
$this->tmp++;
if (strpos($_matches[0], ':') === false) {
return ($_matches[1].$this->tmp.':'.$_matches[2].$_matches[3].$_matches[4].$_matches[5]);
} else {
return $_matches[0];
}
}
/**
* foreach. Gets converted to for (var blah in blih). Supports as $key=>$value
*
* @param string $value
* @return string
*/
private function T_FOREACH($value) {
$_vars = array();
while (true) {
$this->next ($name, $value);
if ($name == 'T_VARIABLE') $_vars[] = $this->cVar($value);
$this->parseToken($name, $value, $js);
if ($name == '{') {
if (count($_vars) == 2) {
$array = $_vars[0];
$val = $_vars[1];
$this->js .=
"for (var {$val}Val in $array) {".
"\n                        $val = $array"."[{$val}Val];";
}
if (count($_vars) == 3) {
$array = $_vars[0];
$key = $_vars[1];
$val = $_vars[2];
$this->js .=
"for (var $key in $array) {".
"\n                        $val = $array"."[$key];";
}
return '';
}
$jsTmp = $js;
}
}

/**
* declare a public class var
*
* @param string $value
* @return string
*/
private function T_PUBLIC ($value) {
$type = $this->findFirst(array('T_VARIABLE', 'T_FUNCTION'));
if ($type == 'T_FUNCTION') return '';
$js = '';
while (true) {
$this->next ($name, $value);
$this->parseToken($name, $value, $js);
if ($name == ';') {
$js = str_replace(array(' '), '', $js);
return 'this.'.$js;
} else if ($name == '=') {
$js = str_replace(array(' ','='), '', $js);
return 'this.'.$js.' =';
}
}
}

/**
* variable. Remove the $
*
* @param string $value
* @return string
*/
private function T_VARIABLE($value) {
return str_replace('$', '', $value);
}

/* helpers */

private function getToken(& $name, & $value, $_token) {
if (is_array($_token)) {
$name = trim(token_name($_token[0]));
$value = $_token[1];
} else {
$name = trim($_token);
$value = '';
}
}

private function cVar($var) {
return str_replace('$', '', $var);
}

/** debugging stuff. Ugly and deprecated. */

/** deprecated and sucks */
private $_openTags = array(
'T_OPEN_TAG', 'T_CLASS', 'T_PUBLIC', 'T_FOREACH', 'T_ARRAY', '{', 'T_VARIABLE', '('
);

/** deprecated and sucks */

/** deprecated and sucks */
private $indent = 0;
/** deprecated and sucks */
private $debug;


private $_closeTags = array(
'}', 'T_CLOSE_TAG', ';', ')',
);

public function __destruct() {
/**
$js = htmlentities ($this->js);
echo ("<pre>$js</pre>");
$this->write();
echo $this->debug;
//*/
}


private function write() {
$_tokens = token_get_all($this->src);
foreach ($_tokens as $key=>$_token) {
if (is_array($_token)) {
$name = trim(token_name($_token[0]));
$value = $_token[1];
} else {
$name = trim($_token);
$value = '';
}
$this->printToken($name, $value, $_token);
}
}

private function printToken ($name, $value, $_token) {
$value = htmlentities($value);

if (in_array($name, $this->_closeTags)) $this->indent--;
$indent = str_repeat('.&nbsp;&nbsp;&nbsp;&nbsp;', $this->indent);
if (in_array($name, $this->_openTags)) $this->indent++;
if (!empty($value))
$this->debug .= "
<br />$indent
<b>$name&nbsp;&nbsp;=&nbsp;&nbsp;'$value'</b>

";
else
$this->debug .= "
<br />$indent
<b>$name</b>

";
}
}
?>

Upload file php2js.php ke server. Kemudian buat file Baru dengan nama bebas, convert.php misalnya. Isikan convert.php dengan code PHP yang ingin anda convert (di bawah "/* Convert Code Start Here */"), kemudian upload ke web server. Misalnya seperti kode di bawah ini:



<?
require_once 'php2js.php';
new php2js(__FILE__);
/**
* My super cool php class that will be converted to js!!!
*/
/* Convert Code Start Here */
class HelloWorld {
/**
* So here goes a function that echos
*
* @param string $foo
* @param string $bar
*/
function foo($foo, $bar) {
echo $foo . ' ' . $bar;
}
}
$H = new HelloWorld;
$H->foo('Hello', 'World');
?>

Convert PHP To JavaScript

Buka file convert.php pada web browser, hasil yang keluar akan tampak seperti pada gambar Screenshot 1. Untuk melihat code JavaScript hasil convert, jika menggunakan browser Mozilla Firefox klik kanan pada halaman kosong web browser kemudian klik View Page Source (Screenshot 2), atau tekan tombol shortcut Ctrl + U. Pada jendela baru yang terbuka, anda akan melihat source code JavaScript hasil convert (Screenshot 3).



<script>
/**
* My super cool php class that will be converted to js!!!
*/
/* Convert Code Start Here */
function HelloWorld()  {
/**
* So here goes a function that echos
*
* @param string $foo
* @param string $bar
*/
this.foo = function(foo, bar) {
document.write( foo + ' ' + bar);
}
}
H = new HelloWorld;
H.foo('Hello', 'World');
</script>

convert_php_to_javascript1

Screenshot 1

convert_php_to_javascript2

Screenshot 2

convert_php_to_javascript3

Screenshot 3

Selesai. Semoga bermanfaat.
:)
Loncat ke Atas ↑