3

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)

16
  • 10
    Maybe I'm being too conservative here, but this sounds like an idea that will eat up way more time than it will ever save. Commented Jul 13, 2010 at 9:52
  • 1
    Maybe you should tell us why you want to do this astoundingly insane thing. Why would users be making requests 5-10 times a second? What, exactly, is the application you're building? There are probably other, better ways to get this done. Commented Jul 13, 2010 at 16:06
  • 2
    Why should I get into that much detail? I already specified the conditions on use, and by giving any more details, these conditions will not change. Now, do you mind focusing on the discussion rather then frivolous "what ifs"? The decision passed through a review of 3 people (2 of which reviewed the technical aspect), so please quit accusing me of not knowing what I'm doing. I might not be that much of a decorated stackoverflow user, but that doesn't mean I'm a novice kid playing with PHP/JS. Commented Jul 14, 2010 at 10:58
  • 1
    @Christian can you post some complete examples of what should be converted? Have you considered building a simplified "meta" language that covers your needs and can compile into both JS and PHP? That might be easier to do than detecting all sorts of language quirks using regular expressions or something. Commented Jul 14, 2010 at 10:59
  • 4
    That's fine, but you have to understand the audience and not bury the lead. Surely, you can't expect the compiler experts to be online 24/7 waiting for your question. I'm convinced that you don't want someone to just hand you some code, but you lead off with a wording that says otherwise: "I need some PHP code to convert some PHP into JS." I'm not saying that this is the reason you're having issues w/ this question. However, there is a communication issue between all parties involved. Put another way, you're presenting the problem incorrectly. Commented Jul 14, 2010 at 13:54

5 Answers 5

7

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?
Sign up to request clarification or add additional context in comments.

9 Comments

Well, there is 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. So, I'm assuming JS to make some garish display, w/o polling the server. Though, that would have to be predictable. that is, the conditions influencing the display.
I just can't imagine a scenario where the user is interacting with the page and it needs to make so many requests to the server to update itself based on user interaction alone. Is it a game, maybe? But if so, wouldn't there already be code in place to handle events from the user? The lack of information makes the question confusing.
Agreed, but ultimately that isn't the point. He doesn't strike me as some neophyte who requires a lot of hand holding; just an impatient, cocky youngin'. He'll learn, sooner or later.
George Marian, very funny ;) Charles, let me describe in brief what is going on; you're correct in likening it to a game (but it isn't one). The server is being polled in batches of async requests to know changes in fields details (by other users). This in turn, affects conditions of the field expression, so it has to be re-evaluated, ultimately showing/hiding the field according to evaluation. This system is a desperate effort at limiting the number of ajax requests, which thanks to popular jquery components, is already big enough. Think of this as a collaborative kind of tool.
Ah, now I understand. The fact that you're having users effectively enter code to be executed pretty much explains everything.
|
3

Have you tried Harmony Framework?

2 Comments

No, never even heard of it. Checking it out right now.
OK, checked it out. It looks very interesting, however, way over my needs (classes and functions support). I see it uses php.js as well.
2

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.

Comments

0

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.

1 Comment

hmm... spreading the reference?
-1

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

2 Comments

Doesn't convert. Returns errors or doesn't convert at all. Even simple 3 line code.
@Green Im fixed it. it was only problem with hosting. see this application mojazuvacka.sk its all made with this convertor. And please repair your vote if works :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.