├── docs
├── public
│ ├── img
│ │ ├── php2js.png
│ │ ├── logo-github.png
│ │ ├── logo-full-scream.png
│ │ ├── laravel_black.svg
│ │ └── laravel-red.svg
│ └── css
│ │ └── style.css
├── javascript-methods
│ ├── get.md
│ ├── destroy.md
│ ├── has.md
│ ├── only.md
│ ├── set.md
│ ├── except.md
│ └── assign.md
├── contribute
│ ├── report-bugs.md
│ └── contribution.md
├── getting-started
│ ├── installation.md
│ ├── versions.md
│ └── changelog.md
├── index.md
├── home.md
├── controllers
│ ├── share-with-js.md
│ ├── share-specific-vars.md
│ ├── view-return.md
│ └── assign-custom-alias.md
└── .vitepress
│ └── config.mts
├── test
└── PHP2JSTest.php
├── package.json
├── phpstan.neon
├── .gitignore
├── src
├── Traits
│ └── Alias.php
├── Stubs
│ └── PHP2JS.stub
├── Bases
│ ├── BaseRender.php
│ └── BaseGenerator.php
├── Macros
│ └── Php2JsServiceProvider.php
├── Elements
│ └── Generator.php
└── Render.php
├── LICENSE.md
├── composer.json
├── .github
└── workflows
│ └── deploy.yml
└── README.md
/docs/public/img/php2js.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rmunate/PHP2JS/HEAD/docs/public/img/php2js.png
--------------------------------------------------------------------------------
/docs/public/img/logo-github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rmunate/PHP2JS/HEAD/docs/public/img/logo-github.png
--------------------------------------------------------------------------------
/docs/public/img/logo-full-scream.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rmunate/PHP2JS/HEAD/docs/public/img/logo-full-scream.png
--------------------------------------------------------------------------------
/test/PHP2JSTest.php:
--------------------------------------------------------------------------------
1 | const {PHP2JS}Helpers={getData:()=>{const t=document.querySelector('meta[name="X-{PHP2JS}-DATA"]');if(t){const n=JSON.parse(t.getAttribute("content"));return t.parentNode.removeChild(t),n}return null}},{PHP2JS}={data:{PHP2JS}Helpers.getData(),destroy:function(){for(let t in this)this.hasOwnProperty(t)&&delete this[t];return!0},assign:function(){return Object.assign({},this)},assignAndDestroy:function(){const t=Object.assign({},this);return this.destroy(),t},only:function(...t){let n={};return t.forEach((t=>{this.data.hasOwnProperty(t)&&(n[t]=this.data[t])})),n},except:function(...t){let n={};for(const e in this.data)t.includes(e)||(n[e]=this.data[e]);return n},has:function(t){return this.data.hasOwnProperty(t)},get:function(t){return this.data[t]||null},set:function(t,n){this.data[t]=n}};
--------------------------------------------------------------------------------
/src/Bases/BaseRender.php:
--------------------------------------------------------------------------------
1 | view)
21 | ->with($this->getData())
22 | ->toJS($alias)
23 | ->compose();
24 | });
25 |
26 | /* Return only specific variables to the JavaScript context */
27 | View::macro('toStrictJS', function (array $values = [], string $alias = 'PHP2JS') {
28 | return Render::view($this->view)
29 | ->with($this->getData())
30 | ->toStrictJS($values, $alias)
31 | ->compose();
32 | });
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/docs/getting-started/versions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Versions
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | # Versions
8 |
9 | During the development of this solution, multiple tool versions were released. It's crucial to note that previous versions are NOT compatible with the latest update. This documentation is tailored specifically for the usage of the current version.
10 |
11 | We highly recommend migrating from older versions to the latest release, as no support is provided for any previous versions.
12 |
13 | | Version | Release Date | End of Support Date |
14 | |--------------------------------------------------------|--------------|---------------------|
15 | | ^0.1 | 2021-10-21 | 2021-12-31 |
16 | | ^1.0 | 2021-11-13 | 2023-01-15 |
17 | | ^2.0 | 2022-10-05 | 2023-06-24 |
18 | | ^3.0 | 2023-06-01 | 2023-11-15 |
19 | | ^4.0 | 2023-11-16 | 2024-12-31 |
20 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rmunate/php2js",
3 | "description": "Effortlessly share PHP Laravel values with external JavaScript files using just one command, thanks to the seamless integration of PHP2JS.",
4 | "keywords": [
5 | "PHP2JS",
6 | "php2js",
7 | "toJS",
8 | "toStrictJS"
9 | ],
10 | "homepage": "https://github.com/rmunate/PHP2JS",
11 | "type": "library",
12 | "license": "MIT",
13 | "autoload": {
14 | "psr-4": {
15 | "Rmunate\\Php2Js\\": "src/"
16 | }
17 | },
18 | "authors": [
19 | {
20 | "name": "Raul Mauricio Uñate Castro",
21 | "email": "raulmauriciounate@gmail.com",
22 | "role": "owner",
23 | "homepage": "https://github.com/rmunate"
24 | }
25 | ],
26 | "require": {
27 | "php": "^8.1",
28 | "illuminate/support": "^10.0|^11.0"
29 | },
30 | "require-dev": {
31 | "phpstan/phpstan": "^1.10",
32 | "phpunit/phpunit": "^10.4|^11.0|^12.0"
33 | },
34 | "extra": {
35 | "branch-alias": {
36 | "dev-main": "v3.0.x-dev"
37 | },
38 | "laravel": {
39 | "providers": [
40 | "Rmunate\\Php2Js\\Macros\\Php2JsServiceProvider"
41 | ]
42 | }
43 | },
44 | "minimum-stability": "dev",
45 | "prefer-stable": true
46 | }
47 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | layout: home
3 |
4 | hero:
5 | name: Laravel
6 | text: PHP2JS
7 | tagline: Developing Laravel monoliths has never been easier and more efficient! 💻✨
8 | image:
9 | src: img/php2js.png
10 | alt: VitePress
11 | actions:
12 | - theme: brand
13 | text: Get Started
14 | link: /home
15 | - theme: alt
16 | text: View on GitHub
17 | link: https://github.com/rmunate/PHP2JS
18 |
19 | features:
20 | - icon: 🚀
21 | title: Share Variables with JavaScript
22 | details: Now, with just one method from your controller, you can easily share variables with external JavaScript files. It's easy, simple, elegant, and highly efficient.
23 | - icon: 🌐
24 | title: Only One Method
25 | details: With just one additional method in your controller, you can pass the variables you need to the JavaScript context. Forget about inserting scripts in your views; it's time to separate the logic in a more elegant, efficient, and secure way.
26 | - icon: 📢
27 | title: Reduced Server Load
28 | details: Recently, some solutions (FullStack Frameworks) have become popular for overloading servers with SSR processes. If you genuinely want a maintainable application over time, you might want to start here.
29 | ---
--------------------------------------------------------------------------------
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Deploy VitePress site to Pages
2 |
3 | on:
4 | push:
5 | branches: [master]
6 | workflow_dispatch:
7 |
8 | permissions:
9 | contents: read
10 | pages: write
11 | id-token: write
12 |
13 | concurrency:
14 | group: "pages"
15 | cancel-in-progress: false
16 |
17 | jobs:
18 | build:
19 | runs-on: ubuntu-latest
20 | steps:
21 | - name: Checkout
22 | uses: actions/checkout@v4
23 |
24 | - name: Setup Node.js
25 | uses: actions/setup-node@v4
26 | with:
27 | node-version: 18
28 | cache: npm
29 |
30 | - name: Install dependencies
31 | run: npm ci
32 |
33 | - name: Build with VitePress
34 | run: |
35 | npm run docs:build
36 | touch docs/.vitepress/dist/.nojekyll
37 |
38 | - name: Upload artifact
39 | uses: actions/upload-pages-artifact@v3
40 | with:
41 | path: docs/.vitepress/dist
42 |
43 | deploy:
44 | needs: build
45 | runs-on: ubuntu-latest
46 | environment:
47 | name: github-pages
48 | url: ${{ steps.deployment.outputs.page_url }}
49 | steps:
50 | - name: Deploy to GitHub Pages
51 | id: deployment
52 | uses: actions/deploy-pages@v4
53 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PHP2JS
2 |
3 | ## 🚀 Seamless Integration: PHP2JS 🚀
4 |
5 | Share PHP Laravel values effortlessly with external JavaScript files using just one command, thanks to the seamless integration of PHP2JS.
6 |
7 | Developing Laravel monoliths has never been easier and more efficient! 💻✨
8 |
9 | ## The Library that Made Handling Monoliths in Laravel Simple - LARAVEL PHP Framework
10 |
11 | 
12 |
13 | ## Documentation
14 | [](https://rmunate.github.io/PHP2JS/)
15 |
16 | ## Installation PHP2JS
17 | To install the dependency via Composer.
18 |
19 | ```shell
20 | composer require rmunate/php2js
21 | ```
22 |
23 | ## License
24 | This project is under the [MIT License](https://choosealicense.com/licenses/mit/).
25 |
26 | 🌟 Support My Projects! 🚀
27 |
28 | [](https://github.com/sponsors/rmunate)
29 |
30 | Make any contributions you see fit; the code is entirely yours. Together, we can do amazing things and improve the world of development. Your support is invaluable. ✨
31 |
32 | If you have ideas, suggestions, or just want to collaborate, we are open to everything! Join our community and be part of our journey to success! 🌐👩💻👨💻
33 |
--------------------------------------------------------------------------------
/docs/javascript-methods/assign.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Assign
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | # `.assign()`
8 |
9 | ## Assign Same Object
10 |
11 | The `.assign()` method assigns the same values of the object delivered by PHP to a new variable or constant. Now you can remove the original object without losing the values you leave in the new one. This will be useful when you want the values not to be accessible from different references to the original object and instead use an object in JavaScript runtime.
12 |
13 | ```javascript
14 | // Assign a copy of the object to a new variable at runtime.
15 | // Remember to replace PHP2JS with the Alias you have used.
16 | const __PHP = PHP2JS.assign();
17 |
18 | // You can now destroy the original object.
19 | PHP2JS.destroy();
20 |
21 | // The values will now be in "__PHP"
22 | ```
23 |
24 | ## Assign and Destroy
25 |
26 | The `.assignAndDestroy()` method assigns the same values of the object delivered by PHP to a new variable or constant and additionally clears the original object. This will be useful when you want the values not to be accessible from different references to the original object and instead use an object in JavaScript runtime.
27 |
28 | ```javascript
29 | // Destroy the Object (All references to the original object will lose their values)
30 | // Remember to replace PHP2JS with the Alias you have used.
31 | const __PHP = PHP2JS.assignAndDestroy();
32 |
33 | // The values will now be in "__PHP"
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/home.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Introduction
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | 
8 |
9 | ## Introduction
10 |
11 | While there are multiple frontend frameworks available today, we acknowledge that monoliths created with the Laravel Framework will continue to exist for a long time, and this is not necessarily a negative aspect. The most effective solution doesn't always lie in adopting the latest-generation framework. Sometimes, it is more efficient for a development team to leverage standard technologies and the knowledge they already possess.
12 |
13 | By using technologies like jQuery, Vanilla JavaScript, HTML, CSS, and Laravel's Blade view engine, remarkable and highly functional results can be achieved. However, we felt something was missing: a simple, elegant, and efficient way to share data from the server to JavaScript on the frontend. We were uncomfortable inserting JavaScript snippets into our views; we always aimed to separate this logic into independent files.
14 |
15 | It was then that server requests began to increase to retrieve variables that were already present in the view. After much contemplation on what would be the most effective solution, we decided to create this solution that standardizes and simplifies the process of sharing data from PHP to JavaScript.
16 |
17 | You might be wondering how it's possible to achieve this, as there are different approaches in each programming language. Let us tell you that we faced that challenge too, but now we have overcome it.
18 |
19 | Enjoy the ease of sharing data with JavaScript.
--------------------------------------------------------------------------------
/docs/controllers/share-with-js.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Sharing Values with JavaScript
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | # Sharing Values with JavaScript
8 |
9 | After grasping the concepts explained on the previous page, we will delve into the utilization of any of the four options mentioned earlier to share the variables returned to the view with JavaScript.
10 |
11 | Upon installing this package, you gain access to the `->toJS()` method. This method facilitates the direct sharing of all variables passed to the view with scripts written in both the same Blade view file and external JavaScript files added using the syntax:
12 |
13 | ```html
14 |
15 | ```
16 |
17 | Consider the following example:
18 |
19 | ```php
20 | class YourController extends Controller
21 | {
22 | public function index()
23 | {
24 | return view('welcome')->with([
25 | 'moonLandingDate' => '1969-07-20'
26 | ])->toJS();
27 | }
28 | }
29 | ```
30 |
31 | Remember, you can utilize any of the four methods for passing variables to the view as explained on the previous page.
32 |
33 | The provided code enables you to promptly access the variables returned from the controller in your JavaScript scripts through a constant named `PHP2JS`.
34 |
35 | ```javascript
36 | let moonLandingDate = PHP2JS.data.moonLandingDate;
37 | // '1969-07-20'
38 | ```
39 |
40 | :::info Important!
41 | Values will be shared with scripts written within `` tags or imported via `` within the `
` of the HTML.
42 | :::
--------------------------------------------------------------------------------
/docs/controllers/share-specific-vars.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Share Specific Values with JavaScript
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 |
8 | # Share Specific Values with JavaScript
9 |
10 | If you need to share only particular values returned to the view with JavaScript, rather than all variables, the `->toStrictJS()` method provides a more targeted approach. This method functions similarly to Laravel Framework's `->with()` method.
11 |
12 | Let's explore an example where distinct values are shared with both the view and JavaScript.
13 |
14 | ```php
15 | class YourController extends Controller
16 | {
17 | public function index()
18 | {
19 | $astronauts = [
20 | 'Neil Armstrong',
21 | 'Buzz Aldrin',
22 | 'Michael Collins'
23 | ];
24 |
25 | $spacecraft = "Lunar Module Eagle";
26 | $event = "Apollo 11 Moon Landing";
27 |
28 | return view('welcome')->with([
29 | 'astronauts' => $astronauts
30 | ])->toStrictJS([
31 | 'spacecraft' => $spacecraft,
32 | 'event' => $event,
33 | ]);
34 | }
35 | }
36 | ```
37 |
38 | In this example, only the values of `spacecraft` and `event` are shared with JavaScript.
39 |
40 | ```javascript
41 | let spacecraft = PHP2JS.data.spacecraft;
42 | // 'Lunar Module Eagle'
43 |
44 | let event = PHP2JS.data.event;
45 | // 'Apollo 11 Moon Landing'
46 | ```
47 |
48 | This method provides a more granular control over the information shared with JavaScript, ensuring a streamlined integration of specific values between your Laravel application and the client-side scripts.
--------------------------------------------------------------------------------
/docs/controllers/view-return.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Return View
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | # Return View
8 |
9 | The following code demonstrates how to return a view conventionally without sharing data with JS, in a native manner as outlined by the framework. It is crucial to understand the various ways a view can be returned with data, as we rely on this to explain how values are shared with JavaScript.
10 |
11 | ## Compact Shape 1
12 | Using the `view` method with `compact`
13 |
14 | ```php
15 | class YourController extends Controller
16 | {
17 | public function index()
18 | {
19 | $library = 'PHP2JS';
20 | return view('welcome', compact('library'));
21 | }
22 | }
23 | ```
24 |
25 | ## Compact Shape 2
26 | Using only the `view` method without `compact`
27 |
28 | ```php
29 | class YourController extends Controller
30 | {
31 | public function index()
32 | {
33 | $library = 'PHP2JS';
34 | return view('welcome', [
35 | 'library' => $library
36 | ]);
37 | }
38 | }
39 | ```
40 |
41 | ## Fluid Methods 1
42 | Using the `view` method, the "with" method, and `compact`
43 |
44 | ```php
45 | class YourController extends Controller
46 | {
47 | public function index()
48 | {
49 | $library = 'PHP2JS';
50 | return view('welcome')->with(compact('library'));
51 | }
52 | }
53 | ```
54 |
55 | ## Fluid Methods 2
56 | Using the `view` method, the "with" method without `compact`
57 |
58 | ```php
59 | class YourController extends Controller
60 | {
61 | public function index()
62 | {
63 | $library = 'PHP2JS';
64 | return view('welcome')->with([
65 | 'library' => $library
66 | ]);
67 | }
68 | }
69 | ```
--------------------------------------------------------------------------------
/docs/controllers/assign-custom-alias.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Customize JavaScript Alias
3 | editLink: true
4 | outline: deep
5 | ---
6 |
7 | # Customize JavaScript Alias
8 |
9 | By default, the package provides access to backend variables in the JavaScript context through the constant `PHP2JS`. However, you can customize this alias to better suit your needs or align with its purpose. For instance:
10 |
11 | - __PHP
12 | - __Laravel
13 | - __Back
14 | - __MyAlias
15 |
16 | ## Assigning a Custom Alias
17 |
18 | ### Method `->toJS()`
19 |
20 | Simply specify the desired constant name as an argument of the `->toJS()` method. Keep in mind that this name becomes reserved and cannot be redeclared in your JavaScript files.
21 |
22 | ```php
23 | class YourController extends Controller
24 | {
25 | public function index()
26 | {
27 | $event = "Apollo 11 Moon Landing";
28 |
29 | return view('welcome')->with([
30 | 'event' => $event
31 | ])->toJS("__PHP");
32 | }
33 | }
34 | ```
35 |
36 | Now access the values using this constant in JavaScript:
37 |
38 | ```javascript
39 | let event = __PHP.data.event;
40 | // 'Apollo 11 Moon Landing'
41 | ```
42 |
43 | ### Method `->toStrictJS()`
44 |
45 | ```php
46 | class YourController extends Controller
47 | {
48 | public function index()
49 | {
50 | $spacecraft = "Lunar Module Eagle";
51 | $event = "Apollo 11 Moon Landing";
52 |
53 | return view('welcome')->with([
54 | 'spacecraft' => $spacecraft
55 | ])->toStrictJS([
56 | 'event' => $event
57 | ], "__PHP");
58 | }
59 | }
60 | ```
61 |
62 | Now in JavaScript:
63 |
64 | ```javascript
65 | let event = __PHP.data.event;
66 | // 'Apollo 11 Moon Landing'
67 | ```
68 |
69 | Customizing the JavaScript alias provides flexibility, allowing you to integrate the package seamlessly with your Laravel application while aligning with your coding preferences.
--------------------------------------------------------------------------------
/src/Elements/Generator.php:
--------------------------------------------------------------------------------
1 | alias = $alias;
30 | }
31 |
32 | /**
33 | * Generate HTML span element with encoded JSON data and a specified alias.
34 | *
35 | * @param array $data The data to be encoded and stored in the span element.
36 | *
37 | * @throws Exception If the provided alias is not valid.
38 | *
39 | * @return string The HTML span element with encoded data.
40 | */
41 | public function data(array $data): string
42 | {
43 | // Encode data to JSON without escaping Unicode characters
44 | $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
45 |
46 | // Replace placeholders in the meta tag template
47 | $metaTag = sprintf(
48 | '',
49 | $this->alias,
50 | htmlspecialchars($jsonData, ENT_QUOTES, 'UTF-8')
51 | );
52 |
53 | // Return the HTML meta tag
54 | return $metaTag;
55 | }
56 |
57 | /**
58 | * Generate PHP2JS script JavaScript stub content with the set alias.
59 | *
60 | * @return string The PHP2JS script JavaScript stub content.
61 | */
62 | public function script(): string
63 | {
64 | // Get the content of the PHP2JS stub file
65 | $stub = file_get_contents(__DIR__.'/../Stubs/PHP2JS.stub');
66 |
67 | // Replace the placeholder with the set alias
68 | return str_replace('{PHP2JS}', $this->alias, $stub);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/docs/public/img/laravel_black.svg:
--------------------------------------------------------------------------------
1 |
4 |
--------------------------------------------------------------------------------
/src/Render.php:
--------------------------------------------------------------------------------
1 | view = $view;
27 | }
28 |
29 | /**
30 | * Add data to the Render instance.
31 | *
32 | * @param array $data
33 | *
34 | * @return static
35 | */
36 | public function with(array $data): static
37 | {
38 | $this->data = $data;
39 |
40 | return $this;
41 | }
42 |
43 | /**
44 | * @param string $alias
45 | *
46 | * @return static
47 | */
48 | public function toJS(string $alias = 'PHP2JS'): static
49 | {
50 | $this->dataJS = $this->data;
51 | $this->alias = $alias;
52 |
53 | return $this;
54 | }
55 |
56 | /**
57 | * @param array $data
58 | * @param string $alias
59 | *
60 | * @return static
61 | */
62 | public function toStrictJS(array $data = [], string $alias = 'PHP2JS'): static
63 | {
64 | $this->dataJS = $data;
65 | $this->alias = $alias;
66 |
67 | return $this;
68 | }
69 |
70 | /**
71 | * Return the View.
72 | *
73 | * @return mixed
74 | */
75 | public function compose()
76 | {
77 | $view = view($this->view)->with($this->data);
78 | $html = $view->render();
79 |
80 | $metas = Generator::alias($this->alias)->data($this->dataJS);
81 | $scripts = Generator::alias($this->alias)->script();
82 |
83 | $posicionCierreHead = strpos($html, '');
84 | $posicionCierreBody = strpos($html, '