Skip to content

Commit 6e4ce7d

Browse files
marvohhakarabakara
andauthored
Scan provided path for all available FQCNs in paths within and outside app folder (rappasoft#1714)
* Updated the make command to scan paths provided and check whether class of the model provided exists in the file. This works with paths that are both within the app folder and outside such as vendor directory --------- Co-authored-by: Marvin Ochieng <[email protected]>
1 parent 9c5a6dd commit 6e4ce7d

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
All notable changes to `laravel-livewire-tables` will be documented in this file
44

5+
=======
56
## [v3.2.6] - UNRELEASED
67
### New Features
78
- Add configurable wire:model for filters by @lrljoe in https://github.com/rappasoft/laravel-livewire-tables/pull/1699

src/Commands/MakeCommand.php

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,14 @@ public function getModelImport(): string
127127
}
128128

129129
if (isset($this->modelPath)) {
130-
if (File::exists(rtrim($this->modelPath, '/').'/'.$this->model.'.php')) {
131-
132-
return Str::studly(str_replace('/', '\\', $this->modelPath)).$this->model;
130+
$filename = rtrim($this->modelPath, '/').'/'.$this->model.'.php';
131+
if (File::exists($filename)) {
132+
//In case the file has more than one class which is highly unlikely but still possible
133+
$classes = array_filter($this->getClassesList($filename), function($class) {
134+
return substr($class,strrpos($class,'\\')+1) == $this->model;
135+
});
136+
if(count($classes) == 1)
137+
return $classes[0];
133138
}
134139
}
135140

@@ -138,6 +143,42 @@ public function getModelImport(): string
138143
return 'App\Models\\'.$this->model;
139144
}
140145

146+
/*
147+
* Credits to Harm Smits: https://stackoverflow.com/a/67099502/2263114
148+
*/
149+
private function getClassesList($file): array
150+
{
151+
$classes = [];
152+
$namespace = '';
153+
$tokens = \PhpToken::tokenize(file_get_contents($file));
154+
155+
for ($i = 0; $i < count($tokens); $i++) {
156+
if ($tokens[$i]->getTokenName() === 'T_NAMESPACE') {
157+
for ($j = $i + 1; $j < count($tokens); $j++) {
158+
if ($tokens[$j]->getTokenName() === 'T_NAME_QUALIFIED') {
159+
$namespace = $tokens[$j]->text;
160+
break;
161+
}
162+
}
163+
}
164+
165+
if ($tokens[$i]->getTokenName() === 'T_CLASS') {
166+
for ($j = $i + 1; $j < count($tokens); $j++) {
167+
if ($tokens[$j]->getTokenName() === 'T_WHITESPACE') {
168+
continue;
169+
}
170+
171+
if ($tokens[$j]->getTokenName() === 'T_STRING') {
172+
$classes[] = $namespace . '\\' . $tokens[$j]->text;
173+
} else {
174+
break;
175+
}
176+
}
177+
}
178+
}
179+
return $classes;
180+
}
181+
141182
/**
142183
* @throws \Exception
143184
*/

0 commit comments

Comments
 (0)