Skip to content
This repository was archived by the owner on Nov 14, 2019. It is now read-only.

Extracted the code related to Composer into a new ComposerManager class #279

Closed
wants to merge 4 commits into from
Closed
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
5 changes: 4 additions & 1 deletion src/Symfony/Installer/DemoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Installer\Exception\AbortException;
use Symfony\Installer\Manager\ComposerManager;

/**
* This command creates a full-featured Symfony demo application.
Expand Down Expand Up @@ -60,6 +61,8 @@ protected function initialize(InputInterface $input, OutputInterface $output)
$this->projectDir = $this->fs->isAbsolutePath($directory) ? $directory : getcwd().DIRECTORY_SEPARATOR.$directory;
$this->projectName = basename($directory);
}

$this->composerManager = new ComposerManager($this->projectDir);
}

/**
Expand All @@ -75,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
->download()
->extract()
->cleanUp()
->updateComposerJson()
->updateComposerConfig()
->createGitIgnore()
->checkSymfonyRequirements()
->displayInstallationResult()
Expand Down
137 changes: 11 additions & 126 deletions src/Symfony/Installer/DownloadCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException;
use Symfony\Installer\Exception\AbortException;
use Symfony\Installer\Manager\ComposerManager;

/**
* Abstract command used by commands which download and extract compressed Symfony files.
Expand Down Expand Up @@ -82,6 +83,9 @@ abstract class DownloadCommand extends Command
*/
protected $requirementsErrors = array();

/** @var ComposerManager */
protected $composerManager;

/**
* Returns the type of the downloaded application in a human readable format.
* It's mainly used to display readable error messages.
Expand Down Expand Up @@ -363,23 +367,9 @@ private function getSymfonyRequirementsFilePath()
*
* @return $this
*/
protected function updateComposerJson()
protected function updateComposerConfig()
{
$composerConfig = $this->getProjectComposerConfig();

if (isset($composerConfig['config']['platform']['php'])) {
unset($composerConfig['config']['platform']['php']);

if (empty($composerConfig['config']['platform'])) {
unset($composerConfig['config']['platform']);
}

if (empty($composerConfig['config'])) {
unset($composerConfig['config']);
}
}

$this->saveProjectComposerConfig($composerConfig);
$this->composerManager->initializeProjectConfig();

return $this;
}
Expand Down Expand Up @@ -418,17 +408,13 @@ protected function createGitIgnore()
*/
protected function getInstalledSymfonyVersion()
{
$composer = json_decode(file_get_contents($this->projectDir.'/composer.lock'), true);
$symfonyVersion = $this->composerManager->getPackageVersion('symfony/symfony');

foreach ($composer['packages'] as $package) {
if ('symfony/symfony' === $package['name']) {
if ('v' === substr($package['version'], 0, 1)) {
return substr($package['version'], 1);
};
if (!empty($symfonyVersion) && 'v' === substr($symfonyVersion, 0, 1)) {
return substr($symfonyVersion, 1);
};

return $package['version'];
}
}
return $symfonyVersion;
}

/**
Expand Down Expand Up @@ -600,107 +586,6 @@ protected function getUrlContents($url)
return $client->get($url)->getBody()->getContents();
}

/**
* It returns the project's Composer config as a PHP array.
*
* @return $this|array
*/
protected function getProjectComposerConfig()
{
$composerJsonFilepath = $this->projectDir.'/composer.json';

if (!is_writable($composerJsonFilepath)) {
if ($this->output->isVerbose()) {
$this->output->writeln(sprintf(
" <comment>[WARNING]</comment> Project's Composer config cannot be updated because\n".
" the <comment>%s</comment> file is not writable.\n",
$composerJsonFilepath
));
}

return $this;
}

return json_decode(file_get_contents($composerJsonFilepath), true);
}

