PHP code to convert PHP to JS [closed]

2019-02-15 12:51发布

I need some PHP code to convert some PHP into JS.

  • functionality - I'm using common PHP functions from php.js
  • syntax - ???

The issue is converting the syntax. I don't need full PHP syntax, mind you; no need for supporting class definitions/declarations. Here's a small checklist of what needs conversion:

  • "." should be "+" (string concat)
  • "->" should be "." (object operator)
  • "::" should be "." (class operator - not really required)

Please note that the resulting code is pretty much independent of the PHP environment, so no "what if it uses a PHP class?".

I'm not asking for full code, just a tip on the right direction to this kind of conversion; I was thinking about employing a state machine/engine.

If you're curious as to why I'm pushing code to the user side: I need a dynamic way to change visibility of certain elements given certain conditions. My plan is to do this without having to execute this code server side and having unnecessary ajax calls.

Edit: Look people. I know not using AJAX sounds ludicrous to you but the world doesn't work on hype and nice-sounding design conditions (=ajax). I simply can't afford each single user polling my server 5 to 10 times per second just for my server to return a "yes" or "no" answer. Keep in mind that switching is asynchronous, and I can't buffer the AJAX calls.

Edit 2: I am sure what I'm doing is the best way in my situation. There is no "possibly better" way, so quit posting non-constructive comments. I can't get into any more detail than I have so already. The conversion from PHP code to JS is simply a matter of shortening user input; we only need one expression, then convert it to whichever language is necessary (in this particular case, from PHP to JS). The conditions on how this works will not change regardless if I describe the system down to the API specs, and inundating the topic with useless (for you) prototype docs will not help at all.

Also, for those thinking this idea came after waking up form some dream; know this has been reviewed between technical development and QA, so please do not deviate into inexistent design issues.

Edit 3: Examples (original PHP code and expected output):

  • (original) -- (converted)
  • 5=="test" -- 5=="test"
  • '$'.(func(12)*10) -- '$'+(func(12)*10)
  • Fields::count()==5 -- Fields.count()==5
  • $this->id==5 -- this.id==5

About the last example, don't worry about context/scope, it is correct. Also note that the expressions may look weird; this is because they are expression; a single line of code that must return a value, which explains the absence of an EOL (;) and the multiple use of returning a boolean value. (exotic stuff like backtick operator execution, PHP tags, echo, die, list, etc.. left out on purpose)

5条回答
女痞
2楼-- · 2019-02-15 12:56

Here's the quick and dirty solution I came up with, written in under 20 minutes (probably lots of bugs), but it looks like it works.

function convertPhpToJs($php){
    $php=str_split($php,1); $js='';
    $str='';                                                                                      // state; either empty or a quote character
    $strs=array('\'','`','"');                                                                    // string quotes; single double and backtick
    $nums=array('0','1','2','3','4','5','6','7','8','9');                                         // numerals
    $wsps=array(chr(9),chr(10),chr(13),chr(32));                                                  // remove whitespace from code
    foreach($php as $n=>$c){
        $p=isset($php[$n-1])?$php[$n-1]:'';
        $f=isset($php[$n+1])?$php[$n+1]:'';
        if($str!='' && $str!=$c){ $js.=$c; continue; }                                        // in a string
        if($str=='' && in_array($c,$strs)){ $str=$c; $js.=$c; continue; }                     // starting a string
        if($str!='' && $str==$c){ $str='';  $js.=$c; continue; }                              // ending a string
        // else, it is inside code
        if($c=='$')continue;                                                                  // filter out perl-style variable names
        if($c==':' && $f==':'){ $js.='.'; continue; }                                         // replace 1st of :: to .
        if($p==':' && $c==':')continue;                                                       // filter out 2nd char of ::
        if($c=='-' && $f=='>'){ $js.='.'; continue; }                                         // replace 1st of -> to .
        if($p=='-' && $c=='>')continue;                                                       // filter out 2nd char of ->
        if($c=='.' && (!in_array($p,$nums) || !in_array($f,$nums))){ $js.='+'; continue; }    // replace string concat op . to +
        if(in_array($c,$wsps))continue;                                                       // filter out whitespace
        $js.=$c;
    }
    return $js;
}

The following:

$window->alert("$".Math::round(450/10));

Converted to:

window.alert("$"+Math.round(450/10));

Edit: Can't believe all the fuss this question caused compared to the time taken.

Feel free to criticize at will. I don't actually like it much personally.

查看更多
在下西门庆
3楼-- · 2019-02-15 13:04

Have you tried Harmony Framework?

查看更多
相关推荐>>
4楼-- · 2019-02-15 13:05

Im created tool PHP-to-JavaScript for converting PHP code to JavaScript. Its support:

  • Namespaces,use
  • Class, abstract class extends and interfaces
  • constants and define
  • Exceptions and catch
  • list()
  • magic methods __get __set and __call
  • and more
查看更多
疯言疯语
5楼-- · 2019-02-15 13:10

I wrote a tool called php2js that can automatically convert PHP code to javascript. It is not perfect, but supports the most common PHP functionality including classes, inheritance, arrays, etc, etc. It also includes and knows about php.js, so code written with php's standard library functions may "just work".

Maybe you will find it useful.

查看更多
Juvenile、少年°
6楼-- · 2019-02-15 13:12

Okay, let me take a stab at this one...

Screw regexes. I love them, but there's a better way, and it's built in. Check out token_get_all(). It will parse PHP source as a string and return a list of the very same tokens that PHP itself uses (including the beloved T_PAAMAYIM_NEKUDOTAYIM). You can then completely reconstruct the source of the script, one token at a time, translating it into Javascript syntax along the way.

[charles@teh ~]$ php --interactive
Interactive shell

php > print_r(token_get_all('<?php class Foo { public function bar() { echo "Yikes!"; } } $f = new Foo();  $f->bar(); ?>'));
Array
(
[0] => Array
    (
        [0] => 368
        [1] => <?php 
        [2] => 1
    )

[1] => Array
    (
        [0] => 353
        [1] => class
        [2] => 1
    )

[2] => Array
    (
        [0] => 371
        [1] =>  
        [2] => 1
    )

[3] => Array
    (
        [0] => 307
        [1] => Foo
        [2] => 1
    )
... 

While this may be a bit overkill, it also uses the same parsing rules PHP uses, and should therefore be less of a long-term pain than regular expressions. It also gives you the flexibility to detect features that can't be translated (i.e. things that php-js doesn't support) and reject the translation and/or work around the problem.


Also, you still haven't told us what you're doing and why you're doing it. There are still probably more accurate, useful answers available. Help us help you by giving us more information.

  • You believe polling to be unrealistic due to an expected stupidly high number of requests per second. Why are you expecting that number? What does your application do that would cause such conditions?
  • Why do you want to translate PHP code rather than writing specific Javascript? You're just manipulating page contents a bit, why do you need PHP code to make that decision?
  • Language translation is probably the least simple solution to this problem, and is therefore an amazingly awful idea. It couldn't have been arrived at as the first option. What are your other options, and why have they been ruled out?
查看更多
登录 后发表回答