create-prisma-php-app 1.9.21 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function bsConfigUrls(e){const s=e.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.PROJECT_ROOT_PATH.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.PROJECT_ROOT_PATH.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e,s){const t=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(t,'const { createProxyMiddleware } = require("http-proxy-middleware");\n const fs = require("fs");\n \n const jsonData = fs.readFileSync("prisma-php.json", "utf8");\n const config = JSON.parse(jsonData);\n \n module.exports = {\n // First middleware: Set Cache-Control headers\n function(req, res, next) {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n // Use the \'middleware\' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n };',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s,t){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,s);i.scripts=Object.assign(Object.assign({},i.scripts),{projectName:"node settings/project-name.cjs"});let r=[];t.tailwindcss&&(i.scripts=Object.assign(Object.assign({},i.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),r.push("tailwind")),t.websocket&&(i.scripts=Object.assign(Object.assign({},i.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),r.push("websocket"));const a=Object.assign({},i.scripts);a["browser-sync"]=c,a.dev=r.length>0?`npm-run-all --parallel projectName browser-sync ${r.join(" ")}`:"npm-run-all --parallel projectName browser-sync",i.scripts=a,i.type="module",t.prisma&&(i.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(i,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";fs.existsSync(t)&&(n=fs.readFileSync(t,"utf8")),s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s){const t=fs.existsSync(e),n=t&&fs.statSync(e);if(t&&n&&n.isDirectory())fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t))}));else{if(checkExcludeFiles(s))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({srcDir:s,destDir:n})=>{if(!t.prisma&&"/prisma-client-php"===s)return;copyRecursiveSync(path.join(__dirname,s),path.join(e,n))}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8");const n='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">',i=s?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");if(checkExcludeFiles(t))return;let n=fs.existsSync(t)?fs.readFileSync(t,"utf8"):"";n.includes(s)||(n+=`${""!==n?"\n\n":""}${s}`,fs.writeFileSync(t,n,{flag:"w"}))}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s,t){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/.env",dest:"/.env"},{src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));n.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"},{srcDir:"/../vendor",destDir:"/vendor"}],s),await updatePackageJson(e,t,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);await createOrUpdateEnvFile(e,'# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n\n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var s,t,n,i;const c=[];e.projectName||c.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"});const r=c,a=()=>{process.exit(0)};try{const c=await prompts(r,{onCancel:a});return 0===Object.keys(c).length?null:{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=c.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=c.websocket)&&void 0!==n?n:e.websocket,prisma:null!==(i=c.prisma)&&void 0!==i?i:e.prisma}}catch(e){return null}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};async function main(){var e,s,t,n,i,c;try{const r=process.argv.slice(2);let a=r[0],o=null;if(a){const c={projectName:a,tailwindcss:r.includes("--tailwindcss"),websocket:r.includes("--websocket"),prisma:r.includes("--prisma")};if(o=await getAnswer(c),null===o)return;const p=process.cwd(),l=path.join(p,"prisma-php.json"),d=readJsonFile(l);let u=[];null===(e=d.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(p,e);fs.existsSync(s)&&u.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:a,tailwindcss:null!==(s=null==o?void 0:o.tailwindcss)&&void 0!==s&&s,websocket:null!==(t=null==o?void 0:o.websocket)&&void 0!==t&&t,prisma:null!==(n=null==o?void 0:o.prisma)&&void 0!==n&&n,isUpdate:!0,excludeFiles:null!==(i=d.excludeFiles)&&void 0!==i?i:[],excludeFilePath:null!=u?u:[],filePath:p}}else o=await getAnswer();if(null===o)return;execSync("npm install -g browser-sync",{stdio:"inherit"}),a||fs.mkdirSync(o.projectName);const p=process.cwd();let l=a?p:path.join(p,o.projectName);a||process.chdir(o.projectName);const d=["typescript","@types/node","ts-node","http-proxy-middleware@^2.0.6","npm-run-all"];o.tailwindcss&&d.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&d.push("chokidar-cli"),o.prisma&&d.push("prisma","@prisma/client"),await installDependencies(l,d,!0),a||execSync("npx tsc --init",{stdio:"inherit"}),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),o.prisma&&execSync("npx prisma init",{stdio:"inherit"});const u=l.replace(/\\/g,"\\"),h=o.prisma?"src/Lib/Prisma/Classes":"",f={PROJECT_NAME:o.projectName,PROJECT_ROOT_PATH:u,PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:h};await createDirectoryStructure(l,o,f);const m=path.join(l,"public");if(fs.existsSync(m)||fs.mkdirSync(m),!o.tailwindcss){const e=path.join(l,"src","app","css");["tailwind.css","styles.css"].forEach((s=>{const t=path.join(e,s);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.websocket){const e=path.join(l,"src","Lib","Websocket");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0});const s=path.join(l,"settings");["restart-websocket.cjs","restart-websocket.bat"].forEach((e=>{const t=path.join(s,e);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.prisma){const e=path.join(l,"prisma"),s=path.join(l,"src","Lib","Prisma");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0}),fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(l,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),e.length>0&&await uninstallDependencies(l,e,!0)}const w=await fetchPackageVersion("create-prisma-php-app"),y=bsConfigUrls(f),g=o.prisma?"src/Lib/Prisma/Classes":"",j={projectName:o.projectName,projectRootPath:u,phpEnvironment:"XAMPP",phpRootPathExe:"D:\\xampp\\php\\php.exe",phpGenerateClassPath:g,bsTarget:y.bsTarget,bsPathRewrite:y.bsPathRewrite,tailwindcss:o.tailwindcss,websocket:o.websocket,prisma:o.prisma,version:w,excludeFiles:null!==(c=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==c?c:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(j,null,2),{flag:"w"})}catch(e){process.exit(1)}}main();
|
|
2
|
+
import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function bsConfigUrls(e){const s=e.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.PROJECT_ROOT_PATH.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.PROJECT_ROOT_PATH.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e,s){const t=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(t,'const { createProxyMiddleware } = require("http-proxy-middleware");\n const fs = require("fs");\n \n const jsonData = fs.readFileSync("prisma-php.json", "utf8");\n const config = JSON.parse(jsonData);\n \n module.exports = {\n // First middleware: Set Cache-Control headers\n function(req, res, next) {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n // Use the \'middleware\' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n };',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s,t){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,s);i.scripts=Object.assign(Object.assign({},i.scripts),{projectName:"node settings/project-name.cjs"});let r=[];t.tailwindcss&&(i.scripts=Object.assign(Object.assign({},i.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),r.push("tailwind")),t.websocket&&(i.scripts=Object.assign(Object.assign({},i.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),r.push("websocket"));const a=Object.assign({},i.scripts);a["browser-sync"]=c,a.dev=r.length>0?`npm-run-all --parallel projectName browser-sync ${r.join(" ")}`:"npm-run-all --parallel projectName browser-sync",i.scripts=a,i.type="module",t.prisma&&(i.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(i,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";fs.existsSync(t)&&(n=fs.readFileSync(t,"utf8")),s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s){const t=fs.existsSync(e),n=t&&fs.statSync(e);if(t&&n&&n.isDirectory())fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t))}));else{if(checkExcludeFiles(s))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({srcDir:s,destDir:n})=>{if(!t.prisma&&"/prisma-client-php"===s)return;copyRecursiveSync(path.join(__dirname,s),path.join(e,n))}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8");const n='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">',i=s?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");if(checkExcludeFiles(t))return;let n=fs.existsSync(t)?fs.readFileSync(t,"utf8"):"";n.includes(s)||(n+=`${""!==n?"\n\n":""}${s}`,fs.writeFileSync(t,n,{flag:"w"}))}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s,t){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/.env",dest:"/.env"},{src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));n.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"},{srcDir:"/../vendor",destDir:"/vendor"}],s),await updatePackageJson(e,t,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);await createOrUpdateEnvFile(e,'# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n\n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var s,t,n,i;const c=[];e.projectName||c.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"});const r=c,a=()=>{process.exit(0)};try{const c=await prompts(r,{onCancel:a});return 0===Object.keys(c).length?null:{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=c.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=c.websocket)&&void 0!==n?n:e.websocket,prisma:null!==(i=c.prisma)&&void 0!==i?i:e.prisma}}catch(e){return null}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};async function main(){var e,s,t,n,i,c;try{const r=process.argv.slice(2);let a=r[0],o=null;if(a){const c={projectName:a,tailwindcss:r.includes("--tailwindcss"),websocket:r.includes("--websocket"),prisma:r.includes("--prisma")};if(o=await getAnswer(c),null===o)return;const p=process.cwd(),l=path.join(p,"prisma-php.json"),d=readJsonFile(l);let u=[];null===(e=d.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(p,e);fs.existsSync(s)&&u.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:a,tailwindcss:null!==(s=null==o?void 0:o.tailwindcss)&&void 0!==s&&s,websocket:null!==(t=null==o?void 0:o.websocket)&&void 0!==t&&t,prisma:null!==(n=null==o?void 0:o.prisma)&&void 0!==n&&n,isUpdate:!0,excludeFiles:null!==(i=d.excludeFiles)&&void 0!==i?i:[],excludeFilePath:null!=u?u:[],filePath:p}}else o=await getAnswer();if(null===o)return;execSync("npm install -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"}),a||fs.mkdirSync(o.projectName);const p=process.cwd();let l=a?p:path.join(p,o.projectName);a||process.chdir(o.projectName);const d=["typescript","@types/node","ts-node","http-proxy-middleware@^2.0.6","npm-run-all"];o.tailwindcss&&d.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&d.push("chokidar-cli"),o.prisma&&d.push("prisma","@prisma/client"),await installDependencies(l,d,!0),a||execSync("npx tsc --init",{stdio:"inherit"}),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),o.prisma&&execSync("npx prisma init",{stdio:"inherit"});const u=l.replace(/\\/g,"\\"),h=o.prisma?"src/Lib/Prisma/Classes":"",f={PROJECT_NAME:o.projectName,PROJECT_ROOT_PATH:u,PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:h};await createDirectoryStructure(l,o,f);const m=path.join(l,"public");if(fs.existsSync(m)||fs.mkdirSync(m),!o.tailwindcss){const e=path.join(l,"src","app","css");["tailwind.css","styles.css"].forEach((s=>{const t=path.join(e,s);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.websocket){const e=path.join(l,"src","Lib","Websocket");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0});const s=path.join(l,"settings");["restart-websocket.cjs","restart-websocket.bat"].forEach((e=>{const t=path.join(s,e);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.prisma){const e=path.join(l,"prisma"),s=path.join(l,"src","Lib","Prisma");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0}),fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(l,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),e.length>0&&await uninstallDependencies(l,e,!0)}const w=await fetchPackageVersion("create-prisma-php-app"),y=bsConfigUrls(f),g=o.prisma?"src/Lib/Prisma/Classes":"",j={projectName:o.projectName,projectRootPath:u,phpEnvironment:"XAMPP",phpRootPathExe:"D:\\xampp\\php\\php.exe",phpGenerateClassPath:g,bsTarget:y.bsTarget,bsPathRewrite:y.bsPathRewrite,tailwindcss:o.tailwindcss,websocket:o.websocket,prisma:o.prisma,version:w,excludeFiles:null!==(c=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==c?c:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(j,null,2),{flag:"w"})}catch(e){process.exit(1)}}main();
|
|
@@ -24,6 +24,33 @@ class Auth
|
|
|
24
24
|
$this->logger = $logger;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Authenticates a user and generates a JWT (JSON Web Token) based on the specified user role
|
|
29
|
+
* and token validity duration. The method first checks if the secret key is set, calculates
|
|
30
|
+
* the token's expiration time, sets the necessary payload, and encodes it into a JWT.
|
|
31
|
+
* If possible (HTTP headers not yet sent), it also sets cookies with the JWT for client-side storage.
|
|
32
|
+
*
|
|
33
|
+
* @param mixed $role A role identifier which can be a simple string or an instance of AuthRole.
|
|
34
|
+
* If an instance of AuthRole is provided, its `value` property will be used as the role in the token.
|
|
35
|
+
* @param string|null $tokenValidity Optional parameter specifying the duration the token is valid for (e.g., '10m', '1h').
|
|
36
|
+
* If null, the default validity period set in the class property is used.
|
|
37
|
+
* The format should be a number followed by a time unit ('s' for seconds, 'm' for minutes,
|
|
38
|
+
* 'h' for hours, 'd' for days), and this is parsed to calculate the exact expiration time.
|
|
39
|
+
*
|
|
40
|
+
* @return string Returns the encoded JWT as a string.
|
|
41
|
+
*
|
|
42
|
+
* @throws InvalidArgumentException Thrown if the secret key is not set or if the duration format is invalid.
|
|
43
|
+
*
|
|
44
|
+
* Example:
|
|
45
|
+
* $auth = new Authentication();
|
|
46
|
+
* $auth->setSecretKey('your_secret_key');
|
|
47
|
+
* try {
|
|
48
|
+
* $jwt = $auth->authenticate('Admin', '1h');
|
|
49
|
+
* echo "JWT: " . $jwt;
|
|
50
|
+
* } catch (\InvalidArgumentException $e) {
|
|
51
|
+
* echo "Error: " . $e->getMessage();
|
|
52
|
+
* }
|
|
53
|
+
*/
|
|
27
54
|
public function authenticate($role, string $tokenValidity = null): string
|
|
28
55
|
{
|
|
29
56
|
if (!$this->secretKey) {
|
|
@@ -54,6 +81,11 @@ class Auth
|
|
|
54
81
|
return $jwt;
|
|
55
82
|
}
|
|
56
83
|
|
|
84
|
+
public function isAuthenticated(): bool
|
|
85
|
+
{
|
|
86
|
+
return isset($_SESSION[self::PAYLOAD]);
|
|
87
|
+
}
|
|
88
|
+
|
|
57
89
|
private function calculateExpirationTime(string $duration): int
|
|
58
90
|
{
|
|
59
91
|
$now = new DateTime();
|
|
@@ -16,8 +16,8 @@ enum AuthRole: string
|
|
|
16
16
|
class AuthConfig
|
|
17
17
|
{
|
|
18
18
|
public const ROLE_IDENTIFIER = 'role';
|
|
19
|
-
public const IS_ROLE_BASE =
|
|
20
|
-
public const IS_TOKEN_AUTO_REFRESH =
|
|
19
|
+
public const IS_ROLE_BASE = false;
|
|
20
|
+
public const IS_TOKEN_AUTO_REFRESH = false;
|
|
21
21
|
|
|
22
22
|
// An array listing the public routes that do not require authentication.
|
|
23
23
|
// Example: public static $publicRoutes = ['/'];
|