resolveComposerVersion(); $build = $this->resolveBuildCount(); if ($version === null) { $this->error('Unable to determine version from composer.json.'); return self::FAILURE; } if ($build === null) { $this->error('Unable to determine build number from git.'); return self::FAILURE; } Setting::updateOrCreate( ['key' => 'version'], ['value' => $version], ); Setting::updateOrCreate( ['key' => 'build'], ['value' => (string) $build], ); if (!$this->syncComposerBuild($build)) { $this->error('Failed to sync version/build to composer.json.'); return self::FAILURE; } $this->info("Version/build synced: {$version} (build {$build})."); return self::SUCCESS; } private function resolveComposerVersion(): ?string { $composerPath = base_path('composer.json'); if (!is_file($composerPath) || !is_readable($composerPath)) { return null; } $raw = file_get_contents($composerPath); if ($raw === false) { return null; } $data = json_decode($raw, true); if (!is_array($data)) { return null; } $version = trim((string) ($data['version'] ?? '')); if ($version === '') { return null; } if (!preg_match('/^\d+\.\d+(?:\.\d+)?(?:[-._][0-9A-Za-z.-]+)?$/', $version)) { return null; } return $version; } private function resolveBuildCount(): ?int { $commands = [ ['git', 'rev-list', '--count', 'master'], ['git', 'rev-list', '--count', 'HEAD'], ]; foreach ($commands as $command) { $process = new Process($command, base_path()); $process->run(); if ($process->isSuccessful()) { $output = trim($process->getOutput()); if (is_numeric($output)) { return (int) $output; } } } return null; } private function syncComposerBuild(int $build): bool { $composerPath = base_path('composer.json'); if (!is_file($composerPath) || !is_readable($composerPath)) { return false; } $raw = file_get_contents($composerPath); if ($raw === false) { return false; } $data = json_decode($raw, true); if (!is_array($data)) { return false; } $data['build'] = (string) $build; $encoded = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); if ($encoded === false) { return false; } $encoded .= "\n"; return file_put_contents($composerPath, $encoded) !== false; } }