Skip to content

Commit 714b9e4

Browse files
committed
V1
0 parents  commit 714b9e4

File tree

11 files changed

+4906
-0
lines changed

11 files changed

+4906
-0
lines changed

.gitignore

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/dist/*
2+
!/dist/.gitkeep
3+
/node_modules
4+
/wordpress
5+
/server
6+
/export
7+
/composer.lock
8+
.DS_Store
9+
/.env
10+
/.ENV
11+
*.log
12+
13+
/vendor/
14+
mix-manifest.json
15+
build
16+
17+
/.idea/*

README.md

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
# JSON To PHP
2+
3+
`JSON To PHP` is an npm package that converts JSON strings into PHP-style associative arrays. It is useful when working
4+
with JavaScript applications that need to generate PHP code for dynamic content or server-side processing.
5+
6+
## Installation
7+
8+
You can install the package via npm:
9+
10+
```bash
11+
npm install jsontophp
12+
```
13+
14+
## Options:
15+
16+
```typescript
17+
interface Options {
18+
beautify?: boolean;
19+
indentLevel?: number;
20+
indentSize?: number;
21+
useTabs?: boolean;
22+
}
23+
```
24+
25+
The Options interface allows you to customize the behavior of the jsonToPhp function. Below are the available
26+
properties:
27+
28+
* `beautify` (optional, boolean): When set to true, the PHP array is formatted with line breaks and indentation for
29+
readability. Default is false.
30+
* `indentLevel` (optional, number): Specifies the initial indentation level for the PHP array. Default is 0.
31+
* `indentSize` (optional, number): Specifies the number of spaces for indentation when beautify is set to true. Ignored
32+
when `useTabs` is `true` Default is 4.
33+
* `useTabs` (optional, boolean): When set to true, tabs are used for indentation instead of spaces. Default is false.
34+
35+
## Usage
36+
37+
After installation, you can import and use `jsonToPhp` to convert JSON strings into PHP array format.
38+
39+
### Basic Conversion
40+
41+
The `jsonToPhp` function takes a JSON string and converts it to a PHP-style associative array.
42+
43+
```javascript
44+
import {jsonToPhp} from 'jsontophp';
45+
46+
const jsonString = '{"name": "John", "age": 30}';
47+
48+
const phpArray = jsonToPhp(jsonString);
49+
console.log(phpArray);
50+
// ['name' => 'John', 'age' => 30]
51+
```
52+
53+
### Nested JSON Conversion
54+
55+
The package supports nested JSON objects, converting them into nested PHP arrays.
56+
57+
```javascript
58+
const nestedJson = '{"user": {"name": "Alice", "email": "alice@example.com"}, "active": true}';
59+
60+
console.log(jsonToPhp(nestedJson));
61+
// ['user' => ['name' => 'Alice', 'email' => 'alice@example.com'], 'active' => true]
62+
```
63+
64+
### Arrays in JSON
65+
66+
You can also convert JSON arrays into PHP arrays.
67+
68+
```javascript
69+
const jsonArray = '{"fruits": ["apple", "banana", "cherry"]}';
70+
71+
console.log(jsonToPhp(jsonArray));
72+
// ['fruits' => ['apple', 'banana', 'cherry']]
73+
```
74+
75+
### Beautifying Output
76+
77+
You can beautify the output using the `beautify` option, which adds line breaks and indentation to make the PHP array
78+
more readable.
79+
80+
```javascript
81+
const jsonString = '{"name": "John", "address": {"city": "New York", "zip": "10001"}}';
82+
83+
console.log(jsonToPhp(jsonString, {beautify: true}));
84+
// [
85+
// 'name' => 'John',
86+
// 'address' => [
87+
// 'city' => 'New York',
88+
// 'zip' => '10001'
89+
// ]
90+
// ]
91+
```
92+
93+
### Indentation Level
94+
95+
The `indentLevel` option allows you to specify the inital indentation level for the PHP array.
96+
97+
```javascript
98+
console.log(jsonToPhp(jsonString, {beautify: true, indentLevel: 2}));
99+
// [
100+
// 'name' => 'John',
101+
// 'address' => [
102+
// 'city' => 'New York',
103+
// 'zip' => '10001'
104+
// ]
105+
// ]
106+
```
107+
108+
You can adjust the indentation size:
109+
110+
```javascript
111+
console.log(jsonToPhp(jsonString, {beautify: true, indentSize: 2}));
112+
// [
113+
// 'name' => 'John',
114+
// 'address' => [
115+
// 'city' => 'New York',
116+
// 'zip' => '10001'
117+
// ]
118+
// ]
119+
```
120+
121+
### Using Tabs for Indentation
122+
123+
You can use tabs for indentation by setting the `useTabs` option to `true`.
124+
125+
```javascript
126+
console.log(jsonToPhp(jsonString, {beautify: true, useTabs: true}));
127+
// [
128+
// 'name' => 'John',
129+
// 'address' => [
130+
// 'city' => 'New York',
131+
// 'zip' => '10001'
132+
// ]
133+
// ]
134+
```
135+
136+
### Handling Different Data Types
137+
138+
The package supports different JSON data types including strings, numbers, booleans, and null values.
139+
140+
```javascript
141+
const jsonWithTypes = '{"isAdmin": true, "balance": 100.5, "preferences": null}';
142+
143+
console.log(jsonToPhp(jsonWithTypes));
144+
// ['isAdmin' => true, 'balance' => 100.5, 'preferences' => null]
145+
```
146+
147+
148+
## Edge Cases
149+
150+
### Empty JSON
151+
152+
If you provide an empty JSON string, the package will return an empty PHP array.
153+
154+
```javascript
155+
console.log(jsonToPhp('{}'));
156+
// []
157+
```
158+
159+
### Invalid JSON
160+
161+
If the provided string is not valid JSON, it will throw an error.
162+
163+
```javascript
164+
try {
165+
jsonToPhp('{invalid}');
166+
} catch (error) {
167+
console.error('Invalid JSON format');
168+
}
169+
```
170+
171+
## License
172+
173+
MIT License
174+
175+
Copyright (c) 2024 Andrei Surdu
176+
177+
Permission is hereby granted, free of charge, to any person obtaining a copy
178+
of this software and associated documentation files (the "Software"), to deal
179+
in the Software without restriction, including without limitation the rights
180+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
181+
copies of the Software, and to permit persons to whom the Software is
182+
furnished to do so, subject to the following conditions:
183+
184+
The above copyright notice and this permission notice shall be included in all
185+
copies or substantial portions of the Software.
186+
187+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
188+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
189+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
190+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
191+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
192+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
193+
SOFTWARE.

index.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
exports.jsonToPhp = jsonToPhp;
4+
function jsonToPhp(jsonObj, options = { beautify: false, indentLevel: 0, indentSize: 4, useTabs: false }) {
5+
var _a;
6+
const indentLevelNumber = (_a = options.indentLevel) !== null && _a !== void 0 ? _a : 0;
7+
const indentSizeNumber = (options.indentSize && options.indentSize > 0 && options.indentSize < 10) ? options.indentSize : 4;
8+
const indentString = options.useTabs ? '\t' : ' '.repeat(indentSizeNumber);
9+
const indent = options.beautify ? indentString.repeat(indentLevelNumber) : '';
10+
const newline = options.beautify ? '\n' : '';
11+
const commaNewline = options.beautify ? ',\n' : ', ';
12+
function convert(obj, options) {
13+
if (Array.isArray(obj)) {
14+
return arrayToPhp(obj, options);
15+
}
16+
else if (typeof obj === "object" && obj !== null) {
17+
return objectToPhp(obj, options);
18+
}
19+
else if (typeof obj === "string") {
20+
return `'${obj.replace(/'/g, "\\'")}'`; // Escape single quotes
21+
}
22+
else if (typeof obj === "number") {
23+
return `${obj}`;
24+
}
25+
else if (typeof obj === "boolean") {
26+
return obj ? "true" : "false";
27+
}
28+
else if (obj === null) {
29+
return "null";
30+
}
31+
return "null"; // Fallback for undefined or other types
32+
}
33+
function arrayToPhp(arr, options) {
34+
var _a, _b;
35+
const innerIndent = options.beautify ? indentString.repeat(((_a = options.indentLevel) !== null && _a !== void 0 ? _a : 0) + 1) : '';
36+
const closingIndent = options.beautify ? indentString.repeat((_b = options.indentLevel) !== null && _b !== void 0 ? _b : 0) : '';
37+
const mapped = arr.map(item => { var _a; return convert(item, Object.assign(Object.assign({}, options), { indentLevel: ((_a = options.indentLevel) !== null && _a !== void 0 ? _a : 0) + 1 })); });
38+
return `[${newline}${innerIndent}${mapped.join(`${commaNewline}${innerIndent}`)}${newline}${closingIndent}]`;
39+
}
40+
function objectToPhp(obj, options) {
41+
var _a, _b;
42+
const innerIndent = options.beautify ? indentString.repeat(((_a = options.indentLevel) !== null && _a !== void 0 ? _a : 0) + 1) : '';
43+
const closingIndent = options.beautify ? indentString.repeat((_b = options.indentLevel) !== null && _b !== void 0 ? _b : 0) : '';
44+
const mapped = Object.keys(obj).map(key => {
45+
var _a;
46+
return `'${key.replace(/'/g, "\\'")}' => ${convert(obj[key], Object.assign(Object.assign({}, options), { indentLevel: ((_a = options.indentLevel) !== null && _a !== void 0 ? _a : 0) + 1 }))}`;
47+
});
48+
return `[${newline}${innerIndent}${mapped.join(`${commaNewline}${innerIndent}`)}${newline}${closingIndent}]`;
49+
}
50+
// if jsonObj is string, use JSON.parse to convert it to object
51+
if (typeof jsonObj === "string") {
52+
jsonObj = JSON.parse(jsonObj);
53+
}
54+
const finalString = convert(jsonObj, options);
55+
// replace empty arrays with with empty space or lines with just []
56+
return `${indent}${finalString}`.replace(/\[\s*\]/g, '[]');
57+
}

index.ts

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
interface Options {
2+
beautify?: boolean;
3+
indentLevel?: number;
4+
indentSize?: number;
5+
useTabs?: boolean;
6+
}
7+
8+
function jsonToPhp(jsonObj: any, options: Options = {beautify: false, indentLevel: 0, indentSize: 4, useTabs: false}): string {
9+
const indentLevelNumber = options.indentLevel ?? 0;
10+
const indentSizeNumber = (options.indentSize && options.indentSize > 0 && options.indentSize < 10) ? options.indentSize : 4;
11+
const indentString = options.useTabs ? '\t' : ' '.repeat(indentSizeNumber);
12+
const indent = options.beautify ? indentString.repeat(indentLevelNumber) : '';
13+
const newline = options.beautify ? '\n' : '';
14+
const commaNewline = options.beautify ? ',\n' : ', ';
15+
16+
function convert(obj: any, options: Options): string {
17+
if (Array.isArray(obj)) {
18+
return arrayToPhp(obj, options);
19+
} else if (typeof obj === "object" && obj !== null) {
20+
return objectToPhp(obj, options);
21+
} else if (typeof obj === "string") {
22+
return `'${obj.replace(/'/g, "\\'")}'`; // Escape single quotes
23+
} else if (typeof obj === "number") {
24+
return `${obj}`;
25+
} else if (typeof obj === "boolean") {
26+
return obj ? "true" : "false";
27+
} else if (obj === null) {
28+
return "null";
29+
}
30+
return "null"; // Fallback for undefined or other types
31+
}
32+
33+
function arrayToPhp(arr: any[], options: Options): string {
34+
const innerIndent = options.beautify ? indentString.repeat((options.indentLevel ?? 0) + 1) : '';
35+
const closingIndent = options.beautify ? indentString.repeat(options.indentLevel ?? 0) : '';
36+
const mapped = arr.map(item => convert(item, {...options, indentLevel: (options.indentLevel ?? 0) + 1}));
37+
return `[${newline}${innerIndent}${mapped.join(`${commaNewline}${innerIndent}`)}${newline}${closingIndent}]`;
38+
}
39+
40+
function objectToPhp(obj: { [key: string]: any }, options: Options): string {
41+
const innerIndent = options.beautify ? indentString.repeat((options.indentLevel ?? 0) + 1) : '';
42+
const closingIndent = options.beautify ? indentString.repeat(options.indentLevel ?? 0) : '';
43+
const mapped = Object.keys(obj).map(key =>
44+
`'${key.replace(/'/g, "\\'")}' => ${convert(obj[key], {
45+
...options,
46+
indentLevel: (options.indentLevel ?? 0) + 1
47+
})}`
48+
);
49+
return `[${newline}${innerIndent}${mapped.join(`${commaNewline}${innerIndent}`)}${newline}${closingIndent}]`;
50+
}
51+
52+
// if jsonObj is string, use JSON.parse to convert it to object
53+
if (typeof jsonObj === "string") {
54+
jsonObj = JSON.parse(jsonObj);
55+
}
56+
57+
const finalString = convert(jsonObj, options);
58+
59+
// replace empty arrays with with empty space or lines with just []
60+
return `${indent}${finalString}`.replace(/\[\s*\]/g, '[]');
61+
}
62+
63+
export {jsonToPhp};

jest.config.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'],
5+
};

0 commit comments

Comments
 (0)