Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Non-Default Namespace for Model Type Export #29

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 39 additions & 10 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ import {
defaultFormRequestPath,
} from "@7nohe/laravel-zodgen";
import { createFormRequestTypes } from "./formRequests/createFormRequestTypes";
import { formatNamespaceForCommand, getPhpAst, getPhpNamespace } from "./utils";

export async function generate(options: CLIOptions) {
const parsedModelPath = path
.join(options.modelPath, "**", "*.php")
.replace(/\\/g, "/");
const models = sync(parsedModelPath).sort();
const modelPaths = sync(parsedModelPath).sort();

const modelData: LaravelModelType[] = [];
const parsedEnumPath = path
.join(options.enumPath, "**", "*.php")
Expand All @@ -35,15 +37,21 @@ export async function generate(options: CLIOptions) {
fs.mkdirSync(tmpDir);
}
// Generate models
for (const model of models) {
const modelName = model
for (const modelPath of modelPaths) {
const modelName = modelPath
.replace(options.modelPath.replace(/\\/g, "/") + "/", "")
.replace(path.extname(model), ""); // remove .php extension
.replace(path.extname(modelPath), "") // remove .php extension
.split("/")
.at(-1)!; // get only model name without directory
Comment on lines +44 to +45
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to extract History from Common/History, otherwise model:show command becomes like model:show App\\Models\\Common\\Common/History


createModelDirectory(modelName);
const modelShowCommand = `php artisan model:show ${modelName} --json > ${path.join(
tmpDir,
`${modelName}.json`
)}`;

const namespacedModel =
getNamespaceForCommand(modelPath) + "\\\\" + modelName;
const outputPath = path.join(tmpDir, `${modelName}.json`);

const modelShowCommand = `php artisan model:show ${namespacedModel} --json > ${outputPath}`;

try {
execSync(modelShowCommand);
const modelJson = JSON.parse(
Expand All @@ -65,8 +73,8 @@ export async function generate(options: CLIOptions) {

// Generate types for ziggy
if (options.ziggy) {
const routeListCommand = `php artisan route:list ${options.vendorRoutes ? "" : "--except-vendor"
} --json > ${tmpDir}/route.json`;
const vendorOption = options.vendorRoutes ? "" : "--except-vendor";
const routeListCommand = `php artisan route:list ${vendorOption} --json > ${tmpDir}/route.json`;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a refactoring

execSync(routeListCommand);
const routeJson = JSON.parse(
fs.readFileSync(`${tmpDir}/route.json`, "utf8")
Expand Down Expand Up @@ -109,3 +117,24 @@ const createModelDirectory = (modelName: string) => {
fs.mkdirSync(path.join(tmpDir, ...modelNameArray));
}
};

/**
* Cache for namespace by directory. Assume namespace is same when its directory is same
* e.g. { 'app/Models': 'App\Models', 'app-modules/{module}/Models': 'Modules/{Module}/Models', ... }
*/
const namespaceDictByDir: { [key: string]: string } = {};

export const getNamespaceForCommand = (phpFilepath: string) => {
const dir = path.dirname(phpFilepath);

if (namespaceDictByDir[dir]) {
return namespaceDictByDir[dir];
}

const ast = getPhpAst(phpFilepath);
const namespace = getPhpNamespace(ast).name;
const namespaceForCommand = formatNamespaceForCommand(namespace);
namespaceDictByDir[dir] = namespaceForCommand;

return namespaceForCommand;
};
30 changes: 27 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { defaultEnumPath } from "./constants";
import { Attribute } from "./types";
import { Engine, Namespace, Program } from "php-parser";
import fs from "fs";

// "app/Enums" -> "App-Enums"
const enumPath = defaultEnumPath
Expand All @@ -13,6 +15,28 @@ export const isEnum = (attribute: Attribute, customEnumPath?: string) => {
.match(new RegExp(customEnumPath ?? enumPath));
};

export const convertCamelToSnake = (camelCaseString: string) => {
return camelCaseString.replace(/[A-Z]/g, str => `_${str.toLowerCase()}`);
}
export const convertCamelToSnake = (camelCaseString: string): string => {
return camelCaseString.replace(/[A-Z]/g, (str) => `_${str.toLowerCase()}`);
};

export const formatNamespaceForCommand = (namespace: string): string => {
return namespace.replaceAll(/\\/g, "\\\\");
};

export const getPhpAst = (phpFilePath: string): Program => {
const parser = new Engine({});

const file = fs.readFileSync(phpFilePath);
const fileName = phpFilePath.split("/").at(-1)!;
const ast = parser.parseCode(file.toString(), fileName);

return ast;
};

export const getPhpNamespace = (phpAst: Program): Namespace => {
const namespaceObj = phpAst.children.find(
(child) => child.kind === "namespace"
) as Namespace;

return namespaceObj;
};