Skip to content
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
21 changes: 21 additions & 0 deletions php-templates/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Taylor Otwell

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
5 changes: 5 additions & 0 deletions php-templates/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
The templates here are based on the official VS Code extension by Laravel https://github.com/laravel/vs-code-extension

Modifications:
- return instead of echo
- do not serialize to JSON
131 changes: 131 additions & 0 deletions php-templates/configs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

$local = collect(glob(config_path('/*.php')))
->merge(glob(config_path('**/*.php')))
->map(fn ($path) => [
(string) Illuminate\Support\Str::of($path)
->replace([config_path('/'), '.php'], '')
->replace('/', '.'),
$path,
]);

$vendor = collect(glob(base_path('vendor/**/**/config/*.php')))->map(fn (
$path
) => [
(string) Illuminate\Support\Str::of($path)
->afterLast('/config/')
->replace('.php', '')
->replace('/', '.'),
$path,
]);

$configPaths = $local
->merge($vendor)
->groupBy(0)
->map(fn ($items) => $items->pluck(1));

$cachedContents = [];
$cachedParsed = [];

function vsCodeGetConfigValue($value, $key, $configPaths)
{
$parts = explode('.', $key);
$toFind = $key;
$found = null;

while (count($parts) > 0) {
array_pop($parts);
$toFind = implode('.', $parts);

if ($configPaths->has($toFind)) {
$found = $toFind;
break;
}
}

if ($found === null) {
return null;
}

$file = null;
$line = null;

if ($found === $key) {
$file = $configPaths->get($found)[0];
} else {
foreach ($configPaths->get($found) as $path) {
$cachedContents[$path] ??= file_get_contents($path);
$cachedParsed[$path] ??= token_get_all($cachedContents[$path]);

$keysToFind = Illuminate\Support\Str::of($key)
->replaceFirst($found, '')
->ltrim('.')
->explode('.');

if (is_numeric($keysToFind->last())) {
$index = $keysToFind->pop();

if ($index !== '0') {
return null;
}

$key = collect(explode('.', $key));
$key->pop();
$key = $key->implode('.');
$value = 'array(...)';
}

$nextKey = $keysToFind->shift();
$expectedDepth = 1;

$depth = 0;

foreach ($cachedParsed[$path] as $token) {
if ($token === '[') {
$depth++;
}

if ($token === ']') {
$depth--;
}

if (!is_array($token)) {
continue;
}

$str = trim($token[1], '"\'');

if (
$str === $nextKey &&
$depth === $expectedDepth &&
$token[0] === T_CONSTANT_ENCAPSED_STRING
) {
$nextKey = $keysToFind->shift();
$expectedDepth++;

if ($nextKey === null) {
$file = $path;
$line = $token[2];
break;
}
}
}

if ($file) {
break;
}
}
}

return [
'name' => $key,
'value' => $value,
'file' => $file === null ? null : str_replace(base_path('/'), '', $file),
'line' => $line,
];
}

return collect(Illuminate\Support\Arr::dot(config()->all()))
->map(fn ($value, $key) => vsCodeGetConfigValue($value, $key, $configPaths))
->filter()
->values();
46 changes: 46 additions & 0 deletions php-templates/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

function vsCodeGetRouterReflection(Illuminate\Routing\Route $route)
{
if ($route->getActionName() === 'Closure') {
return new ReflectionFunction($route->getAction()['uses']);
}

if (!str_contains($route->getActionName(), '@')) {
return new ReflectionClass($route->getActionName());
}

try {
return new ReflectionMethod($route->getControllerClass(), $route->getActionMethod());
} catch (Throwable $e) {
$namespace = app(Illuminate\Routing\UrlGenerator::class)->getRootControllerNamespace()
?? (app()->getNamespace() . 'Http\Controllers');

return new ReflectionMethod(
$namespace . '\\' . ltrim($route->getControllerClass(), '\\'),
$route->getActionMethod(),
);
}
}