/**
* It saves the given PHP array as the project's Composer config. In addition
* to JSON-serializing the contents, it synchronizes the composer.lock file to
* avoid out-of-sync Composer errors.
*
* @param array $config
*/
protected function saveProjectComposerConfig(array $config)
{
$composerJsonFilepath = $this->projectDir.'/composer.json';
$this->fs->dumpFile($composerJsonFilepath, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");

$this->syncComposerLockFile();
}

/**
* Updates the hash values stored in composer.lock to avoid out-of-sync
* problems when the composer.json file contents are changed.
*/
private function syncComposerLockFile()
{
$composerJsonFileContents = file_get_contents($this->projectDir.'/composer.json');
$composerLockFileContents = json_decode(file_get_contents($this->projectDir.'/composer.lock'), true);

if (array_key_exists('hash', $composerLockFileContents)) {
$composerLockFileContents['hash'] = md5($composerJsonFileContents);
}

if (array_key_exists('content-hash', $composerLockFileContents)) {
$composerLockFileContents['content-hash'] = $this->getComposerContentHash($composerJsonFileContents);
}

$this->fs->dumpFile($this->projectDir.'/composer.lock', json_encode($composerLockFileContents, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
}

/**
* Returns the md5 hash of the sorted content of the composer file.
*
* @see https://github.com/composer/composer/blob/master/src/Composer/Package/Locker.php (getContentHash() method)
*
* @param string $composerJsonFileContents The contents of the composer.json file.
*
* @return string The hash of the composer file content.
*/
private function getComposerContentHash($composerJsonFileContents)
{
$composerConfig = json_decode($composerJsonFileContents, true);

$relevantKeys = array(
'name',
'version',
'require',
'require-dev',
'conflict',
'replace',
'provide',
'minimum-stability',
'prefer-stable',
'repositories',
'extra',
);

$relevantComposerConfig = array();

foreach (array_intersect($relevantKeys, array_keys($composerConfig)) as $key) {
$relevantComposerConfig[$key] = $composerConfig[$key];
}

if (isset($composerConfig['config']['platform'])) {
$relevantComposerConfig['config']['platform'] = $composerConfig['config']['platform'];
}

ksort($relevantComposerConfig);

return md5(json_encode($relevantComposerConfig));
}

/**
* Enables the signal handler.
*
Expand Down
193 changes: 193 additions & 0 deletions src/Symfony/Installer/Manager/ComposerManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<?php

namespace Symfony\Installer\Manager;

use Symfony\Component\Filesystem\Filesystem;

class ComposerManager
{
private $projectDir;
private $fs;

public function __construct($projectDir)
{
$this->projectDir = $projectDir;
$this->fs = new Filesystem();
}

public function initializeProjectConfig()
{
$composerConfig = $this->getProjectConfig();

if (isset($composerConfig['config']['platform']['php'])) {
unset($composerConfig['config']['platform']['php']);

if (empty($composerConfig['config']['platform'])) {
unset($composerConfig['config']['platform']);
}

if (empty($composerConfig['config'])) {
unset($composerConfig['config']);
}
}

$this->saveProjectConfig($composerConfig);
}

public function updateProjectConfig(array $newConfig)
{
$oldConfig = $this->getProjectConfig();
$projectConfig = array_replace_recursive($oldConfig, $newConfig);

// remove null values from project's config
$projectConfig = array_filter($projectConfig, function($value) { return !is_null($value); });

$this->saveProjectConfig($projectConfig);
}

public function getPackageVersion($packageName)
{
$composerLockFileContents = json_decode(file_get_contents($this->projectDir.'/composer.lock'), true);

foreach ($composerLockFileContents['packages'] as $packageConfig) {
if ($packageName === $packageConfig['name']) {
return $packageConfig['version'];
}
}
}

/**
* Generates a good Composer project name based on the application name
* and on the user name.
*
* @param $projectName
*
* @return string The generated Composer package name
*/
public function createPackageName($projectName)
{
if (!empty($_SERVER['USERNAME'])) {
$packageName = $_SERVER['USERNAME'].'/'.$projectName;
} elseif (true === extension_loaded('posix') && $user = posix_getpwuid(posix_getuid())) {
$packageName = $user['name'].'/'.$projectName;
} elseif (get_current_user()) {
$packageName = get_current_user().'/'.$projectName;
} else {
// package names must be in the format foo/bar
$packageName = $projectName.'/'.$projectName;
}

return $this->fixPackageName($packageName);
}

/**
* It returns the project's Composer config as a PHP array.
*
* @return array
*/
private function getProjectConfig()
{
$composerJsonPath = $this->projectDir.'/composer.json';
if (!is_writable($composerJsonPath)) {
return [];
}

return json_decode(file_get_contents($composerJsonPath), true);
}

/**
* It saves the given PHP array as the project's Composer config. In addition
* to JSON-serializing the contents, it synchronizes the composer.lock file to
* avoid out-of-sync Composer errors.
*
* @param array $config
*/
private function saveProjectConfig(array $config)
{
$composerJsonPath = $this->projectDir.'/composer.json';
$this->fs->dumpFile($composerJsonPath, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");

$this->syncComposerLockFile();
}

/**
* Updates the hash values stored in composer.lock to avoid out-of-sync
* problems when the composer.json file contents are changed.
*/
private function syncComposerLockFile()
{
$composerJsonFileContents = file_get_contents($this->projectDir.'/composer.json');
$composerLockFileContents = json_decode(file_get_contents($this->projectDir.'/composer.lock'), true);

if (array_key_exists('hash', $composerLockFileContents)) {
$composerLockFileContents['hash'] = md5($composerJsonFileContents);
}

if (array_key_exists('content-hash', $composerLockFileContents)) {
$composerLockFileContents['content-hash'] = $this->getComposerContentHash($composerJsonFileContents);
}

$this->fs->dumpFile($this->projectDir.'/composer.lock', json_encode($composerLockFileContents, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
}

/**
* Returns the md5 hash of the sorted content of the composer file.
*
* @see https://github.com/composer/composer/blob/master/src/Composer/Package/Locker.php (getContentHash() method)
*
* @param string $composerJsonFileContents The contents of the composer.json file.
*
* @return string The hash of the composer file content.
*/
private function getComposerContentHash($composerJsonFileContents)
{
$composerConfig = json_decode($composerJsonFileContents, true);

$relevantKeys = array(
'name',
'version',
'require',
'require-dev',
'conflict',
'replace',
'provide',
'minimum-stability',
'prefer-stable',
'repositories',
'extra',
);

$relevantComposerConfig = array();

foreach (array_intersect($relevantKeys, array_keys($composerConfig)) as $key) {
$relevantComposerConfig[$key] = $composerConfig[$key];
}

if (isset($composerConfig['config']['platform'])) {
$relevantComposerConfig['config']['platform'] = $composerConfig['config']['platform'];
}

ksort($relevantComposerConfig);

return md5(json_encode($relevantComposerConfig));
}

/**
* Transforms a project name into a valid Composer package name.
*
* @param string $name The project name to transform
*
* @return string The valid Composer package name
*/
private function fixPackageName($name)
{
$name = str_replace(
['à', 'á', 'â', 'ä', 'æ', 'ã', 'å', 'ā', 'é', 'è', 'ê', 'ë', 'ę', 'ė', 'ē', 'ī', 'į', 'í', 'ì', 'ï', 'î', 'ō', 'ø', 'œ', 'õ', 'ó', 'ò', 'ö', 'ô', 'ū', 'ú', 'ù', 'ü', 'û', 'ç', 'ć', 'č', 'ł', 'ñ', 'ń', 'ß', 'ś', 'š', 'ŵ', 'ŷ', 'ÿ', 'ź', 'ž', 'ż'],
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'u', 'c', 'c', 'c', 'l', 'n', 'n', 's', 's', 's', 'w', 'y', 'y', 'z', 'z', 'z'],
$name
);
$name = preg_replace('#[^A-Za-z0-9_./-]+#', '', $name);

return strtolower($name);
}
}
Loading