This commit is contained in:
Meghdad committed 2026-06-25 14:40:00 +03:30
commit cd9cc0dabf
21 files changed
+1394

No files matched your search

@@ -0,0 +1,200 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Number;
use Laravel\Prompts\Progress;
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
use Throwable;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\intro;
use function Laravel\Prompts\outro;
use function Laravel\Prompts\progress;
use function Laravel\Prompts\table;
use function Laravel\Prompts\warning;
#[Signature('ftp:deploy
{path? : Local directory to deploy (defaults to services.ftp_deploy.local_root)}
{--disk= : Filesystem disk configured for the FTP server}
{--state= : Remote sync-state file path}
{--exclude=* : Extra exclude path or wildcard pattern; comma-separated values are supported}
{--dry-run : Show what would be uploaded without changing the FTP server}
{--force : Upload every included local file}
{--yes : Skip the confirmation prompt}')]
#[Description('Deploy local changes to the configured FTP server using the remote sync-state file')]
class DeployFtpChangedFilesCommand extends Command
{
public function __construct(private readonly FtpDeployManager $ftpDeployManager)
{
parent::__construct();
}
public function handle(): int
{
try {
$diskName = $this->ftpDeployManager->diskName($this->optionString('disk'));
$localRoot = $this->ftpDeployManager->localRoot($this->argumentString('path'));
$statePath = $this->ftpDeployManager->statePath($this->optionString('state'));
$excludedPatterns = $this->ftpDeployManager->excludedPatterns($this->option('exclude'), $statePath);
intro('Preparing FTP deployment');
info("Local root: {$localRoot}");
info("FTP disk: {$diskName}");
info("Remote state: {$statePath}");
if ($excludedPatterns !== []) {
info('Excluding: '.implode(', ', $excludedPatterns));
}
$remoteDisk = Storage::disk($diskName);
$currentState = $this->ftpDeployManager->buildCurrentState($localRoot, $excludedPatterns);
$remoteState = $this->ftpDeployManager->readRemoteState($remoteDisk, $statePath);
if ($remoteState === null) {
warning("Remote sync-state file was not found at [{$statePath}]. Every included local file will be uploaded.");
$remoteState = $this->ftpDeployManager->emptySyncState();
}
$changedFiles = $this->ftpDeployManager->changedFiles($currentState, $remoteState, (bool) $this->option('force'));
$this->renderSummary($currentState, $changedFiles, $excludedPatterns);
if ($changedFiles === []) {
info('No changed files detected.');
return self::SUCCESS;
}
if ((bool) $this->option('dry-run')) {
$this->renderChangedFiles($changedFiles);
outro('Dry run complete. No files were uploaded.');
return self::SUCCESS;
}
if (! $this->shouldContinue(count($changedFiles), $diskName)) {
warning('FTP deployment cancelled.');
return self::SUCCESS;
}
$this->uploadChangedFiles($remoteDisk, $localRoot, $changedFiles);
$this->ftpDeployManager->writeRemoteState($remoteDisk, $statePath, $currentState);
outro('FTP deployment finished. Uploaded '.Number::format(count($changedFiles)).' files.');
return self::SUCCESS;
} catch (Throwable $exception) {
error($exception->getMessage());
if ($this->output->isVerbose()) {
throw $exception;
}
return self::FAILURE;
}
}
/**
* @param array{data: array<int, array<string, mixed>>} $currentState
* @param array<int, array<string, mixed>> $changedFiles
* @param array<int, string> $excludedPatterns
*/
private function renderSummary(array $currentState, array $changedFiles, array $excludedPatterns): void
{
table(
headers: ['Metric', 'Value'],
rows: [
['Included files', Number::format($this->fileCount($currentState))],
['Files to upload', Number::format(count($changedFiles))],
['Exclude patterns', Number::format(count($excludedPatterns))],
],
);
}
/**
* @param array{data: array<int, array<string, mixed>>} $state
*/
private function fileCount(array $state): int
{
return collect($state['data'])
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
->count();
}
/**
* @param array<int, array<string, mixed>> $changedFiles
*/
private function renderChangedFiles(array $changedFiles): void
{
table(
headers: ['Path', 'Size'],
rows: collect($changedFiles)
->take(20)
->map(fn (array $entry): array => [
(string) $entry['name'],
Number::fileSize((int) $entry['size']),
])
->values()
->all(),
);
if (count($changedFiles) > 20) {
info('...and '.Number::format(count($changedFiles) - 20).' more files.');
}
}
private function shouldContinue(int $changedFileCount, string $diskName): bool
{
if ((bool) $this->option('yes') || ! $this->input->isInteractive()) {
return true;
}
return confirm(
label: 'Upload '.Number::format($changedFileCount)." changed files to [{$diskName}]?",
default: false,
);
}
/**
* @param array<int, array<string, mixed>> $changedFiles
*/
private function uploadChangedFiles(mixed $remoteDisk, string $localRoot, array $changedFiles): void
{
progress(
label: 'Uploading changed files',
steps: $changedFiles,
callback: function (array $entry, Progress $progress) use ($remoteDisk, $localRoot): void {
$path = (string) $entry['name'];
$progress
->label("Uploading {$path}")
->hint(Number::fileSize((int) $entry['size']));
$this->ftpDeployManager->uploadFile($remoteDisk, $localRoot, $path);
},
hint: Number::format(count($changedFiles)).' files',
);
}
private function argumentString(string $key): ?string
{
$value = $this->argument($key);
return is_string($value) && trim($value) !== '' ? $value : null;
}
private function optionString(string $key): ?string
{
$value = $this->option($key);
return is_string($value) && trim($value) !== '' ? $value : null;
}
}
@@ -0,0 +1,88 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Number;
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
use Throwable;
use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\intro;
use function Laravel\Prompts\outro;
use function Laravel\Prompts\table;
class GenerateFtpSyncStateCommand extends Command
{
protected $signature = 'ftp:generate-sync-state
{path=. : Directory path to scan}
{--output= : Output file path (default: {path}/.ftp-deploy-sync-state.json)}
{--exclude= : Comma-separated exclude patterns (relative to path)}';
protected $description = 'Generate .ftp-deploy-sync-state.json from local files';
public function __construct(
private readonly FtpDeployManager $ftpDeployManager,
private readonly SyncStateGenerator $syncStateGenerator,
) {
parent::__construct();
}
public function handle(): int
{
try {
$localRoot = $this->ftpDeployManager->localRoot((string) $this->argument('path'));
$outputPath = $this->outputPath($localRoot);
$excludedPatterns = $this->ftpDeployManager->excludedPatterns($this->option('exclude'));
$state = $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
$counts = $this->syncStateGenerator->counts($state);
intro('Generating FTP sync-state');
info("Scanning: {$localRoot}");
info("Output file: {$outputPath}");
if ($excludedPatterns !== []) {
info('Excluding: '.implode(', ', $excludedPatterns));
}
$this->syncStateGenerator->writeToPath($outputPath, $state);
table(
headers: ['Metric', 'Count'],
rows: [
['Files', Number::format($counts['files'])],
['Folders', Number::format($counts['folders'])],
],
);
outro("Sync state saved to: {$outputPath}");
return self::SUCCESS;
} catch (Throwable $exception) {
error($exception->getMessage());
if ($this->output->isVerbose()) {
throw $exception;
}
return self::FAILURE;
}
}
private function outputPath(string $localRoot): string
{
$output = $this->option('output');
if (is_string($output) && trim($output) !== '') {
if (str_starts_with($output, DIRECTORY_SEPARATOR) || preg_match('/^[A-Za-z]:[\/\\\\]/', $output) === 1) {
return str_replace('\\', '/', $output);
}
return str_replace('\\', '/', getcwd().DIRECTORY_SEPARATOR.$output);
}
return "{$localRoot}/.ftp-deploy-sync-state.json";
}
}
@@ -0,0 +1,36 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Http\Controllers;
use Illuminate\Http\JsonResponse;
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
class GenerateSyncStateController
{
public function __construct(
private readonly FtpDeployManager $ftpDeployManager,
private readonly SyncStateGenerator $syncStateGenerator,
) {}
public function __invoke(): JsonResponse
{
$localRoot = $this->ftpDeployManager->localRoot();
$statePath = $this->ftpDeployManager->statePath();
$outputPath = $this->ftpDeployManager->localStateOutputPath();
$excludedPatterns = $this->ftpDeployManager->excludedPatterns([], $statePath);
$state = $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
$counts = $this->syncStateGenerator->counts($state);
$this->syncStateGenerator->writeToPath($outputPath, $state);
return response()->json([
'success' => true,
'path' => $outputPath,
'files' => $counts['files'],
'folders' => $counts['folders'],
'generated_time' => $state['generatedTime'],
'state' => $state,
]);
}
}
@@ -0,0 +1,38 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureValidFtpDeployToken
{
/**
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
$configuredToken = config('services.ftp_deploy.api_token');
if (! is_string($configuredToken) || $configuredToken === '') {
return $this->forbidden('FTP deploy API token is not configured.');
}
$providedToken = $request->bearerToken() ?: $request->header('X-Ftp-Deploy-Token');
if (! is_string($providedToken) || ! hash_equals($configuredToken, $providedToken)) {
return $this->forbidden('Invalid FTP deploy API token.');
}
return $next($request);
}
private function forbidden(string $message): JsonResponse
{
return response()->json([
'message' => $message,
], 403);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy;
use Illuminate\Support\ServiceProvider;
use MeghdadFadaee\LaravelFtpDeploy\Console\Commands\DeployFtpChangedFilesCommand;
use MeghdadFadaee\LaravelFtpDeploy\Console\Commands\GenerateFtpSyncStateCommand;
use MeghdadFadaee\LaravelFtpDeploy\Services\ExcludeMatcher;
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
class LaravelFtpDeployServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->replaceConfigRecursivelyFrom(__DIR__.'/../config/filesystems.php', 'filesystems');
$this->replaceConfigRecursivelyFrom(__DIR__.'/../config/services.php', 'services');
$this->app->singleton(ExcludeMatcher::class);
$this->app->singleton(SyncStateGenerator::class);
$this->app->singleton(FtpDeployManager::class);
}
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->commands([
DeployFtpChangedFilesCommand::class,
GenerateFtpSyncStateCommand::class,
]);
$this->publishes([
__DIR__.'/../config/filesystems.php' => config_path('ftp-deploy-filesystems.php'),
__DIR__.'/../config/services.php' => config_path('ftp-deploy-services.php'),
], 'ftp-deploy-config');
}
if (config('services.ftp_deploy.route.enabled', true)) {
$this->loadRoutesFrom(__DIR__.'/../routes/api.php');
}
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
class ExcludeMatcher
{
/**
* @return array<int, string>
*/
public function patterns(mixed $values): array
{
return collect(Arr::wrap($values))
->flatMap(fn (mixed $value): array => explode(',', (string) $value))
->map(fn (string $pattern): string => Path::normalizeRelative($pattern))
->filter()
->unique()
->values()
->all();
}
/**
* @param array<int, string> $patterns
*/
public function isExcluded(string $relativePath, array $patterns): bool
{
$relativePath = Path::normalizeRelative($relativePath);
foreach ($patterns as $pattern) {
if ($relativePath === $pattern || Str::startsWith($relativePath, "{$pattern}/")) {
return true;
}
if (Str::is($pattern, $relativePath) || Str::is("{$pattern}/*", $relativePath)) {
return true;
}
}
return false;
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use JsonException;
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
use RuntimeException;
class FtpDeployManager
{
public function __construct(
private readonly SyncStateGenerator $syncStateGenerator,
private readonly ExcludeMatcher $excludeMatcher,
) {}
public function diskName(?string $disk = null): string
{
$diskName = $disk ?: config('services.ftp_deploy.disk', 'ftp_deploy');
if (! is_string($diskName) || trim($diskName) === '') {
throw new RuntimeException('No FTP deploy disk is configured.');
}
return trim($diskName);
}
public function localRoot(?string $path = null): string
{
$path = $path ?: config('services.ftp_deploy.local_root', base_path());
$root = realpath((string) $path);
if ($root === false || ! is_dir($root)) {
throw new RuntimeException("Local deploy path not found: {$path}");
}
return rtrim(str_replace('\\', '/', $root), '/');
}
public function statePath(?string $statePath = null): string
{
$statePath = $statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json');
if (! is_string($statePath) || trim($statePath) === '') {
throw new RuntimeException('No FTP deploy sync-state path is configured.');
}
return Path::normalizeRelative($statePath);
}
public function localStateOutputPath(?string $statePath = null): string
{
$statePath = $statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json');
if (! is_string($statePath) || trim($statePath) === '') {
throw new RuntimeException('No FTP deploy sync-state path is configured.');
}
return Path::absoluteFromBase($statePath);
}
/**
* @return array<int, string>
*/
public function excludedPatterns(mixed $extraExcludes = [], ?string $statePath = null): array
{
return $this->excludeMatcher->patterns([
...Arr::wrap(config('services.ftp_deploy.exclude', [])),
...Arr::wrap($extraExcludes),
$statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json'),
'.ftp-deploy-sync-state.json',
]);
}
/**
* @param array<int, string> $excludedPatterns
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
*/
public function buildCurrentState(string $localRoot, array $excludedPatterns, ?string $outputPath = null): array
{
return $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
}
/**
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}|null
*/
public function readRemoteState(Filesystem $remoteDisk, string $statePath): ?array
{
if (! $remoteDisk->exists($statePath)) {
return null;
}
$contents = $remoteDisk->get($statePath);
if (! is_string($contents) || trim($contents) === '') {
throw new RuntimeException("Remote sync-state file [{$statePath}] is empty.");
}
return $this->decodeSyncState($contents, $statePath);
}
/**
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
*/
public function emptySyncState(): array
{
return [
'description' => SyncStateGenerator::DESCRIPTION,
'version' => '1.0.0',
'generatedTime' => 0,
'data' => [],
];
}
/**
* @param array{data: array<int, array<string, mixed>>} $currentState
* @param array{data: array<int, array<string, mixed>>} $remoteState
* @return array<int, array{type: string, name: string, size: int, hash: string}>
*/
public function changedFiles(array $currentState, array $remoteState, bool $force = false): array
{
$remoteFiles = collect($remoteState['data'])
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file' && isset($entry['name']))
->keyBy(fn (array $entry): string => (string) $entry['name']);
return collect($currentState['data'])
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
->filter(function (array $entry) use ($remoteFiles, $force): bool {
if ($force) {
return true;
}
$remoteEntry = $remoteFiles->get($entry['name']);
if (! is_array($remoteEntry)) {
return true;
}
return (int) ($remoteEntry['size'] ?? -1) !== (int) $entry['size']
|| (string) ($remoteEntry['hash'] ?? '') !== (string) $entry['hash'];
})
->values()
->all();
}
public function uploadFile(Filesystem $remoteDisk, string $localRoot, string $relativePath): void
{
$this->ensureRemoteDirectoryExists($remoteDisk, dirname($relativePath));
$localPath = "{$localRoot}/{$relativePath}";
$stream = fopen($localPath, 'rb');
if ($stream === false) {
throw new RuntimeException("Unable to open local file for upload: {$relativePath}");
}
try {
if (! $remoteDisk->put($relativePath, $stream)) {
throw new RuntimeException("Unable to upload file: {$relativePath}");
}
} finally {
fclose($stream);
}
}
/**
* @param array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>} $currentState
*/
public function writeRemoteState(Filesystem $remoteDisk, string $statePath, array $currentState): void
{
try {
$encoded = json_encode($currentState, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
throw new RuntimeException("Unable to encode updated sync-state JSON: {$exception->getMessage()}", previous: $exception);
}
$this->ensureRemoteDirectoryExists($remoteDisk, dirname($statePath));
if (! $remoteDisk->put($statePath, $encoded)) {
throw new RuntimeException("Unable to write remote sync-state file: {$statePath}");
}
}
private function ensureRemoteDirectoryExists(Filesystem $remoteDisk, string $directory): void
{
if ($directory === '.' || $directory === '/' || $directory === '') {
return;
}
$segments = explode('/', Path::normalizeRelative($directory));
$path = '';
foreach ($segments as $segment) {
$path = $path === '' ? $segment : "{$path}/{$segment}";
if (method_exists($remoteDisk, 'directoryExists') && $remoteDisk->directoryExists($path)) {
continue;
}
$remoteDisk->makeDirectory($path);
}
}
/**
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
*/
private function decodeSyncState(string $contents, string $source): array
{
try {
$state = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
throw new RuntimeException("Remote sync-state file [{$source}] is not valid JSON: {$exception->getMessage()}", previous: $exception);
}
if (! is_array($state) || ! isset($state['data']) || ! is_array($state['data'])) {
throw new RuntimeException("Remote sync-state file [{$source}] does not contain a valid data array.");
}
return [
'description' => (string) ($state['description'] ?? SyncStateGenerator::DESCRIPTION),
'version' => (string) ($state['version'] ?? '1.0.0'),
'generatedTime' => (int) ($state['generatedTime'] ?? 0),
'data' => $state['data'],
];
}
}
+196
View File
@@ -0,0 +1,196 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
use FilesystemIterator;
use JsonException;
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
use RecursiveCallbackFilterIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use SplFileInfo;
class SyncStateGenerator
{
public const DESCRIPTION = 'DO NOT DELETE THIS FILE. This file is used to keep track of which files have been synced in the most recent deployment. If you delete this file a resync will need to be done (which can take a while) - read more: https://github.com/SamKirkland/FTP-Deploy-Action';
public function __construct(private readonly ExcludeMatcher $excludeMatcher) {}
/**
* @param array<int, string> $excludedPatterns
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
*/
public function generate(string $root, array $excludedPatterns = [], ?string $outputPath = null): array
{
$root = $this->resolveRoot($root);
$excludedPatterns = $this->excludeMatcher->patterns($excludedPatterns);
if ($outputPath !== null) {
$outputRelativePath = $this->relativePathIfInsideRoot($root, $outputPath);
if ($outputRelativePath !== null) {
$excludedPatterns = $this->excludeMatcher->patterns([...$excludedPatterns, $outputRelativePath]);
}
}
$files = [];
$folders = [];
$directory = new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS);
$filter = new RecursiveCallbackFilterIterator(
$directory,
function (SplFileInfo $item) use ($root, $excludedPatterns): bool {
if ($item->isLink()) {
return false;
}
return ! $this->excludeMatcher->isExcluded(
Path::relativeToRoot($root, $item->getPathname()),
$excludedPatterns,
);
},
);
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item) {
/** @var SplFileInfo $item */
$relativePath = Path::relativeToRoot($root, $item->getPathname());
if ($relativePath === '' || $this->excludeMatcher->isExcluded($relativePath, $excludedPatterns)) {
continue;
}
if ($item->isDir()) {
$folders[$relativePath] = true;
continue;
}
if (! $item->isFile()) {
continue;
}
$files[] = $this->fileEntry($item, $relativePath);
$this->rememberParentFolders($folders, $relativePath);
}
$folderEntries = collect(array_keys($folders))
->sort()
->map(fn (string $name): array => [
'type' => 'folder',
'name' => $name,
])
->values()
->all();
usort($files, fn (array $first, array $second): int => strcmp($first['name'], $second['name']));
return [
'description' => self::DESCRIPTION,
'version' => '1.0.0',
'generatedTime' => $this->currentMillis(),
'data' => array_merge($files, $folderEntries),
];
}
/**
* @param array{data: array<int, array<string, mixed>>} $state
* @return array{files: int, folders: int}
*/
public function counts(array $state): array
{
return [
'files' => collect($state['data'])
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
->count(),
'folders' => collect($state['data'])
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'folder')
->count(),
];
}
/**
* @param array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>} $state
*/
public function writeToPath(string $path, array $state): void
{
$directory = dirname($path);
if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) {
throw new RuntimeException(sprintf('Directory "%s" was not created.', $directory));
}
try {
file_put_contents($path, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
} catch (JsonException $exception) {
throw new RuntimeException("Unable to encode sync-state JSON: {$exception->getMessage()}", previous: $exception);
}
}
private function resolveRoot(string $root): string
{
$realRoot = realpath($root);
if ($realRoot === false || ! is_dir($realRoot)) {
throw new RuntimeException("Local deploy path not found: {$root}");
}
return rtrim(str_replace('\\', '/', $realRoot), '/');
}
/**
* @return array{type: string, name: string, size: int, hash: string}
*/
private function fileEntry(SplFileInfo $file, string $relativePath): array
{
$hash = hash_file('sha256', $file->getPathname());
if ($hash === false) {
throw new RuntimeException("Unable to hash file: {$relativePath}");
}
return [
'type' => 'file',
'name' => $relativePath,
'size' => $file->getSize(),
'hash' => $hash,
];
}
/**
* @param array<string, bool> $folders
*/
private function rememberParentFolders(array &$folders, string $relativePath): void
{
$parent = dirname($relativePath);
while ($parent !== '.' && $parent !== '/' && $parent !== '') {
$folders[$parent] = true;
$parent = dirname($parent);
}
}
private function relativePathIfInsideRoot(string $root, string $path): ?string
{
$absolutePath = Path::isAbsolute($path) ? str_replace('\\', '/', $path) : str_replace('\\', '/', getcwd().DIRECTORY_SEPARATOR.$path);
$absoluteDirectory = realpath(dirname($absolutePath));
if ($absoluteDirectory === false) {
$absoluteDirectory = dirname($absolutePath);
}
$candidate = rtrim(str_replace('\\', '/', $absoluteDirectory), '/').'/'.basename($absolutePath);
if (! str_starts_with($candidate, "{$root}/") && $candidate !== $root) {
return null;
}
return Path::relativeToRoot($root, $candidate);
}
private function currentMillis(): int
{
return (int) round(microtime(true) * 1000);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace MeghdadFadaee\LaravelFtpDeploy\Support;
final class Path
{
public static function normalizeRelative(string $path): string
{
$path = str_replace('\\', '/', trim($path));
$path = preg_replace('#/+#', '/', $path) ?: $path;
return trim($path, '/');
}
public static function isAbsolute(string $path): bool
{
return str_starts_with($path, DIRECTORY_SEPARATOR)
|| preg_match('/^[A-Za-z]:[\/\\\\]/', $path) === 1;
}
public static function absoluteFromBase(string $path): string
{
if (self::isAbsolute($path)) {
return str_replace('\\', '/', $path);
}
return str_replace('\\', '/', base_path(self::normalizeRelative($path)));
}
public static function relativeToRoot(string $root, string $path): string
{
return self::normalizeRelative(substr(str_replace('\\', '/', $path), strlen($root)));
}
}