return collect(app('router')->getRoutes()->getRoutes())
->map(function (Illuminate\Routing\Route $route) {
try {
$reflection = vsCodeGetRouterReflection($route);
} catch (Throwable $e) {
$reflection = null;
}

return [
'method' => collect($route->methods())->filter(function ($method) {
return $method !== 'HEAD';
})->implode('|'),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
'parameters' => $route->parameterNames(),
'filename' => $reflection ? $reflection->getFileName() : null,
'line' => $reflection ? $reflection->getStartLine() : null,
];
})
;
143 changes: 143 additions & 0 deletions php-templates/translations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

function vsCodeGetTranslationsFromFile($file, $path, $namespace)
{
$key = pathinfo($file, PATHINFO_FILENAME);

if ($namespace) {
$key = "{$namespace}::{$key}";
}

$lang = collect(explode(DIRECTORY_SEPARATOR, str_replace($path, '', $file)))
->filter()
->first();

$fileLines = Illuminate\Support\Facades\File::lines($file);
$lines = [];
$inComment = false;

foreach ($fileLines as $index => $line) {
$trimmed = trim($line);

if (substr($trimmed, 0, 2) === '/*') {
$inComment = true;
continue;
}

if ($inComment) {
if (substr($trimmed, -2) !== '*/') {
continue;
}

$inComment = false;
}

if (substr($trimmed, 0, 2) === '//') {
continue;
}

$lines[] = [$index + 1, $trimmed];
}

return [
'k' => $key,
'la' => $lang,
'vs' => collect(Illuminate\Support\Arr::dot((Illuminate\Support\Arr::wrap(__($key, [], $lang)))))
->map(
fn ($value, $key) => vsCodeTranslationValue(
$key,
$value,
str_replace(base_path(DIRECTORY_SEPARATOR), '', $file),
$lines
)
)
->filter(),
];
}

function vsCodeTranslationValue($key, $value, $file, $lines): ?array
{
if (is_array($value)) {
return null;
}

$lineNumber = 1;
$keys = explode('.', $key);
$index = 0;
$currentKey = array_shift($keys);

foreach ($lines as $index => $line) {
if (
strpos($line[1], '"' . $currentKey . '"', 0) !== false ||
strpos($line[1], "'" . $currentKey . "'", 0) !== false
) {
$lineNumber = $line[0];
$currentKey = array_shift($keys);
}

if ($currentKey === null) {
break;
}
}

return [
'v' => $value,
'p' => $file,
'li' => $lineNumber,
'pa' => preg_match_all("/\:([A-Za-z0-9_]+)/", $value, $matches)
? $matches[1]
: [],
];
}

function vscodeCollectTranslations(string $path, ?string $namespace = null)
{
$realPath = realpath($path);

if (!is_dir($realPath)) {
return collect();
}

return collect(Illuminate\Support\Facades\File::allFiles($realPath))->map(
fn ($file) => vsCodeGetTranslationsFromFile($file, $path, $namespace)
);
}

$loader = app('translator')->getLoader();
$namespaces = $loader->namespaces();

$reflection = new ReflectionClass($loader);
$property = $reflection->hasProperty('paths')
? $reflection->getProperty('paths')
: $reflection->getProperty('path');
$property->setAccessible(true);

$paths = Illuminate\Support\Arr::wrap($property->getValue($loader));

$default = collect($paths)->flatMap(
fn ($path) => vscodeCollectTranslations($path)
);

$namespaced = collect($namespaces)->flatMap(
fn ($path, $namespace) => vscodeCollectTranslations($path, $namespace)
);

$final = [];

foreach ($default->merge($namespaced) as $value) {
foreach ($value['vs'] as $key => $v) {
$dotKey = "{$value['k']}.{$key}";

if (!isset($final[$dotKey])) {
$final[$dotKey] = [];
}

$final[$dotKey][$value['la']] = $v;

if ($value['la'] === Illuminate\Support\Facades\App::currentLocale()) {
$final[$dotKey]['default'] = $v;
}
}
}

return collect($final);
Loading
Loading