WizdomWeb/app/Utils/NamespaceUpdater.php

99 lines
3.3 KiB
PHP

<?php
namespace WizdomNetworks\WizeWeb\Utils;
class NamespaceUpdater
{
public function updateNamespaces(string $basePath, ?string $autoloadNamespace = null): void
{
// Ensure path ends with a directory separator
$basePath = rtrim($basePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// Determine namespace base from composer.json or use default
$namespaceBase = $autoloadNamespace ?? $this->getNamespaceFromComposer($basePath) ?? 'App\\';
$namespaceBase = rtrim(str_replace('\\', '\\', $namespaceBase), '\\') . '\\';
$files = $this->findPhpFiles($basePath);
foreach ($files as $file) {
$this->updateNamespace($file, $namespaceBase, $basePath);
}
echo "Namespace update complete.\n";
}
private function getNamespaceFromComposer(string $basePath): ?string
{
$composerPath = $basePath . 'composer.json';
if (!file_exists($composerPath)) {
echo "composer.json not found. Using default namespace.\n";
return null;
}
$composerConfig = json_decode(file_get_contents($composerPath), true);
if (
isset($composerConfig['autoload']['psr-4']) &&
is_array($composerConfig['autoload']['psr-4'])
) {
$namespaces = array_keys($composerConfig['autoload']['psr-4']);
return $namespaces[0] ?? null;
}
echo "No PSR-4 autoload namespace found in composer.json. Using default namespace.\n";
return null;
}
private function findPhpFiles(string $directory): array
{
$phpFiles = [];
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
foreach ($iterator as $file) {
if ($file->getExtension() === 'php' && strpos($file->getPathname(), DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) === false) {
$phpFiles[] = $file->getPathname();
}
}
return $phpFiles;
}
private function updateNamespace(string $filePath, string $namespaceBase, string $basePath): void
{
// Get the relative path from the base directory
$relativePath = str_replace($basePath, '', $filePath);
// Remove the 'app/' prefix from the relative path
if (strpos($relativePath, 'app/') === 0) {
$relativePath = substr($relativePath, strlen('app/'));
}
// Build the namespace
$namespaceParts = explode(DIRECTORY_SEPARATOR, dirname($relativePath));
$namespace = $namespaceBase . implode('\\', $namespaceParts);
// Get the file content
$content = file_get_contents($filePath);
// Skip files without a namespace declaration
if (!preg_match('/^namespace\s+[^;]+;/m', $content)) {
echo "Skipping file without namespace: $filePath\n";
return;
}
// Skip if the namespace is already correct
if (preg_match('/^namespace\s+' . preg_quote($namespace, '/') . ';$/m', $content)) {
echo "Namespace already correct in file: $filePath\n";
return;
}
// Replace or add the namespace
$content = preg_replace('/^namespace\s+[^;]+;/m', "namespace $namespace;", $content);
// Save the updated file
file_put_contents($filePath, $content);
echo "Updated namespace in file: $filePath\n";
}
}