function JsonManipulator::addLink
File
-
vendor/
composer/ composer/ src/ Composer/ Json/ JsonManipulator.php, line 60
Class
- JsonManipulator
- @author Jordi Boggiano <j.boggiano@seld.be>
Namespace
Composer\JsonCode
public function addLink(string $type, string $package, string $constraint, bool $sortPackages = false) : bool {
$decoded = JsonFile::parseJson($this->contents);
// no link of that type yet
if (!isset($decoded[$type])) {
return $this->addMainKey($type, [
$package => $constraint,
]);
}
$regex = '{' . self::DEFINES . '^(?P<start>\\s*\\{\\s*(?:(?&string)\\s*:\\s*(?&json)\\s*,\\s*)*?)' . '(?P<property>' . preg_quote(JsonFile::encode($type)) . '\\s*:\\s*)(?P<value>(?&json))(?P<end>.*)}sx';
if (!Preg::isMatch($regex, $this->contents, $matches)) {
return false;
}
assert(is_string($matches['start']));
assert(is_string($matches['value']));
assert(is_string($matches['end']));
$links = $matches['value'];
// try to find existing link
$packageRegex = str_replace('/', '\\\\?/', preg_quote($package));
$regex = '{' . self::DEFINES . '"(?P<package>' . $packageRegex . ')"(\\s*:\\s*)(?&string)}ix';
if (Preg::isMatch($regex, $links, $packageMatches)) {
assert(is_string($packageMatches['package']));
// update existing link
$existingPackage = $packageMatches['package'];
$packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage));
$links = Preg::replaceCallback('{' . self::DEFINES . '"' . $packageRegex . '"(?P<separator>\\s*:\\s*)(?&string)}ix', static function ($m) use ($existingPackage, $constraint) : string {
return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"';
}, $links);
}
else {
if (Preg::isMatchStrictGroups('#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s', $links, $match)) {
// link missing but non empty links
$links = Preg::replace('{' . preg_quote($match[1]) . '$}', addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package) . ': ' . JsonFile::encode($constraint) . $match[1], '\\$'), $links);
}
else {
// links empty
$links = '{' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package) . ': ' . JsonFile::encode($constraint) . $this->newline . $this->indent . '}';
}
}
if (true === $sortPackages) {
$requirements = json_decode($links, true);
$this->sortPackages($requirements);
$links = $this->format($requirements);
}
$this->contents = $matches['start'] . $matches['property'] . $links . $matches['end'];
return true;
}