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)

Christian
  • 27,509
  • 17
  • 111
  • 155
  • 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. – Pekka Jul 13 '10 at 09:52
  • The system operates on very small expressions, typically similar to "return fld(45)->test=='aaa';", however, there's a huge amount of these switching at the same time, loads of AJAX requests and throbbers :) – Christian Jul 13 '10 at 09:55
  • There's also the added advantage of leaving client-intensive logic/execution client-side, sparing both server and network usage. – Christian Jul 13 '10 at 09:56
  • 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. – Charles Jul 13 '10 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. – Christian Jul 14 '10 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. – Pekka Jul 14 '10 at 10:59
  • Pekka, I did consider a meta language, but decided on using PHP, considering it will b executed server-side more often; plus, converting PHP to JS would be a simply matter of stripping out stuff (like $) or small replacements (-> and ::). Language-wise, I don't need to support exotix/deep syntaxes like heredoc (& co), class/function definitions. I just need to support basic expression syntax, but including object operators and functions. – Christian Jul 14 '10 at 13:06
  • I don't understand the point of the question. You need to come up with a list of all the conditions that you'll need to support. Figure out how to make the conversions for each of those and then make them. So yah, a state machine sounds right. Am I missing something? Are you expecting to hear particular caveats, as if someone's already done this? – George Marian Jul 14 '10 at 13:40
  • Maybe? I'm pretty sure I'm not the first to do this kind of thing (maybe first in PHP to JS, but definitely not a first). The guy above already differed from a state machine by talking about regular expressions, the design decision is there, I need to decide on implementation, with some help from you guys. If we have experts at compiler theory and design, surely someone must prove proper advise on what I need? – Christian Jul 14 '10 at 13:43
  • 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. – George Marian Jul 14 '10 at 13:54
  • Also, using regular expressions doesn't necessarily mean it's not a state machine. – George Marian Jul 14 '10 at 13:55
  • If I interpret the description of your problem correctly (it's hard because you don't actually specify what you want to achieve exactly, but only your proposed solution) then it sounds to me like you want to have some sort of rule based engine, which will determine a flow in your UI (some sort of interactive inquiry perhaps?). Is this correct? – wimvds Jul 14 '10 at 14:47
  • George Marian, I didn't expect any help at all. I didn't expect, most of all, people that would misunderstand the question and flag it for closing. If people can't/don't want to answer, they're welcome to leave. In fact, I don't recall forcing anyone into helping. Just don't muck things up for others, thank you. (of course, I'm not specifically targeting you) – Christian Jul 14 '10 at 14:47
  • wimvds - Yes, you are correct. Actually, I plainly did specify what I need; converting certain basic PHP to JS. Yet people seem to want to go further and ask "why". That's fine by me, what is not fine is when the "why" turns into "why didn't you just...". – Christian Jul 14 '10 at 14:48
  • George, leaving aside the dynamics of regular expressions, how can a state engine and a regular expression work on the same string at the same time? That said, I usually avoid regular expressions, since I can easily end up unable to maintain them (especially when they get complicated). Of course, this is simply a personal issue. As to what I need; at the end of the day I only need the working code, whether I wrote it, borrowed it or someone else did, it doesn't concern me much (other than accreditation and licensing). – Christian Jul 14 '10 at 14:51
  • 1
    I wrote [PHP to JS AST-based translator](https://gitlab.com/kornelski/babel-preset-php) which allows running PHP code as if it was JavaScript, using Babel. – Kornel Jul 23 '17 at 15:44

5 Answers5

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?
Charles
  • 50,943
  • 13
  • 104
  • 142
  • 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. – George Marian Jul 14 '10 at 22:41
  • 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. – Charles Jul 14 '10 at 22:47
  • 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 Jul 14 '10 at 23:24
  • 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. – Christian Jul 15 '10 at 08:58
  • By the way, I prefer this method way over mine. I've already used this kind of thing in a PHP syntax checking script. To be honest, I didn't give it much though. I'll see which one proves faster, mine or this (I'd hazard a guess at the later one). – Christian Jul 15 '10 at 09:14
  • How many fields are changing at once? How many concurrent users of the system are there, and how many fields do they cause to change within a period of time? In regards to parsing speed, it doesn't have to matter. You can probably just pre-convert the required code, right? – Charles Jul 15 '10 at 14:14
  • 1. Fields at once: can't really say. It all depends on the number of fields plus the conditions. 2/3. Concurrent users: 1 up to 100 at most, can't really tell at this point (we're still prototyping). Yes, I am pre-converting the code. When the user enters the page, the first thing that happens (more or less) is get a full list of fields, complete with expressions which are/should be in JS. – Christian Jul 15 '10 at 15:27
  • These users are not allow to change the expression (PHP/JS) but the client (ie, supervises users) should be able to do modify the expression in a friendly (non-technical) manner: http://stackoverflow.com/questions/3223899/php-eval-and-capturing-errors-as-much-as-possible – Christian Jul 15 '10 at 15:30
  • 2
    Ah, now I understand. The fact that you're having users effectively enter code to be executed pretty much explains everything. – Charles Jul 15 '10 at 15:38
3

Have you tried Harmony Framework?

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.

Christian
  • 27,509
  • 17
  • 111
  • 155
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.

danda
  • 189
  • 2
  • 5
-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
Tito100
  • 1,660
  • 1
  • 12
  • 12
  • Doesn't convert. Returns errors or doesn't convert at all. Even simple 3 line code. – Green Jul 25 '17 at 09:34
  • @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 :) – Tito100 Jul 26 '17 at 09:02