repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php | tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Config;
use Composer\Repository\Vcs\GitBitbucketDriver;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\ProcessExecutor;
/**
* @group bitbucket
*/
class GitBitbucketDriverTest extends TestCase
{
/** @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */
private $io;
/** @var Config */
private $config;
/** @var HttpDownloaderMock */
private $httpDownloader;
/** @var string */
private $home;
protected function setUp(): void
{
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
$this->httpDownloader = $this->getHttpDownloaderMock($this->io, $this->config);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
}
/**
* @param array<string, mixed> $repoConfig
*
* @phpstan-param array{url: string}&array<string, mixed> $repoConfig
*/
private function getDriver(array $repoConfig): GitBitbucketDriver
{
$driver = new GitBitbucketDriver(
$repoConfig,
$this->io,
$this->config,
$this->httpDownloader,
new ProcessExecutor($this->io)
);
$driver->initialize();
return $driver;
}
public function testGetRootIdentifierWrongScmType(): void
{
self::expectException('RuntimeException');
self::expectExceptionMessage('https://bitbucket.org/user/repo.git does not appear to be a git repository, use https://bitbucket.org/user/repo but remember that Bitbucket no longer supports the mercurial repositories. https://bitbucket.org/blog/sunsetting-mercurial-support-in-bitbucket');
$this->httpDownloader->expects([
['url' => 'https://api.bitbucket.org/2.0/repositories/user/repo?fields=-project%2C-owner', 'body' => '{"scm":"hg","website":"","has_wiki":false,"name":"repo","links":{"branches":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/branches"},"tags":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/tags"},"clone":[{"href":"https:\/\/user@bitbucket.org\/user\/repo","name":"https"},{"href":"ssh:\/\/hg@bitbucket.org\/user\/repo","name":"ssh"}],"html":{"href":"https:\/\/bitbucket.org\/user\/repo"}},"language":"php","created_on":"2015-02-18T16:22:24.688+00:00","updated_on":"2016-05-17T13:20:21.993+00:00","is_private":true,"has_issues":false}'],
], true);
$driver = $this->getDriver(['url' => 'https://bitbucket.org/user/repo.git']);
$driver->getRootIdentifier();
}
public function testDriver(): GitBitbucketDriver
{
$driver = $this->getDriver(['url' => 'https://bitbucket.org/user/repo.git']);
$urls = [
'https://api.bitbucket.org/2.0/repositories/user/repo?fields=-project%2C-owner',
'https://api.bitbucket.org/2.0/repositories/user/repo/refs/tags?pagelen=100&fields=values.name%2Cvalues.target.hash%2Cnext&sort=-target.date',
'https://api.bitbucket.org/2.0/repositories/user/repo/refs/branches?pagelen=100&fields=values.name%2Cvalues.target.hash%2Cvalues.heads%2Cnext&sort=-target.date',
'https://api.bitbucket.org/2.0/repositories/user/repo/src/main/composer.json',
'https://api.bitbucket.org/2.0/repositories/user/repo/commit/main?fields=date',
];
$this->httpDownloader->expects([
['url' => $urls[0], 'body' => '{"mainbranch": {"name": "main"}, "scm":"git","website":"","has_wiki":false,"name":"repo","links":{"branches":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/branches"},"tags":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/tags"},"clone":[{"href":"https:\/\/user@bitbucket.org\/user\/repo.git","name":"https"},{"href":"ssh:\/\/git@bitbucket.org\/user\/repo.git","name":"ssh"}],"html":{"href":"https:\/\/bitbucket.org\/user\/repo"}},"language":"php","created_on":"2015-02-18T16:22:24.688+00:00","updated_on":"2016-05-17T13:20:21.993+00:00","is_private":true,"has_issues":false}'],
['url' => $urls[1], 'body' => '{"values":[{"name":"1.0.1","target":{"hash":"9b78a3932143497c519e49b8241083838c8ff8a1"}},{"name":"1.0.0","target":{"hash":"d3393d514318a9267d2f8ebbf463a9aaa389f8eb"}}]}'],
['url' => $urls[2], 'body' => '{"values":[{"name":"main","target":{"hash":"937992d19d72b5116c3e8c4a04f960e5fa270b22"}}]}'],
['url' => $urls[3], 'body' => '{"name": "user/repo","description": "test repo","license": "GPL","authors": [{"name": "Name","email": "local@domain.tld"}],"require": {"creator/package": "^1.0"},"require-dev": {"phpunit/phpunit": "~4.8"}}'],
['url' => $urls[4], 'body' => '{"date": "2016-05-17T13:19:52+00:00"}'],
], true);
self::assertEquals(
'main',
$driver->getRootIdentifier()
);
self::assertEquals(
[
'1.0.1' => '9b78a3932143497c519e49b8241083838c8ff8a1',
'1.0.0' => 'd3393d514318a9267d2f8ebbf463a9aaa389f8eb',
],
$driver->getTags()
);
self::assertEquals(
[
'main' => '937992d19d72b5116c3e8c4a04f960e5fa270b22',
],
$driver->getBranches()
);
self::assertEquals(
[
'name' => 'user/repo',
'description' => 'test repo',
'license' => 'GPL',
'authors' => [
[
'name' => 'Name',
'email' => 'local@domain.tld',
],
],
'require' => [
'creator/package' => '^1.0',
],
'require-dev' => [
'phpunit/phpunit' => '~4.8',
],
'time' => '2016-05-17T13:19:52+00:00',
'support' => [
'source' => 'https://bitbucket.org/user/repo/src/937992d19d72b5116c3e8c4a04f960e5fa270b22/?at=main',
],
'homepage' => 'https://bitbucket.org/user/repo',
],
$driver->getComposerInformation('main')
);
return $driver;
}
/**
* @depends testDriver
*/
public function testGetParams(\Composer\Repository\Vcs\VcsDriverInterface $driver): void
{
$url = 'https://bitbucket.org/user/repo.git';
self::assertEquals($url, $driver->getUrl());
self::assertEquals(
[
'type' => 'zip',
'url' => 'https://bitbucket.org/user/repo/get/reference.zip',
'reference' => 'reference',
'shasum' => '',
],
$driver->getDist('reference')
);
self::assertEquals(
['type' => 'git', 'url' => $url, 'reference' => 'reference'],
$driver->getSource('reference')
);
}
public function testInitializeInvalidRepositoryUrl(): void
{
$this->expectException('\InvalidArgumentException');
$driver = $this->getDriver(['url' => 'https://bitbucket.org/acme']);
$driver->initialize();
}
public function testInvalidSupportData(): void
{
$repoUrl = 'https://bitbucket.org/user/repo.git';
$driver = $this->getDriver(['url' => $repoUrl]);
$urls = [
'https://api.bitbucket.org/2.0/repositories/user/repo?fields=-project%2C-owner',
'https://api.bitbucket.org/2.0/repositories/user/repo/src/main/composer.json',
'https://api.bitbucket.org/2.0/repositories/user/repo/commit/main?fields=date',
'https://api.bitbucket.org/2.0/repositories/user/repo/refs/tags?pagelen=100&fields=values.name%2Cvalues.target.hash%2Cnext&sort=-target.date',
'https://api.bitbucket.org/2.0/repositories/user/repo/refs/branches?pagelen=100&fields=values.name%2Cvalues.target.hash%2Cvalues.heads%2Cnext&sort=-target.date',
];
$this->httpDownloader->expects([
['url' => $urls[0], 'body' => '{"mainbranch": {"name": "main"}, "scm":"git","website":"","has_wiki":false,"name":"repo","links":{"branches":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/branches"},"tags":{"href":"https:\/\/api.bitbucket.org\/2.0\/repositories\/user\/repo\/refs\/tags"},"clone":[{"href":"https:\/\/user@bitbucket.org\/user\/repo.git","name":"https"},{"href":"ssh:\/\/git@bitbucket.org\/user\/repo.git","name":"ssh"}],"html":{"href":"https:\/\/bitbucket.org\/user\/repo"}},"language":"php","created_on":"2015-02-18T16:22:24.688+00:00","updated_on":"2016-05-17T13:20:21.993+00:00","is_private":true,"has_issues":false}'],
['url' => $urls[1], 'body' => '{"support": "' . $repoUrl . '"}'],
['url' => $urls[2], 'body' => '{"date": "2016-05-17T13:19:52+00:00"}'],
['url' => $urls[3], 'body' => '{"values":[{"name":"1.0.1","target":{"hash":"9b78a3932143497c519e49b8241083838c8ff8a1"}},{"name":"1.0.0","target":{"hash":"d3393d514318a9267d2f8ebbf463a9aaa389f8eb"}}]}'],
['url' => $urls[4], 'body' => '{"values":[{"name":"main","target":{"hash":"937992d19d72b5116c3e8c4a04f960e5fa270b22"}}]}'],
], true);
$driver->getRootIdentifier();
$data = $driver->getComposerInformation('main');
self::assertIsArray($data);
self::assertSame('https://bitbucket.org/user/repo/src/937992d19d72b5116c3e8c4a04f960e5fa270b22/?at=main', $data['support']['source']);
}
public function testSupports(): void
{
self::assertTrue(
GitBitbucketDriver::supports($this->io, $this->config, 'https://bitbucket.org/user/repo.git')
);
// should not be changed, see https://github.com/composer/composer/issues/9400
self::assertFalse(
GitBitbucketDriver::supports($this->io, $this->config, 'git@bitbucket.org:user/repo.git')
);
self::assertFalse(
GitBitbucketDriver::supports($this->io, $this->config, 'https://github.com/user/repo.git')
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/GitDriverTest.php | tests/Composer/Test/Repository/Vcs/GitDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Config;
use Composer\Repository\Vcs\GitDriver;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
class GitDriverTest extends TestCase
{
/** @var Config */
private $config;
/** @var string */
private $home;
/** @var false|string */
private $networkEnv;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
$this->networkEnv = Platform::getEnv('COMPOSER_DISABLE_NETWORK');
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
if ($this->networkEnv === false) {
Platform::clearEnv('COMPOSER_DISABLE_NETWORK');
} else {
Platform::putEnv('COMPOSER_DISABLE_NETWORK', $this->networkEnv);
}
}
public function testGetRootIdentifierFromRemoteLocalRepository(): void
{
$process = $this->getProcessExecutorMock();
$io = $this->getIOMock();
$driver = new GitDriver(['url' => $this->home], $io, $this->config, $this->getHttpDownloaderMock(), $process);
$this->setRepoDir($driver, $this->home);
$stdoutFailure = <<<GITFAILURE
fatal: could not read Username for 'https://example.org/acme.git': terminal prompts disabled
GITFAILURE;
$stdout = <<<GIT
* main
2.2
1.10
GIT;
$process
->expects([[
'cmd' => ['git', 'branch', '--no-color'],
'stdout' => $stdout,
]], true);
self::assertSame('main', $driver->getRootIdentifier());
}
public function testGetRootIdentifierFromRemote(): void
{
$process = $this->getProcessExecutorMock();
$io = $this->getIOMock();
$io->expects([], true);
$driver = new GitDriver(['url' => 'https://example.org/acme.git'], $io, $this->config, $this->getHttpDownloaderMock(), $process);
$this->setRepoDir($driver, $this->home);
$stdout = <<<GIT
* remote origin
Fetch URL: https://example.org/acme.git
Push URL: https://example.org/acme.git
HEAD branch: main
Remote branches:
1.10 tracked
2.2 tracked
main tracked
GIT;
$process
->expects([[
'cmd' => ['git', 'remote', '-v'],
'stdout' => '',
], [
'cmd' => ['git', 'remote', 'set-url', 'origin', '--', 'https://example.org/acme.git'],
'stdout' => '',
], [
'cmd' => ['git', 'remote', 'show', 'origin'],
'stdout' => $stdout,
], [
'cmd' => ['git', 'remote', 'set-url', 'origin', '--', 'https://example.org/acme.git'],
'stdout' => '',
]]);
self::assertSame('main', $driver->getRootIdentifier());
}
public function testGetRootIdentifierFromLocalWithNetworkDisabled(): void
{
Platform::putEnv('COMPOSER_DISABLE_NETWORK', '1');
$process = $this->getProcessExecutorMock();
$io = $this->getIOMock();
$driver = new GitDriver(['url' => 'https://example.org/acme.git'], $io, $this->config, $this->getHttpDownloaderMock(), $process);
$this->setRepoDir($driver, $this->home);
$stdout = <<<GIT
* main
2.2
1.10
GIT;
$process
->expects([[
'cmd' => ['git', 'branch', '--no-color'],
'stdout' => $stdout,
]]);
self::assertSame('main', $driver->getRootIdentifier());
}
public function testGetBranchesFilterInvalidBranchNames(): void
{
$process = $this->getProcessExecutorMock();
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$driver = new GitDriver(['url' => 'https://example.org/acme.git'], $io, $this->config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $process);
$this->setRepoDir($driver, $this->home);
// Branches starting with a - character are not valid git branches names
// Still assert that they get filtered to prevent issues later on
$stdout = <<<GIT
* main 089681446ba44d6d9004350192486f2ceb4eaa06 commit
2.2 12681446ba44d6d9004350192486f2ceb4eaa06 commit
-h 089681446ba44d6d9004350192486f2ceb4eaa06 commit
GIT;
$process
->expects([[
'cmd' => ['git', 'branch', '--no-color', '--no-abbrev', '-v'],
'stdout' => $stdout,
]]);
$branches = $driver->getBranches();
self::assertSame([
'main' => '089681446ba44d6d9004350192486f2ceb4eaa06',
'2.2' => '12681446ba44d6d9004350192486f2ceb4eaa06',
], $branches);
}
public function testFileGetContentInvalidIdentifier(): void
{
self::expectException('\RuntimeException');
$process = $this->getProcessExecutorMock();
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$driver = new GitDriver(['url' => 'https://example.org/acme.git'], $io, $this->config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $process);
self::assertNull($driver->getFileContent('file.txt', 'h'));
$driver->getFileContent('file.txt', '-h');
}
private function setRepoDir(GitDriver $driver, string $path): void
{
$reflectionClass = new \ReflectionClass($driver);
$reflectionProperty = $reflectionClass->getProperty('repoDir');
(\PHP_VERSION_ID < 80100) and $reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($driver, $path);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/ForgejoDriverTest.php | tests/Composer/Test/Repository/Vcs/ForgejoDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Repository\Vcs\ForgejoDriver;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use PHPUnit\Framework\MockObject\MockObject;
class ForgejoDriverTest extends TestCase
{
/** @var string */
private $home;
/** @var Config */
private $config;
/** @var IOInterface&MockObject */
private $io;
/** @var HttpDownloaderMock */
private $httpDownloader;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
'forgejo-domains' => ['codeberg.org'],
],
]);
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->httpDownloader = $this->getHttpDownloaderMock($this->io, $this->config);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
}
public function testPublicRepository(): void
{
$this->expectInteractiveIO();
$this->httpDownloader->expects(
[
['url' => 'https://codeberg.org/api/v1/repos/acme/repo', 'body' => (string) json_encode([
'default_branch' => 'main',
'has_issues' => true,
'archived' => false,
'private' => false,
'html_url' => 'https://codeberg.org/acme/repo',
'ssh_url' => 'git@codeberg.org:acme/repo.git',
'clone_url' => 'https://codeberg.org/acme/repo.git',
])],
],
true
);
$driver = $this->initializeDriver('https://codeberg.org/acme/repo.git');
self::assertEquals('main', $driver->getRootIdentifier());
$sha = 'SOMESHA';
$dist = $driver->getDist($sha);
self::assertIsArray($dist);
self::assertEquals('zip', $dist['type']);
self::assertEquals('https://codeberg.org/api/v1/repos/acme/repo/archive/SOMESHA.zip', $dist['url']);
self::assertEquals($sha, $dist['reference']);
$source = $driver->getSource($sha);
self::assertEquals('git', $source['type']);
self::assertEquals('https://codeberg.org/acme/repo.git', $source['url']);
self::assertEquals($sha, $source['reference']);
}
public function testGetBranches(): void
{
$this->expectInteractiveIO();
$this->httpDownloader->expects(
[
['url' => 'https://codeberg.org/api/v1/repos/acme/repo', 'body' => (string) json_encode([
'default_branch' => 'main',
'has_issues' => true,
'archived' => false,
'private' => false,
'html_url' => 'https://codeberg.org/acme/repo',
'ssh_url' => 'git@codeberg.org:acme/repo.git',
'clone_url' => 'https://codeberg.org/acme/repo.git',
])],
['url' => 'https://codeberg.org/api/v1/repos/acme/repo/branches?per_page=100', 'body' => (string) json_encode([
['name' => 'main', 'commit' => ['id' => 'SOMESHA']],
])],
],
true
);
$driver = $this->initializeDriver('https://codeberg.org/acme/repo.git');
self::assertEquals(['main' => 'SOMESHA'], $driver->getBranches());
}
public function testGetTags(): void
{
$this->expectInteractiveIO();
$this->httpDownloader->expects(
[
['url' => 'https://codeberg.org/api/v1/repos/acme/repo', 'body' => (string) json_encode([
'default_branch' => 'main',
'has_issues' => true,
'archived' => false,
'private' => false,
'html_url' => 'https://codeberg.org/acme/repo',
'ssh_url' => 'git@codeberg.org:acme/repo.git',
'clone_url' => 'https://codeberg.org/acme/repo.git',
])],
['url' => 'https://codeberg.org/api/v1/repos/acme/repo/tags?per_page=100', 'body' => (string) json_encode([
['name' => '1.0', 'commit' => ['sha' => 'SOMESHA']],
])],
],
true
);
$driver = $this->initializeDriver('https://codeberg.org/acme/repo.git');
self::assertEquals(['1.0' => 'SOMESHA'], $driver->getTags());
}
public function testGetEmptyFileContent(): void
{
$this->expectInteractiveIO();
$this->httpDownloader->expects(
[
['url' => 'https://codeberg.org/api/v1/repos/acme/repo', 'body' => (string) json_encode([
'default_branch' => 'main',
'has_issues' => true,
'archived' => false,
'private' => false,
'html_url' => 'https://codeberg.org/acme/repo',
'ssh_url' => 'git@codeberg.org:acme/repo.git',
'clone_url' => 'https://codeberg.org/acme/repo.git',
])],
['url' => 'https://codeberg.org/api/v1/repos/acme/repo/contents/composer.json?ref=main', 'body' => '{"encoding":"base64","content":""}'],
],
true
);
$driver = $this->initializeDriver('https://codeberg.org/acme/repo.git');
self::assertSame('', $driver->getFileContent('composer.json', 'main'));
}
/**
* @dataProvider supportsProvider
*/
public function testSupports(bool $expected, string $repoUrl): void
{
self::assertSame($expected, ForgejoDriver::supports($this->io, $this->config, $repoUrl));
}
/**
* @return list<array{bool, string}>
*/
public static function supportsProvider(): array
{
return [
[false, 'https://example.org/acme/repo'],
[true, 'https://codeberg.org/acme/repository'],
];
}
private function initializeDriver(string $repoUrl): ForgejoDriver
{
$driver = new ForgejoDriver(['url' => $repoUrl], $this->io, $this->config, $this->httpDownloader, $this->getProcessExecutorMock());
$driver->initialize();
return $driver;
}
private function expectInteractiveIO(bool $isInteractive = true): void
{
$this->io->expects($this->any())
->method('isInteractive')
->will($this->returnValue($isInteractive));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php | tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Repository\Vcs\PerforceDriver;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Config;
use Composer\Util\Perforce;
use Composer\Test\Mock\ProcessExecutorMock;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceDriverTest extends TestCase
{
/**
* @var Config
*/
protected $config;
/**
* @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $io;
/**
* @var ProcessExecutorMock
*/
protected $process;
/**
* @var \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject
*/
protected $httpDownloader;
/**
* @var string
*/
protected $testPath;
/**
* @var PerforceDriver
*/
protected $driver;
/**
* @var array<string, string>
*/
protected $repoConfig;
/**
* @var Perforce&\PHPUnit\Framework\MockObject\MockObject
*/
protected $perforce;
private const TEST_URL = 'TEST_PERFORCE_URL';
private const TEST_DEPOT = 'TEST_DEPOT_CONFIG';
private const TEST_BRANCH = 'TEST_BRANCH_CONFIG';
protected function setUp(): void
{
$this->testPath = self::getUniqueTmpDirectory();
$this->config = $this->getTestConfig($this->testPath);
$this->repoConfig = [
'url' => self::TEST_URL,
'depot' => self::TEST_DEPOT,
'branch' => self::TEST_BRANCH,
];
$this->io = $this->getMockIOInterface();
$this->process = $this->getProcessExecutorMock();
$this->httpDownloader = $this->getMockHttpDownloader();
$this->perforce = $this->getMockPerforce();
$this->driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process);
$this->overrideDriverInternalPerforce($this->perforce);
}
protected function tearDown(): void
{
parent::tearDown();
//cleanup directory under test path
$fs = new Filesystem;
$fs->removeDirectory($this->testPath);
}
protected function overrideDriverInternalPerforce(Perforce $perforce): void
{
$reflectionClass = new \ReflectionClass($this->driver);
$property = $reflectionClass->getProperty('perforce');
(\PHP_VERSION_ID < 80100) and $property->setAccessible(true);
$property->setValue($this->driver, $perforce);
}
protected function getTestConfig(string $testPath): Config
{
$config = new Config();
$config->merge(['config' => ['home' => $testPath]]);
return $config;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\IO\IOInterface
*/
protected function getMockIOInterface()
{
return $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Util\HttpDownloader
*/
protected function getMockHttpDownloader()
{
return $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&Perforce
*/
protected function getMockPerforce()
{
$methods = ['p4login', 'checkStream', 'writeP4ClientSpec', 'connectClient', 'getComposerInformation', 'cleanupClientSpec'];
return $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
}
public function testInitializeCapturesVariablesFromRepoConfig(): void
{
$driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals(self::TEST_URL, $driver->getUrl());
self::assertEquals(self::TEST_DEPOT, $driver->getDepot());
self::assertEquals(self::TEST_BRANCH, $driver->getBranch());
}
public function testInitializeLogsInAndConnectsClient(): void
{
$this->perforce->expects($this->once())->method('p4Login');
$this->perforce->expects($this->once())->method('checkStream');
$this->perforce->expects($this->once())->method('writeP4ClientSpec');
$this->perforce->expects($this->once())->method('connectClient');
$this->driver->initialize();
}
/**
* @depends testInitializeCapturesVariablesFromRepoConfig
* @depends testInitializeLogsInAndConnectsClient
*/
public function testHasComposerFileReturnsFalseOnNoComposerFile(): void
{
$identifier = 'TEST_IDENTIFIER';
$formatted_depot_path = '//' . self::TEST_DEPOT . '/' . $identifier;
$this->perforce->expects($this->any())->method('getComposerInformation')->with($this->equalTo($formatted_depot_path))->will($this->returnValue([]));
$this->driver->initialize();
$result = $this->driver->hasComposerFile($identifier);
self::assertFalse($result);
}
/**
* @depends testInitializeCapturesVariablesFromRepoConfig
* @depends testInitializeLogsInAndConnectsClient
*/
public function testHasComposerFileReturnsTrueWithOneOrMoreComposerFiles(): void
{
$identifier = 'TEST_IDENTIFIER';
$formatted_depot_path = '//' . self::TEST_DEPOT . '/' . $identifier;
$this->perforce->expects($this->any())->method('getComposerInformation')->with($this->equalTo($formatted_depot_path))->will($this->returnValue(['']));
$this->driver->initialize();
$result = $this->driver->hasComposerFile($identifier);
self::assertTrue($result);
}
/**
* Test that supports() simply return false.
*
* @covers \Composer\Repository\Vcs\PerforceDriver::supports
*/
public function testSupportsReturnsFalseNoDeepCheck(): void
{
$this->expectOutputString('');
self::assertFalse(PerforceDriver::supports($this->io, $this->config, 'existing.url'));
}
public function testCleanup(): void
{
$this->perforce->expects($this->once())->method('cleanupClientSpec');
$this->driver->cleanup();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php | tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Repository\Vcs\GitHubDriver;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Config;
class GitHubDriverTest extends TestCase
{
/** @var string */
private $home;
/** @var Config */
private $config;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
}
public function testPrivateRepository(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$repoSshUrl = 'git@github.com:composer/packagist.git';
$identifier = 'v0.0.0';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'status' => 404],
['url' => 'https://api.github.com/', 'body' => '{}'],
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "private": true, "owner": {"login": "composer"}, "name": "packagist"}'],
],
true
);
$process = $this->getProcessExecutorMock();
$process->expects([], false, ['return' => 1]);
$io->expects($this->once())
->method('askAndHideAnswer')
->with($this->equalTo('Token (hidden): '))
->will($this->returnValue('sometoken'));
$io->expects($this->any())
->method('setAuthentication')
->with($this->equalTo('github.com'), $this->matchesRegularExpression('{sometoken}'), $this->matchesRegularExpression('{x-oauth-basic}'));
$configSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$authConfigSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->setConfigSource($configSource);
$this->config->setAuthConfigSource($authConfigSource);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $process);
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
self::assertEquals('test_master', $gitHubDriver->getRootIdentifier());
$dist = $gitHubDriver->getDist($sha);
self::assertIsArray($dist);
self::assertEquals('zip', $dist['type']);
self::assertEquals('https://api.github.com/repos/composer/packagist/zipball/SOMESHA', $dist['url']);
self::assertEquals('SOMESHA', $dist['reference']);
$source = $gitHubDriver->getSource($sha);
self::assertEquals('git', $source['type']);
self::assertEquals($repoSshUrl, $source['url']);
self::assertEquals('SOMESHA', $source['reference']);
}
public function testPublicRepository(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$identifier = 'v0.0.0';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$repoUrl = 'https://github.com/composer/packagist.git';
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
self::assertEquals('test_master', $gitHubDriver->getRootIdentifier());
$dist = $gitHubDriver->getDist($sha);
self::assertIsArray($dist);
self::assertEquals('zip', $dist['type']);
self::assertEquals('https://api.github.com/repos/composer/packagist/zipball/SOMESHA', $dist['url']);
self::assertEquals($sha, $dist['reference']);
$source = $gitHubDriver->getSource($sha);
self::assertEquals('git', $source['type']);
self::assertEquals($repoUrl, $source['url']);
self::assertEquals($sha, $source['reference']);
}
public function testPublicRepository2(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$identifier = 'feature/3.2-foo';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=feature%2F3.2-foo', 'body' => '{"encoding":"base64","content":"'.base64_encode('{"support": {"source": "'.$repoUrl.'" }}').'"}'],
['url' => 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo', 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$repoUrl = 'https://github.com/composer/packagist.git';
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
self::assertEquals('test_master', $gitHubDriver->getRootIdentifier());
$dist = $gitHubDriver->getDist($sha);
self::assertIsArray($dist);
self::assertEquals('zip', $dist['type']);
self::assertEquals('https://api.github.com/repos/composer/packagist/zipball/SOMESHA', $dist['url']);
self::assertEquals($sha, $dist['reference']);
$source = $gitHubDriver->getSource($sha);
self::assertEquals('git', $source['type']);
self::assertEquals($repoUrl, $source['url']);
self::assertEquals($sha, $source['reference']);
$data = $gitHubDriver->getComposerInformation($identifier);
self::assertIsArray($data);
self::assertArrayNotHasKey('abandoned', $data);
}
public function testInvalidSupportData(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$identifier = 'feature/3.2-foo';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=feature%2F3.2-foo', 'body' => '{"encoding":"base64","content":"'.base64_encode('{"support": "'.$repoUrl.'" }').'"}'],
['url' => 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo', 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
$this->setAttribute($gitHubDriver, 'branches', ['test_master' => $sha]);
$data = $gitHubDriver->getComposerInformation($identifier);
self::assertIsArray($data);
self::assertSame('https://github.com/composer/packagist/tree/feature/3.2-foo', $data['support']['source']);
}
/**
* @dataProvider fundingUrlProvider
* @param array<array{type: string, url: string}>|null $expected
*/
public function testFundingFormat(string $funding, ?array $expected): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$identifier = 'feature/3.2-foo';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=feature%2F3.2-foo', 'body' => '{"encoding":"base64","content":"'.base64_encode('{"support": {"source": "'.$repoUrl.'" }}').'"}'],
['url' => 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo', 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode($funding).'"}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
$this->setAttribute($gitHubDriver, 'branches', ['test_master' => $sha]);
$data = $gitHubDriver->getComposerInformation($identifier);
self::assertIsArray($data);
if ($expected === null) {
self::assertArrayNotHasKey('funding', $data);
} else {
self::assertSame(array_values($expected), array_values($data['funding']));
}
}
public static function fundingUrlProvider(): array
{
$allNamedPlatforms = <<<'FUNDING'
community_bridge: project-name
github: [userA, userB]
issuehunt: userName
ko_fi: userName
liberapay: userName
open_collective: userName
patreon: userName
tidelift: Platform/Package
polar: userName
buy_me_a_coffee: userName
thanks_dev: u/gh/userName
otechie: userName
FUNDING;
return [
'All named platforms' => [
$allNamedPlatforms,
[
[
'type' => 'community_bridge',
'url' => 'https://funding.communitybridge.org/projects/project-name',
],
[
'type' => 'github',
'url' => 'https://github.com/userA',
],
[
'type' => 'github',
'url' => 'https://github.com/userB',
],
[
'type' => 'issuehunt',
'url' => 'https://issuehunt.io/r/userName',
],
[
'type' => 'ko_fi',
'url' => 'https://ko-fi.com/userName',
],
[
'type' => 'liberapay',
'url' => 'https://liberapay.com/userName',
],
[
'type' => 'open_collective',
'url' => 'https://opencollective.com/userName',
],
[
'type' => 'patreon',
'url' => 'https://www.patreon.com/userName',
],
[
'type' => 'tidelift',
'url' => 'https://tidelift.com/funding/github/Platform/Package',
],
[
'type' => 'polar',
'url' => 'https://polar.sh/userName',
],
[
'type' => 'buy_me_a_coffee',
'url' => 'https://www.buymeacoffee.com/userName',
],
[
'type' => 'thanks_dev',
'url' => 'https://thanks.dev/u/gh/userName',
],
[
'type' => 'otechie',
'url' => 'https://otechie.com/userName',
],
],
],
'Custom: single schemaless URL' => [
'custom: example.com',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
],
],
'Custom: single schemaless URL in array format' => [
'custom: [example.com]',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
],
],
'Custom: double-quoted single URL' => [
'custom: "https://example.com"',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
],
],
'Custom: double-quoted single URL in array format' => [
'custom: ["https://example.com"]',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
],
],
'Custom: array with quoted URL and schemaless unquoted URL' => [
'custom: ["https://example.com", example.org]',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
[
'type' => 'custom',
'url' => 'https://example.org',
],
],
],
'Custom: array containing a non-simple scheme-less URL which will be discarded' => [
'custom: [example.net/funding, "https://example.com", example.org]',
[
[
'type' => 'custom',
'url' => 'https://example.com',
],
[
'type' => 'custom',
'url' => 'https://example.org',
],
],
],
];
}
public function testPublicRepositoryArchived(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$identifier = 'v0.0.0';
$sha = 'SOMESHA';
$composerJsonUrl = 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=' . $sha;
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": true}'],
['url' => $composerJsonUrl, 'body' => '{"encoding": "base64", "content": "' . base64_encode('{"name": "composer/packagist"}') . '"}'],
['url' => 'https://api.github.com/repos/composer/packagist/commits/'.$sha, 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', [$identifier => $sha]);
$data = $gitHubDriver->getComposerInformation($sha);
self::assertIsArray($data);
self::assertTrue($data['abandoned']);
}
public function testPrivateRepositoryNoInteraction(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$repoApiUrl = 'https://api.github.com/repos/composer/packagist';
$repoSshUrl = 'git@github.com:composer/packagist.git';
$identifier = 'v0.0.0';
$sha = 'SOMESHA';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(false));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => $repoApiUrl, 'status' => 404],
],
true
);
// clean local clone if present
$fs = new Filesystem();
$fs->removeDirectory(sys_get_temp_dir() . '/composer-test');
$this->config->merge(['config' => ['cache-vcs-dir' => sys_get_temp_dir() . '/composer-test/cache']]);
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', 'config', 'github.accesstoken'], 'return' => 1],
['git', 'clone', '--mirror', '--', $repoSshUrl, $this->config->get('cache-vcs-dir').'/git-github.com-composer-packagist.git/'],
[
'cmd' => ['git', 'show-ref', '--tags', '--dereference'],
'stdout' => $sha.' refs/tags/'.$identifier,
],
[
'cmd' => ['git', 'branch', '--no-color', '--no-abbrev', '-v'],
'stdout' => ' test_master edf93f1fccaebd8764383dc12016d0a1a9672d89 Fix test & behavior',
],
[
'cmd' => ['git', 'branch', '--no-color'],
'stdout' => '* test_master',
],
], true);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $process);
$gitHubDriver->initialize();
self::assertEquals('test_master', $gitHubDriver->getRootIdentifier());
$dist = $gitHubDriver->getDist($sha);
self::assertIsArray($dist);
self::assertEquals('zip', $dist['type']);
self::assertEquals('https://api.github.com/repos/composer/packagist/zipball/SOMESHA', $dist['url']);
self::assertEquals($sha, $dist['reference']);
$source = $gitHubDriver->getSource($identifier);
self::assertEquals('git', $source['type']);
self::assertEquals($repoSshUrl, $source['url']);
self::assertEquals($identifier, $source['reference']);
$source = $gitHubDriver->getSource($sha);
self::assertEquals('git', $source['type']);
self::assertEquals($repoSshUrl, $source['url']);
self::assertEquals($sha, $source['reference']);
}
/**
* @dataProvider invalidUrlProvider
*/
public function testInitializeInvalidRepoUrl(string $url): void
{
$this->expectException('\InvalidArgumentException');
$repoConfig = [
'url' => $url,
];
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')
->setConstructorArgs([$io, $this->config])
->getMock();
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
}
/**
* @return list<array{string}>
*/
public static function invalidUrlProvider()
{
return [
['https://github.com/acme'],
['https://github.com/acme/repository/releases'],
['https://github.com/acme/repository/pulls'],
];
}
/**
* @dataProvider supportsProvider
*/
public function testSupports(bool $expected, string $repoUrl): void
{
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
self::assertSame($expected, GitHubDriver::supports($io, $this->config, $repoUrl));
}
/**
* @return list<array{bool, string}>
*/
public static function supportsProvider(): array
{
return [
[false, 'https://github.com/acme'],
[true, 'https://github.com/acme/repository'],
[true, 'git@github.com:acme/repository.git'],
[false, 'https://github.com/acme/repository/releases'],
[false, 'https://github.com/acme/repository/pulls'],
];
}
public function testGetEmptyFileContent(): void
{
$repoUrl = 'http://github.com/composer/packagist';
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->any())
->method('isInteractive')
->will($this->returnValue(true));
$httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
$httpDownloader->expects(
[
['url' => 'https://api.github.com/repos/composer/packagist', 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": true}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=main', 'body' => '{"encoding":"base64","content":""}'],
],
true
);
$repoConfig = [
'url' => $repoUrl,
];
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize();
self::assertSame('', $gitHubDriver->getFileContent('composer.json', 'main'));
}
/**
* @param string|object $object
* @param mixed $value
*/
protected function setAttribute($object, string $attribute, $value): void
{
$attr = new \ReflectionProperty($object, $attribute);
(\PHP_VERSION_ID < 80100) and $attr->setAccessible(true);
$attr->setValue($object, $value);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php | tests/Composer/Test/Repository/Vcs/SvnDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Repository\Vcs\SvnDriver;
use Composer\Config;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
class SvnDriverTest extends TestCase
{
/**
* @var string
*/
protected $home;
/**
* @var Config
*/
protected $config;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem();
$fs->removeDirectory($this->home);
}
public function testWrongCredentialsInUrl(): void
{
self::expectException('RuntimeException');
self::expectExceptionMessage("Repository https://till:secret@corp.svn.local/repo could not be processed, wrong credentials provided (svn: OPTIONS of 'https://corp.svn.local/repo': authorization failed: Could not authenticate to server: rejected Basic challenge (https://corp.svn.local/))");
$console = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$output = "svn: OPTIONS of 'https://corp.svn.local/repo':";
$output .= " authorization failed: Could not authenticate to server:";
$output .= " rejected Basic challenge (https://corp.svn.local/)";
$process = $this->getProcessExecutorMock();
$authedCommand = ['svn', 'ls', '--verbose', '--non-interactive', '--username', 'till', '--password', 'secret', '--', 'https://till:secret@corp.svn.local/repo/trunk'];
$process->expects([
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => $authedCommand, 'return' => 1, 'stderr' => $output],
['cmd' => ['svn', '--version'], 'return' => 0, 'stdout' => '1.2.3'],
], true);
$repoConfig = [
'url' => 'https://till:secret@corp.svn.local/repo',
];
$svn = new SvnDriver($repoConfig, $console, $this->config, $httpDownloader, $process);
$svn->initialize();
}
public static function supportProvider(): array
{
return [
['http://svn.apache.org', true],
['https://svn.sf.net', true],
['svn://example.org', true],
['svn+ssh://example.org', true],
];
}
/**
* @dataProvider supportProvider
*/
public function testSupport(string $url, bool $assertion): void
{
$config = new Config();
$result = SvnDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url);
self::assertEquals($assertion, $result);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Platform/HhvmDetectorTest.php | tests/Composer/Test/Platform/HhvmDetectorTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Platform;
use Composer\Platform\HhvmDetector;
use Composer\Test\TestCase;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Process\ExecutableFinder;
class HhvmDetectorTest extends TestCase
{
/**
* @var HhvmDetector
*/
private $hhvmDetector;
protected function setUp(): void
{
$this->hhvmDetector = new HhvmDetector();
$this->hhvmDetector->reset();
}
public function testHHVMVersionWhenExecutingInHHVM(): void
{
if (!defined('HHVM_VERSION_ID')) {
self::markTestSkipped('Not running with HHVM');
}
$version = $this->hhvmDetector->getVersion();
self::assertSame(self::versionIdToVersion(), $version);
}
public function testHHVMVersionWhenExecutingInPHP(): void
{
if (defined('HHVM_VERSION_ID')) {
self::markTestSkipped('Running with HHVM');
}
if (Platform::isWindows()) {
self::markTestSkipped('Test does not run on Windows');
}
$finder = new ExecutableFinder();
$hhvm = $finder->find('hhvm');
if ($hhvm === null) {
self::markTestSkipped('HHVM is not installed');
}
$detectedVersion = $this->hhvmDetector->getVersion();
self::assertNotNull($detectedVersion, 'Failed to detect HHVM version');
$process = new ProcessExecutor();
$exitCode = $process->execute(
ProcessExecutor::escape($hhvm).
' --php -d hhvm.jit=0 -r "echo HHVM_VERSION;" 2>/dev/null',
$version
);
self::assertSame(0, $exitCode);
self::assertSame(self::getVersionParser()->normalize($version), self::getVersionParser()->normalize($detectedVersion));
}
private static function versionIdToVersion(): ?string
{
if (!defined('HHVM_VERSION_ID')) {
return null;
}
return sprintf(
'%d.%d.%d',
HHVM_VERSION_ID / 10000,
(HHVM_VERSION_ID / 100) % 100,
HHVM_VERSION_ID % 100
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Platform/VersionTest.php | tests/Composer/Test/Platform/VersionTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Platform;
use Composer\Platform\Version;
use Composer\Test\TestCase;
/**
* @author Lars Strojny <lars@strojny.net>
*/
class VersionTest extends TestCase
{
/**
* Create normalized test data set
*
* 1) Clone OpenSSL repository
* 2) git log --pretty=%h --all -- crypto/opensslv.h include/openssl/opensslv.h | while read hash ; do (git show $hash:crypto/opensslv.h; git show $hash:include/openssl/opensslv.h) | grep "define OPENSSL_VERSION_TEXT" ; done > versions.txt
* 3) cat versions.txt | awk -F "OpenSSL " '{print $2}' | awk -F " " '{print $1}' | sed -e "s:\([0-9]*\.[0-9]*\.[0-9]*\):1.2.3:g" -e "s:1\.2\.3[a-z]\(-.*\)\{0,1\}$:1.2.3a\1:g" -e "s:1\.2\.3[a-z]\{2\}\(-.*\)\{0,1\}$:1.2.3zh\1:g" -e "s:beta[0-9]:beta3:g" -e "s:pre[0-9]*:pre2:g" | sort | uniq
*/
public static function provideOpenSslVersions(): array
{
return [
// Generated
['1.2.3', '1.2.3.0'],
['1.2.3-beta3', '1.2.3.0-beta3'],
['1.2.3-beta3-dev', '1.2.3.0-beta3-dev'],
['1.2.3-beta3-fips', '1.2.3.0-beta3', true],
['1.2.3-beta3-fips-dev', '1.2.3.0-beta3-dev', true],
['1.2.3-dev', '1.2.3.0-dev'],
['1.2.3-fips', '1.2.3.0', true],
['1.2.3-fips-beta3', '1.2.3.0-beta3', true],
['1.2.3-fips-beta3-dev', '1.2.3.0-beta3-dev', true],
['1.2.3-fips-dev', '1.2.3.0-dev', true],
['1.2.3-pre2', '1.2.3.0-alpha2'],
['1.2.3-pre2-dev', '1.2.3.0-alpha2-dev'],
['1.2.3-pre2-fips', '1.2.3.0-alpha2', true],
['1.2.3-pre2-fips-dev', '1.2.3.0-alpha2-dev', true],
['1.2.3a', '1.2.3.1'],
['1.2.3a-beta3','1.2.3.1-beta3'],
['1.2.3a-beta3-dev', '1.2.3.1-beta3-dev'],
['1.2.3a-dev', '1.2.3.1-dev'],
['1.2.3a-dev-fips', '1.2.3.1-dev', true],
['1.2.3a-fips', '1.2.3.1', true],
['1.2.3a-fips-beta3', '1.2.3.1-beta3', true],
['1.2.3a-fips-dev', '1.2.3.1-dev', true],
['1.2.3beta3', '1.2.3.0-beta3'],
['1.2.3beta3-dev', '1.2.3.0-beta3-dev'],
['1.2.3zh', '1.2.3.34'],
['1.2.3zh-dev', '1.2.3.34-dev'],
['1.2.3zh-fips', '1.2.3.34',true],
['1.2.3zh-fips-dev', '1.2.3.34-dev', true],
// Additional cases
['1.2.3zh-fips-rc3', '1.2.3.34-rc3', true, '1.2.3.34-RC3'],
['1.2.3zh-alpha10-fips', '1.2.3.34-alpha10', true],
['1.1.1l (Schannel)', '1.1.1.12'],
// Check that alphabetical patch levels overflow correctly
['1.2.3', '1.2.3.0'],
['1.2.3a', '1.2.3.1'],
['1.2.3z', '1.2.3.26'],
['1.2.3za', '1.2.3.27'],
['1.2.3zy', '1.2.3.51'],
['1.2.3zz', '1.2.3.52'],
// 3.x
['3.0.0', '3.0.0', false, '3.0.0.0'],
['3.2.4-dev', '3.2.4-dev', false, '3.2.4.0-dev'],
];
}
/**
* @dataProvider provideOpenSslVersions
*/
public function testParseOpensslVersions(string $input, string $parsedVersion, bool $fipsExpected = false, ?string $normalizedVersion = null): void
{
self::assertSame($parsedVersion, Version::parseOpenssl($input, $isFips));
self::assertSame($fipsExpected, $isFips);
$normalizedVersion = $normalizedVersion ? $normalizedVersion : $parsedVersion;
self::assertSame($normalizedVersion, $this->getVersionParser()->normalize($parsedVersion));
}
public static function provideLibJpegVersions(): array
{
return [
['9', '9.0'],
['9a', '9.1'],
['9b', '9.2'],
// Never seen in the wild, just for overflow correctness
['9za', '9.27'],
];
}
/**
* @dataProvider provideLibJpegVersions
*/
public function testParseLibjpegVersion(string $input, string $parsedVersion): void
{
self::assertSame($parsedVersion, Version::parseLibjpeg($input));
}
public static function provideZoneinfoVersions(): array
{
return [
['2019c', '2019.3'],
['2020a', '2020.1'],
// Never happened so far but fixate overflow behavior
['2020za', '2020.27'],
];
}
/**
* @dataProvider provideZoneinfoVersions
*/
public function testParseZoneinfoVersion(string $input, string $parsedVersion): void
{
self::assertSame($parsedVersion, Version::parseZoneinfoVersion($input));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/DumpAutoloadCommandTest.php | tests/Composer/Test/Command/DumpAutoloadCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use InvalidArgumentException;
class DumpAutoloadCommandTest extends TestCase
{
public function testDumpAutoload(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload']));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating autoload files', $output);
self::assertStringContainsString('Generated autoload files', $output);
}
public function testDumpDevAutoload(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload', '--dev' => true]));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating autoload files', $output);
self::assertStringContainsString('Generated autoload files', $output);
}
public function testDumpNoDevAutoload(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload', '--dev' => true]));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating autoload files', $output);
self::assertStringContainsString('Generated autoload files', $output);
}
public function testUsingOptimizeAndStrictPsr(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload', '--optimize' => true, '--strict-psr' => true]));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating optimized autoload files', $output);
self::assertMatchesRegularExpression('/Generated optimized autoload files containing \d+ classes/', $output);
}
public function testFailsUsingStrictPsrIfClassMapViolationsAreFound(): void
{
$dir = $this->initTempComposer([
'autoload' => [
'psr-4' => [
'Application\\' => 'src',
],
],
]);
mkdir($dir . '/src/');
file_put_contents($dir . '/src/Foo.php', '<?php namespace Application\Src; class Foo {}');
$appTester = $this->getApplicationTester();
self::assertSame(1, $appTester->run(['command' => 'dump-autoload', '--optimize' => true, '--strict-psr' => true]));
$output = $appTester->getDisplay(true);
self::assertMatchesRegularExpression('#Class Application\\\\Src\\\\Foo located in .*? does not comply with psr-4 autoloading standard \(rule: Application\\\\ => \./src\)\. Skipping\.#', $output);
}
public function testUsingClassmapAuthoritative(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload', '--classmap-authoritative' => true]));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating optimized autoload files (authoritative)', $output);
self::assertMatchesRegularExpression('/Generated optimized autoload files \(authoritative\) containing \d+ classes/', $output);
}
public function testUsingClassmapAuthoritativeAndStrictPsr(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload', '--classmap-authoritative' => true, '--strict-psr' => true]));
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Generating optimized autoload files', $output);
self::assertMatchesRegularExpression('/Generated optimized autoload files \(authoritative\) containing \d+ classes/', $output);
}
public function testStrictPsrDoesNotWorkWithoutOptimizedAutoloader(): void
{
$appTester = $this->getApplicationTester();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('--strict-psr mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.');
$appTester->run(['command' => 'dump-autoload', '--strict-psr' => true]);
}
public function testDevAndNoDevCannotBeCombined(): void
{
$appTester = $this->getApplicationTester();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('You can not use both --no-dev and --dev as they conflict with each other.');
$appTester->run(['command' => 'dump-autoload', '--dev' => true, '--no-dev' => true]);
}
public function testWithCustomAutoloaderSuffix(): void
{
$dir = $this->initTempComposer([
'config' => [
'autoloader-suffix' => 'Foobar',
],
]);
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload']));
self::assertStringContainsString('ComposerAutoloaderInitFoobar', (string) file_get_contents($dir . '/vendor/autoload.php'));
}
public function testWithExistingComposerLockAndAutoloaderSuffix(): void
{
$dir = $this->initTempComposer(
[
'config' => [
'autoloader-suffix' => 'Foobar',
],
],
[],
[
"_readme" => [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically",
],
"content-hash" => "d751713988987e9331980363e24189ce",
"packages" => [],
"packages-dev" => [],
"aliases" => [],
"minimum-stability" => "stable",
"stability-flags" => [],
"prefer-stable" => false,
"prefer-lowest" => false,
"platform" => [],
"platform-dev" => [],
"plugin-api-version" => "2.6.0",
]
);
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload']));
self::assertStringContainsString('ComposerAutoloaderInitFoobar', (string) file_get_contents($dir . '/vendor/autoload.php'));
}
public function testWithExistingComposerLockWithoutAutoloaderSuffix(): void
{
$dir = $this->initTempComposer(
[
'name' => 'foo/bar',
],
[],
[
"_readme" => [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically",
],
"content-hash" => "2d4a6be9a93712c5d6a119b26734a047",
"packages" => [],
"packages-dev" => [],
"aliases" => [],
"minimum-stability" => "stable",
"stability-flags" => [],
"prefer-stable" => false,
"prefer-lowest" => false,
"platform" => [],
"platform-dev" => [],
"plugin-api-version" => "2.6.0",
]
);
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'dump-autoload']));
self::assertStringContainsString('ComposerAutoloaderInit2d4a6be9a93712c5d6a119b26734a047', (string) file_get_contents($dir . '/vendor/autoload.php'));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/AuditCommandTest.php | tests/Composer/Test/Command/AuditCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use UnexpectedValueException;
class AuditCommandTest extends TestCase
{
public function testSuccessfulResponseCodeWhenNoPackagesAreRequired(): void
{
$this->initTempComposer();
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'audit']);
$appTester->assertCommandIsSuccessful();
self::assertEquals('No packages - skipping audit.', trim($appTester->getDisplay(true)));
}
public function testErrorAuditingLockFileWhenItIsMissing(): void
{
$this->initTempComposer();
$this->createInstalledJson([self::getPackage()]);
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage(
"Valid composer.json and composer.lock files are required to run this command with --locked"
);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'audit', '--locked' => true]);
}
public function testAuditPackageWithNoSecurityVulnerabilities(): void
{
$this->initTempComposer();
$packages = [self::getPackage()];
$this->createInstalledJson($packages);
$this->createComposerLock($packages);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'audit', '--locked' => true]);
self::assertStringContainsString(
'No security vulnerability advisories found.',
trim($appTester->getDisplay(true))
);
}
public function testAuditPackageWithNoDevOptionPassed(): void
{
$this->initTempComposer();
$devPackage = [self::getPackage()];
$this->createInstalledJson([], $devPackage);
$this->createComposerLock([], $devPackage);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'audit', '--no-dev' => true]);
self::assertStringContainsString(
'No packages - skipping audit.',
trim($appTester->getDisplay(true))
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/SelfUpdateCommandTest.php | tests/Composer/Test/Command/SelfUpdateCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Composer;
use Composer\Test\TestCase;
use Symfony\Component\Process\Process;
/**
* @group slow
* @depends Composer\Test\AllFunctionalTest::testBuildPhar
*/
class SelfUpdateCommandTest extends TestCase
{
/**
* @var string
*/
private $phar;
public function setUp(): void
{
parent::setUp();
$dir = $this->initTempComposer();
copy(__DIR__.'/../../../composer-test.phar', $dir.'/composer.phar');
$this->phar = $dir.'/composer.phar';
}
public function testSuccessfulUpdate(): void
{
if (Composer::VERSION !== '@package_version'.'@') {
$this->markTestSkipped('On releases this test can fail to upgrade as we are already on latest version');
}
$appTester = new Process([PHP_BINARY, $this->phar, 'self-update']);
$status = $appTester->run();
self::assertSame(0, $status, $appTester->getErrorOutput());
self::assertStringContainsString('Upgrading to version', $appTester->getOutput());
}
public function testUpdateToSpecificVersion(): void
{
$appTester = new Process([PHP_BINARY, $this->phar, 'self-update', '2.4.0']);
$status = $appTester->run();
self::assertSame(0, $status, $appTester->getErrorOutput());
self::assertStringContainsString('Upgrading to version 2.4.0', $appTester->getOutput());
}
public function testUpdateWithInvalidOptionThrowsException(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The "invalid-option" argument does not exist.');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'self-update', 'invalid-option' => true]);
}
/**
* @dataProvider channelOptions
*/
public function testUpdateToDifferentChannel(string $option, string $expectedOutput): void
{
if (Composer::VERSION !== '@package_version'.'@' && in_array($option, ['--stable', '--preview'], true)) {
$this->markTestSkipped('On releases this test can fail to upgrade as we are already on latest version');
}
$appTester = new Process([PHP_BINARY, $this->phar, 'self-update', $option]);
$status = $appTester->run();
self::assertSame(0, $status, $appTester->getErrorOutput());
self::assertStringContainsString('Upgrading to version', $appTester->getOutput());
self::assertStringContainsString($expectedOutput, $appTester->getOutput());
}
/**
* @return array<array<string>>
*/
public function channelOptions(): array
{
return [
['--stable', 'stable channel'],
['--preview', 'preview channel'],
['--snapshot', 'snapshot channel'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/DiagnoseCommandTest.php | tests/Composer/Test/Command/DiagnoseCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Composer\Util\Platform;
class DiagnoseCommandTest extends TestCase
{
public function testCmdFail(): void
{
$this->initTempComposer(['name' => 'foo/bar', 'description' => 'test pkg']);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'diagnose']);
if (Platform::getEnv('COMPOSER_LOWEST_DEPS_TEST') === '1') {
self::assertGreaterThanOrEqual(1, $appTester->getStatusCode());
} else {
self::assertSame(1, $appTester->getStatusCode());
}
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Checking composer.json: <warning>WARNING</warning>
<warning>No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.</warning>', $output);
self::assertStringContainsString('Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com rate limit: ', $output);
}
public function testCmdSuccess(): void
{
$this->initTempComposer(['name' => 'foo/bar', 'description' => 'test pkg', 'license' => 'MIT']);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'diagnose']);
if (Platform::getEnv('COMPOSER_LOWEST_DEPS_TEST') !== '1') {
$appTester->assertCommandIsSuccessful();
}
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Checking composer.json: OK', $output);
self::assertStringContainsString('Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com rate limit: ', $output);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/RunScriptCommandTest.php | tests/Composer/Test/Command/RunScriptCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Composer;
use Composer\Config;
use Composer\Script\Event as ScriptEvent;
use Composer\Test\TestCase;
class RunScriptCommandTest extends TestCase
{
/**
* @dataProvider getDevOptions
*/
public function testDetectAndPassDevModeToEventAndToDispatching(bool $dev, bool $noDev): void
{
$scriptName = 'testScript';
$input = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$input
->method('getOption')
->will($this->returnValueMap([
['list', false],
['dev', $dev],
['no-dev', $noDev],
]));
$input
->method('getArgument')
->will($this->returnValueMap([
['script', $scriptName],
['args', []],
]));
$input
->method('hasArgument')
->with('command')
->willReturn(false);
$input
->method('isInteractive')
->willReturn(false);
$output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$expectedDevMode = $dev || !$noDev;
$ed = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor()
->getMock();
$ed->expects($this->once())
->method('hasEventListeners')
->with($this->callback(static function (ScriptEvent $event) use ($scriptName, $expectedDevMode): bool {
return $event->getName() === $scriptName
&& $event->isDevMode() === $expectedDevMode;
}))
->willReturn(true);
$ed->expects($this->once())
->method('dispatchScript')
->with($scriptName, $expectedDevMode, [])
->willReturn(0);
$composer = $this->createComposerInstance();
$composer->setEventDispatcher($ed);
$command = $this->getMockBuilder('Composer\Command\RunScriptCommand')
->onlyMethods([
'mergeApplicationDefinition',
'getSynopsis',
'initialize',
'requireComposer',
])
->getMock();
$command->expects($this->any())->method('requireComposer')->willReturn($composer);
$command->run($input, $output);
}
public function testCanListScripts(): void
{
$this->initTempComposer([
'scripts' => [
'test' => '@php test',
'fix-cs' => 'php-cs-fixer fix',
],
'scripts-descriptions' => [
'fix-cs' => 'Run the codestyle fixer',
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'run-script', '--list' => true]);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay();
self::assertStringContainsString('Runs the test script as defined in composer.json', $output, 'The default description for the test script should be printed');
self::assertStringContainsString('Run the codestyle fixer', $output, 'The custom description for the fix-cs script should be printed');
}
public function testCanDefineAliases(): void
{
$expectedAliases = ['one', 'two', 'three'];
$this->initTempComposer([
'scripts' => [
'test' => '@php test',
],
'scripts-aliases' => [
'test' => $expectedAliases,
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'test', '--help' => true, '--format' => 'json']);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay();
$array = json_decode($output, true);
$actualAliases = $array['usage'];
array_shift($actualAliases);
self::assertSame($expectedAliases, $actualAliases, 'The custom aliases for the test command should be printed');
}
public function testExecutionOfSimpleSymfonyCommand(): void
{
$description = 'Sample description for test command';
$this->initTempComposer([
'scripts' => [
'test-direct' => 'Test\\MyCommand',
'test-ref' => ['@test-direct --inneropt innerarg'],
],
'scripts-descriptions' => [
'test-direct' => $description,
],
'autoload' => [
'psr-4' => [
'Test\\' => '',
],
],
]);
file_put_contents('MyCommand.php', <<<'TEST'
<?php
namespace Test;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class MyCommand extends Command
{
protected function configure(): void
{
$this->setDefinition([
new InputArgument('req-arg', InputArgument::REQUIRED, 'Required arg.'),
new InputArgument('opt-arg', InputArgument::OPTIONAL, 'Optional arg.'),
new InputOption('inneropt', null, InputOption::VALUE_NONE, 'Option.'),
new InputOption('outeropt', null, InputOption::VALUE_OPTIONAL, 'Optional option.'),
]);
}
public function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln($input->getArgument('req-arg'));
$output->writeln((string) $input->getArgument('opt-arg'));
$output->writeln('inneropt: '.($input->getOption('inneropt') ? 'set' : 'unset'));
$output->writeln('outeropt: '.($input->getOption('outeropt') ? 'set' : 'unset'));
return 2;
}
}
TEST
);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'test-direct', '--outeropt' => true, 'req-arg' => 'lala']);
self::assertSame('lala
inneropt: unset
outeropt: set
', $appTester->getDisplay(true));
self::assertSame(2, $appTester->getStatusCode());
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'test-ref', '--outeropt' => true, 'req-arg' => 'lala']);
self::assertSame('innerarg
lala
inneropt: set
outeropt: set
', $appTester->getDisplay(true));
self::assertSame(2, $appTester->getStatusCode());
//check if the description from composer.json is correctly shown
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'run-script', '--list' => true]);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay();
self::assertStringContainsString($description, $output, 'The contents of scripts-description for the test script should be printed');
}
public function testExecutionOfSymfonyCommandWithConfiguration(): void
{
$cmdName = 'custom-cmd-123';
$cmdAlias = "$cmdName-alias";
$cmdDesc = 'This is a Symfony command with custom configuration';
$wrongDesc = 'this should be ignored';
$this->initTempComposer([
'scripts' => [
$cmdName => 'Test\\MyCommandWithDefinitions',
],
'scripts-descriptions' => [
$cmdName => $wrongDesc,
],
'autoload' => [
'psr-4' => [
'Test\\' => '',
],
],
]);
file_put_contents('MyCommandWithDefinitions.php', <<<TEST
<?php
namespace Test;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class MyCommandWithDefinitions extends Command
{
protected function configure(): void
{
\$this
->setDescription('$cmdDesc')
->setAliases(['$cmdAlias'])
->setDefinition([new InputArgument('req-arg', InputArgument::REQUIRED, 'Required arg.')]);
}
public function execute(InputInterface \$input, OutputInterface \$output): int
{
\$output->writeln(\$input->getArgument('req-arg'));
return Command::SUCCESS;
}
}
TEST
);
//makes sure the command executes with the name defined inside its `configure()`...
$appTester = $this->getApplicationTester();
$appTester->run(['command' => $cmdName, 'req-arg' => 'lala']);
self::assertSame("lala\n", $appTester->getDisplay(true));
//...with the alias defined there as well...
$appTester = $this->getApplicationTester();
$appTester->run(['command' => $cmdAlias, 'req-arg' => 'lala']);
self::assertSame("lala\n", $appTester->getDisplay(true));
//...and also uses its own description, instead of the one in composer.scripts-descriptions
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'run-script', '--list' => true]);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay();
self::assertStringContainsString($cmdDesc, $output, 'The custom description for the test script should be printed');
self::assertStringNotContainsString($wrongDesc, $output, 'The dummy description shouldn\'t show');
}
/** @return bool[][] **/
public static function getDevOptions(): array
{
return [
[true, true],
[true, false],
[false, true],
[false, false],
];
}
/** @return Composer **/
private function createComposerInstance(): Composer
{
$composer = new Composer;
$config = new Config;
$composer->setConfig($config);
return $composer;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ConfigCommandTest.php | tests/Composer/Test/Command/ConfigCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use RuntimeException;
class ConfigCommandTest extends TestCase
{
/**
* @dataProvider provideConfigUpdates
* @param array<mixed> $before
* @param array<mixed> $command
* @param array<mixed> $expected
*/
public function testConfigUpdates(array $before, array $command, array $expected): void
{
$this->initTempComposer($before);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'config'], $command));
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
self::assertSame($expected, json_decode((string) file_get_contents('composer.json'), true));
}
public static function provideConfigUpdates(): \Generator
{
yield 'set scripts' => [
[],
['setting-key' => 'scripts.test', 'setting-value' => ['foo bar']],
['scripts' => ['test' => 'foo bar']],
];
yield 'unset scripts' => [
['scripts' => ['test' => 'foo bar', 'lala' => 'baz']],
['setting-key' => 'scripts.lala', '--unset' => true],
['scripts' => ['test' => 'foo bar']],
];
yield 'set single config with bool normalizer' => [
[],
['setting-key' => 'use-github-api', 'setting-value' => ['1']],
['config' => ['use-github-api' => true]],
];
yield 'set multi config' => [
[],
['setting-key' => 'github-protocols', 'setting-value' => ['https', 'git']],
['config' => ['github-protocols' => ['https', 'git']]],
];
yield 'set version' => [
[],
['setting-key' => 'version', 'setting-value' => ['1.0.0']],
['version' => '1.0.0'],
];
yield 'unset version' => [
['version' => '1.0.0'],
['setting-key' => 'version', '--unset' => true],
[],
];
yield 'unset arbitrary property' => [
['random-prop' => '1.0.0'],
['setting-key' => 'random-prop', '--unset' => true],
[],
];
yield 'set preferred-install' => [
[],
['setting-key' => 'preferred-install.foo/*', 'setting-value' => ['source']],
['config' => ['preferred-install' => ['foo/*' => 'source']]],
];
yield 'unset preferred-install' => [
['config' => ['preferred-install' => ['foo/*' => 'source']]],
['setting-key' => 'preferred-install.foo/*', '--unset' => true],
['config' => ['preferred-install' => []]],
];
yield 'unset platform' => [
['config' => ['platform' => ['php' => '7.2.5'], 'platform-check' => false]],
['setting-key' => 'platform.php', '--unset' => true],
['config' => ['platform' => [], 'platform-check' => false]],
];
yield 'set extra with merge' => [
[],
['setting-key' => 'extra.patches.foo/bar', 'setting-value' => ['{"123":"value"}'], '--json' => true, '--merge' => true],
['extra' => ['patches' => ['foo/bar' => [123 => 'value']]]],
];
yield 'combine extra with merge' => [
['extra' => ['patches' => ['foo/bar' => [5 => 'oldvalue']]]],
['setting-key' => 'extra.patches.foo/bar', 'setting-value' => ['{"123":"value"}'], '--json' => true, '--merge' => true],
['extra' => ['patches' => ['foo/bar' => [123 => 'value', 5 => 'oldvalue']]]],
];
yield 'combine extra with list' => [
['extra' => ['patches' => ['foo/bar' => ['oldvalue']]]],
['setting-key' => 'extra.patches.foo/bar', 'setting-value' => ['{"123":"value"}'], '--json' => true, '--merge' => true],
['extra' => ['patches' => ['foo/bar' => [123 => 'value', 0 => 'oldvalue']]]],
];
yield 'overwrite extra with merge' => [
['extra' => ['patches' => ['foo/bar' => [123 => 'oldvalue']]]],
['setting-key' => 'extra.patches.foo/bar', 'setting-value' => ['{"123":"value"}'], '--json' => true, '--merge' => true],
['extra' => ['patches' => ['foo/bar' => [123 => 'value']]]],
];
yield 'unset autoload' => [
['autoload' => ['psr-4' => ['test'], 'classmap' => ['test']]],
['setting-key' => 'autoload.psr-4', '--unset' => true],
['autoload' => ['classmap' => ['test']]],
];
yield 'unset autoload-dev' => [
['autoload-dev' => ['psr-4' => ['test'], 'classmap' => ['test']]],
['setting-key' => 'autoload-dev.psr-4', '--unset' => true],
['autoload-dev' => ['classmap' => ['test']]],
];
yield 'set audit.ignore-unreachable' => [
[],
['setting-key' => 'audit.ignore-unreachable', 'setting-value' => ['true']],
['config' => ['audit' => ['ignore-unreachable' => true]]],
];
yield 'set audit.block-insecure' => [
[],
['setting-key' => 'audit.block-insecure', 'setting-value' => ['false']],
['config' => ['audit' => ['block-insecure' => false]]],
];
yield 'set audit.block-abandoned' => [
[],
['setting-key' => 'audit.block-abandoned', 'setting-value' => ['true']],
['config' => ['audit' => ['block-abandoned' => true]]],
];
yield 'unset audit.ignore-unreachable' => [
['config' => ['audit' => ['ignore-unreachable' => true]]],
['setting-key' => 'audit.ignore-unreachable', '--unset' => true],
['config' => ['audit' => []]],
];
yield 'set audit.ignore-severity' => [
[],
['setting-key' => 'audit.ignore-severity', 'setting-value' => ['low', 'medium']],
['config' => ['audit' => ['ignore-severity' => ['low', 'medium']]]],
];
yield 'set audit.ignore as array' => [
[],
['setting-key' => 'audit.ignore', 'setting-value' => ['["CVE-2024-1234","GHSA-xxxx-yyyy"]'], '--json' => true],
['config' => ['audit' => ['ignore' => ['CVE-2024-1234', 'GHSA-xxxx-yyyy']]]],
];
yield 'set audit.ignore as object' => [
[],
['setting-key' => 'audit.ignore', 'setting-value' => ['{"CVE-2024-1234":"False positive","GHSA-xxxx-yyyy":"Not applicable"}'], '--json' => true],
['config' => ['audit' => ['ignore' => ['CVE-2024-1234' => 'False positive', 'GHSA-xxxx-yyyy' => 'Not applicable']]]],
];
yield 'merge audit.ignore array' => [
['config' => ['audit' => ['ignore' => ['CVE-2024-1234']]]],
['setting-key' => 'audit.ignore', 'setting-value' => ['["CVE-2024-5678"]'], '--json' => true, '--merge' => true],
['config' => ['audit' => ['ignore' => ['CVE-2024-1234', 'CVE-2024-5678']]]],
];
yield 'merge audit.ignore object' => [
['config' => ['audit' => ['ignore' => ['CVE-2024-1234' => 'Old reason']]]],
['setting-key' => 'audit.ignore', 'setting-value' => ['{"CVE-2024-5678":"New advisory"}'], '--json' => true, '--merge' => true],
['config' => ['audit' => ['ignore' => ['CVE-2024-5678' => 'New advisory', 'CVE-2024-1234' => 'Old reason']]]],
];
yield 'overwrite audit.ignore key with merge' => [
['config' => ['audit' => ['ignore' => ['CVE-2024-1234' => 'Old reason']]]],
['setting-key' => 'audit.ignore', 'setting-value' => ['{"CVE-2024-1234":"New reason"}'], '--json' => true, '--merge' => true],
['config' => ['audit' => ['ignore' => ['CVE-2024-1234' => 'New reason']]]],
];
yield 'set audit.ignore-abandoned as array' => [
[],
['setting-key' => 'audit.ignore-abandoned', 'setting-value' => ['["vendor/package1","vendor/package2"]'], '--json' => true],
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1', 'vendor/package2']]]],
];
yield 'set audit.ignore-abandoned as object' => [
[],
['setting-key' => 'audit.ignore-abandoned', 'setting-value' => ['{"vendor/package1":"Still maintained","vendor/package2":"Fork available"}'], '--json' => true],
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1' => 'Still maintained', 'vendor/package2' => 'Fork available']]]],
];
yield 'merge audit.ignore-abandoned array' => [
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1']]]],
['setting-key' => 'audit.ignore-abandoned', 'setting-value' => ['["vendor/package2"]'], '--json' => true, '--merge' => true],
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1', 'vendor/package2']]]],
];
yield 'merge audit.ignore-abandoned object' => [
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1' => 'Old reason']]]],
['setting-key' => 'audit.ignore-abandoned', 'setting-value' => ['{"vendor/package2":"New reason"}'], '--json' => true, '--merge' => true],
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package2' => 'New reason', 'vendor/package1' => 'Old reason']]]],
];
yield 'unset audit.ignore' => [
['config' => ['audit' => ['ignore' => ['CVE-2024-1234']]]],
['setting-key' => 'audit.ignore', '--unset' => true],
['config' => ['audit' => []]],
];
yield 'unset audit.ignore-abandoned' => [
['config' => ['audit' => ['ignore-abandoned' => ['vendor/package1']]]],
['setting-key' => 'audit.ignore-abandoned', '--unset' => true],
['config' => ['audit' => []]],
];
}
/**
* @dataProvider provideConfigReads
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testConfigReads(array $composerJson, array $command, string $expected): void
{
$this->initTempComposer($composerJson);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'config'], $command));
$appTester->assertCommandIsSuccessful();
self::assertSame($expected, trim($appTester->getDisplay(true)));
self::assertSame($composerJson, json_decode((string) file_get_contents('composer.json'), true), 'The composer.json should not be modified by config reads');
}
public static function provideConfigReads(): \Generator
{
yield 'read description' => [
['description' => 'foo bar'],
['setting-key' => 'description'],
'foo bar',
];
yield 'read vendor-dir with source' => [
['config' => ['vendor-dir' => 'lala']],
['setting-key' => 'vendor-dir', '--source' => true],
'lala (./composer.json)',
];
yield 'read default vendor-dir' => [
[],
['setting-key' => 'vendor-dir'],
'vendor',
];
yield 'read repos by named key' => [
['repositories' => ['foo' => ['type' => 'vcs', 'url' => 'https://example.org'], 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org']]],
['setting-key' => 'repositories.foo'],
'{"type":"vcs","url":"https://example.org"}',
];
yield 'read repos by numeric index' => [
['repositories' => [['type' => 'vcs', 'url' => 'https://example.org'], 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org']]],
['setting-key' => 'repos.0'],
'{"type":"vcs","url":"https://example.org"}',
];
yield 'read all repos includes the default packagist' => [
['repositories' => ['foo' => ['type' => 'vcs', 'url' => 'https://example.org'], 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org']]],
['setting-key' => 'repos'],
'{"foo":{"type":"vcs","url":"https://example.org"},"packagist.org":{"type":"composer","url":"https://repo.packagist.org"}}',
];
yield 'read all repos does not include the disabled packagist' => [
['repositories' => ['foo' => ['type' => 'vcs', 'url' => 'https://example.org'], 'packagist.org' => false]],
['setting-key' => 'repos'],
'{"foo":{"type":"vcs","url":"https://example.org"}}',
];
}
public function testConfigThrowsForInvalidArgCombination(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('--file and --global can not be combined');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'config', '--file' => 'alt.composer.json', '--global' => true]);
}
public function testConfigThrowsForInvalidSeverity(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('valid severities include: low, medium, high, critical');
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'config', 'setting-key' => 'audit.ignore-severity', 'setting-value' => ['low', 'invalid']]);
}
public function testConfigThrowsWhenMergingArrayWithObject(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Cannot merge array and object');
$this->initTempComposer(['config' => ['audit' => ['ignore' => ['CVE-2024-1234']]]]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'config', 'setting-key' => 'audit.ignore', 'setting-value' => ['{"CVE-2024-5678":"reason"}'], '--json' => true, '--merge' => true]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ShowCommandTest.php | tests/Composer/Test/Command/ShowCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Package\Link;
use Composer\Pcre\Preg;
use Composer\Pcre\Regex;
use Composer\Repository\PlatformRepository;
use Composer\Test\TestCase;
use DateTimeImmutable;
use InvalidArgumentException;
class ShowCommandTest extends TestCase
{
/**
* @dataProvider provideShow
* @param array<mixed> $command
* @param array<string, string> $requires
*/
public function testShow(array $command, string $expected, array $requires = []): void
{
$this->initTempComposer([
'name' => 'root/pkg',
'version' => '1.2.3',
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/package', 'description' => 'generic description', 'version' => 'v1.0.0'],
['name' => 'outdated/major', 'description' => 'outdated/major v1.0.0 description', 'version' => 'v1.0.0'],
['name' => 'outdated/major', 'description' => 'outdated/major v1.0.1 description', 'version' => 'v1.0.1'],
['name' => 'outdated/major', 'description' => 'outdated/major v1.1.0 description', 'version' => 'v1.1.0'],
['name' => 'outdated/major', 'description' => 'outdated/major v1.1.1 description', 'version' => 'v1.1.1'],
['name' => 'outdated/major', 'description' => 'outdated/major v2.0.0 description', 'version' => 'v2.0.0'],
['name' => 'outdated/minor', 'description' => 'outdated/minor v1.0.0 description', 'version' => '1.0.0'],
['name' => 'outdated/minor', 'description' => 'outdated/minor v1.0.1 description', 'version' => '1.0.1'],
['name' => 'outdated/minor', 'description' => 'outdated/minor v1.1.0 description', 'version' => '1.1.0'],
['name' => 'outdated/minor', 'description' => 'outdated/minor v1.1.1 description', 'version' => '1.1.1'],
['name' => 'outdated/patch', 'description' => 'outdated/patch v1.0.0 description', 'version' => '1.0.0'],
['name' => 'outdated/patch', 'description' => 'outdated/patch v1.0.1 description', 'version' => '1.0.1'],
],
],
],
'require' => $requires === [] ? new \stdClass : $requires,
]);
$pkg = self::getPackage('vendor/package', 'v1.0.0');
$pkg->setDescription('description of installed package');
$major = self::getPackage('outdated/major', 'v1.0.0');
$major->setReleaseDate(new DateTimeImmutable());
$minor = self::getPackage('outdated/minor', '1.0.0');
$minor->setReleaseDate(new DateTimeImmutable('-2 years'));
$patch = self::getPackage('outdated/patch', '1.0.0');
$patch->setReleaseDate(new DateTimeImmutable('-2 weeks'));
$this->createInstalledJson([$pkg, $major, $minor, $patch]);
$pkg = self::getPackage('vendor/locked', '3.0.0');
$pkg->setDescription('description of locked package');
$this->createComposerLock([
$pkg,
]);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'show'], $command));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public static function provideShow(): \Generator
{
yield 'default shows installed with version and description' => [
[],
'outdated/major 1.0.0
outdated/minor 1.0.0
outdated/patch 1.0.0
vendor/package 1.0.0 description of installed package',
];
yield 'with -s and --installed shows list of installed + self package' => [
['--installed' => true, '--self' => true],
'outdated/major 1.0.0
outdated/minor 1.0.0
outdated/patch 1.0.0
root/pkg 1.2.3
vendor/package 1.0.0 description of installed package',
];
yield 'with -s and --locked shows list of installed + self package' => [
['--locked' => true, '--self' => true],
'root/pkg 1.2.3
vendor/locked 3.0.0 description of locked package',
];
yield 'with -a show available packages with description but no version' => [
['-a' => true],
'outdated/major outdated/major v2.0.0 description
outdated/minor outdated/minor v1.1.1 description
outdated/patch outdated/patch v1.0.1 description
vendor/package generic description',
];
yield 'show with --direct shows nothing if no deps' => [
['--direct' => true],
'',
];
yield 'show with --direct shows only root deps' => [
['--direct' => true],
'outdated/major 1.0.0',
['outdated/major' => '*'],
];
yield 'outdated deps' => [
['command' => 'outdated'],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
outdated/major 1.0.0 ~ 2.0.0
outdated/minor 1.0.0 <highlight>! 1.1.1</highlight>
outdated/patch 1.0.0 <highlight>! 1.0.1</highlight>',
];
yield 'outdated deps sorting by age' => [
['command' => 'outdated', '--sort-by-age' => true],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
outdated/minor 1.0.0 <highlight>! 1.1.1</highlight> 2 years old
outdated/patch 1.0.0 <highlight>! 1.0.1</highlight> 2 weeks old
outdated/major 1.0.0 ~ 2.0.0 from today',
];
yield 'outdated deps with --direct only show direct deps with updated' => [
['command' => 'outdated', '--direct' => true],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
outdated/major 1.0.0 ~ 2.0.0',
[
'vendor/package' => '*',
'outdated/major' => '*',
],
];
yield 'outdated deps with --direct show msg if all up to date' => [
['command' => 'outdated', '--direct' => true],
'All your direct dependencies are up to date',
[
'vendor/package' => '*',
],
];
yield 'outdated deps with --major-only only shows major updates' => [
['command' => 'outdated', '--major-only' => true],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
outdated/major 1.0.0 ~ 2.0.0',
];
yield 'outdated deps with --minor-only only shows minor updates' => [
['command' => 'outdated', '--minor-only' => true],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
outdated/minor 1.0.0 <highlight>! 1.1.1</highlight>
Transitive dependencies not required in composer.json:
outdated/major 1.0.0 <highlight>! 1.1.1</highlight>
outdated/patch 1.0.0 <highlight>! 1.0.1</highlight>',
['outdated/minor' => '*'],
];
yield 'outdated deps with --patch-only only shows patch updates' => [
['command' => 'outdated', '--patch-only' => true],
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
outdated/major 1.0.0 <highlight>! 1.0.1</highlight>
outdated/minor 1.0.0 <highlight>! 1.0.1</highlight>
outdated/patch 1.0.0 <highlight>! 1.0.1</highlight>',
];
}
public function testOutdatedFiltersAccordingToPlatformReqsAndWarns(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.0.0'],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.1.0', 'require' => ['ext-missing' => '3']],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.2.0', 'require' => ['ext-missing' => '3']],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.3.0', 'require' => ['ext-missing' => '3']],
],
],
],
]);
$this->createInstalledJson([
self::getPackage('vendor/package', '1.1.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated']);
self::assertSame("<warning>Cannot use vendor/package 1.1.0 as it requires ext-missing 3 which is missing from your platform.
Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
vendor/package 1.1.0 ~ 1.0.0", trim($appTester->getDisplay(true)));
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated', '--verbose' => true]);
self::assertSame("<warning>Cannot use vendor/package's latest version 1.3.0 as it requires ext-missing 3 which is missing from your platform.
<warning>Cannot use vendor/package 1.2.0 as it requires ext-missing 3 which is missing from your platform.
<warning>Cannot use vendor/package 1.1.0 as it requires ext-missing 3 which is missing from your platform.
Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
vendor/package 1.1.0 ~ 1.0.0", trim($appTester->getDisplay(true)));
}
public function testOutdatedFiltersAccordingToPlatformReqsWithoutWarningForHigherVersions(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.0.0'],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.1.0'],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.2.0'],
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.3.0', 'require' => ['php' => '^99']],
],
],
],
]);
$this->createInstalledJson([
self::getPackage('vendor/package', '1.1.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated']);
self::assertSame("Legend:
! patch or minor release available - update recommended
~ major release available - update possible
Direct dependencies required in composer.json:
Everything up to date
Transitive dependencies not required in composer.json:
vendor/package 1.1.0 <highlight>! 1.2.0</highlight>", trim($appTester->getDisplay(true)));
}
public function testShowDirectWithNameDoesNotShowTransientDependencies(): void
{
self::expectException(InvalidArgumentException::class);
self::expectExceptionMessage('Package "vendor/package" is installed but not a direct dependent of the root package.');
$this->initTempComposer([
'repositories' => [],
'require' => [
'direct/dependent' => '*',
],
]);
$this->createInstalledJson([
$direct = self::getPackage('direct/dependent', '1.0.0'),
self::getPackage('vendor/package', '1.0.0'),
]);
self::configureLinks($direct, ['require' => ['vendor/package' => '*']]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--direct' => true, 'package' => 'vendor/package']);
}
public function testShowDirectWithNameOnlyShowsDirectDependents(): void
{
$this->initTempComposer([
'repositories' => [],
'require' => [
'direct/dependent' => '*',
],
'require-dev' => [
'direct/dependent2' => '*',
],
]);
$this->createInstalledJson([
self::getPackage('direct/dependent', '1.0.0'),
self::getPackage('direct/dependent2', '1.0.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--direct' => true, 'package' => 'direct/dependent']);
$appTester->assertCommandIsSuccessful();
self::assertStringContainsString('name : direct/dependent' . "\n", $appTester->getDisplay(true));
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--direct' => true, 'package' => 'direct/dependent2']);
$appTester->assertCommandIsSuccessful();
self::assertStringContainsString('name : direct/dependent2' . "\n", $appTester->getDisplay(true));
}
public function testShowPlatformOnlyShowsPlatformPackages(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.0.0'],
],
],
],
]);
$this->createInstalledJson([
self::getPackage('vendor/package', '1.0.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '-p' => true]);
$output = trim($appTester->getDisplay(true));
foreach (Regex::matchAll('{^(\w+)}m', $output)->matches as $m) {
self::assertTrue(PlatformRepository::isPlatformPackage((string) $m[1]));
}
}
public function testShowPlatformWorksWithoutComposerJson(): void
{
$this->initTempComposer([]);
unlink('./composer.json');
unlink('./auth.json');
// listing packages
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '-p' => true]);
$output = trim($appTester->getDisplay(true));
foreach (Regex::matchAll('{^(\w+)}m', $output)->matches as $m) {
self::assertTrue(PlatformRepository::isPlatformPackage((string) $m[1]));
}
// getting a single package
$appTester->run(['command' => 'show', '-p' => true, 'package' => 'php']);
$appTester->assertCommandIsSuccessful();
$appTester->run(['command' => 'show', '-p' => true, '-f' => 'json', 'package' => 'php']);
$appTester->assertCommandIsSuccessful();
}
public function testOutdatedWithZeroMajor(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'zerozero/major', 'description' => 'generic description', 'version' => '0.0.1'],
['name' => 'zerozero/major', 'description' => 'generic description', 'version' => '0.0.2'],
['name' => 'zero/major', 'description' => 'generic description', 'version' => '0.1.0'],
['name' => 'zero/major', 'description' => 'generic description', 'version' => '0.2.0'],
['name' => 'zero/minor', 'description' => 'generic description', 'version' => '0.1.0'],
['name' => 'zero/minor', 'description' => 'generic description', 'version' => '0.1.2'],
['name' => 'zero/patch', 'description' => 'generic description', 'version' => '0.1.2'],
['name' => 'zero/patch', 'description' => 'generic description', 'version' => '0.1.2.1'],
],
],
],
'require' => [
'zerozero/major' => '^0.0.1',
'zero/major' => '^0.1',
'zero/minor' => '^0.1',
'zero/patch' => '^0.1',
],
]);
$this->createInstalledJson([
self::getPackage('zerozero/major', '0.0.1'),
self::getPackage('zero/major', '0.1.0'),
self::getPackage('zero/minor', '0.1.0'),
self::getPackage('zero/patch', '0.1.2'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated', '--direct' => true, '--patch-only' => true]);
self::assertSame(
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
zero/patch 0.1.2 <highlight>! 0.1.2.1</highlight>', trim($appTester->getDisplay(true)));
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated', '--direct' => true, '--minor-only' => true]);
self::assertSame(
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
zero/minor 0.1.0 <highlight>! 0.1.2 </highlight>
zero/patch 0.1.2 <highlight>! 0.1.2.1</highlight>', trim($appTester->getDisplay(true)));
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'outdated', '--direct' => true, '--major-only' => true]);
self::assertSame(
'Legend:
! patch or minor release available - update recommended
~ major release available - update possible
zero/major 0.1.0 ~ 0.2.0
zerozero/major 0.0.1 ~ 0.0.2', trim($appTester->getDisplay(true)));
}
public function testShowAllShowsAllSections(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/available', 'description' => 'generic description', 'version' => '1.0.0'],
],
],
],
]);
$pkg = self::getPackage('vendor/installed', '2.0.0');
$pkg->setDescription('description of installed package');
$this->createInstalledJson([
$pkg,
]);
$pkg = self::getPackage('vendor/locked', '3.0.0');
$pkg->setDescription('description of locked package');
$this->createComposerLock([
$pkg,
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--all' => true]);
$output = trim($appTester->getDisplay(true));
$output = Preg::replace('{platform:(\n .*)+}', 'platform: wiped', $output);
self::assertSame('platform: wiped
locked:
vendor/locked 3.0.0 description of locked package
available:
vendor/available generic description
installed:
vendor/installed 2.0.0 description of installed package',
$output
);
}
public function testLockedRequiresValidLockFile(): void
{
$this->initTempComposer();
$this->expectExceptionMessage(
"A valid composer.json and composer.lock files is required to run this command with --locked"
);
$this->getApplicationTester()->run(['command' => 'show', '--locked' => true]);
}
public function testLockedShowsAllLocked(): void
{
$this->initTempComposer();
$pkg = static::getPackage('vendor/locked', '3.0.0');
$pkg->setDescription('description of locked package');
$this->createComposerLock([
$pkg,
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--locked' => true]);
$output = trim($appTester->getDisplay(true));
self::assertSame(
'vendor/locked 3.0.0 description of locked package',
$output
);
$pkg2 = static::getPackage('vendor/locked2', '2.0.0');
$pkg2->setDescription('description of locked2 package');
$this->createComposerLock([
$pkg,
$pkg2,
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--locked' => true]);
$output = trim($appTester->getDisplay(true));
$shouldBe = <<<OUTPUT
vendor/locked 3.0.0 description of locked package
vendor/locked2 2.0.0 description of locked2 package
OUTPUT;
self::assertSame(
$shouldBe,
$output
);
}
public function testInvalidOptionCombinations(): void
{
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--direct' => true, '--all' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--direct' => true, '--available' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--direct' => true, '--platform' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--tree' => true, '--all' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--tree' => true, '--available' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--tree' => true, '--latest' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--tree' => true, '--path' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--patch-only' => true, '--minor-only' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--patch-only' => true, '--major-only' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--minor-only' => true, '--major-only' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--minor-only' => true, '--major-only' => true, '--patch-only' => true]);
self::assertSame(1, $appTester->getStatusCode());
$appTester->run(['command' => 'show', '--format' => 'test']);
self::assertSame(1, $appTester->getStatusCode());
}
public function testIgnoredOptionCombinations(): void
{
$this->initTempComposer();
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--installed' => true]);
self::assertStringContainsString(
'You are using the deprecated option "installed".',
$appTester->getDisplay(true)
);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--ignore' => ['vendor/package']]);
self::assertStringContainsString('You are using the option "ignore"', $appTester->getDisplay(true));
}
public function testSelfAndNameOnly(): void
{
$this->initTempComposer(['name' => 'vendor/package', 'version' => '1.2.3']);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--self' => true, '--name-only' => true]);
self::assertSame('vendor/package', trim($appTester->getDisplay(true)));
}
public function testSelfAndPackageCombination(): void
{
$this->initTempComposer(['name' => 'vendor/package']);
$appTester = $this->getApplicationTester();
$this->expectException(InvalidArgumentException::class);
$appTester->run(['command' => 'show', '--self' => true, 'package' => 'vendor/package']);
}
public function testSelf(): void
{
$this->initTempComposer(['name' => 'vendor/package', 'version' => '1.2.3', 'time' => date('Y-m-d')]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--self' => true]);
$expected = [
'name' => 'vendor/package',
'descrip.' => '',
'keywords' => '',
'versions' => '* 1.2.3',
'released' => date('Y-m-d'). ', today',
'type' => 'library',
'homepage' => '',
'source' => '[] ',
'dist' => '[] ',
'path' => '',
'names' => 'vendor/package',
];
$expectedString = implode(
"\n",
array_map(
static function ($k, $v) {
return sprintf('%-8s : %s', $k, $v);
},
array_keys($expected),
$expected
)
) . "\n";
self::assertSame($expectedString, $appTester->getDisplay(true));
}
public function testNotInstalledError(): void
{
$this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
],
'require-dev' => [
'vendor/package-dev' => '1.0.0',
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show']);
$output = trim($appTester->getDisplay(true));
self::assertStringContainsString(
'No dependencies installed. Try running composer install or update.',
$output,
'Should show error message when no dependencies are installed'
);
}
public function testNoDevOption(): void
{
$this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
],
'require-dev' => [
'vendor/package-dev' => '1.0.0',
],
]);
$this->createInstalledJson([
static::getPackage('vendor/package', '1.0.0'),
static::getPackage('vendor/package-dev', '1.0.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', '--no-dev' => true]);
$output = trim($appTester->getDisplay(true));
self::assertSame(
'vendor/package 1.0.0',
$output
);
}
public function testPackageFilter(): void
{
$this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
'vendor/other-package' => '1.0.0',
'company/package' => '1.0.0',
'company/other-package' => '1.0.0',
],
]);
$this->createInstalledJson([
static::getPackage('vendor/package', '1.0.0'),
static::getPackage('vendor/other-package', '1.0.0'),
static::getPackage('company/package', '1.0.0'),
static::getPackage('company/other-package', '1.0.0'),
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', 'package' => 'vendor/package']);
$output = trim($appTester->getDisplay(true));
self::assertStringContainsString('vendor/package', $output);
self::assertStringNotContainsString('vendor/other-package', $output);
self::assertStringNotContainsString('company/package', $output);
self::assertStringNotContainsString('company/other-package', $output);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', 'package' => 'company/*', '--name-only' => true]);
$output = trim($appTester->getDisplay(true));
self::assertStringNotContainsString('vendor/package', $output);
self::assertStringNotContainsString('vendor/other-package', $output);
self::assertStringContainsString('company/package', $output);
self::assertStringContainsString('company/other-package', $output);
}
/**
* @dataProvider provideNotExistingPackage
* @param array<string, mixed> $options
*/
public function testNotExistingPackage(string $package, array $options, string $expected): void
{
$dir = $this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
],
]);
$pkg = static::getPackage('vendor/package', '1.0.0');
$this->createInstalledJson([$pkg]);
$this->createComposerLock([$pkg]);
if (isset($options['--working-dir'])) {
$options['--working-dir'] = $dir;
}
$this->expectExceptionMessageMatches("/^" . preg_quote($expected, '/') . "/");
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', 'package' => $package] + $options);
}
public function provideNotExistingPackage(): \Generator
{
yield 'package with no options' => [
'not/existing',
[],
'Package "not/existing" not found, try using --available (-a) to show all available packages.',
];
yield 'package with --all option' => [
'not/existing',
['--all' => true],
'Package "not/existing" not found.',
];
yield 'package with --locked option' => [
'not/existing',
['--locked' => true],
'Package "not/existing" not found in lock file, try using --available (-a) to show all available packages.',
];
yield 'platform with --platform' => [
'ext-nonexisting',
['--platform' => true],
'Package "ext-nonexisting" not found, try using --available (-a) to show all available packages.',
];
yield 'platform without --platform' => [
'ext-nonexisting',
[],
'Package "ext-nonexisting" not found, try using --platform (-p) to show platform packages, try using --available (-a) to show all available packages.',
];
}
public function testNotExistingPackageWithWorkingDir(): void
{
$dir = $this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
],
]);
$pkg = static::getPackage('vendor/package', '1.0.0');
$this->createInstalledJson([$pkg]);
$this->expectExceptionMessageMatches("/^" . preg_quote("Package \"not/existing\" not found in {$dir}/composer.json, try using --available (-a) to show all available packages.", '/') . "/");
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', 'package' => 'not/existing', '--working-dir' => $dir]);
}
/**
* @dataProvider providePackageAndTree
* @param array<string, mixed> $options
*/
public function testSpecificPackageAndTree(callable $callable, array $options, string $expected): void
{
$this->initTempComposer([
'require' => [
'vendor/package' => '1.0.0',
],
]);
$this->createInstalledJson($callable());
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'show', 'package' => 'vendor/package', '--tree' => true] + $options);
self::assertSame($expected, trim($appTester->getDisplay(true)));
}
public function providePackageAndTree(): \Generator
{
yield 'just package' => [
static function () {
$pgk = static::getPackage('vendor/package', '1.0.0');
return [$pgk];
},
[],
'vendor/package 1.0.0',
];
yield 'package with one package requirement' => [
static function () {
$pgk = static::getPackage('vendor/package', '1.0.0');
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/CheckPlatformReqsCommandTest.php | tests/Composer/Test/Command/CheckPlatformReqsCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use LogicException;
class CheckPlatformReqsCommandTest extends TestCase
{
/**
* @dataProvider caseProvider
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testPlatformReqsAreSatisfied(
array $composerJson,
array $command,
string $expected,
bool $lock = true
): void {
$this->initTempComposer($composerJson);
$packages = [
self::getPackage('ext-foobar', '2.3.4'),
];
$devPackages = [
self::getPackage('ext-barbaz', '2.3.4.5'),
];
$this->createInstalledJson($packages, $devPackages);
if ($lock) {
$this->createComposerLock($packages, $devPackages);
}
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'check-platform-reqs'], $command));
$appTester->assertCommandIsSuccessful();
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public function testExceptionThrownIfNoLockfileFound(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage("No lockfile found. Unable to read locked packages");
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'check-platform-reqs']);
}
public static function caseProvider(): \Generator
{
yield 'Disables checking of require-dev packages requirements.' => [
[
'require' => [
'ext-foobar' => '^2.0',
],
'require-dev' => [
'ext-barbaz' => '~4.0',
],
],
['--no-dev' => true],
'Checking non-dev platform requirements for packages in the vendor dir
ext-foobar 2.3.4 success',
];
yield 'Checks requirements only from the lock file, not from installed packages.' => [
[
'require' => [
'ext-foobar' => '^2.3',
],
'require-dev' => [
'ext-barbaz' => '~2.0',
],
],
['--lock' => true],
"Checking platform requirements using the lock file\next-barbaz 2.3.4.5 success \next-foobar 2.3.4 success",
];
}
public function testFailedPlatformRequirement(): void
{
$this->initTempComposer([
'require' => [
'ext-foobar' => '^0.3',
],
'require-dev' => [
'ext-barbaz' => '^2.3',
],
]);
$packages = [
self::getPackage('ext-foobar', '2.3.4'),
];
$devPackages = [
self::getPackage('ext-barbaz', '2.3.4.5'),
];
$this->createInstalledJson($packages, $devPackages);
$this->createComposerLock($packages, $devPackages);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'check-platform-reqs', '--format' => 'json']);
$expected = 'Checking platform requirements for packages in the vendor dir
[
{
"name": "ext-barbaz",
"version": "2.3.4.5",
"status": "success",
"failed_requirement": null,
"provider": null
},
{
"name": "ext-foobar",
"version": "2.3.4",
"status": "failed",
"failed_requirement": {
"source": "__root__",
"type": "requires",
"target": "ext-foobar",
"constraint": "^0.3"
},
"provider": null
}
]';
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/SearchCommandTest.php | tests/Composer/Test/Command/SearchCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use InvalidArgumentException;
class SearchCommandTest extends TestCase
{
/**
* @dataProvider provideSearch
* @param array<mixed> $command
*/
public function testSearch(array $command, string $expected = ''): void
{
$this->initTempComposer([
'repositories' => [
['packagist.org' => false],
[
'type' => 'package',
'package' => [
['name' => 'vendor-1/package-1', 'description' => 'generic description', 'version' => '1.0.0'],
['name' => 'foo/bar', 'description' => 'generic description', 'version' => '1.0.0'],
['name' => 'bar/baz', 'description' => 'fancy baz', 'version' => '1.0.0', 'abandoned' => true],
['name' => 'vendor-2/fancy-package', 'fancy description', 'version' => '1.0.0', 'type' => 'foo'],
],
],
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'search'], $command));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public function testInvalidFormat(): void
{
$this->initTempComposer([
'repositories' => [
'packagist.org' => false,
],
]);
$appTester = $this->getApplicationTester();
$result = $appTester->run(['command' => 'search', '--format' => 'test-format', 'tokens' => ['test']]);
self::assertSame(1, $result);
self::assertSame('Unsupported format "test-format". See help for supported formats.', trim($appTester->getDisplay(true)));
}
public function testInvalidFlags(): void
{
$this->initTempComposer([
'repositories' => [
'packagist.org' => false,
],
]);
$appTester = $this->getApplicationTester();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('--only-name and --only-vendor cannot be used together');
$appTester->run(['command' => 'search', '--only-vendor' => true, '--only-name' => true, 'tokens' => ['test']]);
}
public static function provideSearch(): \Generator
{
yield 'by name and description' => [
['tokens' => ['fancy']],
<<<OUTPUT
bar/baz <warning>! Abandoned !</warning> fancy baz
vendor-2/fancy-package
OUTPUT
];
yield 'by name and description with multiple tokens' => [
['tokens' => ['fancy', 'vendor']],
<<<OUTPUT
vendor-1/package-1 generic description
bar/baz <warning>! Abandoned !</warning> fancy baz
vendor-2/fancy-package
OUTPUT
];
yield 'by name only' => [
['tokens' => ['fancy'], '--only-name' => true],
<<<OUTPUT
vendor-2/fancy-package
OUTPUT
];
yield 'by vendor only' => [
['tokens' => ['bar'], '--only-vendor' => true],
<<<OUTPUT
bar
OUTPUT
];
yield 'by type' => [
['tokens' => ['vendor'], '--type' => 'foo'],
<<<OUTPUT
vendor-2/fancy-package
OUTPUT
];
yield 'json format' => [
['tokens' => ['vendor-2/fancy'], '--format' => 'json'],
<<<OUTPUT
[
{
"name": "vendor-2/fancy-package",
"description": null
}
]
OUTPUT
];
yield 'no results' => [
['tokens' => ['invalid-package-name']],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/RequireCommandTest.php | tests/Composer/Test/Command/RequireCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Json\JsonFile;
use Composer\Test\TestCase;
use InvalidArgumentException;
class RequireCommandTest extends TestCase
{
public function testRequireThrowsIfNoneMatches(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Package required/pkg has requirements incompatible with your PHP version, PHP extensions and Composer version:' . PHP_EOL .
' - required/pkg 1.0.0 requires ext-foobar ^1 but it is not present.'
);
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.0.0', 'require' => ['ext-foobar' => '^1']],
],
],
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'require', '--dry-run' => true, '--no-audit' => true, 'packages' => ['required/pkg']]);
}
public function testRequireWarnsIfResolvedToFeatureBranch(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '2.0.0', 'require' => ['common/dep' => '^1']],
['name' => 'required/pkg', 'version' => 'dev-foo-bar', 'require' => ['common/dep' => '^2']],
['name' => 'common/dep', 'version' => '2.0.0'],
],
],
],
'require' => [
'common/dep' => '^2.0',
],
'minimum-stability' => 'dev',
'prefer-stable' => true,
]);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['n']);
$appTester->run(['command' => 'require', '--dry-run' => true, '--no-audit' => true, 'packages' => ['required/pkg']], ['interactive' => true]);
self::assertSame(
'./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking common/dep (2.0.0)
- Locking required/pkg (dev-foo-bar)
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
- Installing common/dep (2.0.0)
- Installing required/pkg (dev-foo-bar)
Using version dev-foo-bar for required/pkg
<warning>Version dev-foo-bar looks like it may be a feature branch which is unlikely to keep working in the long run and may be in an unstable state</warning>
Are you sure you want to use this constraint (y) or would you rather abort (n) the whole operation [y,n]? '.'
Installation failed, reverting ./composer.json to its original content.
', $appTester->getDisplay(true));
}
/**
* @dataProvider provideRequire
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testRequire(array $composerJson, array $command, string $expected): void
{
$this->initTempComposer($composerJson);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'require', '--dry-run' => true, '--no-audit' => true], $command));
if (str_contains($expected, '%d')) {
$pattern = '{^'.str_replace('%d', '[0-9.]+', preg_quote(trim($expected))).'$}';
self::assertMatchesRegularExpression($pattern, trim($appTester->getDisplay(true)));
} else {
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
}
public static function provideRequire(): \Generator
{
yield 'warn once for missing ext but a lower package matches' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.2.0', 'require' => ['ext-foobar' => '^1']],
['name' => 'required/pkg', 'version' => '1.1.0', 'require' => ['ext-foobar' => '^1']],
['name' => 'required/pkg', 'version' => '1.0.0'],
],
],
],
],
['packages' => ['required/pkg']],
<<<OUTPUT
<warning>Cannot use required/pkg's latest version 1.2.0 as it requires ext-foobar ^1 which is missing from your platform.
./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking required/pkg (1.0.0)
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing required/pkg (1.0.0)
Using version ^1.0 for required/pkg
OUTPUT
];
yield 'warn multiple times when verbose' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.2.0', 'require' => ['ext-foobar' => '^1']],
['name' => 'required/pkg', 'version' => '1.1.0', 'require' => ['ext-foobar' => '^1']],
['name' => 'required/pkg', 'version' => '1.0.0'],
],
],
],
],
['packages' => ['required/pkg'], '--no-install' => true, '-v' => true],
<<<OUTPUT
<warning>Cannot use required/pkg's latest version 1.2.0 as it requires ext-foobar ^1 which is missing from your platform.
<warning>Cannot use required/pkg 1.1.0 as it requires ext-foobar ^1 which is missing from your platform.
./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Dependency resolution completed in %d seconds
Analyzed %d packages to resolve dependencies
Analyzed %d rules to resolve dependencies
Lock file operations: 1 install, 0 updates, 0 removals
Installs: required/pkg:1.0.0
- Locking required/pkg (1.0.0)
Using version ^1.0 for required/pkg
OUTPUT
];
yield 'warn for not satisfied req which is satisfied by lower version' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.1.0', 'require' => ['php' => '^20']],
['name' => 'required/pkg', 'version' => '1.0.0', 'require' => ['php' => '>=7']],
],
],
],
],
['packages' => ['required/pkg'], '--no-install' => true],
<<<OUTPUT
<warning>Cannot use required/pkg's latest version 1.1.0 as it requires php ^20 which is not satisfied by your platform.
./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking required/pkg (1.0.0)
Using version ^1.0 for required/pkg
OUTPUT
];
yield 'version selection happens early even if not completely accurate if no update is requested' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.1.0', 'require' => ['php' => '^20']],
['name' => 'required/pkg', 'version' => '1.0.0', 'require' => ['php' => '>=7']],
],
],
],
],
['packages' => ['required/pkg'], '--no-update' => true],
<<<OUTPUT
<warning>Cannot use required/pkg's latest version 1.1.0 as it requires php ^20 which is not satisfied by your platform.
Using version ^1.0 for required/pkg
./composer.json has been updated
OUTPUT
];
yield 'pick best matching version when not provided' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'existing/dep', 'version' => '1.1.0', 'require' => ['required/pkg' => '^1']],
['name' => 'required/pkg', 'version' => '2.0.0'],
['name' => 'required/pkg', 'version' => '1.1.0'],
['name' => 'required/pkg', 'version' => '1.0.0'],
],
],
],
'require' => [
'existing/dep' => '^1',
],
],
['packages' => ['required/pkg'], '--no-install' => true],
<<<OUTPUT
./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking existing/dep (1.1.0)
- Locking required/pkg (1.1.0)
Using version ^1.1 for required/pkg
OUTPUT
];
yield 'use exact constraint with --fixed' => [
[
'type' => 'project',
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.1.0'],
],
],
],
],
['packages' => ['required/pkg'], '--no-install' => true, '--fixed' => true],
<<<OUTPUT
./composer.json has been updated
Running composer update required/pkg
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking required/pkg (1.1.0)
Using version 1.1.0 for required/pkg
OUTPUT
];
}
/**
* @dataProvider provideInconsistentRequireKeys
*/
public function testInconsistentRequireKeys(bool $isDev, bool $isInteractive, string $expectedWarning): void
{
$currentKey = $isDev ? "require" : "require-dev";
$otherKey = $isDev ? "require-dev" : "require";
$dir = $this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'required/pkg', 'version' => '1.0.0'],
],
],
],
$currentKey => [
"required/pkg" => "^1.0",
],
]);
$package = self::getPackage('required/pkg');
if ($isDev) {
$this->createComposerLock([], [$package]);
$this->createInstalledJson([], [$package]);
} else {
$this->createComposerLock([$package], []);
$this->createInstalledJson([$package], []);
}
$appTester = $this->getApplicationTester();
$command = [
'command' => 'require',
'--no-audit' => true,
'--dev' => $isDev,
'--no-install' => true,
'packages' => ['required/pkg'],
];
if ($isInteractive) {
$appTester->setInputs(['yes']);
} else {
$command['--no-interaction'] = true;
}
$appTester->run($command);
self::assertStringContainsString(
$expectedWarning,
$appTester->getDisplay(true)
);
$composer_content = (new JsonFile($dir . '/composer.json'))->read();
self::assertArrayHasKey($otherKey, $composer_content);
self::assertArrayNotHasKey($currentKey, $composer_content);
}
public function provideInconsistentRequireKeys(): \Generator
{
yield [
true,
false,
'<warning>required/pkg is currently present in the require key and you ran the command with the --dev flag, which will move it to the require-dev key.</warning>',
];
yield [
false,
false,
'<warning>required/pkg is currently present in the require-dev key and you ran the command without the --dev flag, which will move it to the require key.</warning>',
];
yield [
true,
true,
'<warning>required/pkg is currently present in the require key and you ran the command with the --dev flag, which will move it to the require-dev key.</warning>',
];
yield [
false,
true,
'<warning>required/pkg is currently present in the require-dev key and you ran the command without the --dev flag, which will move it to the require key.</warning>',
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/AboutCommandTest.php | tests/Composer/Test/Command/AboutCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Composer;
use Composer\Test\TestCase;
class AboutCommandTest extends TestCase
{
public function testAbout(): void
{
$composerVersion = Composer::getVersion();
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'about']));
self::assertStringContainsString("Composer - Dependency Manager for PHP - version $composerVersion", $appTester->getDisplay());
self::assertStringContainsString("Composer is a dependency manager tracking local dependencies of your projects and libraries.", $appTester->getDisplay());
self::assertStringContainsString("See https://getcomposer.org/ for more information.", $appTester->getDisplay());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ReinstallCommandTest.php | tests/Composer/Test/Command/ReinstallCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Generator;
class ReinstallCommandTest extends TestCase
{
/**
* @dataProvider caseProvider
* @param array<mixed> $options
*/
public function testReinstallCommand(array $options, string $expected): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
'require-dev' => [
'root/anotherreq' => '2.*',
'root/anotherreq2' => '2.*',
'root/lala' => '2.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$anotherReqPackage = self::getPackage('root/anotherreq');
$anotherReqPackage2 = self::getPackage('root/anotherreq2');
$anotherReqPackage3 = self::getPackage('root/lala');
$rootReqPackage->setType('metapackage');
$anotherReqPackage->setType('metapackage');
$anotherReqPackage2->setType('metapackage');
$anotherReqPackage3->setType('metapackage');
$this->createComposerLock([$rootReqPackage], [$anotherReqPackage, $anotherReqPackage2, $anotherReqPackage3]);
$this->createInstalledJson([$rootReqPackage], [$anotherReqPackage, $anotherReqPackage2, $anotherReqPackage3]);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge([
'command' => 'reinstall',
'--no-progress' => true,
'--no-plugins' => true,
], $options));
self::assertSame($expected, trim($appTester->getDisplay(true)));
}
public function caseProvider(): Generator
{
yield 'reinstall a package by name' => [
['packages' => ['root/req', 'root/anotherreq*']],
'- Removing root/req (1.0.0)
- Removing root/anotherreq2 (1.0.0)
- Removing root/anotherreq (1.0.0)
- Installing root/anotherreq (1.0.0)
- Installing root/anotherreq2 (1.0.0)
- Installing root/req (1.0.0)',
];
yield 'reinstall packages by type' => [
['--type' => ['metapackage']],
'- Removing root/req (1.0.0)
- Removing root/lala (1.0.0)
- Removing root/anotherreq2 (1.0.0)
- Removing root/anotherreq (1.0.0)
- Installing root/anotherreq (1.0.0)
- Installing root/anotherreq2 (1.0.0)
- Installing root/lala (1.0.0)
- Installing root/req (1.0.0)',
];
yield 'reinstall a package that is not installed' => [
['packages' => ['root/unknownreq']],
'<warning>Pattern "root/unknownreq" does not match any currently installed packages.</warning>
<warning>Found no packages to reinstall, aborting.</warning>',
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/BumpCommandTest.php | tests/Composer/Test/Command/BumpCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Json\JsonFile;
use Composer\Test\TestCase;
class BumpCommandTest extends TestCase
{
/**
* @dataProvider provideTests
* @param array<mixed> $composerJson
* @param array<mixed> $command
* @param array<mixed> $expected
*/
public function testBump(array $composerJson, array $command, array $expected, bool $lock = true, int $exitCode = 0): void
{
$this->initTempComposer($composerJson);
$packages = [
self::getPackage('first/pkg', '2.3.4'),
self::getPackage('second/pkg', '3.4.0'),
];
$devPackages = [
self::getPackage('dev/pkg', '2.3.4.5'),
];
$this->createInstalledJson($packages, $devPackages);
if ($lock) {
$this->createComposerLock($packages, $devPackages);
}
$appTester = $this->getApplicationTester();
self::assertSame($exitCode, $appTester->run(array_merge(['command' => 'bump'], $command)));
$json = new JsonFile('./composer.json');
self::assertSame($expected, $json->read());
}
public function testBumpFailsOnNonExistingComposerFile(): void
{
$dir = $this->initTempComposer([]);
$composerJsonPath = $dir . '/composer.json';
unlink($composerJsonPath);
$appTester = $this->getApplicationTester();
self::assertSame(1, $appTester->run(['command' => 'bump'], ['capture_stderr_separately' => true]));
self::assertStringContainsString("./composer.json is not readable.", $appTester->getErrorOutput());
}
public function testBumpFailsOnWriteErrorToComposerFile(): void
{
if (function_exists('posix_getuid') && posix_getuid() === 0) {
$this->markTestSkipped('Cannot run as root');
}
$dir = $this->initTempComposer([]);
$composerJsonPath = $dir . '/composer.json';
chmod($composerJsonPath, 0444);
$appTester = $this->getApplicationTester();
self::assertSame(1, $appTester->run(['command' => 'bump'], ['capture_stderr_separately' => true]));
self::assertStringContainsString("./composer.json is not writable.", $appTester->getErrorOutput());
}
public static function provideTests(): \Generator
{
yield 'bump all by default' => [
[
'require' => [
'first/pkg' => '^v2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
[],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
];
yield 'bump only dev with --dev-only' => [
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
['--dev-only' => true],
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
];
yield 'bump only non-dev with --no-dev-only' => [
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
['--no-dev-only' => true],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
];
yield 'bump only listed with packages arg' => [
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
['packages' => ['first/pkg:3.0.1', 'dev/*']],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
];
yield 'bump works from installed repo without lock file' => [
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
],
[],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
],
false,
];
yield 'bump with --dry-run with packages to bump' => [
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
['--dry-run' => true],
[
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
],
true,
1,
];
yield 'bump with --dry-run without packages to bump' => [
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
['--dry-run' => true],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
true,
0,
];
yield 'bump works with non-standard package' => [
[
'require' => [
'php' => '>=5.3',
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
[],
[
'require' => [
'php' => '>=5.3',
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
],
'require-dev' => [
'dev/pkg' => '^2.3.4.5',
],
],
];
yield 'bump works with unknown package' => [
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
'third/pkg' => '^1.2',
],
],
[],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => '^3.4',
'third/pkg' => '^1.2',
],
],
];
yield 'bump works with aliased package' => [
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => 'dev-bugfix as 3.4.x-dev',
],
],
[],
[
'require' => [
'first/pkg' => '^2.3.4',
'second/pkg' => 'dev-bugfix as 3.4.x-dev',
],
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/StatusCommandTest.php | tests/Composer/Test/Command/StatusCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Generator;
class StatusCommandTest extends TestCase
{
public function testNoLocalChanges(): void
{
$this->initTempComposer(['require' => ['root/req' => '1.*']]);
$package = self::getPackage('root/req');
$package->setType('metapackage');
$this->createComposerLock([$package], []);
$this->createInstalledJson([$package], []);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'status']);
self::assertSame('No local changes', trim($appTester->getDisplay(true)));
}
/**
* @dataProvider locallyModifiedPackagesUseCaseProvider
* @param array<mixed> $composerJson
* @param array<mixed> $commandFlags
* @param array<mixed> $packageData
*/
public function testLocallyModifiedPackages(
array $composerJson,
array $commandFlags,
array $packageData
): void {
$this->initTempComposer($composerJson);
$package = self::getPackage($packageData['name'], $packageData['version']);
$package->setInstallationSource($packageData['installation_source']);
if ($packageData['installation_source'] === 'source') {
$package->setSourceType($packageData['type']);
$package->setSourceUrl($packageData['url']);
$package->setSourceReference($packageData['reference']);
}
if ($packageData['installation_source'] === 'dist') {
$package->setDistType($packageData['type']);
$package->setDistUrl($packageData['url']);
$package->setDistReference($packageData['reference']);
}
$this->createComposerLock([$package], []);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'install']);
file_put_contents(getcwd() . '/vendor/' . $packageData['name'] . '/composer.json', '{}');
$appTester->run(array_merge(['command' => 'status'], $commandFlags));
$expected = 'You have changes in the following dependencies:';
$actual = trim($appTester->getDisplay(true));
self::assertStringContainsString($expected, $actual);
self::assertStringContainsString($packageData['name'], $actual);
}
public static function locallyModifiedPackagesUseCaseProvider(): Generator
{
yield 'locally modified package from source' => [
['require' => ['composer/class-map-generator' => '^1.0']],
[],
[
'name' => 'composer/class-map-generator' ,
'version' => '1.1',
'installation_source' => 'source',
'type' => 'git',
'url' => 'https://github.com/composer/class-map-generator.git',
'reference' => '953cc4ea32e0c31f2185549c7d216d7921f03da9',
],
];
yield 'locally modified package from dist' => [
['require' => ['smarty/smarty' => '^3.1']],
['--verbose' => true],
[
'name' => 'smarty/smarty',
'version' => '3.1.7',
'installation_source' => 'dist',
'type' => 'zip',
'url' => 'https://www.smarty.net/files/Smarty-3.1.7.zip',
'reference' => null,
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/RepositoryCommandTest.php | tests/Composer/Test/Command/RepositoryCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use RuntimeException;
class RepositoryCommandTest extends TestCase
{
public function testListWithNoRepositories(): void
{
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'list']);
$appTester->assertCommandIsSuccessful();
self::assertSame('[packagist.org] composer https://repo.packagist.org', trim($appTester->getDisplay(true)));
// composer.json should remain unchanged
self::assertSame([], json_decode((string) file_get_contents('composer.json'), true));
}
public function testListWithRepositoriesAsList(): void
{
$this->initTempComposer([
'repositories' => [
['type' => 'composer', 'url' => 'https://first.test'],
['name' => 'foo', 'type' => 'vcs', 'url' => 'https://old.example.org'],
['name' => 'bar', 'type' => 'vcs', 'url' => 'https://other.example.org'],
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'list']);
$appTester->assertCommandIsSuccessful();
self::assertSame('[0] composer https://first.test
[foo] vcs https://old.example.org
[bar] vcs https://other.example.org
[packagist.org] disabled', trim($appTester->getDisplay(true)));
}
public function testListWithRepositoriesAsAssoc(): void
{
$this->initTempComposer([
'repositories' => [
['type' => 'composer', 'url' => 'https://first.test'],
'foo' => ['type' => 'vcs', 'url' => 'https://old.example.org'],
'bar' => ['type' => 'vcs', 'url' => 'https://other.example.org'],
],
]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'list']);
$appTester->assertCommandIsSuccessful();
self::assertSame('[0] composer https://first.test
[foo] vcs https://old.example.org
[bar] vcs https://other.example.org
[packagist.org] disabled', trim($appTester->getDisplay(true)));
}
public function testAddRepositoryWithTypeAndUrl(): void
{
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$result = $appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'vcs',
'arg2' => 'https://example.org/foo.git',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame(['repositories' => [
['name' => 'foo', 'type' => 'vcs', 'url' => 'https://example.org/foo.git'],
]], $json);
}
public function testAddRepositoryWithJson(): void
{
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'bar',
'arg1' => '{"type":"composer","url":"https://repo.example.org"}',
]);
$appTester->assertCommandIsSuccessful();
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame(['repositories' => [
['name' => 'bar', 'type' => 'composer', 'url' => 'https://repo.example.org'],
]], $json);
}
public function testRemoveRepository(): void
{
$this->initTempComposer(['repositories' => ['foo' => ['type' => 'vcs', 'url' => 'https://example.org']]], [], [], false);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'remove', 'name' => 'foo']);
$appTester->assertCommandIsSuccessful();
$json = json_decode((string) file_get_contents('composer.json'), true);
// repositories key may still exist as empty array depending on manipulator, accept either
if (isset($json['repositories'])) {
self::assertSame([], $json['repositories']);
} else {
self::assertSame([], $json);
}
}
/**
* @dataProvider provideTestSetAndGetUrlInRepositoryAssoc
* @param array<string, mixed> $repositories
*/
public function testSetAndGetUrlInRepositoryAssoc(array $repositories, string $name, string $index, string $newUrl): void
{
$this->initTempComposer(['repositories' => $repositories], [], [], false);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'set-url', 'name' => $name, 'arg1' => $newUrl]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
// calling it still in assoc means, the repository has not been converted, which is good
self::assertSame($newUrl, $json['repositories'][$index]['url'] ?? null);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'get-url', 'name' => $name]);
$appTester->assertCommandIsSuccessful();
self::assertSame($newUrl, trim($appTester->getDisplay(true)));
}
/**
* @return iterable<array{0: array, 1: string, 2: string, 3: string}>
*/
public static function provideTestSetAndGetUrlInRepositoryAssoc(): iterable
{
$repositories = [
'first' => ['type' => 'composer', 'url' => 'https://first.test'],
'foo' => ['type' => 'vcs', 'url' => 'https://old.example.org'],
'bar' => ['type' => 'vcs', 'url' => 'https://other.example.org'],
];
yield 'change first of three' => [
$repositories,
'first',
'first',
'https://new.example.org',
];
yield 'change middle of three' => [
$repositories,
'foo',
'foo',
'https://new.example.org',
];
yield 'change last of three' => [
$repositories,
'bar',
'bar',
'https://new.example.org',
];
}
/**
* @dataProvider provideTestSetAndGetUrlInRepositoryList
* @param list<array<string, mixed>> $repositories
*/
public function testSetAndGetUrlInRepositoryList(array $repositories, string $name, int $index, string $newUrl): void
{
$this->initTempComposer(['repositories' => $repositories], [], [], false);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'set-url', 'name' => $name, 'arg1' => $newUrl]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame($name, $json['repositories'][$index]['name'] ?? null);
self::assertSame($newUrl, $json['repositories'][$index]['url'] ?? null);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'get-url', 'name' => $name]);
$appTester->assertCommandIsSuccessful();
self::assertSame($newUrl, trim($appTester->getDisplay(true)));
}
/**
* @return iterable<array{0: array, 1: string, 2: int, 3: string}>
*/
public static function provideTestSetAndGetUrlInRepositoryList(): iterable
{
$repositories = [
['name' => 'first', 'type' => 'composer', 'url' => 'https://first.test'],
['name' => 'foo', 'type' => 'vcs', 'url' => 'https://old.example.org'],
['name' => 'bar', 'type' => 'vcs', 'url' => 'https://other.example.org'],
];
yield 'change first of three' => [
$repositories,
'first',
0,
'https://new.example.org',
];
yield 'change middle of three' => [
$repositories,
'foo',
1,
'https://new.example.org',
];
yield 'change last of three' => [
$repositories,
'bar',
2,
'https://new.example.org',
];
}
public function testDisableAndEnablePackagist(): void
{
$this->initTempComposer([]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'disable', 'name' => 'packagist']);
$appTester->assertCommandIsSuccessful();
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame(['repositories' => [['packagist.org' => false]]], $json);
// enable packagist should remove the override
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', 'action' => 'enable', 'name' => 'packagist']);
$appTester->assertCommandIsSuccessful();
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame([], $json);
}
public function testInvalidArgCombinationThrows(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('--file and --global can not be combined');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'repo', '--file' => 'alt.composer.json', '--global' => true]);
}
public function testPrependRepositoryByNameListToAssoc(): void
{
$this->initTempComposer(['repositories' => [['type' => 'git', 'url' => 'example.tld']]], [], [], false);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'path',
'arg2' => 'foo/bar',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame([
'repositories' => [
['name' => 'foo', 'type' => 'path', 'url' => 'foo/bar'],
['type' => 'git', 'url' => 'example.tld'],
],
], $json);
}
public function testAppendRepositoryByNameListToAssoc(): void
{
$this->initTempComposer(['repositories' => [['type' => 'git', 'url' => 'example.tld']]], [], [], false);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'path',
'arg2' => 'foo/bar',
'--append' => true,
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame([
'repositories' => [
['type' => 'git', 'url' => 'example.tld'],
['name' => 'foo', 'type' => 'path', 'url' => 'foo/bar'],
],
], $json);
}
public function testPrependRepositoryAssocWithPackagistDisabled(): void
{
$this->initTempComposer(['repositories' => [['type' => 'git', 'url' => 'example.tld'], 'packagist.org' => false]]);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'path',
'arg2' => 'foo/bar',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame([
'repositories' => [
['name' => 'foo', 'type' => 'path', 'url' => 'foo/bar'],
['type' => 'git', 'url' => 'example.tld'],
['packagist.org' => false],
],
], $json);
}
public function testAppendRepositoryAssocWithPackagistDisabled(): void
{
$this->initTempComposer(['repositories' => [['type' => 'git', 'url' => 'example.tld'], 'packagist.org' => false]]);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'path',
'arg2' => 'foo/bar',
'--append' => true,
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
self::assertSame([
'repositories' => [
['type' => 'git', 'url' => 'example.tld'],
['packagist.org' => false],
['name' => 'foo', 'type' => 'path', 'url' => 'foo/bar'],
],
], $json);
}
public function testAddBeforeAndAfterByName(): void
{
// Start with two repos as named-list and a disabled packagist boolean
$this->initTempComposer(['repositories' => [
['name' => 'alpha', 'type' => 'vcs', 'url' => 'https://example.org/a'],
['name' => 'omega', 'type' => 'vcs', 'url' => 'https://example.org/o'],
'packagist.org' => false,
]]);
// Insert before omega
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'beta',
'arg1' => 'vcs',
'arg2' => 'https://example.org/b',
'--before' => 'omega',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
// Insert after alpha
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'gamma',
'arg1' => 'vcs',
'arg2' => 'https://example.org/g',
'--after' => 'alpha',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
// Expect order: alpha, gamma, beta, omega, then packagist.org boolean preserved
self::assertSame([
'repositories' => [
['name' => 'alpha', 'type' => 'vcs', 'url' => 'https://example.org/a'],
['name' => 'gamma', 'type' => 'vcs', 'url' => 'https://example.org/g'],
['name' => 'beta', 'type' => 'vcs', 'url' => 'https://example.org/b'],
['name' => 'omega', 'type' => 'vcs', 'url' => 'https://example.org/o'],
['packagist.org' => false],
],
], $json);
}
public function testAddSameNameReplacesExisting(): void
{
$this->initTempComposer([]);
// first add
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'vcs',
'arg2' => 'https://example.org/old',
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
// second add with same name but different url
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'repo',
'action' => 'add',
'name' => 'foo',
'arg1' => 'vcs',
'arg2' => 'https://example.org/new',
'--append' => true,
]);
$appTester->assertCommandIsSuccessful($appTester->getDisplay());
$json = json_decode((string) file_get_contents('composer.json'), true);
// repositories can be stored as assoc or named-list depending on manipulator fallbacks
// Validate there is only one "foo" and its url is the latest
$countFoo = 0;
$url = null;
foreach ($json['repositories'] as $k => $repo) {
if (is_string($k) && $k === 'foo' && is_array($repo)) {
$countFoo++;
$url = $repo['url'] ?? null;
} elseif (is_array($repo) && isset($repo['name']) && $repo['name'] === 'foo') {
$countFoo++;
$url = $repo['url'] ?? null;
}
}
self::assertSame(1, $countFoo, 'Exactly one repository entry with name foo should exist');
self::assertSame('https://example.org/new', $url, 'The foo repository should have been updated to the new URL');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/RemoveCommandTest.php | tests/Composer/Test/Command/RemoveCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Json\JsonFile;
use Composer\Package\Link;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Test\TestCase;
use InvalidArgumentException;
use Symfony\Component\Console\Command\Command;
use UnexpectedValueException;
class RemoveCommandTest extends TestCase
{
public function testExceptionRunningWithNoRemovePackages(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Not enough arguments (missing: "packages").');
$appTester = $this->getApplicationTester();
self::assertEquals(Command::FAILURE, $appTester->run(['command' => 'remove']));
}
public function testExceptionWhenRunningUnusedWithoutLockFile(): void
{
$this->initTempComposer();
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('A valid composer.lock file is required to run this command with --unused');
$appTester = $this->getApplicationTester();
self::assertEquals(Command::FAILURE, $appTester->run(['command' => 'remove', '--unused' => true]));
}
public function testWarningWhenRemovingNonExistentPackage(): void
{
$this->initTempComposer();
$this->createInstalledJson();
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['vendor1/package1']]));
self::assertStringStartsWith('<warning>vendor1/package1 is not required in your composer.json and has not been removed</warning>', trim($appTester->getDisplay(true)));
}
public function testWarningWhenRemovingPackageFromWrongType(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--dev' => true, '--no-update' => true, '--no-interaction' => true]));
self::assertSame('<warning>root/req could not be found in require-dev but it is present in require</warning>
./composer.json has been updated', trim($appTester->getDisplay(true)));
self::assertEquals(['require' => ['root/req' => '1.*']], (new JsonFile('./composer.json'))->read());
}
public function testWarningWhenRemovingPackageWithDeprecatedDependenciesFlag(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--update-with-dependencies' => true, '--no-update' => true, '--no-interaction' => true]));
self::assertSame('<warning>You are using the deprecated option "update-with-dependencies". This is now default behaviour. The --no-update-with-dependencies option can be used to remove a package without its dependencies.</warning>
./composer.json has been updated', trim($appTester->getDisplay(true)));
self::assertEmpty((new JsonFile('./composer.json'))->read());
}
public function testMessageOutputWhenNoUnusedPackagesToRemove(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'require' => ['nested/req' => '^1']],
['name' => 'nested/req', 'version' => '1.1.0'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$requiredPackage = self::getPackage('root/req');
$requiredPackage->setRequires([
'nested/req' => new Link(
'root/req',
'nested/req',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'^1'
),
]);
$nestedPackage = self::getPackage('nested/req', '1.1.0');
$this->createInstalledJson([$requiredPackage, $nestedPackage]);
$this->createComposerLock([$requiredPackage, $nestedPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', '--unused' => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertSame('No unused packages to remove', trim($appTester->getDisplay(true)));
}
public function testRemoveUnusedPackage(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
['name' => 'not/req', 'version' => '1.0.0'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$requiredPackage = self::getPackage('root/req');
$extraneousPackage = self::getPackage('not/req');
$this->createInstalledJson([$requiredPackage]);
$this->createComposerLock([$requiredPackage, $extraneousPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', '--unused' => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertStringStartsWith('<warning>not/req is not required in your composer.json and has not been removed</warning>', $appTester->getDisplay(true));
self::assertStringContainsString('Running composer update not/req', $appTester->getDisplay(true));
self::assertStringContainsString('- Removing not/req (1.0.0)', $appTester->getDisplay(true));
}
public function testRemovePackageByName(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage'],
['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$rootAnotherPackage->setType('metapackage');
$this->createInstalledJson([$rootReqPackage, $rootAnotherPackage]);
$this->createComposerLock([$rootReqPackage, $rootAnotherPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--no-audit' => true, '--no-interaction' => true]));
self::assertStringStartsWith('./composer.json has been updated', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Running composer update root/req', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Lock file operations: 0 installs, 0 updates, 1 removal', trim($appTester->getDisplay(true)));
self::assertStringContainsString('- Removing root/req (1.0.0)', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Package operations: 0 installs, 0 updates, 1 removal', trim($appTester->getDisplay(true)));
self::assertEquals(['root/another' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEquals([['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage']], (new JsonFile('./composer.lock'))->read()['packages']);
}
public function testRemovePackageByNameWithDryRun(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage'],
['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$rootAnotherPackage->setType('metapackage');
$this->createInstalledJson([$rootReqPackage, $rootAnotherPackage]);
$this->createComposerLock([$rootReqPackage, $rootAnotherPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--dry-run' => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertStringContainsString('./composer.json has been updated', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Running composer update root/req', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Lock file operations: 0 installs, 0 updates, 1 removal', trim($appTester->getDisplay(true)));
self::assertStringContainsString('- Removing root/req (1.0.0)', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Package operations: 0 installs, 0 updates, 1 removal', trim($appTester->getDisplay(true)));
self::assertEquals(['root/req' => '1.*', 'root/another' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEquals([['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage'], ['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage']], (new JsonFile('./composer.lock'))->read()['packages']);
}
public function testRemoveAllowedPluginPackageWithNoOtherAllowedPlugins(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage'],
['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
],
'config' => [
'allow-plugins' => [
'root/req' => true,
],
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$rootAnotherPackage->setType('metapackage');
$this->createInstalledJson([$rootReqPackage, $rootAnotherPackage]);
$this->createComposerLock([$rootReqPackage, $rootAnotherPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--no-audit' => true, '--no-interaction' => true]));
self::assertEquals(['root/another' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEmpty((new JsonFile('./composer.json'))->read()['config']);
}
public function testRemoveAllowedPluginPackageWithOtherAllowedPlugins(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage'],
['name' => 'root/another', 'version' => '1.0.0', 'type' => 'metapackage'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
],
'config' => [
'allow-plugins' => [
'root/another' => true,
'root/req' => true,
],
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$rootAnotherPackage->setType('metapackage');
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--no-audit' => true, '--no-interaction' => true]));
self::assertEquals(['root/another' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEquals(['allow-plugins' => ['root/another' => true]], (new JsonFile('./composer.json'))->read()['config']);
}
public function testRemovePackagesByVendor(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
['name' => 'root/another', 'version' => '1.0.0'],
['name' => 'another/req', 'version' => '1.0.0'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
'another/req' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
$anotherReqPackage = self::getPackage('another/req');
$this->createInstalledJson([$rootReqPackage, $rootAnotherPackage, $anotherReqPackage]);
$this->createComposerLock([$rootReqPackage, $rootAnotherPackage, $anotherReqPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/*'], '--no-install' => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertStringStartsWith('./composer.json has been updated', trim($appTester->getDisplay(true)));
self::assertStringContainsString('Running composer update root/*', $appTester->getDisplay(true));
self::assertStringContainsString('- Removing root/another (1.0.0)', $appTester->getDisplay(true));
self::assertStringContainsString('- Removing root/req (1.0.0)', $appTester->getDisplay(true));
self::assertStringContainsString('Writing lock file', $appTester->getDisplay(true));
self::assertEquals(['another/req' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEquals([['name' => 'another/req', 'version' => '1.0.0', 'type' => 'library']], (new JsonFile('./composer.lock'))->read()['packages']);
}
public function testRemovePackagesByVendorWithDryRun(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
['name' => 'root/another', 'version' => '1.0.0'],
['name' => 'another/req', 'version' => '1.0.0'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
'another/req' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootAnotherPackage = self::getPackage('root/another');
$anotherReqPackage = self::getPackage('another/req');
$this->createInstalledJson([$rootReqPackage, $rootAnotherPackage, $anotherReqPackage]);
$this->createComposerLock([$rootReqPackage, $rootAnotherPackage, $anotherReqPackage]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'remove', 'packages' => ['root/*'], '--dry-run' => true, '--no-install' => true, '--no-audit' => true, '--no-interaction' => true]);
self::assertEquals(Command::SUCCESS, $appTester->getStatusCode());
self::assertSame("./composer.json has been updated
Running composer update root/*
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 0 updates, 2 removals
- Removing root/another (1.0.0)
- Removing root/req (1.0.0)", trim($appTester->getDisplay(true)));
self::assertStringNotContainsString('Writing lock file', $appTester->getDisplay(true));
self::assertEquals(['root/req' => '1.*', 'root/another' => '1.*', 'another/req' => '1.*'], (new JsonFile('./composer.json'))->read()['require']);
self::assertEquals([['name' => 'another/req', 'version' => '1.0.0', 'type' => 'library'], ['name' => 'root/another', 'version' => '1.0.0', 'type' => 'library'], ['name' => 'root/req', 'version' => '1.0.0', 'type' => 'library']], (new JsonFile('./composer.lock'))->read()['packages']);
}
public function testWarningWhenRemovingPackagesByVendorFromWrongType(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
'another/req' => '1.*',
],
]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/*'], '--dev' => true, '--no-interaction' => true, '--no-update' => true]));
self::assertSame("<warning>root/req could not be found in require-dev but it is present in require</warning>
<warning>root/another could not be found in require-dev but it is present in require</warning>
./composer.json has been updated", trim($appTester->getDisplay(true)));
self::assertEquals(['require' => ['root/req' => '1.*', 'root/another' => '1.*', 'another/req' => '1.*']], (new JsonFile('./composer.json'))->read());
}
public function testPackageStillPresentErrorWhenNoInstallFlagUsed(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$this->createInstalledJson([$rootReqPackage]);
$this->createComposerLock([$rootReqPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::INVALID, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], '--no-install' => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertStringContainsString('./composer.json has been updated', $appTester->getDisplay(true));
self::assertStringContainsString('Lock file operations: 0 installs, 0 updates, 1 removal', $appTester->getDisplay(true));
self::assertStringContainsString('- Removing root/req (1.0.0)', $appTester->getDisplay(true));
self::assertStringContainsString('Writing lock file', $appTester->getDisplay(true));
self::assertStringContainsString('Removal failed, root/req is still present, it may be required by another package. See `composer why root/req`', $appTester->getDisplay(true));
self::assertEmpty((new JsonFile('./composer.json'))->read());
self::assertEmpty((new JsonFile('./composer.lock'))->read()['packages']);
self::assertEquals([['name' => 'root/req', 'version' => '1.0.0', 'version_normalized' => '1.0.0.0', 'type' => 'library', 'install-path' => '../root/req']], (new JsonFile('./vendor/composer/installed.json'))->read()['packages']);
}
/**
* @dataProvider provideInheritedDependenciesUpdateFlag
*/
public function testUpdateInheritedDependenciesFlagIsPassedToPostRemoveInstaller(string $installFlagName, string $expectedComposerUpdateCommand): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'type' => 'metapackage'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$rootReqPackage->setType('metapackage');
$this->createInstalledJson([$rootReqPackage]);
$this->createComposerLock([$rootReqPackage]);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'remove', 'packages' => ['root/req'], $installFlagName => true, '--no-audit' => true, '--no-interaction' => true]));
self::assertStringContainsString('./composer.json has been updated', $appTester->getDisplay(true));
self::assertStringContainsString($expectedComposerUpdateCommand, $appTester->getDisplay(true));
self::assertStringContainsString('Package operations: 0 installs, 0 updates, 1 removal', $appTester->getDisplay(true));
self::assertStringContainsString('- Removing root/req (1.0.0)', $appTester->getDisplay(true));
self::assertStringContainsString('Writing lock file', $appTester->getDisplay(true));
self::assertStringContainsString('Lock file operations: 0 installs, 0 updates, 1 removal', $appTester->getDisplay(true));
self::assertEmpty((new JsonFile('./composer.lock'))->read()['packages']);
}
public static function provideInheritedDependenciesUpdateFlag(): \Generator
{
yield 'update with all dependencies' => [
'--update-with-all-dependencies',
'Running composer update root/req --with-all-dependencies',
];
yield 'with all dependencies' => [
'--with-all-dependencies',
'Running composer update root/req --with-all-dependencies',
];
yield 'no update with dependencies' => [
'--no-update-with-dependencies',
'Running composer update root/req --with-dependencies',
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ClearCacheCommandTest.php | tests/Composer/Test/Command/ClearCacheCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Composer\Util\Platform;
class ClearCacheCommandTest extends TestCase
{
public function tearDown(): void
{
// --no-cache triggers the env to change so make sure the env is cleaned up after these tests run
Platform::clearEnv('COMPOSER_CACHE_DIR');
}
public function testClearCacheCommandSuccess(): void
{
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'clear-cache']);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay(true);
self::assertStringContainsString('All caches cleared.', $output);
}
public function testClearCacheCommandWithOptionGarbageCollection(): void
{
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'clear-cache', '--gc' => true]);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay(true);
self::assertStringContainsString('All caches garbage-collected.', $output);
}
public function testClearCacheCommandWithOptionNoCache(): void
{
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'clear-cache', '--no-cache' => true]);
$appTester->assertCommandIsSuccessful();
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Cache is not enabled', $output);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ValidateCommandTest.php | tests/Composer/Test/Command/ValidateCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Composer\Util\Platform;
class ValidateCommandTest extends TestCase
{
/**
* @dataProvider provideValidateTests
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testValidate(array $composerJson, array $command, string $expected): void
{
$this->initTempComposer($composerJson);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'validate'], $command));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public function testValidateOnFileIssues(): void
{
$directory = $this->initTempComposer(self::MINIMAL_VALID_CONFIGURATION);
unlink($directory.'/composer.json');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'validate']);
$expected = './composer.json not found.';
self::assertSame($expected, trim($appTester->getDisplay(true)));
}
public function testWithComposerLock(): void
{
$this->initTempComposer(self::MINIMAL_VALID_CONFIGURATION);
$this->createComposerLock();
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'validate']);
$expected = <<<OUTPUT
<warning>Composer could not detect the root package (test/suite) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version</warning>
<warning>Composer could not detect the root package (test/suite) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version</warning>
./composer.json is valid but your composer.lock has some errors
# Lock file errors
- Required package "root/req" is not present in the lock file.
This usually happens when composer files are incorrectly merged or the composer.json file is manually edited.
Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md
and prefer using the "require" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r
OUTPUT;
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public function testUnaccessibleFile(): void
{
if (Platform::isWindows()) {
$this->markTestSkipped('Does not run on windows');
}
if (function_exists('posix_getuid') && posix_getuid() === 0) {
$this->markTestSkipped('Cannot run as root');
}
$directory = $this->initTempComposer(self::MINIMAL_VALID_CONFIGURATION);
chmod($directory.'/composer.json', 0200);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'validate']);
$expected = './composer.json is not readable.';
self::assertSame($expected, trim($appTester->getDisplay(true)));
self::assertSame(3, $appTester->getStatusCode());
chmod($directory.'/composer.json', 0700);
}
private const MINIMAL_VALID_CONFIGURATION = [
'name' => 'test/suite',
'type' => 'library',
'description' => 'A generical test suite',
'license' => 'MIT',
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'require' => ['dep/pkg' => '^1']],
['name' => 'dep/pkg', 'version' => '1.0.0'],
['name' => 'dep/pkg', 'version' => '1.0.1'],
['name' => 'dep/pkg', 'version' => '1.0.2'],
],
],
],
'require' => [
'root/req' => '1.*',
],
];
public static function provideValidateTests(): \Generator
{
yield 'validation passing' => [
self::MINIMAL_VALID_CONFIGURATION,
[],
<<<OUTPUT
<warning>Composer could not detect the root package (test/suite) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version</warning>
<warning>Composer could not detect the root package (test/suite) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version</warning>
./composer.json is valid
OUTPUT
];
$publishDataStripped = array_diff_key(
self::MINIMAL_VALID_CONFIGURATION,
['name' => true, 'type' => true, 'description' => true, 'license' => true]
);
yield 'passing but with warnings' => [
$publishDataStripped,
[],
<<<OUTPUT
./composer.json is valid for simple usage with Composer but has
strict errors that make it unable to be published as a package
<warning>See https://getcomposer.org/doc/04-schema.md for details on the schema</warning>
# Publish errors
- name : The property name is required
- description : The property description is required
<warning># General warnings</warning>
- No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
OUTPUT
];
yield 'passing without publish-check' => [
$publishDataStripped,
[ '--no-check-publish' => true],
<<<OUTPUT
./composer.json is valid, but with a few warnings
<warning>See https://getcomposer.org/doc/04-schema.md for details on the schema</warning>
<warning># General warnings</warning>
- No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
OUTPUT
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/FundCommandTest.php | tests/Composer/Test/Command/FundCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Generator;
class FundCommandTest extends TestCase
{
/**
* @dataProvider useCaseProvider
* @param array<mixed> $composerJson
* @param array<mixed> $command
* @param array<mixed> $funding
*/
public function testFundCommand(
array $composerJson,
array $command,
array $funding,
string $expected
): void {
$this->initTempComposer($composerJson);
$packages = [
'first/pkg' => self::getPackage('first/pkg', '2.3.4'),
'stable/pkg' => self::getPackage('stable/pkg', '1.0.0'),
];
$devPackages = [
'dev/pkg' => self::getPackage('dev/pkg', '2.3.4.5'),
];
if (count($funding) !== 0) {
foreach ($funding as $pkg => $fundingInfo) {
if (isset($packages[$pkg])) {
$packages[$pkg]->setFunding([$fundingInfo]);
}
if (isset($devPackages[$pkg])) {
$devPackages[$pkg]->setFunding([$fundingInfo]);
}
}
}
$this->createInstalledJson($packages, $devPackages);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'fund'], $command));
$appTester->assertCommandIsSuccessful();
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public static function useCaseProvider(): Generator
{
yield 'no funding links present, locally or remotely' => [
[
'repositories' => [],
'require' => [
'first/pkg' => '^2.0',
],
'require-dev' => [
'dev/pkg' => '~4.0',
],
],
[],
[],
"No funding links were found in your package dependencies. This doesn't mean they don't need your support!",
];
yield 'funding links set locally are used as fallback if not found remotely' => [
[
'repositories' => [],
'require' => [
'first/pkg' => '^2.0',
],
'require-dev' => [
'dev/pkg' => '~4.0',
],
],
[],
[
'first/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data',
],
'dev/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data-dev',
],
],
"The following packages were found in your dependencies which publish funding information:
dev
pkg
https://github.com/sponsors/composer-test-data-dev
first
https://github.com/sponsors/composer-test-data
Please consider following these links and sponsoring the work of package authors!
Thank you!",
];
yield 'funding links set remotely are used as primary if found' => [
[
'repositories' => [
[
'type' => 'package',
'package' => [
// should not be used as there is a default branch version of this package available
['name' => 'first/pkg', 'version' => 'dev-foo', 'funding' => [['type' => 'github', 'url' => 'https://github.com/test-should-not-be-used']]],
// should be used as default branch from remote repo takes precedence
['name' => 'first/pkg', 'version' => 'dev-main', 'default-branch' => true, 'funding' => [['type' => 'custom', 'url' => 'https://example.org']]],
// should be used as default branch from remote repo takes precedence
['name' => 'dev/pkg', 'version' => 'dev-foo', 'default-branch' => true, 'funding' => [['type' => 'github', 'url' => 'https://github.com/org']]],
// no default branch available so falling back to locally installed data
['name' => 'stable/pkg', 'version' => '1.0.0', 'funding' => [['type' => 'github', 'url' => 'org2']]],
],
],
],
'require' => [
'first/pkg' => '^2.0',
'stable/pkg' => '^1.0',
],
'require-dev' => [
'dev/pkg' => '~4.0',
],
],
[],
[
'first/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data',
],
'dev/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data-dev',
],
'stable/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data-stable',
],
],
"The following packages were found in your dependencies which publish funding information:
dev
pkg
https://github.com/sponsors/org
first
https://example.org
stable
https://github.com/sponsors/composer-test-data-stable
Please consider following these links and sponsoring the work of package authors!
Thank you!",
];
yield 'format funding links as JSON' => [
[
'repositories' => [],
'require' => [
'first/pkg' => '^2.0',
],
'require-dev' => [
'dev/pkg' => '~4.0',
],
],
['--format' => 'json'],
[
'first/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data',
],
'dev/pkg' => [
'type' => 'github',
'url' => 'https://github.com/composer-test-data-dev',
],
],
'{
"dev": {
"https://github.com/sponsors/composer-test-data-dev": [
"pkg"
]
},
"first": {
"https://github.com/sponsors/composer-test-data": [
"pkg"
]
}
}',
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/LicensesCommandTest.php | tests/Composer/Test/Command/LicensesCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
class LicensesCommandTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->initTempComposer([
'name' => 'test/pkg',
'version' => '1.2.3',
'license' => 'MIT',
'require' => [
'first/pkg' => '^2.0',
'second/pkg' => '3.*',
'third/pkg' => '^1.3',
],
'require-dev' => [
'dev/pkg' => '~2.0',
],
]);
$first = self::getPackage('first/pkg', '2.3.4');
$first->setLicense(['MIT']);
$second = self::getPackage('second/pkg', '3.4.0');
$second->setLicense(['LGPL-2.0-only']);
$second->setHomepage('https://example.org');
$third = self::getPackage('third/pkg', '1.5.4');
$dev = self::getPackage('dev/pkg', '2.3.4.5');
$dev->setLicense(['MIT']);
$this->createInstalledJson([$first, $second, $third], [$dev]);
$this->createComposerLock([$first, $second, $third], [$dev]);
}
public function testBasicRun(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license']));
$expected = [
["Name:", "test/pkg"],
["Version:", "1.2.3"],
["Licenses:", "MIT"],
["Dependencies:"],
[],
["Name", "Version", "Licenses"],
["dev/pkg", "2.3.4.5", "MIT"],
["first/pkg", "2.3.4", "MIT"],
["second/pkg", "3.4.0", "LGPL-2.0-only"],
["third/pkg", "1.5.4", "none"],
];
array_walk_recursive($expected, static function (&$value) {
$value = preg_quote($value, '/');
});
foreach (explode(PHP_EOL, $appTester->getDisplay()) as $i => $line) {
if (trim($line) === '') {
continue;
}
if (!isset($expected[$i])) {
$this->fail('Got more output lines than expected');
}
self::assertMatchesRegularExpression("/" . implode("\s+", $expected[$i]) . "/", $line);
}
}
public function testNoDev(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license', '--no-dev' => true]));
$expected = [
["Name:", "test/pkg"],
["Version:", "1.2.3"],
["Licenses:", "MIT"],
["Dependencies:"],
[],
["Name", "Version", "Licenses"],
["first/pkg", "2.3.4", "MIT"],
["second/pkg", "3.4.0", "LGPL-2.0-only"],
["third/pkg", "1.5.4", "none"],
];
array_walk_recursive($expected, static function (&$value) {
$value = preg_quote($value, '/');
});
foreach (explode(PHP_EOL, $appTester->getDisplay()) as $i => $line) {
if (trim($line) === '') {
continue;
}
if (!isset($expected[$i])) {
$this->fail('Got more output lines than expected');
}
self::assertMatchesRegularExpression("/" . implode("\s+", $expected[$i]) . "/", $line);
}
}
public function testFormatJson(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license', '--format' => 'json'], ['capture_stderr_separately' => true]));
$expected = [
"name" => "test/pkg",
"version" => "1.2.3",
"license" => ["MIT"],
"dependencies" => [
"dev/pkg" => [
"version" => "2.3.4.5",
"license" => [
"MIT",
],
],
"first/pkg" => [
"version" => "2.3.4",
"license" => [
"MIT",
],
],
"second/pkg" => [
"version" => "3.4.0",
"license" => [
"LGPL-2.0-only",
],
],
"third/pkg" => [
"version" => "1.5.4",
"license" => [],
],
],
];
self::assertSame($expected, json_decode($appTester->getDisplay(), true));
}
public function testFormatSummary(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license', '--format' => 'summary']));
$expected = [
['-', '-'],
['License', 'Number of dependencies'],
['-', '-'],
['MIT', '2'],
['LGPL-2.0-only', '1'],
['none', '1'],
['-', '-'],
];
$lines = explode("\n", $appTester->getDisplay());
foreach ($expected as $i => $expect) {
[$key, $value] = $expect;
self::assertMatchesRegularExpression("/$key\s+$value/", $lines[$i]);
}
}
public function testFormatUnknown(): void
{
$this->expectException(\RuntimeException::class);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'license', '--format' => 'unknown']);
}
public function testLocked(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license', '--locked' => true]));
$expected = [
["Name:", "test/pkg"],
["Version:", "1.2.3"],
["Licenses:", "MIT"],
["Dependencies:"],
[],
["Name", "Version", "Licenses"],
["dev/pkg", "2.3.4.5", "MIT"],
["first/pkg", "2.3.4", "MIT"],
["second/pkg", "3.4.0", "LGPL-2.0-only"],
["third/pkg", "1.5.4", "none"],
];
array_walk_recursive($expected, static function (&$value) {
$value = preg_quote($value, '/');
});
foreach (explode(PHP_EOL, $appTester->getDisplay()) as $i => $line) {
if (trim($line) === '') {
continue;
}
if (!isset($expected[$i])) {
$this->fail('Got more output lines than expected');
}
self::assertMatchesRegularExpression("/" . implode("\s+", $expected[$i]) . "/", $line);
}
}
public function testLockedNoDev(): void
{
$appTester = $this->getApplicationTester();
self::assertSame(0, $appTester->run(['command' => 'license', '--locked' => true, '--no-dev' => true]));
$expected = [
["Name:", "test/pkg"],
["Version:", "1.2.3"],
["Licenses:", "MIT"],
["Dependencies:"],
[],
["Name", "Version", "Licenses"],
["first/pkg", "2.3.4", "MIT"],
["second/pkg", "3.4.0", "LGPL-2.0-only"],
["third/pkg", "1.5.4", "none"],
];
array_walk_recursive($expected, static function (&$value) {
$value = preg_quote($value, '/');
});
foreach (explode(PHP_EOL, $appTester->getDisplay()) as $i => $line) {
if (trim($line) === '') {
continue;
}
if (!isset($expected[$i])) {
$this->fail('Got more output lines than expected');
}
self::assertMatchesRegularExpression("/" . implode("\s+", $expected[$i]) . "/", $line);
}
}
public function testLockedWithoutLockFile(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('Valid composer.json and composer.lock files are required to run this command with --locked');
// Remove the lock file
@unlink('./composer.lock');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'license', '--locked' => true]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ArchiveCommandTest.php | tests/Composer/Test/Command/ArchiveCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Composer;
use Composer\Config;
use Composer\Factory;
use Composer\Package\RootPackage;
use Composer\Test\TestCase;
use Composer\Util\Platform;
use Symfony\Component\Console\Input\ArrayInput;
use Composer\Repository\RepositoryManager;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\Archiver\ArchiveManager;
use Composer\Command\ArchiveCommand;
use Composer\EventDispatcher\EventDispatcher;
use Symfony\Component\Console\Output\OutputInterface;
class ArchiveCommandTest extends TestCase
{
public function testUsesConfigFromComposerObject(): void
{
$input = new ArrayInput([]);
$output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')
->getMock();
$ed = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor()->getMock();
$composer = new Composer;
$config = new Config;
$config->merge(['config' => ['archive-format' => 'zip']]);
$composer->setConfig($config);
$manager = $this->getMockBuilder('Composer\Package\Archiver\ArchiveManager')
->disableOriginalConstructor()->getMock();
$package = $this->getMockBuilder('Composer\Package\RootPackageInterface')
->getMock();
$manager->expects($this->once())->method('archive')
->with($package, 'zip', '.', null, false)->willReturn(Platform::getCwd());
$composer->setArchiveManager($manager);
$composer->setEventDispatcher($ed);
$composer->setPackage($package);
$command = $this->getMockBuilder('Composer\Command\ArchiveCommand')
->onlyMethods([
'mergeApplicationDefinition',
'getSynopsis',
'initialize',
'tryComposer',
'requireComposer',
])->getMock();
$command->expects($this->atLeastOnce())->method('tryComposer')
->willReturn($composer);
$command->expects($this->atLeastOnce())->method('requireComposer')
->willReturn($composer);
$command->run($input, $output);
}
public function testUsesConfigFromFactoryWhenComposerIsNotDefined(): void
{
$input = new ArrayInput([]);
$output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')
->getMock();
$config = Factory::createConfig();
$command = $this->getMockBuilder('Composer\Command\ArchiveCommand')
->onlyMethods([
'mergeApplicationDefinition',
'getSynopsis',
'initialize',
'tryComposer',
'archive',
])->getMock();
$command->expects($this->once())->method('tryComposer')
->willReturn(null);
$command->expects($this->once())->method('archive')
->with(
$this->isInstanceOf('Composer\IO\IOInterface'),
$config,
null,
null,
'tar',
'.',
null,
false,
null
)->willReturn(0);
self::assertEquals(0, $command->run($input, $output));
}
public function testUsesConfigFromComposerObjectWithPackageName(): void
{
$input = new ArrayInput([
'package' => 'foo/bar',
]);
$output = $this->getMockBuilder(OutputInterface::class)
->getMock();
$eventDispatcher = $this->getMockBuilder(EventDispatcher::class)
->disableOriginalConstructor()->getMock();
$composer = new Composer;
$config = new Config;
$config->merge(['config' => ['archive-format' => 'zip']]);
$composer->setConfig($config);
$manager = $this->getMockBuilder(ArchiveManager::class)
->disableOriginalConstructor()->getMock();
$package = new RootPackage('foo/bar', '1.0.0', '1.0');
$installedRepository = $this->getMockBuilder(InstalledRepositoryInterface::class)
->getMock();
$installedRepository->expects($this->once())->method('loadPackages')
->willReturn(['packages' => [$package], 'namesFound' => ['foo/bar']]);
$repositoryManager = $this->getMockBuilder(RepositoryManager::class)
->disableOriginalConstructor()->getMock();
$repositoryManager->expects($this->once())->method('getLocalRepository')
->willReturn($installedRepository);
$repositoryManager->expects($this->once())->method('getRepositories')
->willReturn([]);
$manager->expects($this->once())->method('archive')
->with($package, 'zip', '.', null, false)->willReturn(Platform::getCwd());
$composer->setArchiveManager($manager);
$composer->setEventDispatcher($eventDispatcher);
$composer->setPackage($package);
$composer->setRepositoryManager($repositoryManager);
$command = $this->getMockBuilder(ArchiveCommand::class)
->onlyMethods([
'mergeApplicationDefinition',
'getSynopsis',
'initialize',
'tryComposer',
'requireComposer',
])->getMock();
$command->expects($this->atLeastOnce())->method('tryComposer')
->willReturn($composer);
$command->run($input, $output);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/HomeCommandTest.php | tests/Composer/Test/Command/HomeCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Generator;
class HomeCommandTest extends TestCase
{
/**
* @dataProvider useCaseProvider
* @param array<mixed> $composerJson
* @param array<mixed> $command
* @param array<mixed> $urls
*/
public function testHomeCommandWithShowFlag(
array $composerJson,
array $command,
string $expected,
array $urls = []
): void {
$this->initTempComposer($composerJson);
$packages = [
'vendor/package' => self::getPackage('vendor/package', '1.2.3'),
];
$devPackages = [
'vendor/devpackage' => self::getPackage('vendor/devpackage', '2.3.4'),
];
if (count($urls) !== 0) {
foreach ($urls as $pkg => $url) {
if (isset($packages[$pkg])) {
$packages[$pkg]->setHomepage($url);
}
if (isset($devPackages[$pkg])) {
$devPackages[$pkg]->setHomepage($url);
}
}
}
$this->createInstalledJson($packages, $devPackages);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'home', '--show' => true], $command));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public static function useCaseProvider(): Generator
{
yield 'Invalid or missing repository URL' => [
[
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/package', 'description' => 'generic description', 'version' => '1.0.0'],
],
],
],
'require' => [
'vendor/package' => '^1.0',
],
],
['packages' => ['vendor/package']],
<<<OUTPUT
<warning>Invalid or missing repository URL for vendor/package</warning>
OUTPUT
];
yield 'No Packages Provided' => [
['repositories' => []],
[],
<<<OUTPUT
No package specified, opening homepage for the root package
<warning>Invalid or missing repository URL for __root__</warning>
OUTPUT
];
yield 'Package not found' => [
['repositories' => []],
['packages' => ['vendor/anotherpackage']],
<<<OUTPUT
<warning>Package vendor/anotherpackage not found</warning>
<warning>Invalid or missing repository URL for vendor/anotherpackage</warning>
OUTPUT
];
yield 'A valid package URL' => [
['repositories' => []],
['packages' => ['vendor/package']],
<<<OUTPUT
https://example.org
OUTPUT
,
['vendor/package' => 'https://example.org'],
];
yield 'A valid dev package URL' => [
['repositories' => []],
['packages' => ['vendor/devpackage']],
<<<OUTPUT
https://example.org/dev
OUTPUT
,
['vendor/devpackage' => 'https://example.org/dev'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/ExecCommandTest.php | tests/Composer/Test/Command/ExecCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
class ExecCommandTest extends TestCase
{
public function testListThrowsIfNoBinariesExist(): void
{
$composerDir = $this->initTempComposer();
$composerBinDir = "$composerDir/vendor/bin";
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage(
"No binaries found in composer.json or in bin-dir ($composerBinDir)"
);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'exec', '--list' => true]);
}
public function testList(): void
{
$composerDir = $this->initTempComposer([
'bin' => [
'a',
],
]);
$composerBinDir = "$composerDir/vendor/bin";
mkdir($composerBinDir, 0777, true);
touch($composerBinDir . '/b');
touch($composerBinDir . '/b.bat');
touch($composerBinDir . '/c');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'exec', '--list' => true]);
$output = $appTester->getDisplay(true);
self::assertSame(
'Available binaries:
- b
- c
- a (local)',
trim($output)
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/GlobalCommandTest.php | tests/Composer/Test/Command/GlobalCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Composer\Util\Platform;
class GlobalCommandTest extends TestCase
{
public function tearDown(): void
{
parent::tearDown();
Platform::clearEnv('COMPOSER_HOME');
Platform::clearEnv('COMPOSER');
}
public function testGlobal(): void
{
$script = '@php -r "echo \'COMPOSER SCRIPT OUTPUT: \'.getenv(\'COMPOSER\') . PHP_EOL;"';
$fakeComposer = 'TMP_COMPOSER.JSON';
$composerHome = $this->initTempComposer(
[
"scripts" => [
"test-script" => $script,
],
]
);
Platform::putEnv('COMPOSER_HOME', $composerHome);
Platform::putEnv('COMPOSER', $fakeComposer);
$dir = self::getUniqueTmpDirectory();
chdir($dir);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'global',
'command-name' => 'test-script',
'--no-interaction' => true,
]);
$display = $appTester->getDisplay(true);
self::assertSame(
'Changed current directory to ' . $composerHome . "\n".
"COMPOSER SCRIPT OUTPUT: \n",
$display
);
}
public function testCannotCreateHome(): void
{
$dir = self::getUniqueTmpDirectory();
$filename = $dir . '/file';
file_put_contents($filename, '');
Platform::putEnv('COMPOSER_HOME', $filename);
self::expectException(\RuntimeException::class);
$this->expectExceptionMessage($filename . ' exists and is not a directory.');
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'global',
'command-name' => 'test-script',
'--no-interaction' => true,
]);
}
public function testGlobalShow(): void
{
$composerHome = $this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/global-tool', 'version' => '1.0.0'],
],
],
],
'require' => [
'vendor/global-tool' => '1.0.0',
],
]);
$pkg = self::getPackage('vendor/global-tool', '1.0.0');
$pkg->setDescription('A globally installed tool');
$this->createInstalledJson([$pkg]);
Platform::putEnv('COMPOSER_HOME', $composerHome);
$testDir = self::getUniqueTmpDirectory();
chdir($testDir);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
'command-name' => 'show',
]);
$output = $appTester->getDisplay(true);
self::assertStringContainsString('vendor/global-tool', $output);
self::assertStringContainsString('1.0.0', $output);
}
public function testGlobalShowWithoutPackages(): void
{
$composerHome = $this->initTempComposer();
$this->createInstalledJson();
Platform::putEnv('COMPOSER_HOME', $composerHome);
$testDir = self::getUniqueTmpDirectory();
chdir($testDir);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
'command-name' => 'show',
]);
self::assertSame(0, $appTester->getStatusCode());
}
public function testGlobalRequire(): void
{
$composerHome = $this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
[
'name' => 'vendor/required-pkg',
'version' => '2.0.0',
'dist' => ['type' => 'file', 'url' => __FILE__],
],
],
],
],
]);
Platform::putEnv('COMPOSER_HOME', $composerHome);
$testDir = self::getUniqueTmpDirectory();
chdir($testDir);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
'command-name' => 'require',
'packages' => ['vendor/required-pkg:2.0.0'],
]);
self::assertSame(0, $appTester->getStatusCode());
self::assertStringContainsString('Installing vendor/required-pkg', $appTester->getDisplay(true));
}
public function testGlobalUpdate(): void
{
$composerHome = $this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor/pkg', 'version' => '1.0.0'],
],
],
],
'require' => [
'vendor/pkg' => '1.0.0',
],
]);
$pkg = self::getPackage('vendor/pkg', '1.0.0');
$this->createInstalledJson([$pkg]);
$this->createComposerLock([$pkg]);
Platform::putEnv('COMPOSER_HOME', $composerHome);
$testDir = self::getUniqueTmpDirectory();
chdir($testDir);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
'command-name' => 'update',
]);
self::assertSame(0, $appTester->getStatusCode());
}
public function testGlobalChangesDirectory(): void
{
$composerHome = $this->initTempComposer([
'name' => 'test/global',
]);
Platform::putEnv('COMPOSER_HOME', $composerHome);
$testDir = self::getUniqueTmpDirectory();
chdir($testDir);
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
'command-name' => 'config',
'setting-key' => 'name',
]);
$output = $appTester->getDisplay(true);
self::assertStringContainsString('Changed current directory to ' . $composerHome, $output);
}
public function testGlobalMissingCommandName(): void
{
$composerHome = $this->initTempComposer();
Platform::putEnv('COMPOSER_HOME', $composerHome);
$this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class);
$this->expectExceptionMessage('Not enough arguments (missing: "command-name")');
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run([
'command' => 'global',
]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/SuggestsCommandTest.php | tests/Composer/Test/Command/SuggestsCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Package\CompletePackage;
use Composer\Package\Link;
use Composer\Test\TestCase;
use Symfony\Component\Console\Command\Command;
class SuggestsCommandTest extends TestCase
{
public function testInstalledPackagesWithNoSuggestions(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor1/package1', 'version' => '1.0.0'],
['name' => 'vendor2/package2', 'version' => '1.0.0'],
],
],
],
'require' => [
'vendor1/package1' => '1.*',
'vendor2/package2' => '1.*',
],
]);
$packages = [
self::getPackage('vendor1/package1'),
self::getPackage('vendor2/package2'),
];
$this->createInstalledJson($packages);
$this->createComposerLock($packages);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(['command' => 'suggest']));
self::assertEmpty($appTester->getDisplay(true));
}
/**
* @dataProvider provideSuggest
* @param array<string, bool|string|array<int, string>> $command
*/
public function testSuggest(bool $hasLockFile, array $command, string $expected): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor1/package1', 'version' => '1.0.0', 'suggests' => ['vendor3/suggested' => 'helpful for vendor1/package1'], 'require' => ['vendor6/package6' => '^1.0'], 'require-dev' => ['vendor3/suggested' => '^1.0', 'vendor4/dev-suggested' => '^1.0']],
['name' => 'vendor2/package2', 'version' => '1.0.0', 'suggests' => ['vendor4/dev-suggested' => 'helpful for vendor2/package2'], 'require' => ['vendor5/dev-package' => '^1.0']],
['name' => 'vendor5/dev-package', 'version' => '1.0.0', 'suggests' => ['vendor8/dev-transitive' => 'helpful for vendor5/dev-package'], 'require-dev' => ['vendor8/dev-transitive' => '^1.0']],
['name' => 'vendor6/package6', 'version' => '1.0.0', 'suggests' => ['vendor7/transitive' => 'helpful for vendor6/package6']],
],
],
],
'require' => ['vendor1/package1' => '^1'],
'require-dev' => ['vendor2/package2' => '^1'],
]);
$packages = [
self::getPackageWithSuggestAndRequires(
'vendor1/package1',
'1.0.0',
[
'vendor3/suggested' => 'helpful for vendor1/package1',
],
[
'vendor6/package6' => new Link('vendor1/package1', 'vendor6/package6', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE, '^1.0'),
],
[
'vendor4/dev-suggested' => new Link('vendor1/package1', 'vendor4/dev-suggested', self::getVersionConstraint('>=', '1.0'), Link::TYPE_DEV_REQUIRE, '^1.0'),
'vendor3/suggested' => new Link('vendor1/package1', 'vendor3/suggested', self::getVersionConstraint('>=', '1.0'), Link::TYPE_DEV_REQUIRE, '^1.0'),
]
),
self::getPackageWithSuggestAndRequires(
'vendor6/package6',
'1.0.0',
[
'vendor7/transitive' => 'helpful for vendor6/package6',
]
),
];
$devPackages = [
self::getPackageWithSuggestAndRequires(
'vendor2/package2',
'1.0.0',
[
'vendor4/dev-suggested' => 'helpful for vendor2/package2',
],
[
'vendor5/dev-package' => new Link('vendor2/package2', 'vendor5/dev-package', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE, '^1.0'),
]
),
self::getPackageWithSuggestAndRequires(
'vendor5/dev-package',
'1.0.0',
[
'vendor8/dev-transitive' => 'helpful for vendor5/dev-package',
],
[],
[
'vendor8/dev-transitive' => new Link('vendor5/dev-package', 'vendor8/dev-transitive', self::getVersionConstraint('>=', '1.0'), Link::TYPE_DEV_REQUIRE, '^1.0'),
]
),
];
$this->createInstalledJson($packages, $devPackages);
if ($hasLockFile) {
$this->createComposerLock($packages, $devPackages);
}
$appTester = $this->getApplicationTester();
self::assertEquals(Command::SUCCESS, $appTester->run(array_merge(['command' => 'suggest'], $command)));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public static function provideSuggest(): \Generator
{
yield 'with lockfile, show suggested' => [
true,
[],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested' => [
false,
[],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested (excluding dev)' => [
true,
['--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
1 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested (excluding dev)' => [
false,
['--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show all suggested' => [
true,
['--all' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
vendor5/dev-package suggests:
- vendor8/dev-transitive: helpful for vendor5/dev-package
vendor6/package6 suggests:
- vendor7/transitive: helpful for vendor6/package6',
];
yield 'without lockfile, show all suggested' => [
false,
['--all' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
vendor5/dev-package suggests:
- vendor8/dev-transitive: helpful for vendor5/dev-package
vendor6/package6 suggests:
- vendor7/transitive: helpful for vendor6/package6',
];
yield 'with lockfile, show all suggested (excluding dev)' => [
true,
['--all' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor6/package6 suggests:
- vendor7/transitive: helpful for vendor6/package6',
];
yield 'without lockfile, show all suggested (excluding dev)' => [
false,
['--all' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
vendor5/dev-package suggests:
- vendor8/dev-transitive: helpful for vendor5/dev-package
vendor6/package6 suggests:
- vendor7/transitive: helpful for vendor6/package6',
];
yield 'with lockfile, show suggested grouped by package' => [
true,
['--by-package' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by package' => [
false,
['--by-package' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested grouped by package (excluding dev)' => [
true,
['--by-package' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
1 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by package (excluding dev)' => [
false,
['--by-package' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested grouped by suggestion' => [
true,
['--by-suggestion' => true],
'vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by suggestion' => [
false,
['--by-suggestion' => true],
'vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested grouped by suggestion (excluding dev)' => [
true,
['--by-suggestion' => true, '--no-dev' => true],
'vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
1 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by suggestion (excluding dev)' => [
false,
['--by-suggestion' => true, '--no-dev' => true],
'vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested grouped by package and suggestion' => [
true,
['--by-package' => true, '--by-suggestion' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
------------------------------------------------------------------------------
vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by package and suggestion' => [
false,
['--by-package' => true, '--by-suggestion' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
------------------------------------------------------------------------------
vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested grouped by package and suggestion (excluding dev)' => [
true,
['--by-package' => true, '--by-suggestion' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
------------------------------------------------------------------------------
vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
1 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'without lockfile, show suggested grouped by package and suggestion (excluding dev)' => [
false,
['--by-package' => true, '--by-suggestion' => true, '--no-dev' => true],
'vendor1/package1 suggests:
- vendor3/suggested: helpful for vendor1/package1
vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2
------------------------------------------------------------------------------
vendor3/suggested is suggested by:
- vendor1/package1: helpful for vendor1/package1
vendor4/dev-suggested is suggested by:
- vendor2/package2: helpful for vendor2/package2
2 additional suggestions by transitive dependencies can be shown with --all',
];
yield 'with lockfile, show suggested for package' => [
true,
['packages' => ['vendor2/package2']],
'vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2',
];
yield 'without lockfile, show suggested for package' => [
false,
['packages' => ['vendor2/package2']],
'vendor2/package2 suggests:
- vendor4/dev-suggested: helpful for vendor2/package2',
];
yield 'with lockfile, list suggested' => [
true,
['--list' => true],
'vendor3/suggested
vendor4/dev-suggested',
];
yield 'without lockfile, list suggested' => [
false,
['--list' => true],
'vendor3/suggested
vendor4/dev-suggested',
];
yield 'with lockfile, list suggested with no transitive or no-dev dependencies' => [
true,
['--list' => true, '--no-dev' => true],
'vendor3/suggested',
];
yield 'without lockfile, list suggested with no transitive or no-dev dependencies' => [
false,
['--list' => true, '--no-dev' => true],
'vendor3/suggested
vendor4/dev-suggested',
];
yield 'with lockfile, list suggested with all dependencies including transitive and dev dependencies' => [
true,
['--list' => true, '--all' => true],
'vendor3/suggested
vendor4/dev-suggested
vendor7/transitive
vendor8/dev-transitive',
];
yield 'without lockfile, list suggested with all dependencies including transitive and dev dependencies' => [
false,
['--list' => true, '--all' => true],
'vendor3/suggested
vendor4/dev-suggested
vendor7/transitive
vendor8/dev-transitive',
];
yield 'with lockfile, list all suggested (excluding dev)' => [
true,
['--list' => true, '--all' => true, '--no-dev' => true],
'vendor3/suggested
vendor7/transitive',
];
yield 'without lockfile, list all suggested (excluding dev)' => [
false,
['--list' => true, '--all' => true, '--no-dev' => true],
'vendor3/suggested
vendor4/dev-suggested
vendor7/transitive
vendor8/dev-transitive',
];
}
/**
* @param array<string, string> $suggests
* @param array<string, Link> $requires
* @param array<string, Link> $requireDevs
*/
private function getPackageWithSuggestAndRequires(string $name = 'dummy/pkg', string $version = '1.0.0', array $suggests = [], array $requires = [], array $requireDevs = []): CompletePackage
{
$normVersion = self::getVersionParser()->normalize($version);
$pkg = new CompletePackage($name, $normVersion, $version);
$pkg->setSuggests($suggests);
$pkg->setRequires($requires);
$pkg->setDevRequires($requireDevs);
return $pkg;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/InstallCommandTest.php | tests/Composer/Test/Command/InstallCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Test\TestCase;
use Generator;
class InstallCommandTest extends TestCase
{
/**
* @dataProvider errorCaseProvider
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testInstallCommandErrors(
array $composerJson,
array $command,
string $expected
): void {
$this->initTempComposer($composerJson);
$packages = [
self::getPackage('vendor/package', '1.2.3'),
];
$devPackages = [
self::getPackage('vendor/devpackage', '2.3.4'),
];
$this->createComposerLock($packages, $devPackages);
$this->createInstalledJson($packages, $devPackages);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'install'], $command));
self::assertSame(trim($expected), trim($appTester->getDisplay(true)));
}
public function errorCaseProvider(): Generator
{
yield 'it writes an error when the dev flag is passed' => [
[
'repositories' => [],
],
['--dev' => true],
<<<OUTPUT
<warning>You are using the deprecated option "--dev". It has no effect and will break in Composer 3.</warning>
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Generating autoload files
OUTPUT
];
yield 'it writes an error when no-suggest flag passed' => [
[
'repositories' => [],
],
['--no-suggest' => true],
<<<OUTPUT
<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Generating autoload files
OUTPUT
];
yield 'it writes an error when packages passed' => [
[
'repositories' => [],
],
['packages' => ['vendor/package']],
<<<OUTPUT
Invalid argument vendor/package. Use "composer require vendor/package" instead to add packages to your composer.json.
OUTPUT
];
yield 'it writes an error when no-install flag is passed' => [
[
'repositories' => [],
],
['--no-install' => true],
<<<OUTPUT
Invalid option "--no-install". Use "composer update --no-install" instead if you are trying to update the composer.lock file.
OUTPUT
];
}
public function testInstallFromEmptyVendor(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
'require-dev' => [
'root/another' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$anotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$anotherPackage->setType('metapackage');
$this->createComposerLock([$rootReqPackage], [$anotherPackage]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'install', '--no-progress' => true]);
self::assertSame('Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Package operations: 2 installs, 0 updates, 0 removals
- Installing root/another (1.0.0)
- Installing root/req (1.0.0)
Generating autoload files', trim($appTester->getDisplay(true)));
}
public function testInstallFromEmptyVendorNoDev(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
],
'require-dev' => [
'root/another' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$anotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$anotherPackage->setType('metapackage');
$this->createComposerLock([$rootReqPackage], [$anotherPackage]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'install', '--no-progress' => true, '--no-dev' => true]);
self::assertSame('Installing dependencies from lock file
Verifying lock file contents can be installed on current platform.
Package operations: 1 install, 0 updates, 0 removals
- Installing root/req (1.0.0)
Generating autoload files', trim($appTester->getDisplay(true)));
}
public function testInstallNewPackagesWithExistingPartialVendor(): void
{
$this->initTempComposer([
'require' => [
'root/req' => '1.*',
'root/another' => '1.*',
],
]);
$rootReqPackage = self::getPackage('root/req');
$anotherPackage = self::getPackage('root/another');
// Set as a metapackage so that we can do the whole post-remove update & install process without Composer trying to download them (DownloadManager::getDownloaderForPackage).
$rootReqPackage->setType('metapackage');
$anotherPackage->setType('metapackage');
$this->createComposerLock([$rootReqPackage, $anotherPackage], []);
$this->createInstalledJson([$rootReqPackage], []);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'install', '--no-progress' => true]);
self::assertSame('Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Package operations: 1 install, 0 updates, 0 removals
- Installing root/another (1.0.0)
Generating autoload files', trim($appTester->getDisplay(true)));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/BaseDependencyCommandTest.php | tests/Composer/Test/Command/BaseDependencyCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
use Symfony\Component\Console\Command\Command;
use UnexpectedValueException;
use InvalidArgumentException;
use Composer\Test\TestCase;
use Composer\Package\Link;
use RuntimeException;
use Generator;
class BaseDependencyCommandTest extends TestCase
{
/**
* Test that an exception is throw when there weren't provided some parameters
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider noParametersCaseProvider
*
* @param array<string, string> $parameters
*/
public function testExceptionWhenNoRequiredParameters(
string $command,
array $parameters,
string $expectedExceptionMessage
): void {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage($expectedExceptionMessage);
$appTester = $this->getApplicationTester();
self::assertEquals(Command::FAILURE, $appTester->run(['command' => $command] + $parameters));
}
/**
* @return Generator<string, array{string, array<string, string>, string}>
*/
public static function noParametersCaseProvider(): Generator
{
yield '`why` command without package parameter' => [
'why',
[],
'Not enough arguments (missing: "package").',
];
yield '`why-not` command without package and version parameters' => [
'why-not',
[],
'Not enough arguments (missing: "package, version").',
];
yield '`why-not` command without package parameter' => [
'why-not',
['version' => '*'],
'Not enough arguments (missing: "package").',
];
yield '`why-not` command without version parameter' => [
'why-not',
['package' => 'vendor1/package1'],
'Not enough arguments (missing: "version").',
];
}
/**
* Test that an exception is throw when there wasn't provided the locked file alongside `--locked` parameter
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider caseProvider
*
* @param array<string, string> $parameters
*/
public function testExceptionWhenRunningLockedWithoutLockFile(string $command, array $parameters): void
{
$this->initTempComposer();
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('A valid composer.lock file is required to run this command with --locked');
$appTester = $this->getApplicationTester();
self::assertEquals(
Command::FAILURE,
$appTester->run(
['command' => $command] + $parameters + ['--locked' => true]
)
);
}
/**
* Test that an exception is throw when the provided package to be inspected isn't required by the project
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider caseProvider
*
* @param array<string, string> $parameters
*/
public function testExceptionWhenItCouldNotFoundThePackage(string $command, array $parameters): void
{
$packageToBeInspected = $parameters['package'];
$this->initTempComposer();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('Could not find package "%s" in your project', $packageToBeInspected));
$appTester = $this->getApplicationTester();
self::assertEquals(
Command::FAILURE,
$appTester->run(['command' => $command] + $parameters)
);
}
/**
* Test that it shows a warning message when the package to be inspected wasn't found in the project
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider caseProvider
*
* @param array<string, string> $parameters
*/
public function testExceptionWhenPackageWasNotFoundInProject(string $command, array $parameters): void
{
$packageToBeInspected = $parameters['package'];
$this->initTempComposer([
'require' => [
'vendor1/package2' => '1.*',
'vendor2/package1' => '2.*',
],
]);
$firstRequiredPackage = self::getPackage('vendor1/package2');
$secondRequiredPackage = self::getPackage('vendor2/package1');
$this->createInstalledJson([$firstRequiredPackage, $secondRequiredPackage]);
$this->createComposerLock([$firstRequiredPackage, $secondRequiredPackage]);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('Could not find package "%s" in your project', $packageToBeInspected));
$appTester = $this->getApplicationTester();
self::assertEquals(Command::FAILURE, $appTester->run(['command' => $command] + $parameters));
}
/**
* Test that it shows a warning message when the dependencies haven't been installed yet
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider caseProvider
*
* @param array<string, string> $parameters
*/
public function testWarningWhenDependenciesAreNotInstalled(string $command, array $parameters): void
{
$expectedWarningMessage = '<warning>No dependencies installed. Try running composer install or update, or use --locked.</warning>';
$this->initTempComposer([
'require' => [
'vendor1/package1' => '1.*',
],
'require-dev' => [
'vendor2/package1' => '2.*',
],
]);
$someRequiredPackage = self::getPackage('vendor1/package1');
$someDevRequiredPackage = self::getPackage('vendor2/package1');
$this->createComposerLock([$someRequiredPackage], [$someDevRequiredPackage]);
$appTester = $this->getApplicationTester();
$appTester->run(['command' => $command] + $parameters);
self::assertSame($expectedWarningMessage, trim($appTester->getDisplay(true)));
}
/**
* @return Generator<string, array{string, array<string, string>}>
*/
public static function caseProvider(): Generator
{
yield '`why` command' => [
'why',
['package' => 'vendor1/package1'],
];
yield '`why-not` command' => [
'why-not',
['package' => 'vendor1/package1', 'version' => '1.*'],
];
}
/**
* Test that it finishes successfully and show some expected outputs depending on different command parameters
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\DependsCommand
*
* @dataProvider caseWhyProvider
*
* @param array<string, string|bool> $parameters
*/
public function testWhyCommandOutputs(array $parameters, string $expectedOutput, int $expectedStatusCode): void
{
$packageToBeInspected = $parameters['package'];
$renderAsTree = $parameters['--tree'] ?? false;
$renderRecursively = $parameters['--recursive'] ?? false;
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor1/package1', 'version' => '1.3.0', 'require' => ['vendor1/package2' => '^2']],
['name' => 'vendor1/package2', 'version' => '2.3.0', 'require' => ['vendor1/package3' => '^1']],
['name' => 'vendor1/package3', 'version' => '2.1.0'],
],
],
],
'require' => [
'vendor1/package2' => '1.3.0',
'vendor1/package3' => '2.3.0',
],
'require-dev' => [
'vendor2/package1' => '2.*',
],
]);
$firstRequiredPackage = self::getPackage('vendor1/package1', '1.3.0');
$firstRequiredPackage->setRequires([
'vendor1/package2' => new Link(
'vendor1/package1',
'vendor1/package2',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'^2'
),
]);
$secondRequiredPackage = self::getPackage('vendor1/package2', '2.3.0');
$secondRequiredPackage->setRequires([
'vendor1/package3' => new Link(
'vendor1/package2',
'vendor1/package3',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'^1'
),
]);
$thirdRequiredPackage = self::getPackage('vendor1/package3', '2.1.0');
$someDevRequiredPackage = self::getPackage('vendor2/package1');
$this->createComposerLock(
[$firstRequiredPackage, $secondRequiredPackage, $thirdRequiredPackage],
[$someDevRequiredPackage]
);
$this->createInstalledJson(
[$firstRequiredPackage, $secondRequiredPackage, $thirdRequiredPackage],
[$someDevRequiredPackage]
);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'why',
'package' => $packageToBeInspected,
'--tree' => $renderAsTree,
'--recursive' => $renderRecursively,
'--locked' => true,
]);
self::assertSame($expectedStatusCode, $appTester->getStatusCode());
self::assertEquals(trim($expectedOutput), $this->trimLines($appTester->getDisplay(true)));
}
/**
* @return Generator<string, array{array<string, string|bool>, string}>
*/
public static function caseWhyProvider(): Generator
{
yield 'there is no installed package depending on the package' => [
['package' => 'vendor1/package1'],
'There is no installed package depending on "vendor1/package1"',
1,
];
yield 'a nested package dependency' => [
['package' => 'vendor1/package3'],
<<<OUTPUT
__root__ - requires vendor1/package3 (2.3.0)
vendor1/package2 2.3.0 requires vendor1/package3 (^1)
OUTPUT
,
0,
];
yield 'a nested package dependency (tree mode)' => [
['package' => 'vendor1/package3', '--tree' => true],
<<<OUTPUT
vendor1/package3 2.1.0
|--__root__ (requires vendor1/package3 2.3.0)
`--vendor1/package2 2.3.0 (requires vendor1/package3 ^1)
|--__root__ (requires vendor1/package2 1.3.0)
`--vendor1/package1 1.3.0 (requires vendor1/package2 ^2)
OUTPUT
,
0,
];
yield 'a nested package dependency (recursive mode)' => [
['package' => 'vendor1/package3', '--recursive' => true],
<<<OUTPUT
__root__ - requires vendor1/package2 (1.3.0)
vendor1/package1 1.3.0 requires vendor1/package2 (^2)
__root__ - requires vendor1/package3 (2.3.0)
vendor1/package2 2.3.0 requires vendor1/package3 (^1)
OUTPUT
,
0,
];
yield 'a simple package dev dependency' => [
['package' => 'vendor2/package1'],
'__root__ - requires (for development) vendor2/package1 (2.*)',
0,
];
}
/**
* Test that it finishes successfully and show some expected outputs depending on different command parameters
*
* @covers \Composer\Command\BaseDependencyCommand
* @covers \Composer\Command\ProhibitsCommand
*
* @dataProvider caseWhyNotProvider
*
* @param array<string, string> $parameters
*/
public function testWhyNotCommandOutputs(array $parameters, string $expectedOutput, int $expectedStatusCode): void
{
$packageToBeInspected = $parameters['package'];
$packageVersionToBeInspected = $parameters['version'];
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vendor1/package1', 'version' => '1.3.0'],
['name' => 'vendor2/package1', 'version' => '2.0.0'],
['name' => 'vendor2/package2', 'version' => '1.0.0', 'require' => ['vendor2/package3' => '1.4.*', 'php' => '^8.2']],
['name' => 'vendor2/package3', 'version' => '1.4.0'],
['name' => 'vendor2/package3', 'version' => '1.5.0'],
],
],
],
'require' => [
'vendor1/package1' => '1.*',
'php' => '^8',
],
'require-dev' => [
'vendor2/package1' => '2.*',
'vendor2/package2' => '^1',
],
'config' => [
'platform' => [
'php' => '8.3.2',
],
],
]);
$someRequiredPackage = self::getPackage('vendor1/package1', '1.3.0');
$firstDevRequiredPackage = self::getPackage('vendor2/package1', '2.0.0');
$secondDevRequiredPackage = self::getPackage('vendor2/package2', '1.0.0');
$secondDevRequiredPackage->setRequires([
'vendor2/package3' => new Link(
'vendor2/package2',
'vendor2/package3',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'1.4.*'
),
'php' => new Link(
'vendor2/package2',
'php',
new MultiConstraint([self::getVersionConstraint('>=', '8.2.0.0'), self::getVersionConstraint('<', '9.0.0.0-dev')]),
Link::TYPE_REQUIRE,
'^8.2'
),
]);
$secondDevNestedRequiredPackage = self::getPackage('vendor2/package3', '1.4.0');
$this->createComposerLock(
[$someRequiredPackage],
[$firstDevRequiredPackage, $secondDevRequiredPackage]
);
$this->createInstalledJson(
[$someRequiredPackage],
[$firstDevRequiredPackage, $secondDevRequiredPackage, $secondDevNestedRequiredPackage]
);
$appTester = $this->getApplicationTester();
$appTester->run([
'command' => 'why-not',
'package' => $packageToBeInspected,
'version' => $packageVersionToBeInspected,
]);
self::assertSame($expectedStatusCode, $appTester->getStatusCode());
self::assertSame(trim($expectedOutput), $this->trimLines($appTester->getDisplay(true)));
}
/**
* @return Generator<string, array{array<string, string>, string}>
*/
public function caseWhyNotProvider(): Generator
{
yield 'it could not found the package with a specific version' => [
['package' => 'vendor1/package1', 'version' => '3.*'],
<<<OUTPUT
Package "vendor1/package1" could not be found with constraint "3.*", results below will most likely be incomplete.
__root__ - requires vendor1/package1 (1.*)
Not finding what you were looking for? Try calling `composer require "vendor1/package1:3.*" --dry-run` to get another view on the problem.
OUTPUT
,
1,
];
yield 'it could not found the package and there is no installed package with a specific version' => [
['package' => 'vendor1/package1', 'version' => '^1.4'],
<<<OUTPUT
Package "vendor1/package1" could not be found with constraint "^1.4", results below will most likely be incomplete.
There is no installed package depending on "vendor1/package1" in versions not matching ^1.4
Not finding what you were looking for? Try calling `composer require "vendor1/package1:^1.4" --dry-run` to get another view on the problem.
OUTPUT
,
0,
];
yield 'Package is already installed!' => [
['package' => 'vendor1/package1', 'version' => '^1.3'],
<<<OUTPUT
Package "vendor1/package1" 1.3.0 is already installed! To find out why, run `composer why vendor1/package1`
OUTPUT
,
0,
];
yield 'an installed package requires an incompatible version of the inspected package' => [
['package' => 'vendor2/package3', 'version' => '1.5.0'],
<<<OUTPUT
vendor2/package2 1.0.0 requires vendor2/package3 (1.4.*)
Not finding what you were looking for? Try calling `composer update "vendor2/package3:1.5.0" --dry-run` to get another view on the problem.
OUTPUT
,
1,
];
yield 'all compatible with the inspected platform package (range matching installed)' => [
['package' => 'php', 'version' => '^8'],
<<<OUTPUT
Package "php ^8" found in version "8.3.2" (version provided by config.platform).
There is no installed package depending on "php" in versions not matching ^8
OUTPUT
,
0,
];
yield 'an installed package requires an incompatible version of the inspected platform package (fixed non-matching package)' => [
['package' => 'php', 'version' => '9.1.0'],
<<<OUTPUT
__root__ - requires php (^8)
vendor2/package2 1.0.0 requires php (^8.2)
OUTPUT
,
1,
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/InitCommandTest.php | tests/Composer/Test/Command/InitCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Command\InitCommand;
use Composer\Json\JsonFile;
use Composer\Test\TestCase;
use InvalidArgumentException;
class InitCommandTest extends TestCase
{
private const DEFAULT_AUTHORS = [
'name' => 'John Smith',
'email' => 'john@example.com',
];
protected function setUp(): void
{
parent::setUp();
$_SERVER['COMPOSER_DEFAULT_AUTHOR'] = 'John Smith';
$_SERVER['COMPOSER_DEFAULT_EMAIL'] = 'john@example.com';
}
/**
* @dataProvider validAuthorStringProvider
*/
public function testParseValidAuthorString(string $name, ?string $email, string $input): void
{
$author = $this->callParseAuthorString(new InitCommand, $input);
self::assertSame($name, $author['name']);
self::assertSame($email, $author['email']);
}
/**
* @return iterable<string, array{0: string, 1: string|null, 2: string}>
*/
public static function validAuthorStringProvider(): iterable
{
yield 'simple' => [
'John Smith',
'john@example.com',
'John Smith <john@example.com>',
];
yield 'without email' => [
'John Smith',
null,
'John Smith',
];
yield 'UTF-8' => [
'Matti Meikäläinen',
'matti@example.com',
'Matti Meikäläinen <matti@example.com>',
];
// \xCC\x88 is UTF-8 for U+0308 diaeresis (umlaut) combining mark
yield 'UTF-8 with non-spacing marks' => [
"Matti Meika\xCC\x88la\xCC\x88inen",
'matti@example.com',
"Matti Meika\xCC\x88la\xCC\x88inen <matti@example.com>",
];
yield 'numeric author name' => [
'h4x0r',
'h4x@example.com',
'h4x0r <h4x@example.com>',
];
// https://github.com/composer/composer/issues/5631 Issue #5631
yield 'alias 1' => [
'Johnathon "Johnny" Smith',
'john@example.com',
'Johnathon "Johnny" Smith <john@example.com>',
];
// https://github.com/composer/composer/issues/5631 Issue #5631
yield 'alias 2' => [
'Johnathon (Johnny) Smith',
'john@example.com',
'Johnathon (Johnny) Smith <john@example.com>',
];
}
public function testParseEmptyAuthorString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->callParseAuthorString(new InitCommand, '');
}
public function testParseAuthorStringWithInvalidEmail(): void
{
$this->expectException(InvalidArgumentException::class);
$this->callParseAuthorString(new InitCommand, 'John Smith <john>');
}
public function testNamespaceFromValidPackageName(): void
{
$command = new InitCommand;
$namespace = $command->namespaceFromPackageName('new_projects.acme-extra/package-name');
self::assertEquals('NewProjectsAcmeExtra\PackageName', $namespace);
}
public function testNamespaceFromInvalidPackageName(): void
{
$command = new InitCommand;
$namespace = $command->namespaceFromPackageName('invalid-package-name');
self::assertNull($namespace);
}
public function testNamespaceFromMissingPackageName(): void
{
$command = new InitCommand;
$namespace = $command->namespaceFromPackageName('');
self::assertNull($namespace);
}
/**
* @return array{name: string, email: string|null}
*/
private function callParseAuthorString(InitCommand $command, string $string): array
{
$reflMethod = new \ReflectionMethod($command, 'parseAuthorString');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
return $reflMethod->invoke($command, $string);
}
/**
* @dataProvider runDataProvider
*
* @param array<string, mixed> $expected
* @param array<string, mixed> $arguments
*/
public function testRunCommand(array $expected, array $arguments = []): void
{
$dir = $this->initTempComposer();
unlink($dir . '/composer.json');
unlink($dir . '/auth.json');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'init', '--no-interaction' => true] + $arguments);
self::assertSame(0, $appTester->getStatusCode());
$file = new JsonFile($dir . '/composer.json');
self::assertEquals($expected, $file->read());
}
/**
* @return iterable<string, array{0: array<string, mixed>, 1: array<string, mixed>}>
*/
public static function runDataProvider(): iterable
{
yield 'name argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
],
['--name' => 'test/pkg'],
];
yield 'name and author arguments' => [
[
'name' => 'test/pkg',
'require' => [],
'authors' => [
[
'name' => 'Mr. Test',
'email' => 'test@example.org',
],
],
],
['--name' => 'test/pkg', '--author' => 'Mr. Test <test@example.org>'],
];
yield 'name and author arguments without email' => [
[
'name' => 'test/pkg',
'require' => [],
'authors' => [
[
'name' => 'Mr. Test',
],
],
],
['--name' => 'test/pkg', '--author' => 'Mr. Test'],
];
yield 'single repository argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'repositories' => [
[
'type' => 'vcs',
'url' => 'http://packages.example.com',
],
],
],
['--name' => 'test/pkg', '--repository' => ['{"type":"vcs","url":"http://packages.example.com"}']],
];
yield 'multiple repository arguments' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'repositories' => [
[
'type' => 'vcs',
'url' => 'http://vcs.example.com',
],
[
'type' => 'composer',
'url' => 'http://composer.example.com',
],
[
'type' => 'composer',
'url' => 'http://composer2.example.com',
'options' => [
'ssl' => [
'verify_peer' => 'true',
],
],
],
],
],
['--name' => 'test/pkg', '--repository' => [
'{"type":"vcs","url":"http://vcs.example.com"}',
'{"type":"composer","url":"http://composer.example.com"}',
'{"type":"composer","url":"http://composer2.example.com","options":{"ssl":{"verify_peer":"true"}}}',
]],
];
yield 'stability argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'minimum-stability' => 'dev',
],
['--name' => 'test/pkg', '--stability' => 'dev'],
];
yield 'require one argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [
'first/pkg' => '1.0.0',
],
],
['--name' => 'test/pkg', '--require' => ['first/pkg:1.0.0']],
];
yield 'require multiple arguments' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [
'first/pkg' => '1.0.0',
'second/pkg' => '^3.4',
],
],
['--name' => 'test/pkg', '--require' => ['first/pkg:1.0.0', 'second/pkg:^3.4']],
];
yield 'require-dev one argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'require-dev' => [
'first/pkg' => '1.0.0',
],
],
['--name' => 'test/pkg', '--require-dev' => ['first/pkg:1.0.0']],
];
yield 'require-dev multiple arguments' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'require-dev' => [
'first/pkg' => '1.0.0',
'second/pkg' => '^3.4',
],
],
['--name' => 'test/pkg', '--require-dev' => ['first/pkg:1.0.0', 'second/pkg:^3.4']],
];
yield 'autoload argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'autoload' => [
'psr-4' => [
'Test\\Pkg\\' => 'testMapping/',
],
],
],
['--name' => 'test/pkg', '--autoload' => 'testMapping/'],
];
yield 'homepage argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'homepage' => 'https://example.org/',
],
['--name' => 'test/pkg', '--homepage' => 'https://example.org/'],
];
yield 'description argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'description' => 'My first example package',
],
['--name' => 'test/pkg', '--description' => 'My first example package'],
];
yield 'type argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'type' => 'project',
],
['--name' => 'test/pkg', '--type' => 'project'],
];
yield 'license argument' => [
[
'name' => 'test/pkg',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
'license' => 'MIT',
],
['--name' => 'test/pkg', '--license' => 'MIT'],
];
}
/**
* @dataProvider runInvalidDataProvider
*
* @param class-string<\Throwable>|null $exception
* @param array<string, mixed> $arguments
*/
public function testRunCommandInvalid(?string $exception, ?string $message, array $arguments): void
{
if ($exception !== null) {
$this->expectException($exception);
if ($message !== null) {
$this->expectExceptionMessage($message);
}
}
$dir = $this->initTempComposer();
unlink($dir . '/composer.json');
unlink($dir . '/auth.json');
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'init', '--no-interaction' => true] + $arguments, ['capture_stderr_separately' => true]);
if ($exception === null && $message !== null) {
self::assertSame(1, $appTester->getStatusCode());
self::assertMatchesRegularExpression($message, $appTester->getErrorOutput());
}
}
/**
* @return iterable<string, array{0: class-string<\Throwable>|null, 1: string|null, 2: array<string, mixed>}>
*/
public static function runInvalidDataProvider(): iterable
{
yield 'invalid name argument' => [
InvalidArgumentException::class,
null,
['--name' => 'test'],
];
yield 'invalid author argument' => [
InvalidArgumentException::class,
null,
['--name' => 'test/pkg', '--author' => 'Mr. Test <test>'],
];
yield 'invalid stability argument' => [
null,
'/minimum-stability\s+:\s+Does not have a value in the enumeration/',
['--name' => 'test/pkg', '--stability' => 'bogus'],
];
yield 'invalid require argument' => [
\UnexpectedValueException::class,
"Option first is missing a version constraint, use e.g. first:^1.0",
['--name' => 'test/pkg', '--require' => ['first']],
];
yield 'invalid require-dev argument' => [
\UnexpectedValueException::class,
"Option first is missing a version constraint, use e.g. first:^1.0",
['--name' => 'test/pkg', '--require-dev' => ['first']],
];
yield 'invalid homepage argument' => [
null,
"/homepage\s*:\s*Invalid URL format/",
['--name' => 'test/pkg', '--homepage' => 'not-a-url'],
];
}
public function testRunGuessNameFromDirSanitizesDir(): void
{
$dir = $this->initTempComposer();
mkdir($dirName = '_foo_--bar__baz.--..qux__');
chdir($dirName);
$_SERVER['COMPOSER_DEFAULT_VENDOR'] = '.vendorName';
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'init', '--no-interaction' => true]);
self::assertSame(0, $appTester->getStatusCode());
$expected = [
'name' => 'vendor-name/foo-bar_baz.qux',
'authors' => [self::DEFAULT_AUTHORS],
'require' => [],
];
$file = new JsonFile('./composer.json');
self::assertEquals($expected, $file->read());
unset($_SERVER['COMPOSER_DEFAULT_VENDOR']);
}
public function testInteractiveRun(): void
{
$dir = $this->initTempComposer();
unlink($dir . '/composer.json');
unlink($dir . '/auth.json');
$appTester = $this->getApplicationTester();
$appTester->setInputs([
'vendor/pkg', // Pkg name
'my description', // Description
'Mr. Test <test@example.org>', // Author
'stable', // Minimum stability
'library', // Type
'AGPL-3.0-only', // License
'no', // Define dependencies
'no', // Define dev dependencies
'n', // Add PSR-4 autoload mapping
'', // Confirm generation
]);
$appTester->run(['command' => 'init']);
self::assertSame(0, $appTester->getStatusCode());
$expected = [
'name' => 'vendor/pkg',
'description' => 'my description',
'type' => 'library',
'license' => 'AGPL-3.0-only',
'authors' => [['name' => 'Mr. Test', 'email' => 'test@example.org']],
'minimum-stability' => 'stable',
'require' => [],
];
$file = new JsonFile($dir . '/composer.json');
self::assertEquals($expected, $file->read());
}
public function testFormatAuthors(): void
{
$authorWithEmail = 'John Smith <john@example.com>';
$authorWithoutEmail = 'John Smith';
$command = new DummyInitCommand;
$authors = $command->formatAuthors($authorWithEmail);
self::assertEquals(['name' => 'John Smith', 'email' => 'john@example.com'], $authors[0]);
$authors = $command->formatAuthors($authorWithoutEmail);
self::assertEquals(['name' => 'John Smith'], $authors[0]);
}
public function testGetGitConfig(): void
{
$command = new DummyInitCommand;
$gitConfig = $command->getGitConfig();
self::assertArrayHasKey('user.name', $gitConfig);
self::assertArrayHasKey('user.email', $gitConfig);
}
public function testAddVendorIgnore(): void
{
$command = new DummyInitCommand;
$ignoreFile = self::getUniqueTmpDirectory().'/ignore';
$command->addVendorIgnore($ignoreFile);
self::assertFileExists($ignoreFile);
$content = (string) file_get_contents($ignoreFile);
self::assertStringContainsString('/vendor/', $content);
}
public function testHasVendorIgnore(): void
{
$command = new DummyInitCommand;
$ignoreFile = self::getUniqueTmpDirectory().'/ignore';
self::assertFalse($command->hasVendorIgnore($ignoreFile));
$command->addVendorIgnore($ignoreFile);
self::assertTrue($command->hasVendorIgnore($ignoreFile));
}
}
class DummyInitCommand extends InitCommand
{
public function formatAuthors(string $author): array
{
return parent::formatAuthors($author);
}
public function getGitConfig(): array
{
return parent::getGitConfig();
}
public function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/'): void
{
parent::addVendorIgnore($ignoreFile, $vendor);
}
public function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor'): bool
{
return parent::hasVendorIgnore($ignoreFile, $vendor);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Command/UpdateCommandTest.php | tests/Composer/Test/Command/UpdateCommandTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Command;
use Composer\Package\Link;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Test\TestCase;
class UpdateCommandTest extends TestCase
{
/**
* @dataProvider provideUpdates
* @param array<mixed> $composerJson
* @param array<mixed> $command
*/
public function testUpdate(array $composerJson, array $command, string $expected, bool $createLock = false): void
{
$this->initTempComposer($composerJson);
if ($createLock) {
$this->createComposerLock();
}
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'update', '--dry-run' => true, '--no-audit' => true], $command));
self::assertStringMatchesFormat(trim($expected), trim($appTester->getDisplay(true)));
}
public static function provideUpdates(): \Generator
{
$rootDepAndTransitiveDep = [
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'require' => ['dep/pkg' => '^1']],
['name' => 'dep/pkg', 'version' => '1.0.0', 'replace' => ['replaced/pkg' => '1.0.0']],
['name' => 'dep/pkg', 'version' => '1.0.1', 'replace' => ['replaced/pkg' => '1.0.1']],
['name' => 'dep/pkg', 'version' => '1.0.2', 'replace' => ['replaced/pkg' => '1.0.2']],
],
],
],
'require' => [
'root/req' => '1.*',
],
];
yield 'simple update' => [
$rootDepAndTransitiveDep,
[],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking dep/pkg (1.0.2)
- Locking root/req (1.0.0)
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
- Installing dep/pkg (1.0.2)
- Installing root/req (1.0.0)
OUTPUT
];
yield 'simple update with very verbose output' => [
$rootDepAndTransitiveDep,
['-vv' => true],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Dependency resolution completed in %f seconds
Analyzed %d packages to resolve dependencies
Analyzed %d rules to resolve dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
Installs: dep/pkg:1.0.2, root/req:1.0.0
- Locking dep/pkg (1.0.2) from package repo (defining 4 packages)
- Locking root/req (1.0.0) from package repo (defining 4 packages)
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
Installs: dep/pkg:1.0.2, root/req:1.0.0
- Installing dep/pkg (1.0.2)
- Installing root/req (1.0.0)
OUTPUT
];
yield 'update with temporary constraint + --no-install' => [
$rootDepAndTransitiveDep,
['--with' => ['dep/pkg:1.0.0'], '--no-install' => true],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking dep/pkg (1.0.0)
- Locking root/req (1.0.0)
OUTPUT
];
yield 'update with temporary constraint failing resolution' => [
$rootDepAndTransitiveDep,
['--with' => ['dep/pkg:^2']],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires root/req 1.* -> satisfiable by root/req[1.0.0].
- root/req 1.0.0 requires dep/pkg ^1 -> found dep/pkg[1.0.0, 1.0.1, 1.0.2] but it conflicts with your temporary update constraint (dep/pkg:^2).
OUTPUT
];
yield 'update with temporary constraint failing resolution on root package' => [
$rootDepAndTransitiveDep,
['--with' => ['root/req:^2']],
<<<OUTPUT
The temporary constraint "^2" for "root/req" must be a subset of the constraint in your composer.json (1.*)
Run `composer require root/req` or `composer require root/req:^2` instead to replace the constraint
OUTPUT
];
yield 'update & bump' => [
$rootDepAndTransitiveDep,
['--bump-after-update' => true],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking dep/pkg (1.0.2)
- Locking root/req (1.0.0)
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
- Installing dep/pkg (1.0.2)
- Installing root/req (1.0.0)
Bumping dependencies
<warning>Warning: Bumping dependency constraints is not recommended for libraries as it will narrow down your dependencies and may cause problems for your users.</warning>
<warning>If your package is not a library, you can explicitly specify the "type" by using "composer config type project".</warning>
<warning>Alternatively you can use --bump-after-update=dev to only bump dependencies within "require-dev".</warning>
No requirements to update in ./composer.json.
OUTPUT
, true,
];
yield 'update & bump with lock' => [
$rootDepAndTransitiveDep,
['--bump-after-update' => true, '--lock' => true],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
OUTPUT
, true,
];
yield 'update & bump dev only' => [
$rootDepAndTransitiveDep,
['--bump-after-update' => 'dev'],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
- Locking dep/pkg (1.0.2)
- Locking root/req (1.0.0)
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
- Installing dep/pkg (1.0.2)
- Installing root/req (1.0.0)
Bumping dependencies
No requirements to update in ./composer.json.
OUTPUT
, true,
];
yield 'update & dump with failing update' => [
$rootDepAndTransitiveDep,
['--with' => ['dep/pkg:^2'], '--bump-after-update' => true],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires root/req 1.* -> satisfiable by root/req[1.0.0].
- root/req 1.0.0 requires dep/pkg ^1 -> found dep/pkg[1.0.0, 1.0.1, 1.0.2] but it conflicts with your temporary update constraint (dep/pkg:^2).
OUTPUT
];
yield 'update with replaced name filter fails to resolve' => [
$rootDepAndTransitiveDep,
['--with' => ['replaced/pkg:^2']],
<<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires root/req 1.* -> satisfiable by root/req[1.0.0].
- root/req 1.0.0 requires dep/pkg ^1 -> found dep/pkg[1.0.0, 1.0.1, 1.0.2] but it conflicts with your temporary update constraint (replaced/pkg:^2).
OUTPUT
];
}
public function testUpdateWithPatchOnly(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
['name' => 'root/req', 'version' => '1.0.1'],
['name' => 'root/req', 'version' => '1.1.0'],
['name' => 'root/req2', 'version' => '1.0.0'],
['name' => 'root/req2', 'version' => '1.0.1'],
['name' => 'root/req2', 'version' => '1.1.0'],
['name' => 'root/req3', 'version' => '1.0.0'],
['name' => 'root/req3', 'version' => '1.0.1'],
['name' => 'root/req3', 'version' => '1.1.0'],
],
],
],
'require' => [
'root/req' => '1.*',
'root/req2' => '1.*',
'root/req3' => '1.*',
],
]);
$package = self::getPackage('root/req', '1.0.0');
$package2 = self::getPackage('root/req2', '1.0.0');
$package3 = self::getPackage('root/req3', '1.0.0');
$this->createComposerLock([$package, $package2, $package3]);
$appTester = $this->getApplicationTester();
// root/req fails because of incompatible --with requirement
$appTester->run(array_merge(['command' => 'update', '--dry-run' => true, '--no-audit' => true, '--no-install' => true, '--patch-only' => true, '--with' => ['root/req:^1.1']]));
$expected = <<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires root/req 1.*, found root/req[1.0.0, 1.0.1, 1.1.0] but it conflicts with your temporary update constraint (root/req:[[>= 1.1.0.0-dev < 2.0.0.0-dev] [>= 1.0.0.0-dev < 1.1.0.0-dev]]).
OUTPUT;
self::assertStringMatchesFormat(trim($expected), trim($appTester->getDisplay(true)));
$appTester = $this->getApplicationTester();
// root/req upgrades to 1.0.1 as that is compatible with the --with requirement now
// root/req2 upgrades to 1.0.1 only due to --patch-only
// root/req3 does not update as it is not in the allowlist
$appTester->run(array_merge(['command' => 'update', '--dry-run' => true, '--no-audit' => true, '--no-install' => true, '--patch-only' => true, '--with' => ['root/req:^1.0.1'], 'packages' => ['root/req', 'root/req2']]));
$expected = <<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 2 updates, 0 removals
- Upgrading root/req (1.0.0 => 1.0.1)
- Upgrading root/req2 (1.0.0 => 1.0.1)
OUTPUT;
self::assertStringMatchesFormat(trim($expected), trim($appTester->getDisplay(true)));
}
public function testInteractiveModeThrowsIfNoPackageToUpdate(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$this->createComposerLock([self::getPackage('root/req', '1.0.0')]);
self::expectExceptionMessage('Could not find any package with new versions available');
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run(['command' => 'update', '--interactive' => true]);
}
public function testInteractiveModeThrowsIfNoPackageEntered(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0'],
['name' => 'root/req', 'version' => '1.0.1'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$this->createComposerLock([self::getPackage('root/req', '1.0.0')]);
self::expectExceptionMessage('No package named "" is installed.');
$appTester = $this->getApplicationTester();
$appTester->setInputs(['']);
$appTester->run(['command' => 'update', '--interactive' => true]);
}
/**
* @dataProvider provideInteractiveUpdates
* @param array<mixed> $packageNames
*/
public function testInteractiveTmp(array $packageNames, string $expected): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/req', 'version' => '1.0.0', 'require' => ['dep/pkg' => '^1']],
['name' => 'dep/pkg', 'version' => '1.0.0'],
['name' => 'dep/pkg', 'version' => '1.0.1'],
['name' => 'dep/pkg', 'version' => '1.0.2'],
['name' => 'another-dep/pkg', 'version' => '1.0.2'],
],
],
],
'require' => [
'root/req' => '1.*',
],
]);
$rootPackage = self::getPackage('root/req');
$packages = [$rootPackage];
foreach ($packageNames as $pkg => $ver) {
$currentPkg = self::getPackage($pkg, $ver);
array_push($packages, $currentPkg);
}
$rootPackage->setRequires([
'dep/pkg' => new Link(
'root/req',
'dep/pkg',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'^1'
),
'another-dep/pkg' => new Link(
'root/req',
'another-dep/pkg',
new MatchAllConstraint(),
Link::TYPE_REQUIRE,
'^1'
),
]);
$this->createComposerLock($packages);
$this->createInstalledJson($packages);
$appTester = $this->getApplicationTester();
$appTester->setInputs(array_merge(array_keys($packageNames), ['', 'yes']));
$appTester->run([
'command' => 'update', '--interactive' => true,
'--no-audit' => true,
'--dry-run' => true,
]);
self::assertStringEndsWith(
trim($expected),
trim($appTester->getDisplay(true))
);
}
public function provideInteractiveUpdates(): \Generator
{
yield [
['dep/pkg' => '1.0.1'],
<<<OUTPUT
Lock file operations: 1 install, 1 update, 0 removals
- Locking another-dep/pkg (1.0.2)
- Upgrading dep/pkg (1.0.1 => 1.0.2)
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 1 update, 0 removals
- Upgrading dep/pkg (1.0.1 => 1.0.2)
- Installing another-dep/pkg (1.0.2)
OUTPUT
];
yield [
['dep/pkg' => '1.0.1', 'another-dep/pkg' => '1.0.2'],
<<<OUTPUT
Lock file operations: 0 installs, 1 update, 0 removals
- Upgrading dep/pkg (1.0.1 => 1.0.2)
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
- Upgrading dep/pkg (1.0.1 => 1.0.2)
OUTPUT
];
}
public function testNoSecurityBlockingAllowsInsecurePackages(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'vulnerable/pkg', 'version' => '1.0.0'],
['name' => 'vulnerable/pkg', 'version' => '1.1.0'],
],
'security-advisories' => [
'vulnerable/pkg' => [
[
'advisoryId' => 'PKSA-test-001',
'packageName' => 'vulnerable/pkg',
'remoteId' => 'CVE-2024-1234',
'title' => 'Test Security Vulnerability',
'link' => 'https://example.com/advisory',
'cve' => 'CVE-2024-1234',
'affectedVersions' => '>=1.1.0,<2.0.0',
'source' => 'test',
'reportedAt' => '2024-01-01 00:00:00',
'composerRepository' => 'Package Repository',
'severity' => 'high',
'sources' => [
[
'name' => 'test',
'remoteId' => 'CVE-2024-1234',
],
],
],
],
],
],
],
'require' => [
'vulnerable/pkg' => '^1.0',
],
]);
// Test 1: Without --no-security-blocking, the vulnerable version 1.1.0 should be filtered out
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'update', '--dry-run' => true, '--no-audit' => true, '--no-install' => true]);
$display = $appTester->getDisplay(true);
// Should lock the secure version 1.0.0, not the vulnerable 1.1.0
self::assertStringContainsString('Locking vulnerable/pkg (1.0.0)', $display);
self::assertStringNotContainsString('Locking vulnerable/pkg (1.1.0)', $display);
// Test 2: With --no-security-blocking, the vulnerable version 1.1.0 should be allowed
$appTester = $this->getApplicationTester();
$appTester->run(['command' => 'update', '--dry-run' => true, '--no-audit' => true, '--no-install' => true, '--no-security-blocking' => true]);
$display = $appTester->getDisplay(true);
// Should lock the latest version 1.1.0 even though it's vulnerable
self::assertStringContainsString('Locking vulnerable/pkg (1.1.0)', $display);
self::assertStringNotContainsString('Locking vulnerable/pkg (1.0.0)', $display);
}
public function testBumpAfterUpdateWithoutLockfile(): void
{
$this->initTempComposer([
'repositories' => [
'packages' => [
'type' => 'package',
'package' => [
['name' => 'root/a', 'version' => '1.0.0'],
['name' => 'root/a', 'version' => '1.1.0'],
],
],
],
'require-dev' => [
'root/a' => '^1.0.0',
],
'config' => [
'lock' => false
]
]);
$appTester = $this->getApplicationTester();
$appTester->run(array_merge(['command' => 'update', '--dry-run' => true, '--no-audit' => true, '--bump-after-update' => 'dev']));
$expected = <<<OUTPUT
Loading composer repositories with package information
Updating dependencies
Package operations: 1 install, 0 updates, 0 removals
- Installing root/a (1.1.0)
Bumping dependencies
./composer.json would be updated with:
- require-dev.root/a: ^1.1.0
OUTPUT;
self::assertStringMatchesFormat(trim($expected), trim($appTester->getDisplay(true)));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/phpstan/ignore-by-php-version.neon.php | phpstan/ignore-by-php-version.neon.php | <?php declare(strict_types = 1);
// more inspiration at https://github.com/phpstan/phpstan-src/blob/master/build/ignore-by-php-version.neon.php
$includes = [];
if (PHP_VERSION_ID >= 80000) {
$includes[] = __DIR__ . '/baseline-8.4.neon';
}
$config['includes'] = $includes;
$config['parameters']['phpVersion'] = PHP_VERSION_ID;
return $config;
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/index.php | index.php | <?php
/**
* @package Grav.Core
*
* @copyright Copyright (c) 2015 - 2024 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav;
\define('GRAV_REQUEST_TIME', microtime(true));
\define('GRAV_PHP_MIN', '7.3.6');
if (PHP_SAPI === 'cli-server') {
$symfony_server = stripos(getenv('_'), 'symfony') !== false || stripos($_SERVER['SERVER_SOFTWARE'] ?? '', 'symfony') !== false || stripos($_ENV['SERVER_SOFTWARE'] ?? '', 'symfony') !== false;
if (!isset($_SERVER['PHP_CLI_ROUTER']) && !$symfony_server) {
die("PHP webserver requires a router to run Grav, please use: <pre>php -S {$_SERVER['SERVER_NAME']}:{$_SERVER['SERVER_PORT']} system/router.php</pre>");
}
}
// Ensure vendor libraries exist
$autoload = __DIR__ . '/vendor/autoload.php';
if (!is_file($autoload)) {
die('Please run: <i>bin/grav install</i>');
}
// Register the auto-loader.
$loader = require $autoload;
// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());
// Set internal encoding.
@ini_set('default_charset', 'UTF-8');
mb_internal_encoding('UTF-8');
use Grav\Common\Grav;
use RocketTheme\Toolbox\Event\Event;
// Get the Grav instance
$grav = Grav::instance(array('loader' => $loader));
// Process the page
try {
$grav->process();
} catch (\Error|\Exception $e) {
$grav->fireEvent('onFatalException', new Event(array('exception' => $e)));
throw $e;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/defines.php | system/defines.php | <?php
/**
* @package Grav\Core
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
// Some standard defines
define('GRAV', true);
define('GRAV_VERSION', '1.7.49.5');
define('GRAV_SCHEMA', '1.7.0_2020-11-20_1');
define('GRAV_TESTING', false);
// PHP minimum requirement
if (!defined('GRAV_PHP_MIN')) {
define('GRAV_PHP_MIN', '7.3.6');
}
// Directory separator
if (!defined('DS')) {
define('DS', '/');
}
// Absolute path to Grav root. This is where Grav is installed into.
if (!defined('GRAV_ROOT')) {
$path = rtrim(str_replace(DIRECTORY_SEPARATOR, DS, getenv('GRAV_ROOT') ?: getcwd()), DS);
define('GRAV_ROOT', $path ?: DS);
}
// Absolute path to Grav webroot. This is the path where your site is located in.
if (!defined('GRAV_WEBROOT')) {
$path = rtrim(getenv('GRAV_WEBROOT') ?: GRAV_ROOT, DS);
define('GRAV_WEBROOT', $path ?: DS);
}
// Relative path to user folder. This path needs to be located under GRAV_WEBROOT.
if (!defined('GRAV_USER_PATH')) {
$path = rtrim(getenv('GRAV_USER_PATH') ?: 'user', DS);
define('GRAV_USER_PATH', $path);
}
// Absolute or relative path to system folder. Defaults to GRAV_ROOT/system
// If system folder is outside of webroot, see https://github.com/getgrav/grav/issues/3297#issuecomment-810294972
if (!defined('GRAV_SYSTEM_PATH')) {
$path = rtrim(getenv('GRAV_SYSTEM_PATH') ?: 'system', DS);
define('GRAV_SYSTEM_PATH', $path);
}
// Absolute or relative path to cache folder. Defaults to GRAV_ROOT/cache
if (!defined('GRAV_CACHE_PATH')) {
$path = rtrim(getenv('GRAV_CACHE_PATH') ?: 'cache', DS);
define('GRAV_CACHE_PATH', $path);
}
// Absolute or relative path to logs folder. Defaults to GRAV_ROOT/logs
if (!defined('GRAV_LOG_PATH')) {
$path = rtrim(getenv('GRAV_LOG_PATH') ?: 'logs', DS);
define('GRAV_LOG_PATH', $path);
}
// Absolute or relative path to tmp folder. Defaults to GRAV_ROOT/tmp
if (!defined('GRAV_TMP_PATH')) {
$path = rtrim(getenv('GRAV_TMP_PATH') ?: 'tmp', DS);
define('GRAV_TMP_PATH', $path);
}
// Absolute or relative path to backup folder. Defaults to GRAV_ROOT/backup
if (!defined('GRAV_BACKUP_PATH')) {
$path = rtrim(getenv('GRAV_BACKUP_PATH') ?: 'backup', DS);
define('GRAV_BACKUP_PATH', $path);
}
unset($path);
// INTERNAL: Do not use!
define('USER_DIR', GRAV_WEBROOT . '/' . GRAV_USER_PATH . '/');
define('CACHE_DIR', (!preg_match('`^(/|[a-z]:[\\\/])`ui', GRAV_CACHE_PATH) ? GRAV_ROOT . '/' : '') . GRAV_CACHE_PATH . '/');
// DEPRECATED: Do not use!
define('CACHE_PATH', GRAV_CACHE_PATH . DS);
define('USER_PATH', GRAV_USER_PATH . DS);
define('ROOT_DIR', GRAV_ROOT . DS);
define('ASSETS_DIR', GRAV_WEBROOT . '/assets/');
define('IMAGES_DIR', GRAV_WEBROOT . '/images/');
define('ACCOUNTS_DIR', USER_DIR . 'accounts/');
define('PAGES_DIR', USER_DIR . 'pages/');
define('DATA_DIR', USER_DIR . 'data/');
define('PLUGINS_DIR', USER_DIR . 'plugins/');
define('THEMES_DIR', USER_DIR . 'themes/');
define('SYSTEM_DIR', (!preg_match('`^(/|[a-z]:[\\\/])`ui', GRAV_SYSTEM_PATH) ? GRAV_ROOT . '/' : '') . GRAV_SYSTEM_PATH . '/');
define('LIB_DIR', SYSTEM_DIR . 'src/');
define('VENDOR_DIR', GRAV_ROOT . '/vendor/');
define('LOG_DIR', (!preg_match('`^(/|[a-z]:[\\\/])`ui', GRAV_LOG_PATH) ? GRAV_ROOT . '/' : '') . GRAV_LOG_PATH . '/');
// END DEPRECATED
// Some extensions
define('CONTENT_EXT', '.md');
define('TEMPLATE_EXT', '.html.twig');
define('TWIG_EXT', '.twig');
define('PLUGIN_EXT', '.php');
define('YAML_EXT', '.yaml');
// Content types
define('RAW_CONTENT', 1);
define('TWIG_CONTENT', 2);
define('TWIG_CONTENT_LIST', 3);
define('TWIG_TEMPLATES', 4);
// Filters
define('GRAV_SANITIZE_STRING', 5001);
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/install.php | system/install.php | <?php
/**
* @package Grav\Core
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
if (!defined('GRAV_ROOT')) {
die();
}
require_once __DIR__ . '/src/Grav/Installer/Install.php';
return Grav\Installer\Install::instance();
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/router.php | system/router.php | <?php
/**
* @package Grav\Core
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
if (PHP_SAPI !== 'cli-server') {
die('This script cannot be run from browser. Run it from a CLI.');
}
$_SERVER['PHP_CLI_ROUTER'] = true;
$root = $_SERVER['DOCUMENT_ROOT'];
$path = $_SERVER['SCRIPT_NAME'];
if ($path !== '/index.php' && is_file($root . $path)) {
if (!(
// Block all direct access to files and folders beginning with a dot
strpos($path, '/.') !== false
// Block all direct access for these folders
|| preg_match('`^/(\.git|cache|bin|logs|backup|webserver-configs|tests)/`ui', $path)
// Block access to specific file types for these system folders
|| preg_match('`^/(system|vendor)/(.*)\.(txt|xml|md|html|json|yaml|yml|php|pl|py|cgi|twig|sh|bat)$`ui', $path)
// Block access to specific file types for these user folders
|| preg_match('`^/(user)/(.*)\.(txt|md|json|yaml|yml|php|pl|py|cgi|twig|sh|bat)$`ui', $path)
// Block all direct access to .md files
|| preg_match('`\.md$`ui', $path)
// Block access to specific files in the root folder
|| preg_match('`^/(LICENSE\.txt|composer\.lock|composer\.json|\.htaccess)$`ui', $path)
)) {
return false;
}
}
$grav_index = 'index.php';
/* Check the GRAV_BASEDIR environment variable and use if set */
$grav_basedir = getenv('GRAV_BASEDIR') ?: '';
if ($grav_basedir) {
$grav_index = ltrim($grav_basedir, '/') . DIRECTORY_SEPARATOR . $grav_index;
$grav_basedir = DIRECTORY_SEPARATOR . trim($grav_basedir, DIRECTORY_SEPARATOR);
define('GRAV_ROOT', str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . $grav_basedir);
}
$_SERVER = array_merge($_SERVER, $_ENV);
$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . $grav_basedir .DIRECTORY_SEPARATOR . 'index.php';
$_SERVER['SCRIPT_NAME'] = $grav_basedir . DIRECTORY_SEPARATOR . 'index.php';
$_SERVER['PHP_SELF'] = $grav_basedir . DIRECTORY_SEPARATOR . 'index.php';
error_log(sprintf('%s:%d [%d]: %s', $_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_PORT'], http_response_code(), $_SERVER['REQUEST_URI']), 4);
require $grav_index;
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/DOMLettersIterator.php | system/src/DOMLettersIterator.php | <?php
/**
* Iterates individual characters (Unicode codepoints) of DOM text and CDATA nodes
* while keeping track of their position in the document.
*
* Example:
*
* $doc = new DOMDocument();
* $doc->load('example.xml');
* foreach(new DOMLettersIterator($doc) as $letter) echo $letter;
*
* NB: If you only need characters without their position
* in the document, use DOMNode->textContent instead.
*
* @author porneL http://pornel.net
* @license Public Domain
* @url https://github.com/antoligy/dom-string-iterators
*
* @implements Iterator<int,string>
*/
final class DOMLettersIterator implements Iterator
{
/** @var DOMElement */
private $start;
/** @var DOMElement|null */
private $current;
/** @var int */
private $offset = -1;
/** @var int|null */
private $key;
/** @var array<int,string>|null */
private $letters;
/**
* expects DOMElement or DOMDocument (see DOMDocument::load and DOMDocument::loadHTML)
*
* @param DOMNode $el
*/
public function __construct(DOMNode $el)
{
if ($el instanceof DOMDocument) {
$el = $el->documentElement;
}
if (!$el instanceof DOMElement) {
throw new InvalidArgumentException('Invalid arguments, expected DOMElement or DOMDocument');
}
$this->start = $el;
}
/**
* Returns position in text as DOMText node and character offset.
* (it's NOT a byte offset, you must use mb_substr() or similar to use this offset properly).
* node may be NULL if iterator has finished.
*
* @return array
*/
public function currentTextPosition(): array
{
return [$this->current, $this->offset];
}
/**
* Returns DOMElement that is currently being iterated or NULL if iterator has finished.
*
* @return DOMElement|null
*/
public function currentElement(): ?DOMElement
{
return $this->current ? $this->current->parentNode : null;
}
// Implementation of Iterator interface
/**
* @return int|null
*/
public function key(): ?int
{
return $this->key;
}
/**
* @return void
*/
public function next(): void
{
if (null === $this->current) {
return;
}
if ($this->current->nodeType === XML_TEXT_NODE || $this->current->nodeType === XML_CDATA_SECTION_NODE) {
if ($this->offset === -1) {
preg_match_all('/./us', $this->current->textContent, $m);
$this->letters = $m[0];
}
$this->offset++;
$this->key++;
if ($this->letters && $this->offset < count($this->letters)) {
return;
}
$this->offset = -1;
}
while ($this->current->nodeType === XML_ELEMENT_NODE && $this->current->firstChild) {
$this->current = $this->current->firstChild;
if ($this->current->nodeType === XML_TEXT_NODE || $this->current->nodeType === XML_CDATA_SECTION_NODE) {
$this->next();
return;
}
}
while (!$this->current->nextSibling && $this->current->parentNode) {
$this->current = $this->current->parentNode;
if ($this->current === $this->start) {
$this->current = null;
return;
}
}
$this->current = $this->current->nextSibling;
$this->next();
}
/**
* Return the current element
* @link https://php.net/manual/en/iterator.current.php
*
* @return string|null
*/
public function current(): ?string
{
return $this->letters ? $this->letters[$this->offset] : null;
}
/**
* Checks if current position is valid
* @link https://php.net/manual/en/iterator.valid.php
*
* @return bool
*/
public function valid(): bool
{
return (bool)$this->current;
}
/**
* @return void
*/
public function rewind(): void
{
$this->current = $this->start;
$this->offset = -1;
$this->key = 0;
$this->letters = [];
$this->next();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/DOMWordsIterator.php | system/src/DOMWordsIterator.php | <?php
/**
* Iterates individual words of DOM text and CDATA nodes
* while keeping track of their position in the document.
*
* Example:
*
* $doc = new DOMDocument();
* $doc->load('example.xml');
* foreach(new DOMWordsIterator($doc) as $word) echo $word;
*
* @author pjgalbraith http://www.pjgalbraith.com
* @author porneL http://pornel.net (based on DOMLettersIterator available at http://pornel.net/source/domlettersiterator.php)
* @license Public Domain
* @url https://github.com/antoligy/dom-string-iterators
*
* @implements Iterator<int,string>
*/
final class DOMWordsIterator implements Iterator
{
/** @var DOMElement */
private $start;
/** @var DOMElement|null */
private $current;
/** @var int */
private $offset = -1;
/** @var int|null */
private $key;
/** @var array<int,array<int,int|string>>|null */
private $words;
/**
* expects DOMElement or DOMDocument (see DOMDocument::load and DOMDocument::loadHTML)
*
* @param DOMNode $el
*/
public function __construct(DOMNode $el)
{
if ($el instanceof DOMDocument) {
$el = $el->documentElement;
}
if (!$el instanceof DOMElement) {
throw new InvalidArgumentException('Invalid arguments, expected DOMElement or DOMDocument');
}
$this->start = $el;
}
/**
* Returns position in text as DOMText node and character offset.
* (it's NOT a byte offset, you must use mb_substr() or similar to use this offset properly).
* node may be NULL if iterator has finished.
*
* @return array
*/
public function currentWordPosition(): array
{
return [$this->current, $this->offset, $this->words];
}
/**
* Returns DOMElement that is currently being iterated or NULL if iterator has finished.
*
* @return DOMElement|null
*/
public function currentElement(): ?DOMElement
{
return $this->current ? $this->current->parentNode : null;
}
// Implementation of Iterator interface
/**
* Return the key of the current element
* @link https://php.net/manual/en/iterator.key.php
* @return int|null
*/
public function key(): ?int
{
return $this->key;
}
/**
* @return void
*/
public function next(): void
{
if (null === $this->current) {
return;
}
if ($this->current->nodeType === XML_TEXT_NODE || $this->current->nodeType === XML_CDATA_SECTION_NODE) {
if ($this->offset === -1) {
$this->words = preg_split("/[\n\r\t ]+/", $this->current->textContent, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE) ?: [];
}
$this->offset++;
if ($this->words && $this->offset < count($this->words)) {
$this->key++;
return;
}
$this->offset = -1;
}
while ($this->current->nodeType === XML_ELEMENT_NODE && $this->current->firstChild) {
$this->current = $this->current->firstChild;
if ($this->current->nodeType === XML_TEXT_NODE || $this->current->nodeType === XML_CDATA_SECTION_NODE) {
$this->next();
return;
}
}
while (!$this->current->nextSibling && $this->current->parentNode) {
$this->current = $this->current->parentNode;
if ($this->current === $this->start) {
$this->current = null;
return;
}
}
$this->current = $this->current->nextSibling;
$this->next();
}
/**
* Return the current element
* @link https://php.net/manual/en/iterator.current.php
* @return string|null
*/
public function current(): ?string
{
return $this->words ? (string)$this->words[$this->offset][0] : null;
}
/**
* Checks if current position is valid
* @link https://php.net/manual/en/iterator.valid.php
* @return bool
*/
public function valid(): bool
{
return (bool)$this->current;
}
public function rewind(): void
{
$this->current = $this->start;
$this->offset = -1;
$this->key = 0;
$this->words = [];
$this->next();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredDeclareNode.php | system/src/Twig/DeferredExtension/DeferredDeclareNode.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Compiler;
use Twig\Node\Node;
final class DeferredDeclareNode extends Node
{
public function compile(Compiler $compiler) : void
{
$compiler
->write("private \$deferred;\n")
;
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredNode.php | system/src/Twig/DeferredExtension/DeferredNode.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Compiler;
use Twig\Node\Node;
final class DeferredNode extends Node
{
public function compile(Compiler $compiler) : void
{
$compiler
->write("\$this->deferred->resolve(\$this, \$context, \$blocks);\n")
;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredNodeVisitorCompat.php | system/src/Twig/DeferredExtension/DeferredNodeVisitorCompat.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Environment;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;
final class DeferredNodeVisitorCompat implements NodeVisitorInterface
{
private $hasDeferred = false;
/**
* @param \Twig_NodeInterface $node
* @param Environment $env
* @return Node
*/
public function enterNode(\Twig_NodeInterface $node, Environment $env): Node
{
if (!$this->hasDeferred && $node instanceof DeferredBlockNode) {
$this->hasDeferred = true;
}
\assert($node instanceof Node);
return $node;
}
/**
* @param \Twig_NodeInterface $node
* @param Environment $env
* @return Node|null
*/
public function leaveNode(\Twig_NodeInterface $node, Environment $env): ?Node
{
if ($this->hasDeferred && $node instanceof ModuleNode) {
$node->getNode('constructor_end')->setNode('deferred_initialize', new DeferredInitializeNode());
$node->getNode('display_end')->setNode('deferred_resolve', new DeferredResolveNode());
$node->getNode('class_end')->setNode('deferred_declare', new DeferredDeclareNode());
$this->hasDeferred = false;
}
\assert($node instanceof Node);
return $node;
}
/**
* @return int
*/
public function getPriority() : int
{
return 0;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredNodeVisitor.php | system/src/Twig/DeferredExtension/DeferredNodeVisitor.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Environment;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;
final class DeferredNodeVisitor implements NodeVisitorInterface
{
private $hasDeferred = false;
public function enterNode(Node $node, Environment $env) : Node
{
if (!$this->hasDeferred && $node instanceof DeferredBlockNode) {
$this->hasDeferred = true;
}
return $node;
}
public function leaveNode(Node $node, Environment $env) : ?Node
{
if ($this->hasDeferred && $node instanceof ModuleNode) {
$node->getNode('constructor_end')->setNode('deferred_initialize', new DeferredInitializeNode());
$node->getNode('display_end')->setNode('deferred_resolve', new DeferredResolveNode());
$node->getNode('class_end')->setNode('deferred_declare', new DeferredDeclareNode());
$this->hasDeferred = false;
}
return $node;
}
public function getPriority() : int
{
return 0;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredBlockNode.php | system/src/Twig/DeferredExtension/DeferredBlockNode.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Compiler;
use Twig\Node\BlockNode;
final class DeferredBlockNode extends BlockNode
{
public function compile(Compiler $compiler) : void
{
$name = $this->getAttribute('name');
$compiler
->write("public function block_$name(\$context, array \$blocks = [])\n", "{\n")
->indent()
->write("\$this->deferred->defer(\$this, '$name');\n")
->outdent()
->write("}\n\n")
;
$compiler
->addDebugInfo($this)
->write("public function block_{$name}_deferred(\$context, array \$blocks = [])\n", "{\n")
->indent()
->subcompile($this->getNode('body'))
->write("\$this->deferred->resolve(\$this, \$context, \$blocks);\n")
->outdent()
->write("}\n\n")
;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredExtension.php | system/src/Twig/DeferredExtension/DeferredExtension.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Template;
final class DeferredExtension extends AbstractExtension
{
private $blocks = [];
public function getTokenParsers() : array
{
return [new DeferredTokenParser()];
}
public function getNodeVisitors() : array
{
if (Environment::VERSION_ID < 20000) {
// Twig 1.x support
return [new DeferredNodeVisitorCompat()];
}
return [new DeferredNodeVisitor()];
}
public function defer(Template $template, string $blockName) : void
{
$templateName = $template->getTemplateName();
$this->blocks[$templateName][] = $blockName;
$index = \count($this->blocks[$templateName]) - 1;
\ob_start(function (string $buffer) use ($index, $templateName) {
unset($this->blocks[$templateName][$index]);
return $buffer;
});
}
public function resolve(Template $template, array $context, array $blocks) : void
{
$templateName = $template->getTemplateName();
if (empty($this->blocks[$templateName])) {
return;
}
while ($blockName = \array_pop($this->blocks[$templateName])) {
$buffer = \ob_get_clean();
$blocks[$blockName] = [$template, 'block_'.$blockName.'_deferred'];
$template->displayBlock($blockName, $context, $blocks);
echo $buffer;
}
if ($parent = $template->getParent($context)) {
$this->resolve($parent, $context, $blocks);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredInitializeNode.php | system/src/Twig/DeferredExtension/DeferredInitializeNode.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Compiler;
use Twig\Node\Node;
final class DeferredInitializeNode extends Node
{
public function compile(Compiler $compiler) : void
{
$compiler
->write("\$this->deferred = \$this->env->getExtension('".DeferredExtension::class."');\n")
;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredTokenParser.php | system/src/Twig/DeferredExtension/DeferredTokenParser.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Node\BlockNode;
use Twig\Node\Node;
use Twig\Parser;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
use Twig\TokenParser\BlockTokenParser;
final class DeferredTokenParser extends AbstractTokenParser
{
private $blockTokenParser;
public function setParser(Parser $parser) : void
{
parent::setParser($parser);
$this->blockTokenParser = new BlockTokenParser();
$this->blockTokenParser->setParser($parser);
}
public function parse(Token $token) : Node
{
$stream = $this->parser->getStream();
$nameToken = $stream->next();
$deferredToken = $stream->nextIf(Token::NAME_TYPE, 'deferred');
$stream->injectTokens([$nameToken]);
$node = $this->blockTokenParser->parse($token);
if ($deferredToken) {
$this->replaceBlockNode($nameToken->getValue());
}
return $node;
}
public function getTag() : string
{
return 'block';
}
private function replaceBlockNode(string $name) : void
{
$block = $this->parser->getBlock($name)->getNode('0');
$this->parser->setBlock($name, $this->createDeferredBlockNode($block));
}
private function createDeferredBlockNode(BlockNode $block) : DeferredBlockNode
{
$name = $block->getAttribute('name');
$deferredBlock = new DeferredBlockNode($name, new Node([]), $block->getTemplateLine());
foreach ($block as $nodeName => $node) {
$deferredBlock->setNode($nodeName, $node);
}
if ($sourceContext = $block->getSourceContext()) {
$deferredBlock->setSourceContext($sourceContext);
}
return $deferredBlock;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Twig/DeferredExtension/DeferredResolveNode.php | system/src/Twig/DeferredExtension/DeferredResolveNode.php | <?php
/**
* This file is part of the rybakit/twig-deferred-extension package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Twig\DeferredExtension;
use Twig\Compiler;
use Twig\Node\Node;
final class DeferredResolveNode extends Node
{
public function compile(Compiler $compiler) : void
{
$compiler
->write("\$this->deferred->resolve(\$this, \$context, \$blocks);\n")
;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Plugin.php | system/src/Grav/Common/Plugin.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use ArrayAccess;
use Composer\Autoload\ClassLoader;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Data;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Config\Config;
use LogicException;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function defined;
use function is_bool;
use function is_string;
/**
* Class Plugin
* @package Grav\Common
*/
class Plugin implements EventSubscriberInterface, ArrayAccess
{
/** @var string */
public $name;
/** @var array */
public $features = [];
/** @var Grav */
protected $grav;
/** @var Config|null */
protected $config;
/** @var bool */
protected $active = true;
/** @var Blueprint|null */
protected $blueprint;
/** @var ClassLoader|null */
protected $loader;
/**
* By default assign all methods as listeners using the default priority.
*
* @return array
*/
public static function getSubscribedEvents()
{
$methods = get_class_methods(static::class);
$list = [];
foreach ($methods as $method) {
if (strpos($method, 'on') === 0) {
$list[$method] = [$method, 0];
}
}
return $list;
}
/**
* Constructor.
*
* @param string $name
* @param Grav $grav
* @param Config|null $config
*/
public function __construct($name, Grav $grav, Config $config = null)
{
$this->name = $name;
$this->grav = $grav;
if ($config) {
$this->setConfig($config);
}
}
/**
* @return ClassLoader|null
* @internal
*/
final public function getAutoloader(): ?ClassLoader
{
return $this->loader;
}
/**
* @param ClassLoader|null $loader
* @internal
*/
final public function setAutoloader(?ClassLoader $loader): void
{
$this->loader = $loader;
}
/**
* @param Config $config
* @return $this
*/
public function setConfig(Config $config)
{
$this->config = $config;
return $this;
}
/**
* Get configuration of the plugin.
*
* @return array
*/
public function config()
{
return $this->config["plugins.{$this->name}"] ?? [];
}
/**
* Determine if plugin is running under the admin
*
* @return bool
*/
public function isAdmin()
{
return Utils::isAdminPlugin();
}
/**
* Determine if plugin is running under the CLI
*
* @return bool
*/
public function isCli()
{
return defined('GRAV_CLI');
}
/**
* Determine if this route is in Admin and active for the plugin
*
* @param string $plugin_route
* @return bool
*/
protected function isPluginActiveAdmin($plugin_route)
{
$active = false;
/** @var Uri $uri */
$uri = $this->grav['uri'];
/** @var Config $config */
$config = $this->config ?? $this->grav['config'];
if (strpos($uri->path(), $config->get('plugins.admin.route') . '/' . $plugin_route) === false) {
$active = false;
} elseif (isset($uri->paths()[1]) && $uri->paths()[1] === $plugin_route) {
$active = true;
}
return $active;
}
/**
* @param array $events
* @return void
*/
protected function enable(array $events)
{
/** @var EventDispatcher $dispatcher */
$dispatcher = $this->grav['events'];
foreach ($events as $eventName => $params) {
if (is_string($params)) {
$dispatcher->addListener($eventName, [$this, $params]);
} elseif (is_string($params[0])) {
$dispatcher->addListener($eventName, [$this, $params[0]], $this->getPriority($params, $eventName));
} else {
foreach ($params as $listener) {
$dispatcher->addListener($eventName, [$this, $listener[0]], $this->getPriority($listener, $eventName));
}
}
}
}
/**
* @param array $params
* @param string $eventName
* @return int
*/
private function getPriority($params, $eventName)
{
$override = implode('.', ['priorities', $this->name, $eventName, $params[0]]);
return $this->grav['config']->get($override) ?? $params[1] ?? 0;
}
/**
* @param array $events
* @return void
*/
protected function disable(array $events)
{
/** @var EventDispatcher $dispatcher */
$dispatcher = $this->grav['events'];
foreach ($events as $eventName => $params) {
if (is_string($params)) {
$dispatcher->removeListener($eventName, [$this, $params]);
} elseif (is_string($params[0])) {
$dispatcher->removeListener($eventName, [$this, $params[0]]);
} else {
foreach ($params as $listener) {
$dispatcher->removeListener($eventName, [$this, $listener[0]]);
}
}
}
}
/**
* Whether or not an offset exists.
*
* @param string $offset An offset to check for.
* @return bool Returns TRUE on success or FALSE on failure.
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
if ($offset === 'title') {
$offset = 'name';
}
$blueprint = $this->getBlueprint();
return isset($blueprint[$offset]);
}
/**
* Returns the value at specified offset.
*
* @param string $offset The offset to retrieve.
* @return mixed Can return all value types.
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
if ($offset === 'title') {
$offset = 'name';
}
$blueprint = $this->getBlueprint();
return $blueprint[$offset] ?? null;
}
/**
* Assigns a value to the specified offset.
*
* @param string $offset The offset to assign the value to.
* @param mixed $value The value to set.
* @throws LogicException
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
throw new LogicException(__CLASS__ . ' blueprints cannot be modified.');
}
/**
* Unsets an offset.
*
* @param string $offset The offset to unset.
* @throws LogicException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
throw new LogicException(__CLASS__ . ' blueprints cannot be modified.');
}
/**
* @return array
*/
public function __debugInfo(): array
{
$array = (array)$this;
unset($array["\0*\0grav"]);
$array["\0*\0config"] = $this->config();
return $array;
}
/**
* This function will search a string for markdown links in a specific format. The link value can be
* optionally compared against via the $internal_regex and operated on by the callback $function
* provided.
*
* format: [plugin:myplugin_name](function_data)
*
* @param string $content The string to perform operations upon
* @param callable $function The anonymous callback function
* @param string $internal_regex Optional internal regex to extra data from
* @return string
*/
protected function parseLinks($content, $function, $internal_regex = '(.*)')
{
$regex = '/\[plugin:(?:' . preg_quote($this->name, '/') . ')\]\(' . $internal_regex . '\)/i';
$result = preg_replace_callback($regex, $function, $content);
\assert($result !== null);
return $result;
}
/**
* Merge global and page configurations.
*
* WARNING: This method modifies page header!
*
* @param PageInterface $page The page to merge the configurations with the
* plugin settings.
* @param mixed $deep false = shallow|true = recursive|merge = recursive+unique
* @param array $params Array of additional configuration options to
* merge with the plugin settings.
* @param string $type Is this 'plugins' or 'themes'
* @return Data
*/
protected function mergeConfig(PageInterface $page, $deep = false, $params = [], $type = 'plugins')
{
/** @var Config $config */
$config = $this->config ?? $this->grav['config'];
$class_name = $this->name;
$class_name_merged = $class_name . '.merged';
$defaults = $config->get($type . '.' . $class_name, []);
$page_header = $page->header();
$header = [];
if (!isset($page_header->{$class_name_merged}) && isset($page_header->{$class_name})) {
// Get default plugin configurations and retrieve page header configuration
$config = $page_header->{$class_name};
if (is_bool($config)) {
// Overwrite enabled option with boolean value in page header
$config = ['enabled' => $config];
}
// Merge page header settings using deep or shallow merging technique
$header = $this->mergeArrays($deep, $defaults, $config);
// Create new config object and set it on the page object so it's cached for next time
$page->modifyHeader($class_name_merged, new Data($header));
} elseif (isset($page_header->{$class_name_merged})) {
$merged = $page_header->{$class_name_merged};
$header = $merged->toArray();
}
if (empty($header)) {
$header = $defaults;
}
// Merge additional parameter with configuration options
$header = $this->mergeArrays($deep, $header, $params);
// Return configurations as a new data config class
return new Data($header);
}
/**
* Merge arrays based on deepness
*
* @param string|bool $deep
* @param array $array1
* @param array $array2
* @return array
*/
private function mergeArrays($deep, $array1, $array2)
{
if ($deep === 'merge') {
return Utils::arrayMergeRecursiveUnique($array1, $array2);
}
if ($deep === true) {
return array_replace_recursive($array1, $array2);
}
return array_merge($array1, $array2);
}
/**
* Persists to disk the plugin parameters currently stored in the Grav Config object
*
* @param string $name The name of the plugin whose config it should store.
* @return bool
*/
public static function saveConfig($name)
{
if (!$name) {
return false;
}
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$filename = 'config://plugins/' . $name . '.yaml';
$file = YamlFile::instance((string)$locator->findResource($filename, true, true));
$content = $grav['config']->get('plugins.' . $name);
$file->save($content);
$file->free();
unset($file);
return true;
}
public static function inheritedConfigOption(string $plugin, string $var, PageInterface $page = null, $default = null)
{
if (Utils::isAdminPlugin()) {
$page = Grav::instance()['admin']->page() ?? null;
} else {
$page = $page ?? Grav::instance()['page'] ?? null;
}
// Try to find var in the page headers
if ($page instanceof PageInterface && $page->exists()) {
// Loop over pages and look for header vars
while ($page && !$page->root()) {
$header = new Data((array)$page->header());
$value = $header->get("$plugin.$var");
if (isset($value)) {
return $value;
}
$page = $page->parent();
}
}
return Grav::instance()['config']->get("plugins.$plugin.$var", $default);
}
/**
* Simpler getter for the plugin blueprint
*
* @return Blueprint
*/
public function getBlueprint()
{
if (null === $this->blueprint) {
$this->loadBlueprint();
\assert($this->blueprint instanceof Blueprint);
}
return $this->blueprint;
}
/**
* Load blueprints.
*
* @return void
*/
protected function loadBlueprint()
{
if (null === $this->blueprint) {
$grav = Grav::instance();
/** @var Plugins $plugins */
$plugins = $grav['plugins'];
$data = $plugins->get($this->name);
\assert($data !== null);
$this->blueprint = $data->blueprints();
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GravTrait.php | system/src/Grav/Common/GravTrait.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
/**
* @deprecated 1.4 Use Grav::instance() instead.
*/
trait GravTrait
{
/** @var Grav */
protected static $grav;
/**
* @return Grav
* @deprecated 1.4 Use Grav::instance() instead.
*/
public static function getGrav()
{
user_error(__TRAIT__ . ' is deprecated since Grav 1.4, use Grav::instance() instead', E_USER_DEPRECATED);
if (null === self::$grav) {
self::$grav = Grav::instance();
}
return self::$grav;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Uri.php | system/src/Grav/Common/Uri.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Common\Config\Config;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Framework\Route\Route;
use Grav\Framework\Route\RouteFactory;
use Grav\Framework\Uri\UriFactory;
use Grav\Framework\Uri\UriPartsFilter;
use RocketTheme\Toolbox\Event\Event;
use RuntimeException;
use function array_key_exists;
use function count;
use function in_array;
use function is_array;
use function is_string;
use function strlen;
/**
* Class Uri
* @package Grav\Common
*/
class Uri
{
const HOSTNAME_REGEX = '/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/';
/** @var \Grav\Framework\Uri\Uri|null */
protected static $currentUri;
/** @var Route|null */
protected static $currentRoute;
/** @var string */
public $url;
// Uri parts.
/** @var string|null */
protected $scheme;
/** @var string|null */
protected $user;
/** @var string|null */
protected $password;
/** @var string|null */
protected $host;
/** @var int|null */
protected $port;
/** @var string */
protected $path;
/** @var string */
protected $query;
/** @var string|null */
protected $fragment;
// Internal stuff.
/** @var string */
protected $base;
/** @var string|null */
protected $basename;
/** @var string */
protected $content_path;
/** @var string|null */
protected $extension;
/** @var string */
protected $env;
/** @var array */
protected $paths;
/** @var array */
protected $queries;
/** @var array */
protected $params;
/** @var string */
protected $root;
/** @var string */
protected $setup_base;
/** @var string */
protected $root_path;
/** @var string */
protected $uri;
/** @var array */
protected $post;
/**
* Uri constructor.
* @param string|array|null $env
*/
public function __construct($env = null)
{
if (is_string($env)) {
$this->createFromString($env);
} else {
$this->createFromEnvironment(is_array($env) ? $env : $_SERVER);
}
}
/**
* Initialize the URI class with a url passed via parameter.
* Used for testing purposes.
*
* @param string $url the URL to use in the class
* @return $this
*/
public function initializeWithUrl($url = '')
{
if ($url) {
$this->createFromString($url);
}
return $this;
}
/**
* Initialize the URI class by providing url and root_path arguments
*
* @param string $url
* @param string $root_path
* @return $this
*/
public function initializeWithUrlAndRootPath($url, $root_path)
{
$this->initializeWithUrl($url);
$this->root_path = $root_path;
return $this;
}
/**
* Validate a hostname
*
* @param string $hostname The hostname
* @return bool
*/
public function validateHostname($hostname)
{
return (bool)preg_match(static::HOSTNAME_REGEX, $hostname);
}
/**
* Initializes the URI object based on the url set on the object
*
* @return void
*/
public function init()
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
/** @var Language $language */
$language = $grav['language'];
// add the port to the base for non-standard ports
if ($this->port && $config->get('system.reverse_proxy_setup') === false) {
$this->base .= ':' . $this->port;
}
// Handle custom base
$custom_base = rtrim($grav['config']->get('system.custom_base_url', ''), '/');
if ($custom_base) {
$custom_parts = parse_url($custom_base);
if ($custom_parts === false) {
throw new RuntimeException('Bad configuration: system.custom_base_url');
}
$orig_root_path = $this->root_path;
$this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : '';
if (isset($custom_parts['scheme'])) {
$this->base = $custom_parts['scheme'] . '://' . $custom_parts['host'];
$this->port = $custom_parts['port'] ?? null;
if ($this->port && $config->get('system.reverse_proxy_setup') === false) {
$this->base .= ':' . $this->port;
}
$this->root = $custom_base;
} else {
$this->root = $this->base . $this->root_path;
}
$this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri);
} else {
$this->root = $this->base . $this->root_path;
}
$this->url = $this->base . $this->uri;
$uri = Utils::replaceFirstOccurrence(static::filterPath($this->root), '', $this->url);
// remove the setup.php based base if set:
$setup_base = $grav['pages']->base();
if ($setup_base) {
$uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri);
}
$this->setup_base = $setup_base;
// process params
$uri = $this->processParams($uri, $config->get('system.param_sep'));
// set active language
$uri = $language->setActiveFromUri($uri);
// split the URL and params (and make sure that the path isn't seen as domain)
$bits = static::parseUrl('http://domain.com' . $uri);
//process fragment
if (isset($bits['fragment'])) {
$this->fragment = $bits['fragment'];
}
// Get the path. If there's no path, make sure pathinfo() still returns dirname variable
$path = $bits['path'] ?? '/';
// remove the extension if there is one set
$parts = Utils::pathinfo($path);
// set the original basename
$this->basename = $parts['basename'];
// set the extension
if (isset($parts['extension'])) {
$this->extension = $parts['extension'];
}
// Strip the file extension for valid page types
if ($this->isValidExtension($this->extension)) {
$path = Utils::replaceLastOccurrence(".{$this->extension}", '', $path);
}
// set the new url
$this->url = $this->root . $path;
$this->path = static::cleanPath($path);
$this->content_path = trim(Utils::replaceFirstOccurrence($this->base, '', $this->path), '/');
if ($this->content_path !== '') {
$this->paths = explode('/', $this->content_path);
}
// Set some Grav stuff
$grav['base_url_absolute'] = $config->get('system.custom_base_url') ?: $this->rootUrl(true);
$grav['base_url_relative'] = $this->rootUrl(false);
$grav['base_url'] = $config->get('system.absolute_urls') ? $grav['base_url_absolute'] : $grav['base_url_relative'];
RouteFactory::setRoot($this->root_path . $setup_base);
RouteFactory::setLanguage($language->getLanguageURLPrefix());
RouteFactory::setParamValueDelimiter($config->get('system.param_sep'));
}
/**
* Return URI path.
*
* @param int|null $id
* @return string|string[]
*/
public function paths($id = null)
{
if ($id !== null) {
return $this->paths[$id];
}
return $this->paths;
}
/**
* Return route to the current URI. By default route doesn't include base path.
*
* @param bool $absolute True to include full path.
* @param bool $domain True to include domain. Works only if first parameter is also true.
* @return string
*/
public function route($absolute = false, $domain = false)
{
return ($absolute ? $this->rootUrl($domain) : '') . '/' . implode('/', $this->paths);
}
/**
* Return full query string or a single query attribute.
*
* @param string|null $id Optional attribute. Get a single query attribute if set
* @param bool $raw If true and $id is not set, return the full query array. Otherwise return the query string
*
* @return string|array Returns an array if $id = null and $raw = true
*/
public function query($id = null, $raw = false)
{
if ($id !== null) {
return $this->queries[$id] ?? null;
}
if ($raw) {
return $this->queries;
}
if (!$this->queries) {
return '';
}
return http_build_query($this->queries);
}
/**
* Return all or a single query parameter as a URI compatible string.
*
* @param string|null $id Optional parameter name.
* @param boolean $array return the array format or not
* @return null|string|array
*/
public function params($id = null, $array = false)
{
$config = Grav::instance()['config'];
$sep = $config->get('system.param_sep');
$params = null;
if ($id === null) {
if ($array) {
return $this->params;
}
$output = [];
foreach ($this->params as $key => $value) {
$output[] = "{$key}{$sep}{$value}";
$params = '/' . implode('/', $output);
}
} elseif (isset($this->params[$id])) {
if ($array) {
return $this->params[$id];
}
$params = "/{$id}{$sep}{$this->params[$id]}";
}
return $params;
}
/**
* Get URI parameter.
*
* @param string $id
* @param string|false|null $default
* @return string|false|null
*/
public function param($id, $default = false)
{
if (isset($this->params[$id])) {
return html_entity_decode(rawurldecode($this->params[$id]), ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
return $default;
}
/**
* Gets the Fragment portion of a URI (eg #target)
*
* @param string|null $fragment
* @return string|null
*/
public function fragment($fragment = null)
{
if ($fragment !== null) {
$this->fragment = $fragment;
}
return $this->fragment;
}
/**
* Return URL.
*
* @param bool $include_host Include hostname.
* @return string
*/
public function url($include_host = false)
{
if ($include_host) {
return $this->url;
}
$url = Utils::replaceFirstOccurrence($this->base, '', rtrim($this->url, '/'));
return $url ?: '/';
}
/**
* Return the Path
*
* @return string The path of the URI
*/
public function path()
{
return $this->path;
}
/**
* Return the Extension of the URI
*
* @param string|null $default
* @return string|null The extension of the URI
*/
public function extension($default = null)
{
if (!$this->extension) {
$this->extension = $default;
}
return $this->extension;
}
/**
* @return string
*/
public function method()
{
$method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
}
return $method;
}
/**
* Return the scheme of the URI
*
* @param bool|null $raw
* @return string The scheme of the URI
*/
public function scheme($raw = false)
{
if (!$raw) {
$scheme = '';
if ($this->scheme) {
$scheme = $this->scheme . '://';
} elseif ($this->host) {
$scheme = '//';
}
return $scheme;
}
return $this->scheme;
}
/**
* Return the host of the URI
*
* @return string|null The host of the URI
*/
public function host()
{
return $this->host;
}
/**
* Return the port number if it can be figured out
*
* @param bool $raw
* @return int|null
*/
public function port($raw = false)
{
$port = $this->port;
// If not in raw mode and port is not set or is 0, figure it out from scheme.
if (!$raw && !$port) {
if ($this->scheme === 'http') {
$this->port = 80;
} elseif ($this->scheme === 'https') {
$this->port = 443;
}
}
return $this->port ?: null;
}
/**
* Return user
*
* @return string|null
*/
public function user()
{
return $this->user;
}
/**
* Return password
*
* @return string|null
*/
public function password()
{
return $this->password;
}
/**
* Gets the environment name
*
* @return string
*/
public function environment()
{
return $this->env;
}
/**
* Return the basename of the URI
*
* @return string The basename of the URI
*/
public function basename()
{
return $this->basename;
}
/**
* Return the full uri
*
* @param bool $include_root
* @return string
*/
public function uri($include_root = true)
{
if ($include_root) {
return $this->uri;
}
return Utils::replaceFirstOccurrence($this->root_path, '', $this->uri);
}
/**
* Return the base of the URI
*
* @return string The base of the URI
*/
public function base()
{
return $this->base;
}
/**
* Return the base relative URL including the language prefix
* or the base relative url if multi-language is not enabled
*
* @return string The base of the URI
*/
public function baseIncludingLanguage()
{
$grav = Grav::instance();
/** @var Pages $pages */
$pages = $grav['pages'];
return $pages->baseUrl(null, false);
}
/**
* Return root URL to the site.
*
* @param bool $include_host Include hostname.
* @return string
*/
public function rootUrl($include_host = false)
{
if ($include_host) {
return $this->root;
}
return Utils::replaceFirstOccurrence($this->base, '', $this->root);
}
/**
* Return current page number.
*
* @return int
*/
public function currentPage()
{
$page = (int)($this->params['page'] ?? 1);
return max(1, $page);
}
/**
* Return relative path to the referrer defaulting to current or given page.
*
* You should set the third parameter to `true` for redirects as long as you came from the same sub-site and language.
*
* @param string|null $default
* @param string|null $attributes
* @param bool $withoutBaseRoute
* @return string
*/
public function referrer($default = null, $attributes = null, bool $withoutBaseRoute = false)
{
$referrer = $_SERVER['HTTP_REFERER'] ?? null;
// Check that referrer came from our site.
if ($withoutBaseRoute) {
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
$base = $pages->baseUrl(null, true);
} else {
$base = $this->rootUrl(true);
}
// Referrer should always have host set and it should come from the same base address.
if (!is_string($referrer) || !str_starts_with($referrer, $base)) {
$referrer = $default ?: $this->route(true, true);
}
// Relative path from grav root.
$referrer = substr($referrer, strlen($base));
if ($attributes) {
$referrer .= $attributes;
}
return $referrer;
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return static::buildUrl($this->toArray());
}
/**
* @return string
*/
public function toOriginalString()
{
return static::buildUrl($this->toArray(true));
}
/**
* @param bool $full
* @return array
*/
public function toArray($full = false)
{
if ($full === true) {
$root_path = $this->root_path ?? '';
$extension = isset($this->extension) && $this->isValidExtension($this->extension) ? '.' . $this->extension : '';
$path = $root_path . $this->path . $extension;
} else {
$path = $this->path;
}
return [
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port ?: null,
'user' => $this->user,
'pass' => $this->password,
'path' => $path,
'params' => $this->params,
'query' => $this->query,
'fragment' => $this->fragment
];
}
/**
* Calculate the parameter regex based on the param_sep setting
*
* @return string
*/
public static function paramsRegex()
{
return '/\/{1,}([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/';
}
/**
* Return the IP address of the current user
*
* @return string ip address
*/
public static function ip()
{
$ip = 'UNKNOWN';
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_CF_CONNECTING_IP')) {
$ip = getenv('HTTP_CF_CONNECTING_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
$ips = array_map('trim', explode(',', getenv('HTTP_X_FORWARDED_FOR')));
$ip = array_shift($ips);
} elseif (getenv('HTTP_X_FORWARDED') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
$ip = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ip = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ip = getenv('HTTP_FORWARDED');
} elseif (getenv('REMOTE_ADDR')) {
$ip = getenv('REMOTE_ADDR');
}
return $ip;
}
/**
* Returns current Uri.
*
* @return \Grav\Framework\Uri\Uri
*/
public static function getCurrentUri()
{
if (!static::$currentUri) {
static::$currentUri = UriFactory::createFromEnvironment($_SERVER);
}
return static::$currentUri;
}
/**
* Returns current route.
*
* @return Route
*/
public static function getCurrentRoute()
{
if (!static::$currentRoute) {
/** @var Uri $uri */
$uri = Grav::instance()['uri'];
static::$currentRoute = RouteFactory::createFromLegacyUri($uri);
}
return static::$currentRoute;
}
/**
* Is this an external URL? if it starts with `http` then yes, else false
*
* @param string $url the URL in question
* @return bool is eternal state
*/
public static function isExternal($url)
{
return (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://') || 0 === strpos($url, '//') || 0 === strpos($url, 'mailto:') || 0 === strpos($url, 'tel:') || 0 === strpos($url, 'ftp://') || 0 === strpos($url, 'ftps://') || 0 === strpos($url, 'news:') || 0 === strpos($url, 'irc:') || 0 === strpos($url, 'gopher:') || 0 === strpos($url, 'nntp:') || 0 === strpos($url, 'feed:') || 0 === strpos($url, 'cvs:') || 0 === strpos($url, 'ssh:') || 0 === strpos($url, 'git:') || 0 === strpos($url, 'svn:') || 0 === strpos($url, 'hg:'));
}
/**
* The opposite of built-in PHP method parse_url()
*
* @param array $parsed_url
* @return string
*/
public static function buildUrl($parsed_url)
{
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
$authority = isset($parsed_url['host']) ? '//' : '';
$host = $parsed_url['host'] ?? '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = $parsed_url['user'] ?? '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "{$pass}@" : '';
$path = $parsed_url['path'] ?? '';
$path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path;
$query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "{$scheme}{$authority}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}";
}
/**
* @param array $params
* @return string
*/
public static function buildParams(array $params)
{
if (!$params) {
return '';
}
$grav = Grav::instance();
$sep = $grav['config']->get('system.param_sep');
$output = [];
foreach ($params as $key => $value) {
$output[] = "{$key}{$sep}{$value}";
}
return '/' . implode('/', $output);
}
/**
* Converts links from absolute '/' or relative (../..) to a Grav friendly format
*
* @param PageInterface $page the current page to use as reference
* @param string|array $url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param bool $absolute if null, will use system default, if true will use absolute links internally
* @param bool $route_only only return the route, not full URL path
* @return string|array the more friendly formatted url
*/
public static function convertUrl(PageInterface $page, $url, $type = 'link', $absolute = false, $route_only = false)
{
$grav = Grav::instance();
$uri = $grav['uri'];
// Link processing should prepend language
$language = $grav['language'];
$language_append = '';
if ($type === 'link' && $language->enabled()) {
$language_append = $language->getLanguageURLPrefix();
}
// Handle Excerpt style $url array
$url_path = is_array($url) ? $url['path'] : $url;
$external = false;
$base = $grav['base_url_relative'];
$base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
$pages_dir = $grav['locator']->findResource('page://');
// if absolute and starts with a base_url move on
if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) {
$external = true;
} elseif ($url_path === '' && isset($url['fragment'])) {
$external = true;
} elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) {
$url_path = $base_url . $url_path;
} else {
// see if page is relative to this or absolute
if (Utils::startsWith($url_path, '/')) {
$normalized_url = Utils::normalizePath($base_url . $url_path);
$normalized_path = Utils::normalizePath($pages_dir . $url_path);
} else {
$page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route();
$normalized_url = $base_url . Utils::normalizePath(rtrim($page_route, '/') . '/' . $url_path);
$normalized_path = Utils::normalizePath($page->path() . '/' . $url_path);
}
// special check to see if path checking is required.
$just_path = Utils::replaceFirstOccurrence($normalized_url, '', $normalized_path);
if ($normalized_url === '/' || $just_path === $page->path()) {
$url_path = $normalized_url;
} else {
$url_bits = static::parseUrl($normalized_path);
$full_path = $url_bits['path'];
$raw_full_path = rawurldecode($full_path);
if (file_exists($raw_full_path)) {
$full_path = $raw_full_path;
} elseif (!file_exists($full_path)) {
$full_path = false;
}
if ($full_path) {
$path_info = Utils::pathinfo($full_path);
$page_path = $path_info['dirname'];
$filename = '';
if ($url_path === '..') {
$page_path = $full_path;
} else {
// save the filename if a file is part of the path
if (is_file($full_path)) {
if ($path_info['extension'] !== 'md') {
$filename = '/' . $path_info['basename'];
}
} else {
$page_path = $full_path;
}
}
// get page instances and try to find one that fits
$instances = $grav['pages']->instances();
if (isset($instances[$page_path])) {
/** @var PageInterface $target */
$target = $instances[$page_path];
$url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
$url_path = Uri::buildUrl($url_bits);
} else {
$url_path = $normalized_url;
}
} else {
$url_path = $normalized_url;
}
}
}
// handle absolute URLs
if (is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) {
$url['scheme'] = $uri->scheme(true);
$url['host'] = $uri->host();
$url['port'] = $uri->port(true);
// check if page exists for this route, and if so, check if it has SSL enabled
$pages = $grav['pages'];
$routes = $pages->routes();
// if this is an image, get the proper path
$url_bits = Utils::pathinfo($url_path);
if (isset($url_bits['extension'])) {
$target_path = $url_bits['dirname'];
} else {
$target_path = $url_path;
}
// strip base from this path
$target_path = Utils::replaceFirstOccurrence($uri->rootUrl(), '', $target_path);
// set to / if root
if (empty($target_path)) {
$target_path = '/';
}
// look to see if this page exists and has ssl enabled
if (isset($routes[$target_path])) {
$target_page = $pages->get($routes[$target_path]);
if ($target_page) {
$ssl_enabled = $target_page->ssl();
if ($ssl_enabled !== null) {
if ($ssl_enabled) {
$url['scheme'] = 'https';
} else {
$url['scheme'] = 'http';
}
}
}
}
}
// Handle route only
if ($route_only) {
$url_path = Utils::replaceFirstOccurrence(static::filterPath($base_url), '', $url_path);
}
// transform back to string/array as needed
if (is_array($url)) {
$url['path'] = $url_path;
} else {
$url = $url_path;
}
return $url;
}
/**
* @param string $url
* @return array|false
*/
public static function parseUrl($url)
{
$grav = Grav::instance();
// Remove extra slash from streams, parse_url() doesn't like it.
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
$encodedUrl = preg_replace_callback(
'%[^:/@?&=#]+%usD',
static function ($matches) {
return rawurlencode($matches[0]);
},
$url
);
$parts = parse_url($encodedUrl);
if (false === $parts) {
return false;
}
foreach ($parts as $name => $value) {
$parts[$name] = rawurldecode($value);
}
if (!isset($parts['path'])) {
$parts['path'] = '';
}
[$stripped_path, $params] = static::extractParams($parts['path'], $grav['config']->get('system.param_sep'));
if (!empty($params)) {
$parts['path'] = $stripped_path;
$parts['params'] = $params;
}
return $parts;
}
/**
* @param string $uri
* @param string $delimiter
* @return array
*/
public static function extractParams($uri, $delimiter)
{
$params = [];
if (strpos($uri, $delimiter) !== false) {
preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$param = explode($delimiter, $match[1]);
if (count($param) === 2) {
$plain_var = htmlspecialchars(strip_tags(rawurldecode($param[1])), ENT_QUOTES, 'UTF-8');
$params[$param[0]] = $plain_var;
$uri = str_replace($match[0], '', $uri);
}
}
}
return [$uri, $params];
}
/**
* Converts links from absolute '/' or relative (../..) to a Grav friendly format
*
* @param PageInterface $page the current page to use as reference
* @param string $markdown_url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param bool|null $relative if null, will use system default, if true will use relative links internally
*
* @return string the more friendly formatted url
*/
public static function convertUrlOld(PageInterface $page, $markdown_url, $type = 'link', $relative = null)
{
$grav = Grav::instance();
$language = $grav['language'];
// Link processing should prepend language
$language_append = '';
if ($type === 'link' && $language->enabled()) {
$language_append = $language->getLanguageURLPrefix();
}
$pages_dir = $grav['locator']->findResource('page://');
if ($relative === null) {
$base = $grav['base_url'];
} else {
$base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
}
$base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
// if absolute and starts with a base_url move on
if (Utils::pathinfo($markdown_url, PATHINFO_DIRNAME) === '.' && $page->url() === '/') {
return '/' . $markdown_url;
}
// no path to convert
if ($base_url !== '' && Utils::startsWith($markdown_url, $base_url)) {
return $markdown_url;
}
// if contains only a fragment
if (Utils::startsWith($markdown_url, '#')) {
return $markdown_url;
}
$target = null;
// see if page is relative to this or absolute
if (Utils::startsWith($markdown_url, '/')) {
$normalized_url = Utils::normalizePath($base_url . $markdown_url);
$normalized_path = Utils::normalizePath($pages_dir . $markdown_url);
} else {
$normalized_url = $base_url . Utils::normalizePath($page->route() . '/' . $markdown_url);
$normalized_path = Utils::normalizePath($page->path() . '/' . $markdown_url);
}
// special check to see if path checking is required.
$just_path = Utils::replaceFirstOccurrence($normalized_url, '', $normalized_path);
if ($just_path === $page->path()) {
return $normalized_url;
}
$url_bits = parse_url($normalized_path);
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Grav.php | system/src/Grav/Common/Grav.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Composer\Autoload\ClassLoader;
use Grav\Common\Config\Config;
use Grav\Common\Config\Setup;
use Grav\Common\Helpers\Exif;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Medium\ImageMedium;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Pages;
use Grav\Common\Processors\AssetsProcessor;
use Grav\Common\Processors\BackupsProcessor;
use Grav\Common\Processors\DebuggerAssetsProcessor;
use Grav\Common\Processors\InitializeProcessor;
use Grav\Common\Processors\PagesProcessor;
use Grav\Common\Processors\PluginsProcessor;
use Grav\Common\Processors\RenderProcessor;
use Grav\Common\Processors\RequestProcessor;
use Grav\Common\Processors\SchedulerProcessor;
use Grav\Common\Processors\TasksProcessor;
use Grav\Common\Processors\ThemesProcessor;
use Grav\Common\Processors\TwigProcessor;
use Grav\Common\Scheduler\Scheduler;
use Grav\Common\Service\AccountsServiceProvider;
use Grav\Common\Service\AssetsServiceProvider;
use Grav\Common\Service\BackupsServiceProvider;
use Grav\Common\Service\ConfigServiceProvider;
use Grav\Common\Service\ErrorServiceProvider;
use Grav\Common\Service\FilesystemServiceProvider;
use Grav\Common\Service\FlexServiceProvider;
use Grav\Common\Service\InflectorServiceProvider;
use Grav\Common\Service\LoggerServiceProvider;
use Grav\Common\Service\OutputServiceProvider;
use Grav\Common\Service\PagesServiceProvider;
use Grav\Common\Service\RequestServiceProvider;
use Grav\Common\Service\SessionServiceProvider;
use Grav\Common\Service\StreamsServiceProvider;
use Grav\Common\Service\TaskServiceProvider;
use Grav\Common\Twig\Twig;
use Grav\Framework\DI\Container;
use Grav\Framework\Psr7\Response;
use Grav\Framework\RequestHandler\Middlewares\MultipartRequestSupport;
use Grav\Framework\RequestHandler\RequestHandler;
use Grav\Framework\Route\Route;
use Grav\Framework\Session\Messages;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use RocketTheme\Toolbox\Event\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use function array_key_exists;
use function call_user_func_array;
use function function_exists;
use function get_class;
use function in_array;
use function is_array;
use function is_callable;
use function is_int;
use function is_string;
use function strlen;
/**
* Grav container is the heart of Grav.
*
* @package Grav\Common
*/
class Grav extends Container
{
/** @var string Processed output for the page. */
public $output;
/** @var static The singleton instance */
protected static $instance;
/**
* @var array Contains all Services and ServicesProviders that are mapped
* to the dependency injection container.
*/
protected static $diMap = [
AccountsServiceProvider::class,
AssetsServiceProvider::class,
BackupsServiceProvider::class,
ConfigServiceProvider::class,
ErrorServiceProvider::class,
FilesystemServiceProvider::class,
FlexServiceProvider::class,
InflectorServiceProvider::class,
LoggerServiceProvider::class,
OutputServiceProvider::class,
PagesServiceProvider::class,
RequestServiceProvider::class,
SessionServiceProvider::class,
StreamsServiceProvider::class,
TaskServiceProvider::class,
'browser' => Browser::class,
'cache' => Cache::class,
'events' => EventDispatcher::class,
'exif' => Exif::class,
'plugins' => Plugins::class,
'scheduler' => Scheduler::class,
'taxonomy' => Taxonomy::class,
'themes' => Themes::class,
'twig' => Twig::class,
'uri' => Uri::class,
];
/**
* @var array All middleware processors that are processed in $this->process()
*/
protected $middleware = [
'multipartRequestSupport',
'initializeProcessor',
'pluginsProcessor',
'themesProcessor',
'requestProcessor',
'tasksProcessor',
'backupsProcessor',
'schedulerProcessor',
'assetsProcessor',
'twigProcessor',
'pagesProcessor',
'debuggerAssetsProcessor',
'renderProcessor',
];
/** @var array */
protected $initialized = [];
/**
* Reset the Grav instance.
*
* @return void
*/
public static function resetInstance(): void
{
if (self::$instance) {
// @phpstan-ignore-next-line
self::$instance = null;
}
}
/**
* Return the Grav instance. Create it if it's not already instanced
*
* @param array $values
* @return Grav
*/
public static function instance(array $values = [])
{
if (null === self::$instance) {
self::$instance = static::load($values);
/** @var ClassLoader|null $loader */
$loader = self::$instance['loader'] ?? null;
if ($loader) {
// Load fix for Deferred Twig Extension
$loader->addPsr4('Phive\\Twig\\Extensions\\Deferred\\', LIB_DIR . 'Phive/Twig/Extensions/Deferred/', true);
}
} elseif ($values) {
$instance = self::$instance;
foreach ($values as $key => $value) {
$instance->offsetSet($key, $value);
}
}
return self::$instance;
}
/**
* Get Grav version.
*
* @return string
*/
public function getVersion(): string
{
return GRAV_VERSION;
}
/**
* @return bool
*/
public function isSetup(): bool
{
return isset($this->initialized['setup']);
}
/**
* Setup Grav instance using specific environment.
*
* @param string|null $environment
* @return $this
*/
public function setup(string $environment = null)
{
if (isset($this->initialized['setup'])) {
return $this;
}
$this->initialized['setup'] = true;
// Force environment if passed to the method.
if ($environment) {
Setup::$environment = $environment;
}
// Initialize setup and streams.
$this['setup'];
$this['streams'];
return $this;
}
/**
* Initialize CLI environment.
*
* Call after `$grav->setup($environment)`
*
* - Load configuration
* - Initialize logger
* - Disable debugger
* - Set timezone, locale
* - Load plugins (call PluginsLoadedEvent)
* - Set Pages and Users type to be used in the site
*
* This method WILL NOT initialize assets, twig or pages.
*
* @return $this
*/
public function initializeCli()
{
InitializeProcessor::initializeCli($this);
return $this;
}
/**
* Process a request
*
* @return void
*/
public function process(): void
{
if (isset($this->initialized['process'])) {
return;
}
// Initialize Grav if needed.
$this->setup();
$this->initialized['process'] = true;
$container = new Container(
[
'multipartRequestSupport' => function () {
return new MultipartRequestSupport();
},
'initializeProcessor' => function () {
return new InitializeProcessor($this);
},
'backupsProcessor' => function () {
return new BackupsProcessor($this);
},
'pluginsProcessor' => function () {
return new PluginsProcessor($this);
},
'themesProcessor' => function () {
return new ThemesProcessor($this);
},
'schedulerProcessor' => function () {
return new SchedulerProcessor($this);
},
'requestProcessor' => function () {
return new RequestProcessor($this);
},
'tasksProcessor' => function () {
return new TasksProcessor($this);
},
'assetsProcessor' => function () {
return new AssetsProcessor($this);
},
'twigProcessor' => function () {
return new TwigProcessor($this);
},
'pagesProcessor' => function () {
return new PagesProcessor($this);
},
'debuggerAssetsProcessor' => function () {
return new DebuggerAssetsProcessor($this);
},
'renderProcessor' => function () {
return new RenderProcessor($this);
},
]
);
$default = static function () {
return new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-store, max-age=0'], 'Not Found');
};
$collection = new RequestHandler($this->middleware, $default, $container);
$response = $collection->handle($this['request']);
$body = $response->getBody();
/** @var Messages $messages */
$messages = $this['messages'];
// Prevent caching if session messages were displayed in the page.
$noCache = $messages->isCleared();
if ($noCache) {
$response = $response->withHeader('Cache-Control', 'no-store, max-age=0');
}
// Handle ETag and If-None-Match headers.
if ($response->getHeaderLine('ETag') === '1') {
$etag = md5($body);
$response = $response->withHeader('ETag', '"' . $etag . '"');
$search = trim($this['request']->getHeaderLine('If-None-Match'), '"');
if ($noCache === false && $search === $etag) {
$response = $response->withStatus(304);
$body = '';
}
}
// Echo page content.
$this->header($response);
echo $body;
$this['debugger']->render();
// Response object can turn off all shutdown processing. This can be used for example to speed up AJAX responses.
// Note that using this feature will also turn off response compression.
if ($response->getHeaderLine('Grav-Internal-SkipShutdown') !== '1') {
register_shutdown_function([$this, 'shutdown']);
}
}
/**
* Clean any output buffers. Useful when exiting from the application.
*
* Please use $grav->close() and $grav->redirect() instead of calling this one!
*
* @return void
*/
public function cleanOutputBuffers(): void
{
// Make sure nothing extra gets written to the response.
while (ob_get_level()) {
ob_end_clean();
}
// Work around PHP bug #8218 (8.0.17 & 8.1.4).
header_remove('Content-Encoding');
}
/**
* Terminates Grav request with a response.
*
* Please use this method instead of calling `die();` or `exit();`. Note that you need to create a response object.
*
* @param ResponseInterface $response
* @return never-return
*/
public function close(ResponseInterface $response): void
{
$this->cleanOutputBuffers();
// Close the session.
if (isset($this['session'])) {
$this['session']->close();
}
/** @var ServerRequestInterface $request */
$request = $this['request'];
/** @var Debugger $debugger */
$debugger = $this['debugger'];
$response = $debugger->logRequest($request, $response);
$body = $response->getBody();
/** @var Messages $messages */
$messages = $this['messages'];
// Prevent caching if session messages were displayed in the page.
$noCache = $messages->isCleared();
if ($noCache) {
$response = $response->withHeader('Cache-Control', 'no-store, max-age=0');
}
// Handle ETag and If-None-Match headers.
if ($response->getHeaderLine('ETag') === '1') {
$etag = md5($body);
$response = $response->withHeader('ETag', '"' . $etag . '"');
$search = trim($this['request']->getHeaderLine('If-None-Match'), '"');
if ($noCache === false && $search === $etag) {
$response = $response->withStatus(304);
$body = '';
}
}
// Echo page content.
$this->header($response);
echo $body;
exit();
}
/**
* @param ResponseInterface $response
* @return never-return
* @deprecated 1.7 Use $grav->close() instead.
*/
public function exit(ResponseInterface $response): void
{
$this->close($response);
}
/**
* Terminates Grav request and redirects browser to another location.
*
* Please use this method instead of calling `header("Location: {$url}", true, 302); exit();`.
*
* @param Route|string $route Internal route.
* @param int|null $code Redirection code (30x)
* @return never-return
*/
public function redirect($route, $code = null): void
{
$response = $this->getRedirectResponse($route, $code);
$this->close($response);
}
/**
* Returns redirect response object from Grav.
*
* @param Route|string $route Internal route.
* @param int|null $code Redirection code (30x)
* @return ResponseInterface
*/
public function getRedirectResponse($route, $code = null): ResponseInterface
{
/** @var Uri $uri */
$uri = $this['uri'];
if (is_string($route)) {
// Clean route for redirect
$route = preg_replace("#^\/[\\\/]+\/#", '/', $route);
if (null === $code) {
// Check for redirect code in the route: e.g. /new/[301], /new[301]/route or /new[301].html
$regex = '/.*(\[(30[1-7])\])(.\w+|\/.*?)?$/';
preg_match($regex, $route, $matches);
if ($matches) {
$route = str_replace($matches[1], '', $matches[0]);
$code = $matches[2];
}
}
if ($uri::isExternal($route)) {
$url = $route;
} else {
$url = rtrim($uri->rootUrl(), '/') . '/';
if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
$url .= trim($route, '/'); // Remove trailing slash
} else {
$url .= ltrim($route, '/'); // Support trailing slash default routes
}
}
} elseif ($route instanceof Route) {
$url = $route->toString(true);
} else {
throw new InvalidArgumentException('Bad $route');
}
if ($code < 300 || $code > 399) {
$code = null;
}
if ($code === null) {
$code = $this['config']->get('system.pages.redirect_default_code', 302);
}
if ($uri->extension() === 'json') {
return new Response(200, ['Content-Type' => 'application/json'], json_encode(['code' => $code, 'redirect' => $url], JSON_THROW_ON_ERROR));
}
return new Response($code, ['Location' => $url]);
}
/**
* Redirect browser to another location taking language into account (preferred)
*
* @param string $route Internal route.
* @param int $code Redirection code (30x)
* @return void
*/
public function redirectLangSafe($route, $code = null): void
{
if (!$this['uri']->isExternal($route)) {
$this->redirect($this['pages']->route($route), $code);
} else {
$this->redirect($route, $code);
}
}
/**
* Set response header.
*
* @param ResponseInterface|null $response
* @return void
*/
public function header(ResponseInterface $response = null): void
{
if (null === $response) {
/** @var PageInterface $page */
$page = $this['page'];
$response = new Response($page->httpResponseCode(), $page->httpHeaders(), '');
}
header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}");
foreach ($response->getHeaders() as $key => $values) {
// Skip internal Grav headers.
if (strpos($key, 'Grav-Internal-') === 0) {
continue;
}
foreach ($values as $i => $value) {
header($key . ': ' . $value, $i === 0);
}
}
}
/**
* Set the system locale based on the language and configuration
*
* @return void
*/
public function setLocale(): void
{
// Initialize Locale if set and configured.
if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) {
$language = $this['language']->getLanguage();
setlocale(LC_ALL, strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language);
} elseif ($this['config']->get('system.default_locale')) {
setlocale(LC_ALL, $this['config']->get('system.default_locale'));
}
}
/**
* @param object $event
* @return object
*/
public function dispatchEvent($event)
{
/** @var EventDispatcherInterface $events */
$events = $this['events'];
$eventName = get_class($event);
$timestamp = microtime(true);
$event = $events->dispatch($event);
/** @var Debugger $debugger */
$debugger = $this['debugger'];
$debugger->addEvent($eventName, $event, $events, $timestamp);
return $event;
}
/**
* Fires an event with optional parameters.
*
* @param string $eventName
* @param Event|null $event
* @return Event
*/
public function fireEvent($eventName, Event $event = null)
{
/** @var EventDispatcherInterface $events */
$events = $this['events'];
if (null === $event) {
$event = new Event();
}
$timestamp = microtime(true);
$events->dispatch($event, $eventName);
/** @var Debugger $debugger */
$debugger = $this['debugger'];
$debugger->addEvent($eventName, $event, $events, $timestamp);
return $event;
}
/**
* Set the final content length for the page and flush the buffer
*
* @return void
*/
public function shutdown(): void
{
// Prevent user abort allowing onShutdown event to run without interruptions.
if (function_exists('ignore_user_abort')) {
@ignore_user_abort(true);
}
// Close the session allowing new requests to be handled.
if (isset($this['session'])) {
$this['session']->close();
}
/** @var Config $config */
$config = $this['config'];
if ($config->get('system.debugger.shutdown.close_connection', true)) {
// Flush the response and close the connection to allow time consuming tasks to be performed without leaving
// the connection to the client open. This will make page loads to feel much faster.
// FastCGI allows us to flush all response data to the client and finish the request.
$success = function_exists('fastcgi_finish_request') ? @fastcgi_finish_request() : false;
if (!$success) {
// Unfortunately without FastCGI there is no way to force close the connection.
// We need to ask browser to close the connection for us.
if ($config->get('system.cache.gzip')) {
// Flush gzhandler buffer if gzip setting was enabled to get the size of the compressed output.
ob_end_flush();
} elseif ($config->get('system.cache.allow_webserver_gzip')) {
// Let web server to do the hard work.
header('Content-Encoding: identity');
} elseif (function_exists('apache_setenv')) {
// Without gzip we have no other choice than to prevent server from compressing the output.
// This action turns off mod_deflate which would prevent us from closing the connection.
@apache_setenv('no-gzip', '1');
} else {
// Fall back to unknown content encoding, it prevents most servers from deflating the content.
header('Content-Encoding: none');
}
// Get length and close the connection.
header('Content-Length: ' . ob_get_length());
header('Connection: close');
ob_end_flush();
@ob_flush();
flush();
}
}
// Run any time consuming tasks.
$this->fireEvent('onShutdown');
}
/**
* Magic Catch All Function
*
* Used to call closures.
*
* Source: http://stackoverflow.com/questions/419804/closures-as-class-members
*
* @param string $method
* @param array $args
* @return mixed|null
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
{
$closure = $this->{$method} ?? null;
return is_callable($closure) ? $closure(...$args) : null;
}
/**
* Measure how long it takes to do an action.
*
* @param string $timerId
* @param string $timerTitle
* @param callable $callback
* @return mixed Returns value returned by the callable.
*/
public function measureTime(string $timerId, string $timerTitle, callable $callback)
{
$debugger = $this['debugger'];
$debugger->startTimer($timerId, $timerTitle);
$result = $callback();
$debugger->stopTimer($timerId);
return $result;
}
/**
* Initialize and return a Grav instance
*
* @param array $values
* @return static
*/
protected static function load(array $values)
{
$container = new static($values);
$container['debugger'] = new Debugger();
$container['grav'] = function (Container $container) {
user_error('Calling $grav[\'grav\'] or {{ grav.grav }} is deprecated since Grav 1.6, just use $grav or {{ grav }}', E_USER_DEPRECATED);
return $container;
};
$container->registerServices();
return $container;
}
/**
* Register all services
* Services are defined in the diMap. They can either only the class
* of a Service Provider or a pair of serviceKey => serviceClass that
* gets directly mapped into the container.
*
* @return void
*/
protected function registerServices(): void
{
foreach (self::$diMap as $serviceKey => $serviceClass) {
if (is_int($serviceKey)) {
$this->register(new $serviceClass);
} else {
$this[$serviceKey] = function ($c) use ($serviceClass) {
return new $serviceClass($c);
};
}
}
}
/**
* This attempts to find media, other files, and download them
*
* @param string $path
* @return PageInterface|false
*/
public function fallbackUrl($path)
{
$path_parts = Utils::pathinfo($path);
if (!is_array($path_parts)) {
return false;
}
/** @var Uri $uri */
$uri = $this['uri'];
/** @var Config $config */
$config = $this['config'];
/** @var Pages $pages */
$pages = $this['pages'];
$page = $pages->find($path_parts['dirname'], true);
$uri_extension = strtolower($uri->extension() ?? '');
$fallback_types = $config->get('system.media.allowed_fallback_types');
$supported_types = $config->get('media.types');
$parsed_url = parse_url(rawurldecode($uri->basename()));
$media_file = $parsed_url['path'];
$event = new Event([
'uri' => $uri,
'page' => &$page,
'filename' => &$media_file,
'extension' => $uri_extension,
'allowed_fallback_types' => &$fallback_types,
'media_types' => &$supported_types
]);
$this->fireEvent('onPageFallBackUrl', $event);
// Check whitelist first, then ensure extension is a valid media type
if (!empty($fallback_types) && !in_array($uri_extension, $fallback_types, true)) {
return false;
}
if (!array_key_exists($uri_extension, $supported_types)) {
return false;
}
if ($page) {
$media = $page->media()->all();
// if this is a media object, try actions first
if (isset($media[$media_file])) {
/** @var Medium $medium */
$medium = $media[$media_file];
foreach ($uri->query(null, true) as $action => $params) {
if (in_array($action, ImageMedium::$magic_actions, true)) {
call_user_func_array([&$medium, $action], explode(',', $params));
}
}
Utils::download($medium->path(), false);
}
// unsupported media type, try to download it...
if ($uri_extension) {
$extension = $uri_extension;
} elseif (isset($path_parts['extension'])) {
$extension = $path_parts['extension'];
} else {
$extension = null;
}
if ($extension) {
$download = true;
if (in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
$download = false;
}
Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);
}
}
// Nothing found
return false;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Theme.php | system/src/Grav/Common/Theme.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Common\Config\Config;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class Theme
* @package Grav\Common
*/
class Theme extends Plugin
{
/**
* Constructor.
*
* @param Grav $grav
* @param Config $config
* @param string $name
*/
public function __construct(Grav $grav, Config $config, $name)
{
parent::__construct($name, $grav, $config);
}
/**
* Get configuration of the plugin.
*
* @return array
*/
public function config()
{
return $this->config["themes.{$this->name}"] ?? [];
}
/**
* Persists to disk the theme parameters currently stored in the Grav Config object
*
* @param string $name The name of the theme whose config it should store.
* @return bool
*/
public static function saveConfig($name)
{
if (!$name) {
return false;
}
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$filename = 'config://themes/' . $name . '.yaml';
$file = YamlFile::instance((string)$locator->findResource($filename, true, true));
$content = $grav['config']->get('themes.' . $name);
$file->save($content);
$file->free();
unset($file);
return true;
}
/**
* Load blueprints.
*
* @return void
*/
protected function loadBlueprint()
{
if (!$this->blueprint) {
$grav = Grav::instance();
/** @var Themes $themes */
$themes = $grav['themes'];
$data = $themes->get($this->name);
\assert($data !== null);
$this->blueprint = $data->blueprints();
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Yaml.php | system/src/Grav/Common/Yaml.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Framework\File\Formatter\YamlFormatter;
/**
* Class Yaml
* @package Grav\Common
*/
abstract class Yaml
{
/** @var YamlFormatter|null */
protected static $yaml;
/**
* @param string $data
* @return array
*/
public static function parse($data)
{
if (null === static::$yaml) {
static::init();
}
return static::$yaml->decode($data);
}
/**
* @param array $data
* @param int|null $inline
* @param int|null $indent
* @return string
*/
public static function dump($data, $inline = null, $indent = null)
{
if (null === static::$yaml) {
static::init();
}
return static::$yaml->encode($data, $inline, $indent);
}
/**
* @return void
*/
protected static function init()
{
$config = [
'inline' => 5,
'indent' => 2,
'native' => true,
'compat' => true
];
static::$yaml = new YamlFormatter($config);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Composer.php | system/src/Grav/Common/Composer.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use function function_exists;
/**
* Class Composer
* @package Grav\Common
*/
class Composer
{
/** @const Default composer location */
const DEFAULT_PATH = 'bin/composer.phar';
/**
* Returns the location of composer.
*
* @return string
*/
public static function getComposerLocation()
{
if (!function_exists('shell_exec') || stripos(PHP_OS, 'win') === 0) {
return self::DEFAULT_PATH;
}
// check for global composer install
$path = trim((string)shell_exec('command -v composer'));
// fall back to grav bundled composer
if (!$path || !preg_match('/(composer|composer\.phar)$/', $path)) {
$path = self::DEFAULT_PATH;
}
return $path;
}
/**
* Return the composer executable file path
*
* @return string
*/
public static function getComposerExecutor()
{
$executor = PHP_BINARY . ' ';
$composer = static::getComposerLocation();
if ($composer !== static::DEFAULT_PATH && is_executable($composer)) {
$file = fopen($composer, 'rb');
$firstLine = fgets($file);
fclose($file);
if (!preg_match('/^#!.+php/i', $firstLine)) {
$executor = '';
}
}
return $executor . $composer;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Themes.php | system/src/Grav/Common/Themes.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DirectoryIterator;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Data\Blueprints;
use Grav\Common\Data\Data;
use Grav\Framework\Psr7\Response;
use InvalidArgumentException;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function defined;
use function in_array;
use function strlen;
/**
* Class Themes
* @package Grav\Common
*/
class Themes extends Iterator
{
/** @var Grav */
protected $grav;
/** @var Config */
protected $config;
/** @var bool */
protected $inited = false;
/**
* Themes constructor.
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
parent::__construct();
$this->grav = $grav;
$this->config = $grav['config'];
// Register instance as autoloader for theme inheritance
spl_autoload_register([$this, 'autoloadTheme']);
}
/**
* @return void
*/
public function init()
{
/** @var Themes $themes */
$themes = $this->grav['themes'];
$themes->configure();
$this->initTheme();
}
/**
* @return void
*/
public function initTheme()
{
if ($this->inited === false) {
/** @var Themes $themes */
$themes = $this->grav['themes'];
try {
$instance = $themes->load();
} catch (InvalidArgumentException $e) {
throw new RuntimeException($this->current() . ' theme could not be found');
}
// Register autoloader.
if (method_exists($instance, 'autoload')) {
$instance->autoload();
}
// Register event listeners.
if ($instance instanceof EventSubscriberInterface) {
/** @var EventDispatcher $events */
$events = $this->grav['events'];
$events->addSubscriber($instance);
}
// Register blueprints.
if (is_dir('theme://blueprints/pages')) {
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('blueprints', '', ['theme://blueprints'], ['user', 'blueprints']);
}
// Register form fields.
if (method_exists($instance, 'getFormFieldTypes')) {
/** @var Plugins $plugins */
$plugins = $this->grav['plugins'];
$plugins->formFieldTypes = $instance->getFormFieldTypes() + $plugins->formFieldTypes;
}
$this->grav['theme'] = $instance;
$this->grav->fireEvent('onThemeInitialized');
$this->inited = true;
}
}
/**
* Return list of all theme data with their blueprints.
*
* @return array
*/
public function all()
{
$list = [];
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$iterator = $locator->getIterator('themes://');
/** @var DirectoryIterator $directory */
foreach ($iterator as $directory) {
if (!$directory->isDir() || $directory->isDot()) {
continue;
}
$theme = $directory->getFilename();
try {
$result = $this->get($theme);
} catch (Exception $e) {
$exception = new RuntimeException(sprintf('Theme %s: %s', $theme, $e->getMessage()), $e->getCode(), $e);
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addMessage("Theme {$theme} cannot be loaded, please check Exceptions tab", 'error');
$debugger->addException($exception);
continue;
}
if ($result) {
$list[$theme] = $result;
}
}
ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
return $list;
}
/**
* Get theme configuration or throw exception if it cannot be found.
*
* @param string $name
* @return Data|null
* @throws RuntimeException
*/
public function get($name)
{
if (!$name) {
throw new RuntimeException('Theme name not provided.');
}
$blueprints = new Blueprints('themes://');
$blueprint = $blueprints->get("{$name}/blueprints");
// Load default configuration.
$file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT);
// ensure this is a valid theme
if (!$file->exists()) {
return null;
}
// Find thumbnail.
$thumb = "themes://{$name}/thumbnail.jpg";
$path = $this->grav['locator']->findResource($thumb, false);
if ($path) {
$blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path);
}
$obj = new Data((array)$file->content(), $blueprint);
// Override with user configuration.
$obj->merge($this->config->get('themes.' . $name) ?: []);
// Save configuration always to user/config.
$file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT);
$obj->file($file);
return $obj;
}
/**
* Return name of the current theme.
*
* @return string
*/
public function current()
{
return (string)$this->config->get('system.pages.theme');
}
/**
* Load current theme.
*
* @return Theme
*/
public function load()
{
// NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
$grav = $this->grav;
$config = $this->config;
$name = $this->current();
$class = null;
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
// Start by attempting to load the theme.php file.
$file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
if ($file) {
// Local variables available in the file: $grav, $config, $name, $file
$class = include $file;
if (!\is_object($class) || !is_subclass_of($class, Theme::class, true)) {
$class = null;
}
} elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
$response = new Response(500, [], "Theme '$name' does not exist, unable to display page.");
$grav->close($response);
}
// If the class hasn't been initialized yet, guess the class name and create a new instance.
if (null === $class) {
$themeClassFormat = [
'Grav\\Theme\\' . Inflector::camelize($name),
'Grav\\Theme\\' . ucfirst($name)
];
foreach ($themeClassFormat as $themeClass) {
if (is_subclass_of($themeClass, Theme::class, true)) {
$class = new $themeClass($grav, $config, $name);
break;
}
}
}
// Finally if everything else fails, just create a new instance from the default Theme class.
if (null === $class) {
$class = new Theme($grav, $config, $name);
}
$this->config->set('theme', $config->get('themes.' . $name));
return $class;
}
/**
* Configure and prepare streams for current template.
*
* @return void
* @throws InvalidArgumentException
*/
public function configure()
{
$name = $this->current();
$config = $this->config;
$this->loadConfiguration($name, $config);
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$registered = stream_get_wrappers();
$schemes = $config->get("themes.{$name}.streams.schemes", []);
$schemes += [
'theme' => [
'type' => 'ReadOnlyStream',
'paths' => $locator->findResources("themes://{$name}", false)
]
];
foreach ($schemes as $scheme => $config) {
if (isset($config['paths'])) {
$locator->addPath($scheme, '', $config['paths']);
}
if (isset($config['prefixes'])) {
foreach ($config['prefixes'] as $prefix => $paths) {
$locator->addPath($scheme, $prefix, $paths);
}
}
if (in_array($scheme, $registered, true)) {
stream_wrapper_unregister($scheme);
}
$type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
if ($type[0] !== '\\') {
$type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
}
if (!stream_wrapper_register($scheme, $type)) {
throw new InvalidArgumentException("Stream '{$type}' could not be initialized.");
}
}
// Load languages after streams has been properly initialized
$this->loadLanguages($this->config);
}
/**
* Load theme configuration.
*
* @param string $name Theme name
* @param Config $config Configuration class
* @return void
*/
protected function loadConfiguration($name, Config $config)
{
$themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
$config->joinDefaults("themes.{$name}", $themeConfig);
}
/**
* Load theme languages.
* Reads ALL language files from theme stream and merges them.
*
* @param Config $config Configuration class
* @return void
*/
protected function loadLanguages(Config $config)
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
if ($config->get('system.languages.translations', true)) {
$language_files = array_reverse($locator->findResources('theme://languages' . YAML_EXT));
foreach ($language_files as $language_file) {
$language = CompiledYamlFile::instance($language_file)->content();
$this->grav['languages']->mergeRecursive($language);
}
$languages_folders = array_reverse($locator->findResources('theme://languages'));
foreach ($languages_folders as $languages_folder) {
$languages = [];
$iterator = new DirectoryIterator($languages_folder);
foreach ($iterator as $file) {
if ($file->getExtension() !== 'yaml') {
continue;
}
$languages[$file->getBasename('.yaml')] = CompiledYamlFile::instance($file->getPathname())->content();
}
$this->grav['languages']->mergeRecursive($languages);
}
}
}
/**
* Autoload theme classes for inheritance
*
* @param string $class Class name
* @return mixed|false FALSE if unable to load $class; Class name if
* $class is successfully loaded
*/
protected function autoloadTheme($class)
{
$prefix = 'Grav\\Theme\\';
if (false !== strpos($class, $prefix)) {
// Remove prefix from class
$class = substr($class, strlen($prefix));
$locator = $this->grav['locator'];
// First try lowercase version of the classname.
$path = strtolower($class);
$file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
if ($file) {
return include_once $file;
}
// Replace namespace tokens to directory separators
$path = $this->grav['inflector']->hyphenize($class);
$file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
// Load class
if ($file) {
return include_once $file;
}
// Try Old style theme classes
$path = preg_replace('#\\\|_(?!.+\\\)#', '/', $class);
\assert(null !== $path);
$path = strtolower($path);
$file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
// Load class
if ($file) {
return include_once $file;
}
}
return false;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Debugger.php | system/src/Grav/Common/Debugger.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Clockwork\Clockwork;
use Clockwork\DataSource\MonologDataSource;
use Clockwork\DataSource\PsrMessageDataSource;
use Clockwork\DataSource\XdebugDataSource;
use Clockwork\Helpers\ServerTiming;
use Clockwork\Request\UserData;
use Clockwork\Storage\FileStorage;
use DebugBar\DataCollector\ConfigCollector;
use DebugBar\DataCollector\DataCollectorInterface;
use DebugBar\DataCollector\ExceptionsCollector;
use DebugBar\DataCollector\MemoryCollector;
use DebugBar\DataCollector\MessagesCollector;
use DebugBar\DataCollector\PhpInfoCollector;
use DebugBar\DataCollector\RequestDataCollector;
use DebugBar\DataCollector\TimeDataCollector;
use DebugBar\DebugBar;
use DebugBar\DebugBarException;
use DebugBar\JavascriptRenderer;
use Grav\Common\Config\Config;
use Grav\Common\Processors\ProcessorInterface;
use Grav\Common\Twig\TwigClockworkDataSource;
use Grav\Framework\Psr7\Response;
use Monolog\Logger;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionObject;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Throwable;
use Twig\Environment;
use Twig\Template;
use Twig\TemplateWrapper;
use function array_slice;
use function call_user_func;
use function count;
use function define;
use function defined;
use function extension_loaded;
use function get_class;
use function gettype;
use function is_array;
use function is_bool;
use function is_object;
use function is_scalar;
use function is_string;
/**
* Class Debugger
* @package Grav\Common
*/
class Debugger
{
/** @var static */
protected static $instance;
/** @var Grav|null */
protected $grav;
/** @var Config|null */
protected $config;
/** @var JavascriptRenderer|null */
protected $renderer;
/** @var DebugBar|null */
protected $debugbar;
/** @var Clockwork|null */
protected $clockwork;
/** @var bool */
protected $enabled = false;
/** @var bool */
protected $initialized = false;
/** @var array */
protected $timers = [];
/** @var array */
protected $deprecations = [];
/** @var callable|null */
protected $errorHandler;
/** @var float */
protected $requestTime;
/** @var float */
protected $currentTime;
/** @var int */
protected $profiling = 0;
/** @var bool */
protected $censored = false;
/**
* Debugger constructor.
*/
public function __construct()
{
static::$instance = $this;
$this->currentTime = microtime(true);
if (!defined('GRAV_REQUEST_TIME')) {
define('GRAV_REQUEST_TIME', $this->currentTime);
}
$this->requestTime = $_SERVER['REQUEST_TIME_FLOAT'] ?? GRAV_REQUEST_TIME;
// Set deprecation collector.
$this->setErrorHandler();
}
/**
* @return Clockwork|null
*/
public function getClockwork(): ?Clockwork
{
return $this->enabled ? $this->clockwork : null;
}
/**
* Initialize the debugger
*
* @return $this
* @throws DebugBarException
*/
public function init()
{
if ($this->initialized) {
return $this;
}
$this->grav = Grav::instance();
$this->config = $this->grav['config'];
// Enable/disable debugger based on configuration.
$this->enabled = (bool)$this->config->get('system.debugger.enabled');
$this->censored = (bool)$this->config->get('system.debugger.censored', false);
if ($this->enabled) {
$this->initialized = true;
$clockwork = $debugbar = null;
switch ($this->config->get('system.debugger.provider', 'debugbar')) {
case 'clockwork':
$this->clockwork = $clockwork = new Clockwork();
break;
default:
$this->debugbar = $debugbar = new DebugBar();
}
$plugins_config = (array)$this->config->get('plugins');
ksort($plugins_config);
if ($clockwork) {
$log = $this->grav['log'];
$clockwork->setStorage(new FileStorage('cache://clockwork'));
if (extension_loaded('xdebug')) {
$clockwork->addDataSource(new XdebugDataSource());
}
if ($log instanceof Logger) {
$clockwork->addDataSource(new MonologDataSource($log));
}
$timeline = $clockwork->timeline();
if ($this->requestTime !== GRAV_REQUEST_TIME) {
$event = $timeline->event('Server');
$event->finalize($this->requestTime, GRAV_REQUEST_TIME);
}
if ($this->currentTime !== GRAV_REQUEST_TIME) {
$event = $timeline->event('Loading');
$event->finalize(GRAV_REQUEST_TIME, $this->currentTime);
}
$event = $timeline->event('Site Setup');
$event->finalize($this->currentTime, microtime(true));
}
if ($this->censored) {
$censored = ['CENSORED' => true];
}
if ($debugbar) {
$debugbar->addCollector(new PhpInfoCollector());
$debugbar->addCollector(new MessagesCollector());
if (!$this->censored) {
$debugbar->addCollector(new RequestDataCollector());
}
$debugbar->addCollector(new TimeDataCollector($this->requestTime));
$debugbar->addCollector(new MemoryCollector());
$debugbar->addCollector(new ExceptionsCollector());
$debugbar->addCollector(new ConfigCollector($censored ?? (array)$this->config->get('system'), 'Config'));
$debugbar->addCollector(new ConfigCollector($censored ?? $plugins_config, 'Plugins'));
$debugbar->addCollector(new ConfigCollector($this->config->get('streams.schemes'), 'Streams'));
if ($this->requestTime !== GRAV_REQUEST_TIME) {
$debugbar['time']->addMeasure('Server', $debugbar['time']->getRequestStartTime(), GRAV_REQUEST_TIME);
}
if ($this->currentTime !== GRAV_REQUEST_TIME) {
$debugbar['time']->addMeasure('Loading', GRAV_REQUEST_TIME, $this->currentTime);
}
$debugbar['time']->addMeasure('Site Setup', $this->currentTime, microtime(true));
}
$this->addMessage('Grav v' . GRAV_VERSION . ' - PHP ' . PHP_VERSION);
$this->config->debug();
if ($clockwork) {
$clockwork->info('System Configuration', $censored ?? $this->config->get('system'));
$clockwork->info('Plugins Configuration', $censored ?? $plugins_config);
$clockwork->info('Streams', $this->config->get('streams.schemes'));
}
}
return $this;
}
public function finalize(): void
{
if ($this->clockwork && $this->enabled) {
$this->stopProfiling('Profiler Analysis');
$this->addMeasures();
$deprecations = $this->getDeprecations();
$count = count($deprecations);
if (!$count) {
return;
}
/** @var UserData $userData */
$userData = $this->clockwork->userData('Deprecated');
$userData->counters([
'Deprecated' => count($deprecations)
]);
/*
foreach ($deprecations as &$deprecation) {
$d = $deprecation;
unset($d['message']);
$this->clockwork->log('deprecated', $deprecation['message'], $d);
}
unset($deprecation);
*/
$userData->table('Your site is using following deprecated features', $deprecations);
}
}
public function logRequest(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
if (!$this->enabled || !$this->clockwork) {
return $response;
}
$clockwork = $this->clockwork;
$this->finalize();
$clockwork->timeline()->finalize($request->getAttribute('request_time'));
if ($this->censored) {
$censored = 'CENSORED';
$request = $request
->withCookieParams([$censored => ''])
->withUploadedFiles([])
->withHeader('cookie', $censored);
$request = $request->withParsedBody([$censored => '']);
}
$clockwork->addDataSource(new PsrMessageDataSource($request, $response));
$clockwork->resolveRequest();
$clockwork->storeRequest();
$clockworkRequest = $clockwork->getRequest();
$response = $response
->withHeader('X-Clockwork-Id', $clockworkRequest->id)
->withHeader('X-Clockwork-Version', $clockwork::VERSION);
$response = $response->withHeader('X-Clockwork-Path', Utils::url('/__clockwork/'));
return $response->withHeader('Server-Timing', ServerTiming::fromRequest($clockworkRequest)->value());
}
public function debuggerRequest(RequestInterface $request): Response
{
$clockwork = $this->clockwork;
$headers = [
'Content-Type' => 'application/json',
'Grav-Internal-SkipShutdown' => 1
];
$path = $request->getUri()->getPath();
$clockworkDataUri = '#/__clockwork(?:/(?<id>[0-9-]+))?(?:/(?<direction>(?:previous|next)))?(?:/(?<count>\d+))?#';
if (preg_match($clockworkDataUri, $path, $matches) === false) {
$response = ['message' => 'Bad Input'];
return new Response(400, $headers, json_encode($response));
}
$id = $matches['id'] ?? null;
$direction = $matches['direction'] ?? 'latest';
$count = $matches['count'] ?? null;
$storage = $clockwork->getStorage();
if ($direction === 'previous') {
$data = $storage->previous($id, $count);
} elseif ($direction === 'next') {
$data = $storage->next($id, $count);
} elseif ($direction === 'latest' || $id === 'latest') {
$data = $storage->latest();
} else {
$data = $storage->find($id);
}
if (preg_match('#(?<id>[0-9-]+|latest)/extended#', $path)) {
$clockwork->extendRequest($data);
}
if (!$data) {
$response = ['message' => 'Not Found'];
return new Response(404, $headers, json_encode($response));
}
$data = is_array($data) ? array_map(static function ($item) {
return $item->toArray();
}, $data) : $data->toArray();
return new Response(200, $headers, json_encode($data));
}
/**
* @return void
*/
protected function addMeasures(): void
{
if (!$this->enabled) {
return;
}
$nowTime = microtime(true);
$clkTimeLine = $this->clockwork ? $this->clockwork->timeline() : null;
$debTimeLine = $this->debugbar ? $this->debugbar['time'] : null;
foreach ($this->timers as $name => $data) {
$description = $data[0];
$startTime = $data[1] ?? null;
$endTime = $data[2] ?? $nowTime;
if ($clkTimeLine) {
$event = $clkTimeLine->event($description);
$event->finalize($startTime, $endTime);
} elseif ($debTimeLine) {
if ($endTime - $startTime < 0.001) {
continue;
}
$debTimeLine->addMeasure($description ?? $name, $startTime, $endTime);
}
}
$this->timers = [];
}
/**
* Set/get the enabled state of the debugger
*
* @param bool|null $state If null, the method returns the enabled value. If set, the method sets the enabled state
* @return bool
*/
public function enabled($state = null)
{
if ($state !== null) {
$this->enabled = (bool)$state;
}
return $this->enabled;
}
/**
* Add the debugger assets to the Grav Assets
*
* @return $this
*/
public function addAssets()
{
if ($this->enabled) {
// Only add assets if Page is HTML
$page = $this->grav['page'];
if ($page->templateFormat() !== 'html') {
return $this;
}
/** @var Assets $assets */
$assets = $this->grav['assets'];
// Clockwork specific assets
if ($this->clockwork) {
if ($this->config->get('plugins.clockwork-web.enabled')) {
$route = Utils::url($this->grav['config']->get('plugins.clockwork-web.route'));
} else {
$route = 'https://github.com/getgrav/grav-plugin-clockwork-web';
}
$assets->addCss('/system/assets/debugger/clockwork.css');
$assets->addJs('/system/assets/debugger/clockwork.js', [
'id' => 'clockwork-script',
'data-route' => $route
]);
}
// Debugbar specific assets
if ($this->debugbar) {
// Add jquery library
$assets->add('jquery', 101);
$this->renderer = $this->debugbar->getJavascriptRenderer();
$this->renderer->setIncludeVendors(false);
[$css_files, $js_files] = $this->renderer->getAssets(null, JavascriptRenderer::RELATIVE_URL);
foreach ((array)$css_files as $css) {
$assets->addCss($css);
}
$assets->addCss('/system/assets/debugger/phpdebugbar.css', ['loading' => 'inline']);
foreach ((array)$js_files as $js) {
$assets->addJs($js);
}
}
}
return $this;
}
/**
* @param int $limit
* @return array
*/
public function getCaller($limit = 2)
{
$trace = debug_backtrace(false, $limit);
return array_pop($trace);
}
/**
* Adds a data collector
*
* @param DataCollectorInterface $collector
* @return $this
* @throws DebugBarException
*/
public function addCollector($collector)
{
if ($this->debugbar && !$this->debugbar->hasCollector($collector->getName())) {
$this->debugbar->addCollector($collector);
}
return $this;
}
/**
* Returns a data collector
*
* @param string $name
* @return DataCollectorInterface|null
* @throws DebugBarException
*/
public function getCollector($name)
{
if ($this->debugbar && $this->debugbar->hasCollector($name)) {
return $this->debugbar->getCollector($name);
}
return null;
}
/**
* Displays the debug bar
*
* @return $this
*/
public function render()
{
if ($this->enabled && $this->debugbar) {
// Only add assets if Page is HTML
$page = $this->grav['page'];
if (!$this->renderer || $page->templateFormat() !== 'html') {
return $this;
}
$this->addMeasures();
$this->addDeprecations();
echo $this->renderer->render();
}
return $this;
}
/**
* Sends the data through the HTTP headers
*
* @return $this
*/
public function sendDataInHeaders()
{
if ($this->enabled && $this->debugbar) {
$this->addMeasures();
$this->addDeprecations();
$this->debugbar->sendDataInHeaders();
}
return $this;
}
/**
* Returns collected debugger data.
*
* @return array|null
*/
public function getData()
{
if (!$this->enabled || !$this->debugbar) {
return null;
}
$this->addMeasures();
$this->addDeprecations();
$this->timers = [];
return $this->debugbar->getData();
}
/**
* Hierarchical Profiler support.
*
* @param callable $callable
* @param string|null $message
* @return mixed
*/
public function profile(callable $callable, string $message = null)
{
$this->startProfiling();
$response = $callable();
$this->stopProfiling($message);
return $response;
}
public function addTwigProfiler(Environment $twig): void
{
$clockwork = $this->getClockwork();
if ($clockwork) {
$source = new TwigClockworkDataSource($twig);
$source->listenToEvents();
$clockwork->addDataSource($source);
}
}
/**
* Start profiling code.
*
* @return void
*/
public function startProfiling(): void
{
if ($this->enabled && extension_loaded('tideways_xhprof')) {
$this->profiling++;
if ($this->profiling === 1) {
// @phpstan-ignore-next-line
\tideways_xhprof_enable(TIDEWAYS_XHPROF_FLAGS_NO_BUILTINS);
}
}
}
/**
* Stop profiling code. Returns profiling array or null if profiling couldn't be done.
*
* @param string|null $message
* @return array|null
*/
public function stopProfiling(string $message = null): ?array
{
$timings = null;
if ($this->enabled && extension_loaded('tideways_xhprof')) {
$profiling = $this->profiling - 1;
if ($profiling === 0) {
// @phpstan-ignore-next-line
$timings = \tideways_xhprof_disable();
$timings = $this->buildProfilerTimings($timings);
if ($this->clockwork) {
/** @var UserData $userData */
$userData = $this->clockwork->userData('Profiler');
$userData->counters([
'Calls' => count($timings)
]);
$userData->table('Profiler', $timings);
} else {
$this->addMessage($message ?? 'Profiler Analysis', 'debug', $timings);
}
}
$this->profiling = max(0, $profiling);
}
return $timings;
}
/**
* @param array $timings
* @return array
*/
protected function buildProfilerTimings(array $timings): array
{
// Filter method calls which take almost no time.
$timings = array_filter($timings, function ($value) {
return $value['wt'] > 50;
});
uasort($timings, function (array $a, array $b) {
return $b['wt'] <=> $a['wt'];
});
$table = [];
foreach ($timings as $key => $timing) {
$parts = explode('==>', $key);
$method = $this->parseProfilerCall(array_pop($parts));
$context = $this->parseProfilerCall(array_pop($parts));
// Skip redundant method calls.
if ($context === 'Grav\Framework\RequestHandler\RequestHandler::handle()') {
continue;
}
// Do not profile library calls.
if (strpos($context, 'Grav\\') !== 0) {
continue;
}
$table[] = [
'Context' => $context,
'Method' => $method,
'Calls' => $timing['ct'],
'Time (ms)' => $timing['wt'] / 1000,
];
}
return $table;
}
/**
* @param string|null $call
* @return mixed|string|null
*/
protected function parseProfilerCall(?string $call)
{
if (null === $call) {
return '';
}
if (strpos($call, '@')) {
[$call,] = explode('@', $call);
}
if (strpos($call, '::')) {
[$class, $call] = explode('::', $call);
}
if (!isset($class)) {
return $call;
}
// It is also possible to display twig files, but they are being logged in views.
/*
if (strpos($class, '__TwigTemplate_') === 0 && class_exists($class)) {
$env = new Environment();
/ ** @var Template $template * /
$template = new $class($env);
return $template->getTemplateName();
}
*/
return "{$class}::{$call}()";
}
/**
* Start a timer with an associated name and description
*
* @param string $name
* @param string|null $description
* @return $this
*/
public function startTimer($name, $description = null)
{
$this->timers[$name] = [$description, microtime(true)];
return $this;
}
/**
* Stop the named timer
*
* @param string $name
* @return $this
*/
public function stopTimer($name)
{
if (isset($this->timers[$name])) {
$endTime = microtime(true);
$this->timers[$name][] = $endTime;
}
return $this;
}
/**
* Dump variables into the Messages tab of the Debug Bar
*
* @param mixed $message
* @param string $label
* @param mixed|bool $isString
* @return $this
*/
public function addMessage($message, $label = 'info', $isString = true)
{
if ($this->enabled) {
if ($this->censored) {
if (!is_scalar($message)) {
$message = 'CENSORED';
}
if (!is_scalar($isString)) {
$isString = ['CENSORED'];
}
}
if ($this->debugbar) {
if (is_array($isString)) {
$message = $isString;
$isString = false;
} elseif (is_string($isString)) {
$message = $isString;
$isString = true;
}
$this->debugbar['messages']->addMessage($message, $label, $isString);
}
if ($this->clockwork) {
$context = $isString;
if (!is_scalar($message)) {
$context = $message;
$message = gettype($context);
}
if (is_bool($context)) {
$context = [];
} elseif (!is_array($context)) {
$type = gettype($context);
$context = [$type => $context];
}
$this->clockwork->log($label, $message, $context);
}
}
return $this;
}
/**
* @param string $name
* @param object $event
* @param EventDispatcherInterface $dispatcher
* @param float|null $time
* @return $this
*/
public function addEvent(string $name, $event, EventDispatcherInterface $dispatcher, float $time = null)
{
if ($this->enabled && $this->clockwork) {
$time = $time ?? microtime(true);
$duration = (microtime(true) - $time) * 1000;
$data = null;
if ($event && method_exists($event, '__debugInfo')) {
$data = $event;
}
$listeners = [];
foreach ($dispatcher->getListeners($name) as $listener) {
$listeners[] = $this->resolveCallable($listener);
}
$this->clockwork->addEvent($name, $data, $time, ['listeners' => $listeners, 'duration' => $duration]);
}
return $this;
}
/**
* Dump exception into the Messages tab of the Debug Bar
*
* @param Throwable $e
* @return Debugger
*/
public function addException(Throwable $e)
{
if ($this->initialized && $this->enabled) {
if ($this->debugbar) {
$this->debugbar['exceptions']->addThrowable($e);
}
if ($this->clockwork) {
/** @var UserData $exceptions */
$exceptions = $this->clockwork->userData('Exceptions');
$exceptions->data(['message' => $e->getMessage()]);
$this->clockwork->alert($e->getMessage(), ['exception' => $e]);
}
}
return $this;
}
/**
* @return void
*/
public function setErrorHandler()
{
$this->errorHandler = set_error_handler(
[$this, 'deprecatedErrorHandler']
);
}
/**
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return bool
*/
public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline)
{
if ($errno !== E_USER_DEPRECATED && $errno !== E_DEPRECATED) {
if ($this->errorHandler) {
return call_user_func($this->errorHandler, $errno, $errstr, $errfile, $errline);
}
return true;
}
if (!$this->enabled) {
return true;
}
// Figure out error scope from the error.
$scope = 'unknown';
if (stripos($errstr, 'grav') !== false) {
$scope = 'grav';
} elseif (strpos($errfile, '/twig/') !== false) {
$scope = 'twig';
// TODO: remove when upgrading to Twig 2+
if (str_contains($errstr, '#[\ReturnTypeWillChange]') || str_contains($errstr, 'Passing null to parameter')) {
return true;
}
} elseif (stripos($errfile, '/yaml/') !== false) {
$scope = 'yaml';
} elseif (strpos($errfile, '/vendor/') !== false) {
$scope = 'vendor';
}
// Clean up backtrace to make it more useful.
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
// Skip current call.
array_shift($backtrace);
// Find yaml file where the error happened.
if ($scope === 'yaml') {
foreach ($backtrace as $current) {
if (isset($current['args'])) {
foreach ($current['args'] as $arg) {
if ($arg instanceof SplFileInfo) {
$arg = $arg->getPathname();
}
if (is_string($arg) && preg_match('/.+\.(yaml|md)$/i', $arg)) {
$errfile = $arg;
$errline = 0;
break 2;
}
}
}
}
}
// Filter arguments.
$cut = 0;
$previous = null;
foreach ($backtrace as $i => &$current) {
if (isset($current['args'])) {
$args = [];
foreach ($current['args'] as $arg) {
if (is_string($arg)) {
$arg = "'" . $arg . "'";
if (mb_strlen($arg) > 100) {
$arg = 'string';
}
} elseif (is_bool($arg)) {
$arg = $arg ? 'true' : 'false';
} elseif (is_scalar($arg)) {
$arg = $arg;
} elseif (is_object($arg)) {
$arg = get_class($arg) . ' $object';
} elseif (is_array($arg)) {
$arg = '$array';
} else {
$arg = '$object';
}
$args[] = $arg;
}
$current['args'] = $args;
}
$object = $current['object'] ?? null;
unset($current['object']);
$reflection = null;
if ($object instanceof TemplateWrapper) {
$reflection = new ReflectionObject($object);
$property = $reflection->getProperty('template');
$property->setAccessible(true);
$object = $property->getValue($object);
}
if ($object instanceof Template) {
$file = $current['file'] ?? null;
if (preg_match('`(Template.php|TemplateWrapper.php)$`', $file)) {
$current = null;
continue;
}
$debugInfo = $object->getDebugInfo();
$line = 1;
if (!$reflection) {
foreach ($debugInfo as $codeLine => $templateLine) {
if ($codeLine <= $current['line']) {
$line = $templateLine;
break;
}
}
}
$src = $object->getSourceContext();
//$code = preg_split('/\r\n|\r|\n/', $src->getCode());
//$current['twig']['twig'] = trim($code[$line - 1]);
$current['twig']['file'] = $src->getPath();
$current['twig']['line'] = $line;
$prevFile = $previous['file'] ?? null;
if ($prevFile && $file === $prevFile) {
$prevLine = $previous['line'];
$line = 1;
foreach ($debugInfo as $codeLine => $templateLine) {
if ($codeLine <= $prevLine) {
$line = $templateLine;
break;
}
}
//$previous['twig']['twig'] = trim($code[$line - 1]);
$previous['twig']['file'] = $src->getPath();
$previous['twig']['line'] = $line;
}
$cut = $i;
} elseif ($object instanceof ProcessorInterface) {
$cut = $cut ?: $i;
break;
}
$previous = &$backtrace[$i];
}
unset($current);
if ($cut) {
$backtrace = array_slice($backtrace, 0, $cut + 1);
}
$backtrace = array_values(array_filter($backtrace));
// Skip vendor libraries and the method where error was triggered.
foreach ($backtrace as $i => $current) {
if (!isset($current['file'])) {
continue;
}
if (strpos($current['file'], '/vendor/') !== false) {
$cut = $i + 1;
continue;
}
if (isset($current['function']) && ($current['function'] === 'user_error' || $current['function'] === 'trigger_error')) {
$cut = $i + 1;
continue;
}
break;
}
if ($cut) {
$backtrace = array_slice($backtrace, $cut);
}
$backtrace = array_values(array_filter($backtrace));
$current = reset($backtrace);
// If the issue happened inside twig file, change the file and line to match that file.
$file = $current['twig']['file'] ?? '';
if ($file) {
$errfile = $file;
$errline = $current['twig']['line'] ?? 0;
}
$deprecation = [
'scope' => $scope,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'trace' => $backtrace,
'count' => 1
];
$this->deprecations[] = $deprecation;
// Do not pass forward.
return true;
}
/**
* @return array
*/
protected function getDeprecations(): array
{
if (!$this->deprecations) {
return [];
}
$list = [];
/** @var array $deprecated */
foreach ($this->deprecations as $deprecated) {
$list[] = $this->getDepracatedMessage($deprecated)[0];
}
return $list;
}
/**
* @return void
* @throws DebugBarException
*/
protected function addDeprecations()
{
if (!$this->deprecations) {
return;
}
$collector = new MessagesCollector('deprecated');
$this->addCollector($collector);
$collector->addMessage('Your site is using following deprecated features:');
/** @var array $deprecated */
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Plugins.php | system/src/Grav/Common/Plugins.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprints;
use Grav\Common\Data\Data;
use Grav\Common\File\CompiledYamlFile;
use Grav\Events\PluginsLoadedEvent;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcher;
use function get_class;
use function is_object;
/**
* Class Plugins
* @package Grav\Common
*/
class Plugins extends Iterator
{
/** @var array|null */
public $formFieldTypes;
/** @var bool */
private $plugins_initialized = false;
/**
* Plugins constructor.
*/
public function __construct()
{
parent::__construct();
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$iterator = $locator->getIterator('plugins://');
$plugins = [];
/** @var SplFileInfo $directory */
foreach ($iterator as $directory) {
if (!$directory->isDir()) {
continue;
}
$plugins[] = $directory->getFilename();
}
sort($plugins, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($plugins as $plugin) {
$object = $this->loadPlugin($plugin);
if ($object) {
$this->add($object);
}
}
}
/**
* @return $this
*/
public function setup()
{
$blueprints = [];
$formFields = [];
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
/** @var Plugin $plugin */
foreach ($this->items as $plugin) {
// Setup only enabled plugins.
if ($config["plugins.{$plugin->name}.enabled"] && $plugin instanceof Plugin) {
if (isset($plugin->features['blueprints'])) {
$blueprints["plugin://{$plugin->name}/blueprints"] = $plugin->features['blueprints'];
}
if (method_exists($plugin, 'getFormFieldTypes')) {
$formFields[get_class($plugin)] = $plugin->features['formfields'] ?? 0;
}
}
}
if ($blueprints) {
// Order by priority.
arsort($blueprints, SORT_NUMERIC);
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$locator->addPath('blueprints', '', array_keys($blueprints), ['system', 'blueprints']);
}
if ($formFields) {
// Order by priority.
arsort($formFields, SORT_NUMERIC);
$list = [];
foreach ($formFields as $className => $priority) {
$plugin = $this->items[$className];
$list += $plugin->getFormFieldTypes();
}
$this->formFieldTypes = $list;
}
return $this;
}
/**
* Registers all plugins.
*
* @return Plugin[] array of Plugin objects
* @throws RuntimeException
*/
public function init()
{
if ($this->plugins_initialized) {
return $this->items;
}
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
/** @var EventDispatcher $events */
$events = $grav['events'];
foreach ($this->items as $instance) {
// Register only enabled plugins.
if ($config["plugins.{$instance->name}.enabled"] && $instance instanceof Plugin) {
// Set plugin configuration.
$instance->setConfig($config);
// Register autoloader.
if (method_exists($instance, 'autoload')) {
$instance->setAutoloader($instance->autoload());
}
// Register event listeners.
$events->addSubscriber($instance);
}
}
// Plugins Loaded Event
$event = new PluginsLoadedEvent($grav, $this);
$grav->dispatchEvent($event);
$this->plugins_initialized = true;
return $this->items;
}
/**
* Add a plugin
*
* @param Plugin $plugin
* @return void
*/
public function add($plugin)
{
if (is_object($plugin)) {
$this->items[get_class($plugin)] = $plugin;
}
}
/**
* @return array
*/
public function __debugInfo(): array
{
$array = (array)$this;
unset($array["\0Grav\Common\Iterator\0iteratorUnset"]);
return $array;
}
/**
* @return Plugin[] Index of all plugins by plugin name.
*/
public static function getPlugins(): array
{
/** @var Plugins $plugins */
$plugins = Grav::instance()['plugins'];
$list = [];
foreach ($plugins as $instance) {
$list[$instance->name] = $instance;
}
return $list;
}
/**
* @param string $name Plugin name
* @return Plugin|null Plugin object or null if plugin cannot be found.
*/
public static function getPlugin(string $name)
{
$list = static::getPlugins();
return $list[$name] ?? null;
}
/**
* Return list of all plugin data with their blueprints.
*
* @return Data[]
*/
public static function all()
{
$grav = Grav::instance();
/** @var Plugins $plugins */
$plugins = $grav['plugins'];
$list = [];
foreach ($plugins as $instance) {
$name = $instance->name;
try {
$result = self::get($name);
} catch (Exception $e) {
$exception = new RuntimeException(sprintf('Plugin %s: %s', $name, $e->getMessage()), $e->getCode(), $e);
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addMessage("Plugin {$name} cannot be loaded, please check Exceptions tab", 'error');
$debugger->addException($exception);
continue;
}
if ($result) {
$list[$name] = $result;
}
}
return $list;
}
/**
* Get a plugin by name
*
* @param string $name
* @return Data|null
*/
public static function get($name)
{
$blueprints = new Blueprints('plugins://');
$blueprint = $blueprints->get("{$name}/blueprints");
// Load default configuration.
$file = CompiledYamlFile::instance("plugins://{$name}/{$name}" . YAML_EXT);
// ensure this is a valid plugin
if (!$file->exists()) {
return null;
}
$obj = new Data((array)$file->content(), $blueprint);
// Override with user configuration.
$obj->merge(Grav::instance()['config']->get('plugins.' . $name) ?: []);
// Save configuration always to user/config.
$file = CompiledYamlFile::instance("config://plugins/{$name}.yaml");
$obj->file($file);
return $obj;
}
/**
* @param string $name
* @return Plugin|null
*/
protected function loadPlugin($name)
{
// NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$class = null;
// Start by attempting to load the plugin_name.php file.
$file = $locator->findResource('plugins://' . $name . DS . $name . PLUGIN_EXT);
if (is_file($file)) {
// Local variables available in the file: $grav, $name, $file
$class = include_once $file;
if (!is_object($class) || !is_subclass_of($class, Plugin::class, true)) {
$class = null;
}
}
// If the class hasn't been initialized yet, guess the class name and create a new instance.
if (null === $class) {
$className = Inflector::camelize($name);
$pluginClassFormat = [
'Grav\\Plugin\\' . ucfirst($name). 'Plugin',
'Grav\\Plugin\\' . $className . 'Plugin',
'Grav\\Plugin\\' . $className
];
foreach ($pluginClassFormat as $pluginClass) {
if (is_subclass_of($pluginClass, Plugin::class, true)) {
$class = new $pluginClass($name, $grav);
break;
}
}
}
// Log a warning if plugin cannot be found.
if (null === $class) {
$grav['log']->addWarning(
sprintf("Plugin '%s' enabled but not found! Try clearing cache with `bin/grav clearcache`", $name)
);
}
return $class;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets.php | system/src/Grav/Common/Assets.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Closure;
use Grav\Common\Assets\Pipeline;
use Grav\Common\Assets\Traits\LegacyAssetsTrait;
use Grav\Common\Assets\Traits\TestingAssetsTrait;
use Grav\Common\Config\Config;
use Grav\Framework\Object\PropertyObject;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function array_slice;
use function call_user_func_array;
use function func_get_args;
use function is_array;
/**
* Class Assets
* @package Grav\Common
*/
class Assets extends PropertyObject
{
use TestingAssetsTrait;
use LegacyAssetsTrait;
const LINK = 'link';
const CSS = 'css';
const JS = 'js';
const JS_MODULE = 'js_module';
const LINK_COLLECTION = 'assets_link';
const CSS_COLLECTION = 'assets_css';
const JS_COLLECTION = 'assets_js';
const JS_MODULE_COLLECTION = 'assets_js_module';
const LINK_TYPE = Assets\Link::class;
const CSS_TYPE = Assets\Css::class;
const JS_TYPE = Assets\Js::class;
const JS_MODULE_TYPE = Assets\JsModule::class;
const INLINE_CSS_TYPE = Assets\InlineCss::class;
const INLINE_JS_TYPE = Assets\InlineJs::class;
const INLINE_JS_MODULE_TYPE = Assets\InlineJsModule::class;
/** @const Regex to match CSS and JavaScript files */
const DEFAULT_REGEX = '/.\.(css|js)$/i';
/** @const Regex to match CSS files */
const CSS_REGEX = '/.\.css$/i';
/** @const Regex to match JavaScript files */
const JS_REGEX = '/.\.js$/i';
/** @const Regex to match JavaScriptModyle files */
const JS_MODULE_REGEX = '/.\.mjs$/i';
/** @var string */
protected $assets_dir;
/** @var string */
protected $assets_url;
/** @var array */
protected $assets_link = [];
/** @var array */
protected $assets_css = [];
/** @var array */
protected $assets_js = [];
/** @var array */
protected $assets_js_module = [];
// Following variables come from the configuration:
/** @var bool */
protected $css_pipeline;
/** @var bool */
protected $css_pipeline_include_externals;
/** @var bool */
protected $css_pipeline_before_excludes;
/** @var bool */
protected $js_pipeline;
/** @var bool */
protected $js_pipeline_include_externals;
/** @var bool */
protected $js_pipeline_before_excludes;
/** @var bool */
protected $js_module_pipeline;
/** @var bool */
protected $js_module_pipeline_include_externals;
/** @var bool */
protected $js_module_pipeline_before_excludes;
/** @var array */
protected $pipeline_options = [];
/** @var Closure|string */
protected $fetch_command;
/** @var string */
protected $autoload;
/** @var bool */
protected $enable_asset_timestamp;
/** @var array|null */
protected $collections;
/** @var string */
protected $timestamp;
/** @var array Keeping track for order counts (for sorting) */
protected $order = [];
/**
* Initialization called in the Grav lifecycle to initialize the Assets with appropriate configuration
*
* @return void
*/
public function init()
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
$asset_config = (array)$config->get('system.assets');
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$this->assets_dir = $locator->findResource('asset://');
$this->assets_url = $locator->findResource('asset://', false);
$this->config($asset_config);
// Register any preconfigured collections
foreach ((array) $this->collections as $name => $collection) {
$this->registerCollection($name, (array)$collection);
}
}
/**
* Set up configuration options.
*
* All the class properties except 'js' and 'css' are accepted here.
* Also, an extra option 'autoload' may be passed containing an array of
* assets and/or collections that will be automatically added on startup.
*
* @param array $config Configurable options.
* @return $this
*/
public function config(array $config)
{
foreach ($config as $key => $value) {
if ($this->hasProperty($key)) {
$this->setProperty($key, $value);
} elseif (Utils::startsWith($key, 'css_') || Utils::startsWith($key, 'js_')) {
$this->pipeline_options[$key] = $value;
}
}
// Add timestamp if it's enabled
if ($this->enable_asset_timestamp) {
$this->timestamp = Grav::instance()['cache']->getKey();
}
return $this;
}
/**
* Add an asset or a collection of assets.
*
* It automatically detects the asset type (JavaScript, CSS or collection).
* You may add more than one asset passing an array as argument.
*
* @param string|string[] $asset
* @return $this
*/
public function add($asset)
{
if (!$asset) {
return $this;
}
$args = func_get_args();
// More than one asset
if (is_array($asset)) {
foreach ($asset as $index => $location) {
$params = array_slice($args, 1);
if (is_array($location)) {
$params = array_shift($params);
if (is_numeric($params)) {
$params = [ 'priority' => $params ];
}
$params = [array_replace_recursive([], $location, $params)];
$location = $index;
}
$params = array_merge([$location], $params);
call_user_func_array([$this, 'add'], $params);
}
} elseif (isset($this->collections[$asset])) {
array_shift($args);
$args = array_merge([$this->collections[$asset]], $args);
call_user_func_array([$this, 'add'], $args);
} else {
// Get extension
$path = parse_url($asset, PHP_URL_PATH);
$extension = $path ? Utils::pathinfo($path, PATHINFO_EXTENSION) : '';
// JavaScript or CSS
if ($extension !== '') {
$extension = strtolower($extension);
if ($extension === 'css') {
call_user_func_array([$this, 'addCss'], $args);
} elseif ($extension === 'js') {
call_user_func_array([$this, 'addJs'], $args);
} elseif ($extension === 'mjs') {
call_user_func_array([$this, 'addJsModule'], $args);
}
}
}
return $this;
}
/**
* @param string $collection
* @param string $type
* @param string|string[] $asset
* @param array $options
* @return $this
*/
protected function addType($collection, $type, $asset, $options)
{
if (is_array($asset)) {
foreach ($asset as $index => $location) {
$assetOptions = $options;
if (is_array($location)) {
$assetOptions = array_replace_recursive([], $options, $location);
$location = $index;
}
$this->addType($collection, $type, $location, $assetOptions);
}
return $this;
}
if ($this->isValidType($type) && isset($this->collections[$asset])) {
$this->addType($collection, $type, $this->collections[$asset], $options);
return $this;
}
// If pipeline disabled, set to position if provided, else after
if (isset($options['pipeline'])) {
if ($options['pipeline'] === false) {
$exclude_type = $this->getBaseType($type);
$excludes = strtolower($exclude_type . '_pipeline_before_excludes');
if ($this->{$excludes}) {
$default = 'after';
} else {
$default = 'before';
}
$options['position'] = $options['position'] ?? $default;
}
unset($options['pipeline']);
}
// Add timestamp
$timestamp_override = $options['timestamp'] ?? true;
if (filter_var($timestamp_override, FILTER_VALIDATE_BOOLEAN)) {
$options['timestamp'] = $this->timestamp;
} else {
$options['timestamp'] = null;
}
// Set order
$group = $options['group'] ?? 'head';
$position = $options['position'] ?? 'pipeline';
$orderKey = "{$type}|{$group}|{$position}";
if (!isset($this->order[$orderKey])) {
$this->order[$orderKey] = 0;
}
$options['order'] = $this->order[$orderKey]++;
// Create asset of correct type
$asset_object = new $type();
// If exists
if ($asset_object->init($asset, $options)) {
$this->$collection[md5($asset)] = $asset_object;
}
return $this;
}
/**
* Add a CSS asset or a collection of assets.
*
* @return $this
*/
public function addLink($asset)
{
return $this->addType($this::LINK_COLLECTION, $this::LINK_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::LINK_TYPE));
}
/**
* Add a CSS asset or a collection of assets.
*
* @return $this
*/
public function addCss($asset)
{
return $this->addType($this::CSS_COLLECTION, $this::CSS_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::CSS_TYPE));
}
/**
* Add an Inline CSS asset or a collection of assets.
*
* @return $this
*/
public function addInlineCss($asset)
{
return $this->addType($this::CSS_COLLECTION, $this::INLINE_CSS_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::INLINE_CSS_TYPE));
}
/**
* Add a JS asset or a collection of assets.
*
* @return $this
*/
public function addJs($asset)
{
return $this->addType($this::JS_COLLECTION, $this::JS_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::JS_TYPE));
}
/**
* Add an Inline JS asset or a collection of assets.
*
* @return $this
*/
public function addInlineJs($asset)
{
return $this->addType($this::JS_COLLECTION, $this::INLINE_JS_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::INLINE_JS_TYPE));
}
/**
* Add a JS asset or a collection of assets.
*
* @return $this
*/
public function addJsModule($asset)
{
return $this->addType($this::JS_MODULE_COLLECTION, $this::JS_MODULE_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::JS_MODULE_TYPE));
}
/**
* Add an Inline JS asset or a collection of assets.
*
* @return $this
*/
public function addInlineJsModule($asset)
{
return $this->addType($this::JS_MODULE_COLLECTION, $this::INLINE_JS_MODULE_TYPE, $asset, $this->unifyLegacyArguments(func_get_args(), $this::INLINE_JS_MODULE_TYPE));
}
/**
* Add/replace collection.
*
* @param string $collectionName
* @param array $assets
* @param bool $overwrite
* @return $this
*/
public function registerCollection($collectionName, array $assets, $overwrite = false)
{
if ($overwrite || !isset($this->collections[$collectionName])) {
$this->collections[$collectionName] = $assets;
}
return $this;
}
/**
* @param array $assets
* @param string $key
* @param string $value
* @param bool $sort
* @return array|false
*/
protected function filterAssets($assets, $key, $value, $sort = false)
{
$results = array_filter($assets, function ($asset) use ($key, $value) {
if ($key === 'position' && $value === 'pipeline') {
$type = $asset->getType();
if ($type === 'jsmodule') {
$type = 'js_module';
}
if ($asset->getRemote() && $this->{strtolower($type) . '_pipeline_include_externals'} === false && $asset['position'] === 'pipeline') {
if ($this->{strtolower($type) . '_pipeline_before_excludes'}) {
$asset->setPosition('after');
} else {
$asset->setPosition('before');
}
return false;
}
}
if ($asset[$key] === $value) {
return true;
}
return false;
});
if ($sort && !empty($results)) {
$results = $this->sortAssets($results);
}
return $results;
}
/**
* @param array $assets
* @return array
*/
protected function sortAssets($assets)
{
uasort($assets, static function ($a, $b) {
return $b['priority'] <=> $a['priority'] ?: $a['order'] <=> $b['order'];
});
return $assets;
}
/**
* @param string $type
* @param string $group
* @param array $attributes
* @return string
*/
public function render($type, $group = 'head', $attributes = [])
{
$before_output = '';
$pipeline_output = '';
$after_output = '';
$assets = 'assets_' . $type;
$pipeline_enabled = $type . '_pipeline';
$render_pipeline = 'render' . ucfirst($type);
$group_assets = $this->filterAssets($this->$assets, 'group', $group);
$pipeline_assets = $this->filterAssets($group_assets, 'position', 'pipeline', true);
$before_assets = $this->filterAssets($group_assets, 'position', 'before', true);
$after_assets = $this->filterAssets($group_assets, 'position', 'after', true);
// Pipeline
if ($this->{$pipeline_enabled} ?? false) {
$options = array_merge($this->pipeline_options, ['timestamp' => $this->timestamp]);
$pipeline = new Pipeline($options);
$pipeline_output = $pipeline->$render_pipeline($pipeline_assets, $group, $attributes);
} else {
foreach ($pipeline_assets as $asset) {
$pipeline_output .= $asset->render();
}
}
// Before Pipeline
foreach ($before_assets as $asset) {
$before_output .= $asset->render();
}
// After Pipeline
foreach ($after_assets as $asset) {
$after_output .= $asset->render();
}
return $before_output . $pipeline_output . $after_output;
}
/**
* Build the CSS link tags.
*
* @param string $group name of the group
* @param array $attributes
* @return string
*/
public function css($group = 'head', $attributes = [], $include_link = true)
{
$output = '';
if ($include_link) {
$output = $this->link($group, $attributes);
}
$output .= $this->render(self::CSS, $group, $attributes);
return $output;
}
/**
* Build the CSS link tags.
*
* @param string $group name of the group
* @param array $attributes
* @return string
*/
public function link($group = 'head', $attributes = [])
{
return $this->render(self::LINK, $group, $attributes);
}
/**
* Build the JavaScript script tags.
*
* @param string $group name of the group
* @param array $attributes
* @return string
*/
public function js($group = 'head', $attributes = [], $include_js_module = true)
{
$output = $this->render(self::JS, $group, $attributes);
if ($include_js_module) {
$output .= $this->jsModule($group, $attributes);
}
return $output;
}
/**
* Build the Javascript Modules tags
*
* @param string $group
* @param array $attributes
* @return string
*/
public function jsModule($group = 'head', $attributes = [])
{
return $this->render(self::JS_MODULE, $group, $attributes);
}
/**
* @param string $group
* @param array $attributes
* @return string
*/
public function all($group = 'head', $attributes = [])
{
$output = $this->css($group, $attributes, false);
$output .= $this->link($group, $attributes);
$output .= $this->js($group, $attributes, false);
$output .= $this->jsModule($group, $attributes);
return $output;
}
/**
* @param class-string $type
* @return bool
*/
protected function isValidType($type)
{
return in_array($type, [self::CSS_TYPE, self::JS_TYPE, self::JS_MODULE_TYPE]);
}
/**
* @param class-string $type
* @return string
*/
protected function getBaseType($type)
{
switch ($type) {
case $this::JS_TYPE:
case $this::INLINE_JS_TYPE:
$base_type = $this::JS;
break;
case $this::JS_MODULE_TYPE:
case $this::INLINE_JS_MODULE_TYPE:
$base_type = $this::JS_MODULE;
break;
default:
$base_type = $this::CSS;
}
return $base_type;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Taxonomy.php | system/src/Grav/Common/Taxonomy.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Common\Config\Config;
use Grav\Common\Language\Language;
use Grav\Common\Page\Collection;
use Grav\Common\Page\Interfaces\PageInterface;
use function is_string;
/**
* The Taxonomy object is a singleton that holds a reference to a 'taxonomy map'. This map is
* constructed as a multidimensional array.
*
* uses the taxonomy defined in the site.yaml file and is built when the page objects are recursed.
* Basically every time a page is found that has taxonomy references, an entry to the page is stored in
* the taxonomy map. The map has the following format:
*
* [taxonomy_type][taxonomy_value][page_path]
*
* For example:
*
* [category][blog][path/to/item1]
* [tag][grav][path/to/item1]
* [tag][grav][path/to/item2]
* [tag][dog][path/to/item3]
*/
class Taxonomy
{
/** @var array */
protected $taxonomy_map;
/** @var Grav */
protected $grav;
/** @var Language */
protected $language;
/**
* Constructor that resets the map
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
$this->language = $grav['language'];
$this->taxonomy_map[$this->language->getLanguage()] = [];
}
/**
* Takes an individual page and processes the taxonomies configured in its header. It
* then adds those taxonomies to the map
*
* @param PageInterface $page the page to process
* @param array|null $page_taxonomy
*/
public function addTaxonomy(PageInterface $page, $page_taxonomy = null)
{
if (!$page->published()) {
return;
}
if (!$page_taxonomy) {
$page_taxonomy = $page->taxonomy();
}
if (empty($page_taxonomy)) {
return;
}
/** @var Config $config */
$config = $this->grav['config'];
$taxonomies = (array)$config->get('site.taxonomies');
foreach ($taxonomies as $taxonomy) {
// Skip invalid taxonomies.
if (!\is_string($taxonomy)) {
continue;
}
$current = $page_taxonomy[$taxonomy] ?? null;
foreach ((array)$current as $item) {
$this->iterateTaxonomy($page, $taxonomy, '', $item);
}
}
}
/**
* Iterate through taxonomy fields
*
* Reduces [taxonomy_type] to dot-notation where necessary
*
* @param PageInterface $page The Page to process
* @param string $taxonomy Taxonomy type to add
* @param string $key Taxonomy type to concatenate
* @param iterable|string $value Taxonomy value to add or iterate
* @return void
*/
public function iterateTaxonomy(PageInterface $page, string $taxonomy, string $key, $value)
{
if (is_iterable($value)) {
foreach ($value as $identifier => $item) {
$identifier = "{$key}.{$identifier}";
$this->iterateTaxonomy($page, $taxonomy, $identifier, $item);
}
} elseif (is_string($value)) {
if (!empty($key)) {
$taxonomy .= $key;
}
$active = $this->language->getLanguage();
$this->taxonomy_map[$active][$taxonomy][(string) $value][$page->path()] = ['slug' => $page->slug()];
}
}
/**
* Returns a new Page object with the sub-pages containing all the values set for a
* particular taxonomy.
*
* @param array $taxonomies taxonomies to search, eg ['tag'=>['animal','cat']]
* @param string $operator can be 'or' or 'and' (defaults to 'and')
* @return Collection Collection object set to contain matches found in the taxonomy map
*/
public function findTaxonomy($taxonomies, $operator = 'and')
{
$matches = [];
$results = [];
$active = $this->language->getLanguage();
foreach ((array)$taxonomies as $taxonomy => $items) {
foreach ((array)$items as $item) {
$matches[] = $this->taxonomy_map[$active][$taxonomy][$item] ?? [];
}
}
if (strtolower($operator) === 'or') {
foreach ($matches as $match) {
$results = array_merge($results, $match);
}
} else {
$results = $matches ? array_pop($matches) : [];
foreach ($matches as $match) {
$results = array_intersect_key($results, $match);
}
}
return new Collection($results, ['taxonomies' => $taxonomies]);
}
/**
* Gets and Sets the taxonomy map
*
* @param array|null $var the taxonomy map
* @return array the taxonomy map
*/
public function taxonomy($var = null)
{
$active = $this->language->getLanguage();
if ($var) {
$this->taxonomy_map[$active] = $var;
}
return $this->taxonomy_map[$active] ?? [];
}
/**
* Gets item keys per taxonomy
*
* @param string $taxonomy taxonomy name
* @return array keys of this taxonomy
*/
public function getTaxonomyItemKeys($taxonomy)
{
$active = $this->language->getLanguage();
return isset($this->taxonomy_map[$active][$taxonomy]) ? array_keys($this->taxonomy_map[$active][$taxonomy]) : [];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Security.php | system/src/Grav/Common/Security.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Page\Pages;
use Rhukster\DomSanitizer\DOMSanitizer;
use function chr;
use function count;
use function is_array;
use function is_string;
/**
* Class Security
* @package Grav\Common
*/
class Security
{
/**
* @param string $filepath
* @param array|null $options
* @return string|null
*/
public static function detectXssFromSvgFile(string $filepath, array $options = null): ?string
{
if (file_exists($filepath) && Grav::instance()['config']->get('security.sanitize_svg')) {
$content = file_get_contents($filepath);
return static::detectXss($content, $options);
}
return null;
}
/**
* Sanitize SVG string for XSS code
*
* @param string $svg
* @return string
*/
public static function sanitizeSvgString(string $svg): string
{
if (Grav::instance()['config']->get('security.sanitize_svg')) {
$sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
$sanitized = $sanitizer->sanitize($svg);
if (is_string($sanitized)) {
$svg = $sanitized;
}
}
return $svg;
}
/**
* Sanitize SVG for XSS code
*
* @param string $file
* @return void
*/
public static function sanitizeSVG(string $file): void
{
if (file_exists($file) && Grav::instance()['config']->get('security.sanitize_svg')) {
$sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
$original_svg = file_get_contents($file);
$clean_svg = $sanitizer->sanitize($original_svg);
// Quarantine bad SVG files and throw exception
if ($clean_svg !== false ) {
file_put_contents($file, $clean_svg);
} else {
$quarantine_file = Utils::basename($file);
$quarantine_dir = 'log://quarantine';
Folder::mkdir($quarantine_dir);
file_put_contents("$quarantine_dir/$quarantine_file", $original_svg);
unlink($file);
throw new Exception('SVG could not be sanitized, it has been moved to the logs/quarantine folder');
}
}
}
/**
* Detect XSS code in Grav pages
*
* @param Pages $pages
* @param bool $route
* @param callable|null $status
* @return array
*/
public static function detectXssFromPages(Pages $pages, $route = true, callable $status = null)
{
$routes = $pages->getList(null, 0, true);
// Remove duplicate for homepage
unset($routes['/']);
$list = [];
// This needs Symfony 4.1 to work
$status && $status([
'type' => 'count',
'steps' => count($routes),
]);
foreach (array_keys($routes) as $route) {
$status && $status([
'type' => 'progress',
]);
try {
$page = $pages->find($route);
if ($page->exists()) {
// call the content to load/cache it
$header = (array) $page->header();
$content = $page->value('content');
$data = ['header' => $header, 'content' => $content];
$results = static::detectXssFromArray($data);
if (!empty($results)) {
$list[$page->rawRoute()] = $results;
}
}
} catch (Exception $e) {
continue;
}
}
return $list;
}
/**
* Detect XSS in an array or strings such as $_POST or $_GET
*
* @param array $array Array such as $_POST or $_GET
* @param array|null $options Extra options to be passed.
* @param string $prefix Prefix for returned values.
* @return array Returns flatten list of potentially dangerous input values, such as 'data.content'.
*/
public static function detectXssFromArray(array $array, string $prefix = '', array $options = null)
{
if (null === $options) {
$options = static::getXssDefaults();
}
$list = [[]];
foreach ($array as $key => $value) {
if (is_array($value)) {
$list[] = static::detectXssFromArray($value, $prefix . $key . '.', $options);
}
if ($result = static::detectXss($value, $options)) {
$list[] = [$prefix . $key => $result];
}
}
return array_merge(...$list);
}
/**
* Determine if string potentially has a XSS attack. This simple function does not catch all XSS and it is likely to
*
* return false positives because of it tags all potentially dangerous HTML tags and attributes without looking into
* their content.
*
* @param string|null $string The string to run XSS detection logic on
* @param array|null $options
* @return string|null Type of XSS vector if the given `$string` may contain XSS, false otherwise.
*
* Copies the code from: https://github.com/symphonycms/xssfilter/blob/master/extension.driver.php#L138
*/
public static function detectXss($string, array $options = null): ?string
{
// Skip any null or non string values
if (null === $string || !is_string($string) || empty($string)) {
return null;
}
if (null === $options) {
$options = static::getXssDefaults();
}
$enabled_rules = (array)($options['enabled_rules'] ?? null);
$dangerous_tags = (array)($options['dangerous_tags'] ?? null);
if (!$dangerous_tags) {
$enabled_rules['dangerous_tags'] = false;
}
$invalid_protocols = (array)($options['invalid_protocols'] ?? null);
if (!$invalid_protocols) {
$enabled_rules['invalid_protocols'] = false;
}
$enabled_rules = array_filter($enabled_rules, static function ($val) { return !empty($val); });
if (!$enabled_rules) {
return null;
}
// Keep a copy of the original string before cleaning up
$orig = $string;
// URL decode
$string = urldecode($string);
// Convert Hexadecimals
$string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) {
return chr(hexdec($m[2]));
}, $string);
// Clean up entities
$string = preg_replace('!(&#[0-9]+);?!u', '$1;', $string);
// Decode entities
$string = html_entity_decode($string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
// Strip whitespace characters
$string = preg_replace('!\s!u', ' ', $string);
$stripped = preg_replace('!\s!u', '', $string);
// Set the patterns we'll test against
$patterns = [
// Match any attribute starting with "on" or xmlns
'on_events' => '#(<[^>]+[a-z\x00-\x20\"\'\/])(on[a-z]+|xmlns)\s*=[\s|\'\"].*[\s|\'\"]>#iUu',
// Match javascript:, livescript:, vbscript:, mocha:, feed: and data: protocols
'invalid_protocols' => '#(' . implode('|', array_map('preg_quote', $invalid_protocols, ['#'])) . ')(:|\&\#58)\S.*?#iUu',
// Match -moz-bindings
'moz_binding' => '#-moz-binding[a-z\x00-\x20]*:#u',
// Match style attributes
'html_inline_styles' => '#(<[^>]+[a-z\x00-\x20\"\'\/])(style=[^>]*(url\:|x\:expression).*)>?#iUu',
// Match potentially dangerous tags
'dangerous_tags' => '#</*(' . implode('|', array_map('preg_quote', $dangerous_tags, ['#'])) . ')[^>]*>?#ui'
];
// Iterate over rules and return label if fail
foreach ($patterns as $name => $regex) {
if (!empty($enabled_rules[$name])) {
if (preg_match($regex, $string) || preg_match($regex, $stripped) || preg_match($regex, $orig)) {
return $name;
}
}
}
return null;
}
public static function getXssDefaults(): array
{
/** @var Config $config */
$config = Grav::instance()['config'];
return [
'enabled_rules' => $config->get('security.xss_enabled'),
'dangerous_tags' => array_map('trim', $config->get('security.xss_dangerous_tags')),
'invalid_protocols' => array_map('trim', $config->get('security.xss_invalid_protocols')),
];
}
public static function cleanDangerousTwig(string $string): string
{
if ($string === '') {
return $string;
}
$bad_twig = [
'twig_array_map',
'twig_array_filter',
'call_user_func',
'registerUndefinedFunctionCallback',
'undefined_functions',
'twig.getFunction',
'core.setEscaper',
'twig.safe_functions',
'read_file',
];
$string = preg_replace('/(({{\s*|{%\s*)[^}]*?(' . implode('|', $bad_twig) . ')[^}]*?(\s*}}|\s*%}))/i', '{# $1 #}', $string);
return $string;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Utils.php | system/src/Grav/Common/Utils.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DateTime;
use DateTimeZone;
use Exception;
use Grav\Common\Flex\Types\Pages\PageObject;
use Grav\Common\Helpers\Truncator;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Pages;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Media\Interfaces\MediaInterface;
use InvalidArgumentException;
use Negotiation\Accept;
use Negotiation\Negotiator;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function array_key_exists;
use function array_slice;
use function count;
use function extension_loaded;
use function function_exists;
use function in_array;
use function is_array;
use function is_callable;
use function is_string;
use function strlen;
/**
* Class Utils
* @package Grav\Common
*/
abstract class Utils
{
/** @var array */
protected static $nonces = [];
protected const ROOTURL_REGEX = '{^((?:http[s]?:\/\/[^\/]+)|(?:\/\/[^\/]+))(.*)}';
// ^((?:http[s]?:)?[\/]?(?:\/))
/**
* Simple helper method to make getting a Grav URL easier
*
* @param string|object $input
* @param bool $domain
* @param bool $fail_gracefully
* @return string|false
*/
public static function url($input, $domain = false, $fail_gracefully = false)
{
if ((!is_string($input) && !is_callable([$input, '__toString'])) || !trim($input)) {
if ($fail_gracefully) {
$input = '/';
} else {
return false;
}
}
$input = (string)$input;
if (Uri::isExternal($input)) {
return $input;
}
$grav = Grav::instance();
/** @var Uri $uri */
$uri = $grav['uri'];
$resource = false;
if (static::contains((string)$input, '://')) {
// Url contains a scheme (https:// , user:// etc).
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$parts = Uri::parseUrl($input);
if (is_array($parts)) {
// Make sure we always have scheme, host, port and path.
$scheme = $parts['scheme'] ?? '';
$host = $parts['host'] ?? '';
$port = $parts['port'] ?? '';
$path = $parts['path'] ?? '';
if ($scheme && !$port) {
// If URL has a scheme, we need to check if it's one of Grav streams.
if (!$locator->schemeExists($scheme)) {
// If scheme does not exists as a stream, assume it's external.
return str_replace(' ', '%20', $input);
}
// Attempt to find the resource (because of parse_url() we need to put host back to path).
$resource = $locator->findResource("{$scheme}://{$host}{$path}", false);
if ($resource === false) {
if (!$fail_gracefully) {
return false;
}
// Return location where the file would be if it was saved.
$resource = $locator->findResource("{$scheme}://{$host}{$path}", false, true);
}
} elseif ($host || $port) {
// If URL doesn't have scheme but has host or port, it is external.
return str_replace(' ', '%20', $input);
}
if (!empty($resource)) {
// Add query string back.
if (isset($parts['query'])) {
$resource .= '?' . $parts['query'];
}
// Add fragment back.
if (isset($parts['fragment'])) {
$resource .= '#' . $parts['fragment'];
}
}
} else {
// Not a valid URL (can still be a stream).
$resource = $locator->findResource($input, false);
}
} else {
// Just a path.
/** @var Pages $pages */
$pages = $grav['pages'];
// Is this a page?
$page = $pages->find($input, true);
if ($page && $page->routable()) {
return $page->url($domain);
}
$root = preg_quote($uri->rootUrl(), '#');
$pattern = '#(' . $root . '$|' . $root . '/)#';
if (!empty($root) && preg_match($pattern, $input, $matches)) {
$input = static::replaceFirstOccurrence($matches[0], '', $input);
}
$input = ltrim($input, '/');
$resource = $input;
}
if (!$fail_gracefully && $resource === false) {
return false;
}
$domain = $domain ?: $grav['config']->get('system.absolute_urls', false);
return rtrim($uri->rootUrl($domain), '/') . '/' . ($resource ?: '');
}
/**
* Helper method to find the full path to a file, be it a stream, a relative path, or
* already a full path
*
* @param string $path
* @return string
*/
public static function fullPath($path)
{
$locator = Grav::instance()['locator'];
if ($locator->isStream($path)) {
$path = $locator->findResource($path, true);
} elseif (!static::startsWith($path, GRAV_ROOT)) {
$base_url = Grav::instance()['base_url'];
$path = GRAV_ROOT . '/' . ltrim(static::replaceFirstOccurrence($base_url, '', $path), '/');
}
return $path;
}
/**
* Check if the $haystack string starts with the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function startsWith($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
foreach ((array)$needle as $each_needle) {
$status = $each_needle === '' || $compare_func((string) $haystack, $each_needle) === 0;
if ($status) {
break;
}
}
return $status;
}
/**
* Check if the $haystack string ends with the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function endsWith($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strrpos' : 'mb_strripos';
foreach ((array)$needle as $each_needle) {
$expectedPosition = mb_strlen((string) $haystack) - mb_strlen($each_needle);
$status = $each_needle === '' || $compare_func((string) $haystack, $each_needle, 0) === $expectedPosition;
if ($status) {
break;
}
}
return $status;
}
/**
* Check if the $haystack string contains the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function contains($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
foreach ((array)$needle as $each_needle) {
$status = $each_needle === '' || $compare_func((string) $haystack, $each_needle) !== false;
if ($status) {
break;
}
}
return $status;
}
/**
* Function that can match wildcards
*
* match_wildcard('foo*', $test), // TRUE
* match_wildcard('bar*', $test), // FALSE
* match_wildcard('*bar*', $test), // TRUE
* match_wildcard('**blob**', $test), // TRUE
* match_wildcard('*a?d*', $test), // TRUE
* match_wildcard('*etc**', $test) // TRUE
*
* @param string $wildcard_pattern
* @param string $haystack
* @return false|int
*/
public static function matchWildcard($wildcard_pattern, $haystack)
{
$regex = str_replace(
array("\*", "\?"), // wildcard chars
array('.*', '.'), // regexp chars
preg_quote($wildcard_pattern, '/')
);
return preg_match('/^' . $regex . '$/is', $haystack);
}
/**
* Render simple template filling up the variables in it. If value is not defined, leave it as it was.
*
* @param string $template Template string
* @param array $variables Variables with values
* @param array $brackets Optional array of opening and closing brackets or symbols
* @return string Final string filled with values
*/
public static function simpleTemplate(string $template, array $variables, array $brackets = ['{', '}']): string
{
$opening = $brackets[0] ?? '{';
$closing = $brackets[1] ?? '}';
$expression = '/' . preg_quote($opening, '/') . '(.*?)' . preg_quote($closing, '/') . '/';
$callback = static function ($match) use ($variables) {
return $variables[$match[1]] ?? $match[0];
};
return preg_replace_callback($expression, $callback, $template);
}
/**
* Returns the substring of a string up to a specified needle. if not found, return the whole haystack
*
* @param string $haystack
* @param string $needle
* @param bool $case_sensitive
*
* @return string
*/
public static function substrToString($haystack, $needle, $case_sensitive = true)
{
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
if (static::contains($haystack, $needle, $case_sensitive)) {
return mb_substr($haystack, 0, $compare_func($haystack, $needle, $case_sensitive));
}
return $haystack;
}
/**
* Utility method to replace only the first occurrence in a string
*
* @param string $search
* @param string $replace
* @param string $subject
*
* @return string
*/
public static function replaceFirstOccurrence($search, $replace, $subject)
{
if (!$search) {
return $subject;
}
$pos = mb_strpos($subject, $search);
if ($pos !== false) {
$subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
}
return $subject;
}
/**
* Utility method to replace only the last occurrence in a string
*
* @param string $search
* @param string $replace
* @param string $subject
* @return string
*/
public static function replaceLastOccurrence($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
}
return $subject;
}
/**
* Multibyte compatible substr_replace
*
* @param string $original
* @param string $replacement
* @param int $position
* @param int $length
* @return string
*/
public static function mb_substr_replace($original, $replacement, $position, $length)
{
$startString = mb_substr($original, 0, $position, 'UTF-8');
$endString = mb_substr($original, $position + $length, mb_strlen($original), 'UTF-8');
return $startString . $replacement . $endString;
}
/**
* Merge two objects into one.
*
* @param object $obj1
* @param object $obj2
*
* @return object
*/
public static function mergeObjects($obj1, $obj2)
{
return (object)array_merge((array)$obj1, (array)$obj2);
}
/**
* @param array $array
* @return bool
*/
public static function isAssoc(array $array)
{
return (array_values($array) !== $array);
}
/**
* Lowercase an entire array. Useful when combined with `in_array()`
*
* @param array $a
* @return array|false
*/
public static function arrayLower(array $a)
{
return array_map('mb_strtolower', $a);
}
/**
* Simple function to remove item/s in an array by value
*
* @param array $search
* @param string|array $value
* @return array
*/
public static function arrayRemoveValue(array $search, $value)
{
foreach ((array)$value as $val) {
$key = array_search($val, $search);
if ($key !== false) {
unset($search[$key]);
}
}
return $search;
}
/**
* Recursive Merge with uniqueness
*
* @param array $array1
* @param array $array2
* @return array
*/
public static function arrayMergeRecursiveUnique($array1, $array2)
{
if (empty($array1)) {
// Optimize the base case
return $array2;
}
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$value = static::arrayMergeRecursiveUnique($array1[$key], $value);
}
$array1[$key] = $value;
}
return $array1;
}
/**
* Returns an array with the differences between $array1 and $array2
*
* @param array $array1
* @param array $array2
* @return array
*/
public static function arrayDiffMultidimensional($array1, $array2)
{
$result = array();
foreach ($array1 as $key => $value) {
if (!is_array($array2) || !array_key_exists($key, $array2)) {
$result[$key] = $value;
continue;
}
if (is_array($value)) {
$recursiveArrayDiff = static::ArrayDiffMultidimensional($value, $array2[$key]);
if (count($recursiveArrayDiff)) {
$result[$key] = $recursiveArrayDiff;
}
continue;
}
if ($value != $array2[$key]) {
$result[$key] = $value;
}
}
return $result;
}
/**
* Array combine but supports different array lengths
*
* @param array $arr1
* @param array $arr2
* @return array|false
*/
public static function arrayCombine($arr1, $arr2)
{
$count = min(count($arr1), count($arr2));
return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}
/**
* Array is associative or not
*
* @param array $arr
* @return bool
*/
public static function arrayIsAssociative($arr)
{
if ([] === $arr) {
return false;
}
return array_keys($arr) !== range(0, count($arr) - 1);
}
/**
* Return the Grav date formats allowed
*
* @return array
*/
public static function dateFormats()
{
$now = new DateTime();
$date_formats = [
'd-m-Y H:i' => 'd-m-Y H:i (e.g. ' . $now->format('d-m-Y H:i') . ')',
'Y-m-d H:i' => 'Y-m-d H:i (e.g. ' . $now->format('Y-m-d H:i') . ')',
'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. ' . $now->format('m/d/Y h:i a') . ')',
'H:i d-m-Y' => 'H:i d-m-Y (e.g. ' . $now->format('H:i d-m-Y') . ')',
'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. ' . $now->format('h:i a m/d/Y') . ')',
];
$default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
if ($default_format) {
$date_formats = array_merge([$default_format => $default_format . ' (e.g. ' . $now->format($default_format) . ')'], $date_formats);
}
return $date_formats;
}
/**
* Get current date/time
*
* @param string|null $default_format
* @return string
* @throws Exception
*/
public static function dateNow($default_format = null)
{
$now = new DateTime();
if (null === $default_format) {
$default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
}
return $now->format($default_format);
}
/**
* Truncate text by number of characters but can cut off words.
*
* @param string $string
* @param int $limit Max number of characters.
* @param bool $up_to_break truncate up to breakpoint after char count
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
* @return string
*/
public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '…')
{
// return with no change if string is shorter than $limit
if (mb_strlen($string) <= $limit) {
return $string;
}
// is $break present between $limit and the end of the string?
if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
if ($breakpoint < mb_strlen($string) - 1) {
$string = mb_substr($string, 0, $breakpoint) . $pad;
}
} else {
$string = mb_substr($string, 0, $limit) . $pad;
}
return $string;
}
/**
* Truncate text by number of characters in a "word-safe" manor.
*
* @param string $string
* @param int $limit
* @return string
*/
public static function safeTruncate($string, $limit = 150)
{
return static::truncate($string, $limit, true);
}
/**
* Truncate HTML by number of characters. not "word-safe"!
*
* @param string $text
* @param int $length in characters
* @param string $ellipsis
* @return string
*/
public static function truncateHtml($text, $length = 100, $ellipsis = '...')
{
return Truncator::truncateLetters($text, $length, $ellipsis);
}
/**
* Truncate HTML by number of characters in a "word-safe" manor.
*
* @param string $text
* @param int $length in words
* @param string $ellipsis
* @return string
*/
public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
{
return Truncator::truncateWords($text, $length, $ellipsis);
}
/**
* Generate a random string of a given length
*
* @param int $length
* @return string
*/
public static function generateRandomString($length = 5)
{
return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}
/**
* Generates a random string with configurable length, prefix and suffix.
* Unlike the built-in `uniqid()`, this string is non-conflicting and safe
*
* @param int $length
* @param array $options
* @return string
* @throws Exception
*/
public static function uniqueId(int $length = 13, array $options = []): string
{
$options = array_merge(['prefix' => '', 'suffix' => ''], $options);
$bytes = random_bytes(ceil($length / 2));
return $options['prefix'] . substr(bin2hex($bytes), 0, $length) . $options['suffix'];
}
/**
* Provides the ability to download a file to the browser
*
* @param string $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
* @param int $sec Throttling, try 0.1 for some speed throttling of downloads
* @param int $bytes Size of chunks to send in bytes. Default is 1024
* @param array $options Extra options: [mime, download_name, expires]
* @throws Exception
*/
public static function download($file, $force_download = true, $sec = 0, $bytes = 1024, array $options = [])
{
$grav = Grav::instance();
if (file_exists($file)) {
// fire download event
$grav->fireEvent('onBeforeDownload', new Event(['file' => $file, 'options' => &$options]));
$file_parts = static::pathinfo($file);
$mimetype = $options['mime'] ?? static::getMimeByExtension($file_parts['extension']);
$size = filesize($file); // File size
$grav->cleanOutputBuffers();
// required for IE, otherwise Content-Disposition may be ignored
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Content-Type: ' . $mimetype);
header('Accept-Ranges: bytes');
if ($force_download) {
// output the regular HTTP headers
header('Content-Disposition: attachment; filename="' . ($options['download_name'] ?? $file_parts['basename']) . '"');
}
// multipart-download and download resuming support
if (isset($_SERVER['HTTP_RANGE'])) {
[$a, $range] = explode('=', $_SERVER['HTTP_RANGE'], 2);
[$range] = explode(',', $range, 2);
[$range, $range_end] = explode('-', $range);
$range = (int)$range;
if (!$range_end) {
$range_end = $size - 1;
} else {
$range_end = (int)$range_end;
}
$new_length = $range_end - $range + 1;
header('HTTP/1.1 206 Partial Content');
header("Content-Length: {$new_length}");
header("Content-Range: bytes {$range}-{$range_end}/{$size}");
} else {
$range = 0;
$new_length = $size;
header('Content-Length: ' . $size);
if ($grav['config']->get('system.cache.enabled')) {
$expires = $options['expires'] ?? $grav['config']->get('system.pages.expires');
if ($expires > 0) {
$expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
header('Cache-Control: max-age=' . $expires);
header('Expires: ' . $expires_date);
header('Pragma: cache');
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
// Return 304 Not Modified if the file is already cached in the browser
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
header('HTTP/1.1 304 Not Modified');
exit();
}
}
}
/* output the file itself */
$chunksize = $bytes * 8; //you may want to change this
$bytes_send = 0;
$fp = @fopen($file, 'rb');
if ($fp) {
if ($range) {
fseek($fp, $range);
}
while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length)) {
$buffer = fread($fp, $chunksize);
echo($buffer); //echo($buffer); // is also possible
flush();
usleep($sec * 1000000);
$bytes_send += strlen($buffer);
}
fclose($fp);
} else {
throw new RuntimeException('Error - can not open file.');
}
exit;
}
}
/**
* Returns the output render format, usually the extension provided in the URL. (e.g. `html`, `json`, `xml`, etc).
*
* @return string
*/
public static function getPageFormat(): string
{
/** @var Uri $uri */
$uri = Grav::instance()['uri'];
// Set from uri extension
$uri_extension = $uri->extension();
if (is_string($uri_extension) && $uri->isValidExtension($uri_extension)) {
return ($uri_extension);
}
// Use content negotiation via the `accept:` header
$http_accept = $_SERVER['HTTP_ACCEPT'] ?? null;
if (is_string($http_accept)) {
$negotiator = new Negotiator();
$supported_types = static::getSupportPageTypes(['html', 'json']);
$priorities = static::getMimeTypes($supported_types);
$media_type = $negotiator->getBest($http_accept, $priorities);
$mimetype = $media_type instanceof Accept ? $media_type->getValue() : '';
return static::getExtensionByMime($mimetype);
}
return 'html';
}
/**
* Return the mimetype based on filename extension
*
* @param string $extension Extension of file (eg "txt")
* @param string $default
* @return string
*/
public static function getMimeByExtension($extension, $default = 'application/octet-stream')
{
$extension = strtolower($extension);
// look for some standard types
switch ($extension) {
case null:
return $default;
case 'json':
return 'application/json';
case 'html':
return 'text/html';
case 'atom':
return 'application/atom+xml';
case 'rss':
return 'application/rss+xml';
case 'xml':
return 'application/xml';
}
$media_types = Grav::instance()['config']->get('media.types');
return $media_types[$extension]['mime'] ?? $default;
}
/**
* Get all the mimetypes for an array of extensions
*
* @param array $extensions
* @return array
*/
public static function getMimeTypes(array $extensions)
{
$mimetypes = [];
foreach ($extensions as $extension) {
$mimetype = static::getMimeByExtension($extension, false);
if ($mimetype && !in_array($mimetype, $mimetypes)) {
$mimetypes[] = $mimetype;
}
}
return $mimetypes;
}
/**
* Return all extensions for given mimetype. The first extension is the default one.
*
* @param string $mime Mime type (eg 'image/jpeg')
* @return string[] List of extensions eg. ['jpg', 'jpe', 'jpeg']
*/
public static function getExtensionsByMime($mime)
{
$mime = strtolower($mime);
$media_types = (array)Grav::instance()['config']->get('media.types');
$list = [];
foreach ($media_types as $extension => $type) {
if ($extension === '' || $extension === 'defaults') {
continue;
}
if (isset($type['mime']) && $type['mime'] === $mime) {
$list[] = $extension;
}
}
return $list;
}
/**
* Return the mimetype based on filename extension
*
* @param string $mime mime type (eg "text/html")
* @param string $default default value
* @return string
*/
public static function getExtensionByMime($mime, $default = 'html')
{
$mime = strtolower($mime);
// look for some standard mime types
switch ($mime) {
case '*/*':
case 'text/*':
case 'text/html':
return 'html';
case 'application/json':
return 'json';
case 'application/atom+xml':
return 'atom';
case 'application/rss+xml':
return 'rss';
case 'application/xml':
return 'xml';
}
$media_types = (array)Grav::instance()['config']->get('media.types');
foreach ($media_types as $extension => $type) {
if ($extension === 'defaults') {
continue;
}
if (isset($type['mime']) && $type['mime'] === $mime) {
return $extension;
}
}
return $default;
}
/**
* Get all the extensions for an array of mimetypes
*
* @param array $mimetypes
* @return array
*/
public static function getExtensions(array $mimetypes)
{
$extensions = [];
foreach ($mimetypes as $mimetype) {
$extension = static::getExtensionByMime($mimetype, false);
if ($extension && !in_array($extension, $extensions, true)) {
$extensions[] = $extension;
}
}
return $extensions;
}
/**
* Return the mimetype based on filename
*
* @param string $filename Filename or path to file
* @param string $default default value
* @return string
*/
public static function getMimeByFilename($filename, $default = 'application/octet-stream')
{
return static::getMimeByExtension(static::pathinfo($filename, PATHINFO_EXTENSION), $default);
}
/**
* Return the mimetype based on existing local file
*
* @param string $filename Path to the file
* @param string $default
* @return string|bool
*/
public static function getMimeByLocalFile($filename, $default = 'application/octet-stream')
{
$type = false;
// For local files we can detect type by the file content.
if (!stream_is_local($filename) || !file_exists($filename)) {
return false;
}
// Prefer using finfo if it exists.
if (extension_loaded('fileinfo')) {
$finfo = finfo_open(FILEINFO_SYMLINK | FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $filename);
finfo_close($finfo);
} else {
// Fall back to use getimagesize() if it is available (not recommended, but better than nothing)
$info = @getimagesize($filename);
if ($info) {
$type = $info['mime'];
}
}
return $type ?: static::getMimeByFilename($filename, $default);
}
/**
* Returns true if filename is considered safe.
*
* @param string $filename
* @return bool
*/
public static function checkFilename($filename): bool
{
$dangerous_extensions = Grav::instance()['config']->get('security.uploads_dangerous_extensions', []);
$extension = mb_strtolower(static::pathinfo($filename, PATHINFO_EXTENSION));
return !(
// Empty filenames are not allowed.
!$filename
// Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
|| strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
// Filename should not start or end with dot or space.
|| trim($filename, '. ') !== $filename
// Filename should not contain path traversal
|| str_replace('..', '', $filename) !== $filename
// File extension should not be part of configured dangerous extensions
|| in_array($extension, $dangerous_extensions)
);
}
/**
* Unicode-safe version of PHP’s pathinfo() function.
*
* @link https://www.php.net/manual/en/function.pathinfo.php
*
* @param string $path
* @param int|null $flags
* @return array|string
*/
public static function pathinfo($path, int $flags = null)
{
$path = str_replace(['%2F', '%5C'], ['/', '\\'], rawurlencode($path));
if (null === $flags) {
$info = pathinfo($path);
} else {
$info = pathinfo($path, $flags);
}
if (is_array($info)) {
return array_map('rawurldecode', $info);
}
return rawurldecode($info);
}
/**
* Unicode-safe version of the PHP basename() function.
*
* @link https://www.php.net/manual/en/function.basename.php
*
* @param string $path
* @param string $suffix
* @return string
*/
public static function basename($path, string $suffix = ''): string
{
return rawurldecode(basename(str_replace(['%2F', '%5C'], '/', rawurlencode($path)), $suffix));
}
/**
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Browser.php | system/src/Grav/Common/Browser.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use InvalidArgumentException;
use function donatj\UserAgent\parse_user_agent;
/**
* Internally uses the PhpUserAgent package https://github.com/donatj/PhpUserAgent
*/
class Browser
{
/** @var string[] */
protected $useragent = [];
/**
* Browser constructor.
*/
public function __construct()
{
try {
$this->useragent = parse_user_agent();
} catch (InvalidArgumentException $e) {
$this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)");
}
}
/**
* Get the current browser identifier
*
* Currently detected browsers:
*
* Android Browser
* BlackBerry Browser
* Camino
* Kindle / Silk
* Firefox / Iceweasel
* Safari
* Internet Explorer
* IEMobile
* Chrome
* Opera
* Midori
* Vivaldi
* TizenBrowser
* Lynx
* Wget
* Curl
*
* @return string the lowercase browser name
*/
public function getBrowser()
{
return strtolower($this->useragent['browser']);
}
/**
* Get the current platform identifier
*
* Currently detected platforms:
*
* Desktop
* -> Windows
* -> Linux
* -> Macintosh
* -> Chrome OS
* Mobile
* -> Android
* -> iPhone
* -> iPad / iPod Touch
* -> Windows Phone OS
* -> Kindle
* -> Kindle Fire
* -> BlackBerry
* -> Playbook
* -> Tizen
* Console
* -> Nintendo 3DS
* -> New Nintendo 3DS
* -> Nintendo Wii
* -> Nintendo WiiU
* -> PlayStation 3
* -> PlayStation 4
* -> PlayStation Vita
* -> Xbox 360
* -> Xbox One
*
* @return string the lowercase platform name
*/
public function getPlatform()
{
return strtolower($this->useragent['platform']);
}
/**
* Get the current full version identifier
*
* @return string the browser full version identifier
*/
public function getLongVersion()
{
return $this->useragent['version'];
}
/**
* Get the current major version identifier
*
* @return int the browser major version identifier
*/
public function getVersion()
{
$version = explode('.', $this->getLongVersion());
return (int)$version[0];
}
/**
* Determine if the request comes from a human, or from a bot/crawler
*
* @return bool
*/
public function isHuman()
{
$browser = $this->getBrowser();
if (empty($browser)) {
return false;
}
if (preg_match('~(bot|crawl)~i', $browser)) {
return false;
}
return true;
}
/**
* Determine if “Do Not Track” is set by browser
* @see https://www.w3.org/TR/tracking-dnt/
*
* @return bool
*/
public function isTrackable(): bool
{
return !(isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] === '1');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Inflector.php | system/src/Grav/Common/Inflector.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DateInterval;
use DateTime;
use Grav\Common\Language\Language;
use function in_array;
use function is_array;
use function strlen;
/**
* This file was originally part of the Akelos Framework
*/
class Inflector
{
/** @var bool */
protected static $initialized = false;
/** @var array|null */
protected static $plural;
/** @var array|null */
protected static $singular;
/** @var array|null */
protected static $uncountable;
/** @var array|null */
protected static $irregular;
/** @var array|null */
protected static $ordinals;
/**
* @return void
*/
public static function init()
{
if (!static::$initialized) {
static::$initialized = true;
/** @var Language $language */
$language = Grav::instance()['language'];
if (!$language->isDebug()) {
static::$plural = $language->translate('GRAV.INFLECTOR_PLURALS', null, true);
static::$singular = $language->translate('GRAV.INFLECTOR_SINGULAR', null, true);
static::$uncountable = $language->translate('GRAV.INFLECTOR_UNCOUNTABLE', null, true);
static::$irregular = $language->translate('GRAV.INFLECTOR_IRREGULAR', null, true);
static::$ordinals = $language->translate('GRAV.INFLECTOR_ORDINALS', null, true);
}
}
}
/**
* Pluralizes English nouns.
*
* @param string $word English noun to pluralize
* @param int $count The count
* @return string|false Plural noun
*/
public static function pluralize($word, $count = 2)
{
static::init();
if ((int)$count === 1) {
return $word;
}
$lowercased_word = strtolower($word);
if (is_array(static::$uncountable)) {
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
return $word;
}
}
}
if (is_array(static::$irregular)) {
foreach (static::$irregular as $_plural => $_singular) {
if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
}
}
}
if (is_array(static::$plural)) {
foreach (static::$plural as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
}
}
}
return false;
}
/**
* Singularizes English nouns.
*
* @param string $word English noun to singularize
* @param int $count
*
* @return string Singular noun.
*/
public static function singularize($word, $count = 1)
{
static::init();
if ((int)$count !== 1) {
return $word;
}
$lowercased_word = strtolower($word);
if (is_array(static::$uncountable)) {
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
return $word;
}
}
}
if (is_array(static::$irregular)) {
foreach (static::$irregular as $_plural => $_singular) {
if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
}
}
}
if (is_array(static::$singular)) {
foreach (static::$singular as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
}
}
}
return $word;
}
/**
* Converts an underscored or CamelCase word into a English
* sentence.
*
* The titleize public function converts text like "WelcomePage",
* "welcome_page" or "welcome page" to this "Welcome
* Page".
* If second parameter is set to 'first' it will only
* capitalize the first character of the title.
*
* @param string $word Word to format as tile
* @param string $uppercase If set to 'first' it will only uppercase the
* first character. Otherwise it will uppercase all
* the words in the title.
*
* @return string Text formatted as title
*/
public static function titleize($word, $uppercase = '')
{
$humanize_underscorize = static::humanize(static::underscorize($word));
if ($uppercase === 'first') {
$firstLetter = mb_strtoupper(mb_substr($humanize_underscorize, 0, 1, "UTF-8"), "UTF-8");
return $firstLetter . mb_substr($humanize_underscorize, 1, mb_strlen($humanize_underscorize, "UTF-8"), "UTF-8");
} else {
return mb_convert_case($humanize_underscorize, MB_CASE_TITLE, 'UTF-8');
}
}
/**
* Returns given word as CamelCased
*
* Converts a word like "send_email" to "SendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "WhoSOnline"
*
* @see variablize
*
* @param string $word Word to convert to camel case
* @return string UpperCamelCasedWord
*/
public static function camelize($word)
{
return str_replace(' ', '', ucwords(preg_replace('/[^\p{L}^0-9]+/', ' ', $word)));
}
/**
* Converts a word "into_it_s_underscored_version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "underscored_word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to underscore
* @return string Underscored word
*/
public static function underscorize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
$regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', $regex1);
$regex3 = preg_replace('/[^\p{L}^0-9]+/u', '_', $regex2);
return strtolower($regex3);
}
/**
* Converts a word "into-it-s-hyphenated-version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "hyphenated-word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to hyphenate
* @return string hyphenized word
*/
public static function hyphenize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1-\2', $word);
$regex2 = preg_replace('/([a-z])([A-Z])/', '\1-\2', $regex1);
$regex3 = preg_replace('/([0-9])([A-Z])/', '\1-\2', $regex2);
$regex4 = preg_replace('/[^\p{L}^0-9]+/', '-', $regex3);
$regex4 = trim($regex4, '-');
return strtolower($regex4);
}
/**
* Returns a human-readable string from $word
*
* Returns a human-readable string from $word, by replacing
* underscores with a space, and by upper-casing the initial
* character by default.
*
* If you need to uppercase all the words you just have to
* pass 'all' as a second parameter.
*
* @param string $word String to "humanize"
* @param string $uppercase If set to 'all' it will uppercase all the words
* instead of just the first one.
*
* @return string Human-readable word
*/
public static function humanize($word, $uppercase = '')
{
$uppercase = $uppercase === 'all' ? 'ucwords' : 'ucfirst';
return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
}
/**
* Same as camelize but first char is underscored
*
* Converts a word like "send_email" to "sendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "whoSOnline"
*
* @see camelize
*
* @param string $word Word to lowerCamelCase
* @return string Returns a lowerCamelCasedWord
*/
public static function variablize($word)
{
$word = static::camelize($word);
return strtolower($word[0]) . substr($word, 1);
}
/**
* Converts a class name to its table name according to rails
* naming conventions.
*
* Converts "Person" to "people"
*
* @see classify
*
* @param string $class_name Class name for getting related table_name.
* @return string plural_table_name
*/
public static function tableize($class_name)
{
return static::pluralize(static::underscorize($class_name));
}
/**
* Converts a table name to its class name according to rails
* naming conventions.
*
* Converts "people" to "Person"
*
* @see tableize
*
* @param string $table_name Table name for getting related ClassName.
* @return string SingularClassName
*/
public static function classify($table_name)
{
return static::camelize(static::singularize($table_name));
}
/**
* Converts number to its ordinal English form.
*
* This method converts 13 to 13th, 2 to 2nd ...
*
* @param int $number Number to get its ordinal value
* @return string Ordinal representation of given string.
*/
public static function ordinalize($number)
{
static::init();
if (!is_array(static::$ordinals)) {
return (string)$number;
}
if (in_array($number % 100, range(11, 13), true)) {
return $number . static::$ordinals['default'];
}
switch ($number % 10) {
case 1:
return $number . static::$ordinals['first'];
case 2:
return $number . static::$ordinals['second'];
case 3:
return $number . static::$ordinals['third'];
default:
return $number . static::$ordinals['default'];
}
}
/**
* Converts a number of days to a number of months
*
* @param int $days
* @return int
*/
public static function monthize($days)
{
$now = new DateTime();
$end = new DateTime();
$duration = new DateInterval("P{$days}D");
$diff = $end->add($duration)->diff($now);
// handle years
if ($diff->y > 0) {
$diff->m += 12 * $diff->y;
}
return $diff->m;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Cache.php | system/src/Grav/Common/Cache.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DirectoryIterator;
use \Doctrine\Common\Cache as DoctrineCache;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Scheduler\Scheduler;
use LogicException;
use Psr\SimpleCache\CacheInterface;
use RocketTheme\Toolbox\Event\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use function dirname;
use function extension_loaded;
use function function_exists;
use function in_array;
use function is_array;
/**
* The GravCache object is used throughout Grav to store and retrieve cached data.
* It uses DoctrineCache library and supports a variety of caching mechanisms. Those include:
*
* APCu
* RedisCache
* MemCache
* MemCacheD
* FileSystem
*/
class Cache extends Getters
{
/** @var string Cache key. */
protected $key;
/** @var int */
protected $lifetime;
/** @var int */
protected $now;
/** @var Config $config */
protected $config;
/** @var DoctrineCache\CacheProvider */
protected $driver;
/** @var CacheInterface */
protected $simpleCache;
/** @var string */
protected $driver_name;
/** @var string */
protected $driver_setting;
/** @var bool */
protected $enabled;
/** @var string */
protected $cache_dir;
protected static $standard_remove = [
'cache://twig/',
'cache://doctrine/',
'cache://compiled/',
'cache://clockwork/',
'cache://validated-',
'cache://images',
'asset://',
];
protected static $standard_remove_no_images = [
'cache://twig/',
'cache://doctrine/',
'cache://compiled/',
'cache://clockwork/',
'cache://validated-',
'asset://',
];
protected static $all_remove = [
'cache://',
'cache://images',
'asset://',
'tmp://'
];
protected static $assets_remove = [
'asset://'
];
protected static $images_remove = [
'cache://images'
];
protected static $cache_remove = [
'cache://'
];
protected static $tmp_remove = [
'tmp://'
];
/**
* Constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->init($grav);
}
/**
* Initialization that sets a base key and the driver based on configuration settings
*
* @param Grav $grav
* @return void
*/
public function init(Grav $grav)
{
$this->config = $grav['config'];
$this->now = time();
if (null === $this->enabled) {
$this->enabled = (bool)$this->config->get('system.cache.enabled');
}
/** @var Uri $uri */
$uri = $grav['uri'];
$prefix = $this->config->get('system.cache.prefix');
$uniqueness = substr(md5($uri->rootUrl(true) . $this->config->key() . GRAV_VERSION), 2, 8);
// Cache key allows us to invalidate all cache on configuration changes.
$this->key = ($prefix ?: 'g') . '-' . $uniqueness;
$this->cache_dir = $grav['locator']->findResource('cache://doctrine/' . $uniqueness, true, true);
$this->driver_setting = $this->config->get('system.cache.driver');
$this->driver = $this->getCacheDriver();
$this->driver->setNamespace($this->key);
/** @var EventDispatcher $dispatcher */
$dispatcher = Grav::instance()['events'];
$dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']);
}
/**
* @return CacheInterface
*/
public function getSimpleCache()
{
if (null === $this->simpleCache) {
$cache = new \Grav\Framework\Cache\Adapter\DoctrineCache($this->driver, '', $this->getLifetime());
// Disable cache key validation.
$cache->setValidation(false);
$this->simpleCache = $cache;
}
return $this->simpleCache;
}
/**
* Deletes old cache files based on age
*
* @return int
*/
public function purgeOldCache()
{
// Get the max age for cache files from config (default 30 days)
$max_age_days = $this->config->get('system.cache.purge_max_age_days', 30);
$max_age_seconds = $max_age_days * 86400; // Convert days to seconds
$now = time();
$count = 0;
// First, clean up old orphaned cache directories (not the current one)
$cache_dir = dirname($this->cache_dir);
$current = Utils::basename($this->cache_dir);
foreach (new DirectoryIterator($cache_dir) as $file) {
$dir = $file->getBasename();
if ($dir === $current || $file->isDot() || $file->isFile()) {
continue;
}
// Check if directory is old and empty or very old (90+ days)
$dir_age = $now - $file->getMTime();
if ($dir_age > 7776000) { // 90 days
Folder::delete($file->getPathname());
$count++;
}
}
// Now clean up old cache files within the current cache directory
if (is_dir($this->cache_dir)) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->cache_dir, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$file_age = $now - $file->getMTime();
if ($file_age > $max_age_seconds) {
@unlink($file->getPathname());
$count++;
}
}
}
}
// Also clean up old files in compiled cache
$grav = Grav::instance();
$compiled_dir = $this->config->get('system.cache.compiled_dir', 'cache://compiled');
$compiled_path = $grav['locator']->findResource($compiled_dir, true);
if ($compiled_path && is_dir($compiled_path)) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($compiled_path, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$file_age = $now - $file->getMTime();
// Compiled files can be kept longer (60 days)
if ($file_age > ($max_age_seconds * 2)) {
@unlink($file->getPathname());
$count++;
}
}
}
}
return $count;
}
/**
* Public accessor to set the enabled state of the cache
*
* @param bool|int $enabled
* @return void
*/
public function setEnabled($enabled)
{
$this->enabled = (bool)$enabled;
}
/**
* Returns the current enabled state
*
* @return bool
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Get cache state
*
* @return string
*/
public function getCacheStatus()
{
return 'Cache: [' . ($this->enabled ? 'true' : 'false') . '] Setting: [' . $this->driver_setting . '] Driver: [' . $this->driver_name . ']';
}
/**
* Automatically picks the cache mechanism to use. If you pick one manually it will use that
* If there is no config option for $driver in the config, or it's set to 'auto', it will
* pick the best option based on which cache extensions are installed.
*
* @return DoctrineCache\CacheProvider The cache driver to use
*/
public function getCacheDriver()
{
$setting = $this->driver_setting;
$driver_name = 'file';
// CLI compatibility requires a non-volatile cache driver
if ($this->config->get('system.cache.cli_compatibility') && (
$setting === 'auto' || $this->isVolatileDriver($setting))) {
$setting = $driver_name;
}
if (!$setting || $setting === 'auto') {
if (extension_loaded('apcu')) {
$driver_name = 'apcu';
} elseif (extension_loaded('wincache')) {
$driver_name = 'wincache';
}
} else {
$driver_name = $setting;
}
$this->driver_name = $driver_name;
switch ($driver_name) {
case 'apc':
case 'apcu':
$driver = new DoctrineCache\ApcuCache();
break;
case 'wincache':
$driver = new DoctrineCache\WinCacheCache();
break;
case 'memcache':
if (extension_loaded('memcache')) {
$memcache = new \Memcache();
$memcache->connect(
$this->config->get('system.cache.memcache.server', 'localhost'),
$this->config->get('system.cache.memcache.port', 11211)
);
$driver = new DoctrineCache\MemcacheCache();
$driver->setMemcache($memcache);
} else {
throw new LogicException('Memcache PHP extension has not been installed');
}
break;
case 'memcached':
if (extension_loaded('memcached')) {
$memcached = new \Memcached();
$memcached->addServer(
$this->config->get('system.cache.memcached.server', 'localhost'),
$this->config->get('system.cache.memcached.port', 11211)
);
$driver = new DoctrineCache\MemcachedCache();
$driver->setMemcached($memcached);
} else {
throw new LogicException('Memcached PHP extension has not been installed');
}
break;
case 'redis':
if (extension_loaded('redis')) {
$redis = new \Redis();
$socket = $this->config->get('system.cache.redis.socket', false);
$password = $this->config->get('system.cache.redis.password', false);
$databaseId = $this->config->get('system.cache.redis.database', 0);
if ($socket) {
$redis->connect($socket);
} else {
$redis->connect(
$this->config->get('system.cache.redis.server', 'localhost'),
$this->config->get('system.cache.redis.port', 6379)
);
}
// Authenticate with password if set
if ($password && !$redis->auth($password)) {
throw new \RedisException('Redis authentication failed');
}
// Select alternate ( !=0 ) database ID if set
if ($databaseId && !$redis->select($databaseId)) {
throw new \RedisException('Could not select alternate Redis database ID');
}
$driver = new DoctrineCache\RedisCache();
$driver->setRedis($redis);
} else {
throw new LogicException('Redis PHP extension has not been installed');
}
break;
default:
$driver = new DoctrineCache\FilesystemCache($this->cache_dir);
break;
}
return $driver;
}
/**
* Gets a cached entry if it exists based on an id. If it does not exist, it returns false
*
* @param string $id the id of the cached entry
* @return mixed|bool returns the cached entry, can be any type, or false if doesn't exist
*/
public function fetch($id)
{
if ($this->enabled) {
return $this->driver->fetch($id);
}
return false;
}
/**
* Stores a new cached entry.
*
* @param string $id the id of the cached entry
* @param array|object|int $data the data for the cached entry to store
* @param int|null $lifetime the lifetime to store the entry in seconds
*/
public function save($id, $data, $lifetime = null)
{
if ($this->enabled) {
if ($lifetime === null) {
$lifetime = $this->getLifetime();
}
$this->driver->save($id, $data, $lifetime);
}
}
/**
* Deletes an item in the cache based on the id
*
* @param string $id the id of the cached data entry
* @return bool true if the item was deleted successfully
*/
public function delete($id)
{
if ($this->enabled) {
return $this->driver->delete($id);
}
return false;
}
/**
* Deletes all cache
*
* @return bool
*/
public function deleteAll()
{
if ($this->enabled) {
return $this->driver->deleteAll();
}
return false;
}
/**
* Returns a boolean state of whether or not the item exists in the cache based on id key
*
* @param string $id the id of the cached data entry
* @return bool true if the cached items exists
*/
public function contains($id)
{
if ($this->enabled) {
return $this->driver->contains(($id));
}
return false;
}
/**
* Getter method to get the cache key
*
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* Setter method to set key (Advanced)
*
* @param string $key
* @return void
*/
public function setKey($key)
{
$this->key = $key;
$this->driver->setNamespace($this->key);
}
/**
* Helper method to clear all Grav caches
*
* @param string $remove standard|all|assets-only|images-only|cache-only
* @return array
*/
public static function clearCache($remove = 'standard')
{
$locator = Grav::instance()['locator'];
$output = [];
$user_config = USER_DIR . 'config/system.yaml';
switch ($remove) {
case 'all':
$remove_paths = self::$all_remove;
break;
case 'assets-only':
$remove_paths = self::$assets_remove;
break;
case 'images-only':
$remove_paths = self::$images_remove;
break;
case 'cache-only':
$remove_paths = self::$cache_remove;
break;
case 'tmp-only':
$remove_paths = self::$tmp_remove;
break;
case 'invalidate':
$remove_paths = [];
break;
default:
if (Grav::instance()['config']->get('system.cache.clear_images_by_default')) {
$remove_paths = self::$standard_remove;
} else {
$remove_paths = self::$standard_remove_no_images;
}
}
// Delete entries in the doctrine cache if required
if (in_array($remove, ['all', 'standard'])) {
$cache = Grav::instance()['cache'];
$cache->driver->deleteAll();
}
// Clearing cache event to add paths to clear
Grav::instance()->fireEvent('onBeforeCacheClear', new Event(['remove' => $remove, 'paths' => &$remove_paths]));
foreach ($remove_paths as $stream) {
// Convert stream to a real path
try {
$path = $locator->findResource($stream, true, true);
if ($path === false) {
continue;
}
$anything = false;
$files = glob($path . '/*');
if (is_array($files)) {
foreach ($files as $file) {
if (is_link($file)) {
$output[] = '<yellow>Skipping symlink: </yellow>' . $file;
} elseif (is_file($file)) {
if (@unlink($file)) {
$anything = true;
}
} elseif (is_dir($file)) {
if (Folder::delete($file, false)) {
$anything = true;
}
}
}
}
if ($anything) {
$output[] = '<red>Cleared: </red>' . $path . '/*';
}
} catch (Exception $e) {
// stream not found or another error while deleting files.
$output[] = '<red>ERROR: </red>' . $e->getMessage();
}
}
$output[] = '';
if (($remove === 'all' || $remove === 'standard') && file_exists($user_config)) {
touch($user_config);
$output[] = '<red>Touched: </red>' . $user_config;
$output[] = '';
}
// Clear stat cache
@clearstatcache();
// Clear opcache
if (function_exists('opcache_reset')) {
@opcache_reset();
}
Grav::instance()->fireEvent('onAfterCacheClear', new Event(['remove' => $remove, 'output' => &$output]));
return $output;
}
/**
* @return void
*/
public static function invalidateCache()
{
$user_config = USER_DIR . 'config/system.yaml';
if (file_exists($user_config)) {
touch($user_config);
}
// Clear stat cache
@clearstatcache();
// Clear opcache
if (function_exists('opcache_reset')) {
@opcache_reset();
}
}
/**
* Set the cache lifetime programmatically
*
* @param int $future timestamp
* @return void
*/
public function setLifetime($future)
{
if (!$future) {
return;
}
$interval = (int)($future - $this->now);
if ($interval > 0 && $interval < $this->getLifetime()) {
$this->lifetime = $interval;
}
}
/**
* Retrieve the cache lifetime (in seconds)
*
* @return int
*/
public function getLifetime()
{
if ($this->lifetime === null) {
$this->lifetime = (int)($this->config->get('system.cache.lifetime') ?: 604800); // 1 week default
}
return $this->lifetime;
}
/**
* Returns the current driver name
*
* @return string
*/
public function getDriverName()
{
return $this->driver_name;
}
/**
* Returns the current driver setting
*
* @return string
*/
public function getDriverSetting()
{
return $this->driver_setting;
}
/**
* is this driver a volatile driver in that it resides in PHP process memory
*
* @param string $setting
* @return bool
*/
public function isVolatileDriver($setting)
{
return in_array($setting, ['apc', 'apcu', 'xcache', 'wincache'], true);
}
/**
* Static function to call as a scheduled Job to purge old Doctrine files
*
* @param bool $echo
*
* @return string|void
*/
public static function purgeJob($echo = false)
{
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
$deleted_items = $cache->purgeOldCache();
$max_age = $cache->config->get('system.cache.purge_max_age_days', 30);
$msg = 'Purged ' . $deleted_items . ' old cache items (files older than ' . $max_age . ' days)';
if ($echo) {
echo $msg;
} else {
return $msg;
}
}
/**
* Static function to call as a scheduled Job to clear Grav cache
*
* @param string $type
* @return void
*/
public static function clearJob($type)
{
$result = static::clearCache($type);
static::invalidateCache();
echo strip_tags(implode("\n", $result));
}
/**
* @param Event $event
* @return void
*/
public function onSchedulerInitialized(Event $event)
{
/** @var Scheduler $scheduler */
$scheduler = $event['scheduler'];
$config = Grav::instance()['config'];
// File Cache Purge
$at = $config->get('system.cache.purge_at');
$name = 'cache-purge';
$logs = 'logs/' . $name . '.out';
$job = $scheduler->addFunction('Grav\Common\Cache::purgeJob', [true], $name);
$job->at($at);
$job->output($logs);
$job->backlink('/config/system#caching');
// Cache Clear
$at = $config->get('system.cache.clear_at');
$clear_type = $config->get('system.cache.clear_job_type');
$name = 'cache-clear';
$logs = 'logs/' . $name . '.out';
$job = $scheduler->addFunction('Grav\Common\Cache::clearJob', [$clear_type], $name);
$job->at($at);
$job->output($logs);
$job->backlink('/config/system#caching');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Iterator.php | system/src/Grav/Common/Iterator.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use RocketTheme\Toolbox\ArrayTraits\ArrayAccessWithGetters;
use RocketTheme\Toolbox\ArrayTraits\Iterator as ArrayIterator;
use RocketTheme\Toolbox\ArrayTraits\Constructor;
use RocketTheme\Toolbox\ArrayTraits\Countable;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\Serializable;
use function array_slice;
use function count;
use function is_callable;
use function is_object;
/**
* Class Iterator
* @package Grav\Common
*/
class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
{
use Constructor, ArrayAccessWithGetters, ArrayIterator, Countable, Serializable, Export;
/** @var array */
protected $items = [];
/**
* Convert function calls for the existing keys into their values.
*
* @param string $key
* @param mixed $args
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __call($key, $args)
{
return $this->items[$key] ?? null;
}
/**
* Clone the iterator.
*/
#[\ReturnTypeWillChange]
public function __clone()
{
foreach ($this as $key => $value) {
if (is_object($value)) {
$this->{$key} = clone $this->{$key};
}
}
}
/**
* Convents iterator to a comma separated list.
*
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return implode(',', $this->items);
}
/**
* Remove item from the list.
*
* @param string $key
* @return void
*/
public function remove($key)
{
$this->offsetUnset($key);
}
/**
* Return previous item.
*
* @return mixed
*/
public function prev()
{
return prev($this->items);
}
/**
* Return nth item.
*
* @param int $key
* @return mixed|bool
*/
public function nth($key)
{
$items = array_keys($this->items);
return isset($items[$key]) ? $this->offsetGet($items[$key]) : false;
}
/**
* Get the first item
*
* @return mixed
*/
public function first()
{
$items = array_keys($this->items);
return $this->offsetGet(array_shift($items));
}
/**
* Get the last item
*
* @return mixed
*/
public function last()
{
$items = array_keys($this->items);
return $this->offsetGet(array_pop($items));
}
/**
* Reverse the Iterator
*
* @return $this
*/
public function reverse()
{
$this->items = array_reverse($this->items);
return $this;
}
/**
* @param mixed $needle Searched value.
*
* @return string|int|false Key if found, otherwise false.
*/
public function indexOf($needle)
{
foreach (array_values($this->items) as $key => $value) {
if ($value === $needle) {
return $key;
}
}
return false;
}
/**
* Shuffle items.
*
* @return $this
*/
public function shuffle()
{
$keys = array_keys($this->items);
shuffle($keys);
$new = [];
foreach ($keys as $key) {
$new[$key] = $this->items[$key];
}
$this->items = $new;
return $this;
}
/**
* Slice the list.
*
* @param int $offset
* @param int|null $length
* @return $this
*/
public function slice($offset, $length = null)
{
$this->items = array_slice($this->items, $offset, $length);
return $this;
}
/**
* Pick one or more random entries.
*
* @param int $num Specifies how many entries should be picked.
* @return $this
*/
public function random($num = 1)
{
$count = count($this->items);
if ($num > $count) {
$num = $count;
}
$this->items = array_intersect_key($this->items, array_flip((array)array_rand($this->items, $num)));
return $this;
}
/**
* Append new elements to the list.
*
* @param array|Iterator $items Items to be appended. Existing keys will be overridden with the new values.
* @return $this
*/
public function append($items)
{
if ($items instanceof static) {
$items = $items->toArray();
}
$this->items = array_merge($this->items, (array)$items);
return $this;
}
/**
* Filter elements from the list
*
* @param callable|null $callback A function the receives ($value, $key) and must return a boolean to indicate
* filter status
*
* @return $this
*/
public function filter(callable $callback = null)
{
foreach ($this->items as $key => $value) {
if ((!$callback && !(bool)$value) || ($callback && !$callback($value, $key))) {
unset($this->items[$key]);
}
}
return $this;
}
/**
* Sorts elements from the list and returns a copy of the list in the proper order
*
* @param callable|null $callback
* @param bool $desc
* @return $this|array
*
*/
public function sort(callable $callback = null, $desc = false)
{
if (!$callback || !is_callable($callback)) {
return $this;
}
$items = $this->items;
uasort($items, $callback);
return !$desc ? $items : array_reverse($items, true);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Getters.php | system/src/Grav/Common/Getters.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use ArrayAccess;
use Countable;
use function count;
/**
* Class Getters
* @package Grav\Common
*/
abstract class Getters implements ArrayAccess, Countable
{
/** @var string Define variable used in getters. */
protected $gettersVariable = null;
/**
* Magic setter method
*
* @param int|string $offset Medium name value
* @param mixed $value Medium value
*/
#[\ReturnTypeWillChange]
public function __set($offset, $value)
{
$this->offsetSet($offset, $value);
}
/**
* Magic getter method
*
* @param int|string $offset Medium name value
* @return mixed Medium value
*/
#[\ReturnTypeWillChange]
public function __get($offset)
{
return $this->offsetGet($offset);
}
/**
* Magic method to determine if the attribute is set
*
* @param int|string $offset Medium name value
* @return boolean True if the value is set
*/
#[\ReturnTypeWillChange]
public function __isset($offset)
{
return $this->offsetExists($offset);
}
/**
* Magic method to unset the attribute
*
* @param int|string $offset The name value to unset
*/
#[\ReturnTypeWillChange]
public function __unset($offset)
{
$this->offsetUnset($offset);
}
/**
* @param int|string $offset
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return isset($this->{$var}[$offset]);
}
return isset($this->{$offset});
}
/**
* @param int|string $offset
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return $this->{$var}[$offset] ?? null;
}
return $this->{$offset} ?? null;
}
/**
* @param int|string $offset
* @param mixed $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
$this->{$var}[$offset] = $value;
} else {
$this->{$offset} = $value;
}
}
/**
* @param int|string $offset
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
unset($this->{$var}[$offset]);
} else {
unset($this->{$offset});
}
}
/**
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return count($this->{$var});
}
return count($this->toArray());
}
/**
* Returns an associative array of object properties.
*
* @return array
*/
public function toArray()
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return $this->{$var};
}
$properties = (array)$this;
$list = [];
foreach ($properties as $property => $value) {
if ($property[0] !== "\0") {
$list[$property] = $value;
}
}
return $list;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Session.php | system/src/Grav/Common/Session.php | <?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Common\Form\FormFlash;
use Grav\Events\BeforeSessionStartEvent;
use Grav\Events\SessionStartEvent;
use Grav\Plugin\Form\Forms;
use JsonException;
use function is_string;
/**
* Class Session
* @package Grav\Common
*/
class Session extends \Grav\Framework\Session\Session
{
/** @var bool */
protected $autoStart = false;
/**
* @return \Grav\Framework\Session\Session
* @deprecated 1.5 Use ->getInstance() method instead.
*/
public static function instance()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getInstance() method instead', E_USER_DEPRECATED);
return static::getInstance();
}
/**
* Initialize session.
*
* Code in this function has been moved into SessionServiceProvider class.
*
* @return void
*/
public function init()
{
if ($this->autoStart && !$this->isStarted()) {
$this->start();
$this->autoStart = false;
}
}
/**
* @param bool $auto
* @return $this
*/
public function setAutoStart($auto)
{
$this->autoStart = (bool)$auto;
return $this;
}
/**
* Returns attributes.
*
* @return array Attributes
* @deprecated 1.5 Use ->getAll() method instead.
*/
public function all()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getAll() method instead', E_USER_DEPRECATED);
return $this->getAll();
}
/**
* Checks if the session was started.
*
* @return bool
* @deprecated 1.5 Use ->isStarted() method instead.
*/
public function started()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->isStarted() method instead', E_USER_DEPRECATED);
return $this->isStarted();
}
/**
* Store something in session temporarily.
*
* @param string $name
* @param mixed $object
* @return $this
*/
public function setFlashObject($name, $object)
{
$this->__set($name, serialize($object));
return $this;
}
/**
* Return object and remove it from session.
*
* @param string $name
* @return mixed
*/
public function getFlashObject($name)
{
$serialized = $this->__get($name);
$object = is_string($serialized) ? unserialize($serialized, ['allowed_classes' => true]) : $serialized;
$this->__unset($name);
if ($name === 'files-upload') {
$grav = Grav::instance();
// Make sure that Forms 3.0+ has been installed.
if (null === $object && isset($grav['forms'])) {
// user_error(
// __CLASS__ . '::' . __FUNCTION__ . '(\'files-upload\') is deprecated since Grav 1.6, use $form->getFlash()->getLegacyFiles() instead',
// E_USER_DEPRECATED
// );
/** @var Uri $uri */
$uri = $grav['uri'];
/** @var Forms|null $form */
$form = $grav['forms']->getActiveForm(); // @phpstan-ignore-line (form plugin)
$sessionField = base64_encode($uri->url);
/** @var FormFlash|null $flash */
$flash = $form ? $form->getFlash() : null; // @phpstan-ignore-line (form plugin)
$object = $flash && method_exists($flash, 'getLegacyFiles') ? [$sessionField => $flash->getLegacyFiles()] : null;
}
}
return $object;
}
/**
* Store something in cookie temporarily.
*
* @param string $name
* @param mixed $object
* @param int $time
* @return $this
* @throws JsonException
*/
public function setFlashCookieObject($name, $object, $time = 60)
{
setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), $this->getCookieOptions($time));
return $this;
}
/**
* Return object and remove it from the cookie.
*
* @param string $name
* @return mixed|null
* @throws JsonException
*/
public function getFlashCookieObject($name)
{
if (isset($_COOKIE[$name])) {
$cookie = $_COOKIE[$name];
setcookie($name, '', $this->getCookieOptions(-42000));
return json_decode($cookie, false, 512, JSON_THROW_ON_ERROR);
}
return null;
}
/**
* @return void
*/
protected function onBeforeSessionStart(): void
{
$event = new BeforeSessionStartEvent($this);
$grav = Grav::instance();
$grav->dispatchEvent($event);
}
/**
* @return void
*/
protected function onSessionStart(): void
{
$event = new SessionStartEvent($this);
$grav = Grav::instance();
$grav->dispatchEvent($event);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Markdown/Parsedown.php | system/src/Grav/Common/Markdown/Parsedown.php | <?php
/**
* @package Grav\Common\Markdown
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Markdown;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Markdown\Excerpts;
/**
* Class Parsedown
* @package Grav\Common\Markdown
*/
class Parsedown extends \Parsedown
{
use ParsedownGravTrait;
/**
* Parsedown constructor.
*
* @param Excerpts|PageInterface|null $excerpts
* @param array|null $defaults
*/
public function __construct($excerpts = null, $defaults = null)
{
if (!$excerpts || $excerpts instanceof PageInterface || null !== $defaults) {
// Deprecated in Grav 1.6.10
if ($defaults) {
$defaults = ['markdown' => $defaults];
}
$excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
}
$this->init($excerpts, $defaults);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Markdown/ParsedownGravTrait.php | system/src/Grav/Common/Markdown/ParsedownGravTrait.php | <?php
/**
* @package Grav\Common\Markdown
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Markdown;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Interfaces\PageInterface;
use function call_user_func_array;
use function in_array;
use function strlen;
/**
* Trait ParsedownGravTrait
* @package Grav\Common\Markdown
*/
trait ParsedownGravTrait
{
/** @var array */
public $completable_blocks = [];
/** @var array */
public $continuable_blocks = [];
public $plugins = [];
/** @var Excerpts */
protected $excerpts;
/** @var array */
protected $special_chars;
/** @var string */
protected $twig_link_regex = '/\!*\[(?:.*)\]\((\{([\{%#])\s*(.*?)\s*(?:\2|\})\})\)/';
/**
* Initialization function to setup key variables needed by the MarkdownGravLinkTrait
*
* @param PageInterface|Excerpts|null $excerpts
* @param array|null $defaults
* @return void
*/
protected function init($excerpts = null, $defaults = null)
{
if (!$excerpts || $excerpts instanceof PageInterface) {
// Deprecated in Grav 1.6.10
if ($defaults) {
$defaults = ['markdown' => $defaults];
}
$this->excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use ->init(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
} else {
$this->excerpts = $excerpts;
}
$this->BlockTypes['{'][] = 'TwigTag';
$this->special_chars = ['>' => 'gt', '<' => 'lt', '"' => 'quot'];
$defaults = $this->excerpts->getConfig();
if (isset($defaults['markdown']['auto_line_breaks'])) {
$this->setBreaksEnabled($defaults['markdown']['auto_line_breaks']);
}
if (isset($defaults['markdown']['auto_url_links'])) {
$this->setUrlsLinked($defaults['markdown']['auto_url_links']);
}
if (isset($defaults['markdown']['escape_markup'])) {
$this->setMarkupEscaped($defaults['markdown']['escape_markup']);
}
if (isset($defaults['markdown']['special_chars'])) {
$this->setSpecialChars($defaults['markdown']['special_chars']);
}
$this->excerpts->fireInitializedEvent($this);
}
/**
* @return Excerpts
*/
public function getExcerpts()
{
return $this->excerpts;
}
/**
* Be able to define a new Block type or override an existing one
*
* @param string $type
* @param string $tag
* @param bool $continuable
* @param bool $completable
* @param int|null $index
* @return void
*/
public function addBlockType($type, $tag, $continuable = false, $completable = false, $index = null)
{
$block = &$this->unmarkedBlockTypes;
if ($type) {
if (!isset($this->BlockTypes[$type])) {
$this->BlockTypes[$type] = [];
}
$block = &$this->BlockTypes[$type];
}
if (null === $index) {
$block[] = $tag;
} else {
array_splice($block, $index, 0, [$tag]);
}
if ($continuable) {
$this->continuable_blocks[] = $tag;
}
if ($completable) {
$this->completable_blocks[] = $tag;
}
}
/**
* Be able to define a new Inline type or override an existing one
*
* @param string $type
* @param string $tag
* @param int|null $index
* @return void
*/
public function addInlineType($type, $tag, $index = null)
{
if (null === $index || !isset($this->InlineTypes[$type])) {
$this->InlineTypes[$type] [] = $tag;
} else {
array_splice($this->InlineTypes[$type], $index, 0, [$tag]);
}
if (strpos($this->inlineMarkerList, $type) === false) {
$this->inlineMarkerList .= $type;
}
}
/**
* Overrides the default behavior to allow for plugin-provided blocks to be continuable
*
* @param string $Type
* @return bool
*/
protected function isBlockContinuable($Type)
{
$continuable = in_array($Type, $this->continuable_blocks, true)
|| method_exists($this, 'block' . $Type . 'Continue');
return $continuable;
}
/**
* Overrides the default behavior to allow for plugin-provided blocks to be completable
*
* @param string $Type
* @return bool
*/
protected function isBlockCompletable($Type)
{
$completable = in_array($Type, $this->completable_blocks, true)
|| method_exists($this, 'block' . $Type . 'Complete');
return $completable;
}
/**
* Make the element function publicly accessible, Medium uses this to render from Twig
*
* @param array $Element
* @return string markup
*/
public function elementToHtml(array $Element)
{
return $this->element($Element);
}
/**
* Setter for special chars
*
* @param array $special_chars
* @return $this
*/
public function setSpecialChars($special_chars)
{
$this->special_chars = $special_chars;
return $this;
}
/**
* Ensure Twig tags are treated as block level items with no <p></p> tags
*
* @param array $line
* @return array|null
*/
protected function blockTwigTag($line)
{
if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', $line['body'], $matches)) {
return ['markup' => $line['body']];
}
return null;
}
/**
* @param array $excerpt
* @return array|null
*/
protected function inlineSpecialCharacter($excerpt)
{
if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', $excerpt['text'])) {
return [
'markup' => '&',
'extent' => 1,
];
}
if (isset($this->special_chars[$excerpt['text'][0]])) {
return [
'markup' => '&' . $this->special_chars[$excerpt['text'][0]] . ';',
'extent' => 1,
];
}
return null;
}
/**
* @param array $excerpt
* @return array
*/
protected function inlineImage($excerpt)
{
if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) {
$excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']);
$excerpt = parent::inlineImage($excerpt);
$excerpt['element']['attributes']['src'] = $matches[1];
$excerpt['extent'] = $excerpt['extent'] + strlen($matches[1]) - 1;
return $excerpt;
}
$excerpt['type'] = 'image';
$excerpt = parent::inlineImage($excerpt);
// if this is an image process it
if (isset($excerpt['element']['attributes']['src'])) {
$excerpt = $this->excerpts->processImageExcerpt($excerpt);
}
return $excerpt;
}
/**
* @param array $excerpt
* @return array
*/
protected function inlineLink($excerpt)
{
$type = $excerpt['type'] ?? 'link';
// do some trickery to get around Parsedown requirement for valid URL if its Twig in there
if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) {
$excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']);
$excerpt = parent::inlineLink($excerpt);
$excerpt['element']['attributes']['href'] = $matches[1];
$excerpt['extent'] = $excerpt['extent'] + strlen($matches[1]) - 1;
return $excerpt;
}
$excerpt = parent::inlineLink($excerpt);
// if this is a link
if (isset($excerpt['element']['attributes']['href'])) {
$excerpt = $this->excerpts->processLinkExcerpt($excerpt, $type);
}
return $excerpt;
}
/**
* For extending this class via plugins
*
* @param string $method
* @param array $args
* @return mixed|null
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
{
if (isset($this->plugins[$method]) === true) {
$func = $this->plugins[$method];
return call_user_func_array($func, $args);
} elseif (isset($this->{$method}) === true) {
$func = $this->{$method};
return call_user_func_array($func, $args);
}
return null;
}
public function __set($name, $value)
{
if (is_callable($value)) {
$this->plugins[$name] = $value;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Markdown/ParsedownExtra.php | system/src/Grav/Common/Markdown/ParsedownExtra.php | <?php
/**
* @package Grav\Common\Markdown
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Markdown;
use Exception;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Markdown\Excerpts;
/**
* Class ParsedownExtra
* @package Grav\Common\Markdown
*/
class ParsedownExtra extends \ParsedownExtra
{
use ParsedownGravTrait;
/**
* ParsedownExtra constructor.
*
* @param Excerpts|PageInterface|null $excerpts
* @param array|null $defaults
* @throws Exception
*/
public function __construct($excerpts = null, $defaults = null)
{
if (!$excerpts || $excerpts instanceof PageInterface || null !== $defaults) {
// Deprecated in Grav 1.6.10
if ($defaults) {
$defaults = ['markdown' => $defaults];
}
$excerpts = new Excerpts($excerpts, $defaults);
user_error(__CLASS__ . '::' . __FUNCTION__ . '($page, $defaults) is deprecated since Grav 1.6.10, use new ' . __CLASS__ . '(new ' . Excerpts::class . '($page, [\'markdown\' => $defaults])) instead.', E_USER_DEPRECATED);
}
parent::__construct();
$this->init($excerpts, $defaults);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/LogViewer.php | system/src/Grav/Common/Helpers/LogViewer.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use DateTime;
use function array_slice;
use function is_array;
use function is_string;
/**
* Class LogViewer
* @package Grav\Common\Helpers
*/
class LogViewer
{
/** @var string */
protected $pattern = '/\[(?P<date>.*?)\] (?P<logger>\w+)\.(?P<level>\w+): (?P<message>.*[^ ]+) (?P<context>[^ ]+) (?P<extra>[^ ]+)/';
/**
* Get the objects of a tailed file
*
* @param string $filepath
* @param int $lines
* @param bool $desc
* @return array
*/
public function objectTail($filepath, $lines = 1, $desc = true)
{
$data = $this->tail($filepath, $lines);
$tailed_log = $data ? explode(PHP_EOL, $data) : [];
$line_objects = [];
foreach ($tailed_log as $line) {
$line_objects[] = $this->parse($line);
}
return $desc ? $line_objects : array_reverse($line_objects);
}
/**
* Optimized way to get just the last few entries of a log file
*
* @param string $filepath
* @param int $lines
* @return string|false
*/
public function tail($filepath, $lines = 1)
{
$f = $filepath ? @fopen($filepath, 'rb') : false;
if ($f === false) {
return false;
}
$buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
fseek($f, -1, SEEK_END);
if (fread($f, 1) !== "\n") {
--$lines;
}
// Start reading
$output = '';
// While we would like more
while (ftell($f) > 0 && $lines >= 0) {
// Figure out how far back we should jump
$seek = min(ftell($f), $buffer);
// Do the jump (backwards, relative to where we are)
fseek($f, -$seek, SEEK_CUR);
// Read a chunk and prepend it to our output
$chunk = fread($f, $seek);
if ($chunk === false) {
throw new \RuntimeException('Cannot read file');
}
$output = $chunk . $output;
// Jump back to where we started reading
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
// Decrease our line counter
$lines -= substr_count($chunk, "\n");
}
// While we have too many lines
// (Because of buffer size we might have read too many)
while ($lines++ < 0) {
// Find first newline and remove all text before that
$output = substr($output, strpos($output, "\n") + 1);
}
// Close file and return
fclose($f);
return trim($output);
}
/**
* Helper class to get level color
*
* @param string $level
* @return string
*/
public static function levelColor($level)
{
$colors = [
'DEBUG' => 'green',
'INFO' => 'cyan',
'NOTICE' => 'yellow',
'WARNING' => 'yellow',
'ERROR' => 'red',
'CRITICAL' => 'red',
'ALERT' => 'red',
'EMERGENCY' => 'magenta'
];
return $colors[$level] ?? 'white';
}
/**
* Parse a monolog row into array bits
*
* @param string $line
* @return array
*/
public function parse($line)
{
if (!is_string($line) || $line === '') {
return [];
}
preg_match($this->pattern, $line, $data);
if (!isset($data['date'])) {
return [];
}
preg_match('/(.*)- Trace:(.*)/', $data['message'], $matches);
if (is_array($matches) && isset($matches[1])) {
$data['message'] = trim($matches[1]);
$data['trace'] = trim($matches[2]);
}
return [
'date' => DateTime::createFromFormat('Y-m-d H:i:s', $data['date']),
'logger' => $data['logger'],
'level' => $data['level'],
'message' => $data['message'],
'trace' => isset($data['trace']) ? self::parseTrace($data['trace']) : null,
'context' => json_decode($data['context'], true),
'extra' => json_decode($data['extra'], true)
];
}
/**
* Parse text of trace into an array of lines
*
* @param string $trace
* @param int $rows
* @return array
*/
public static function parseTrace($trace, $rows = 10)
{
$lines = array_filter(preg_split('/#\d*/m', $trace));
return array_slice($lines, 0, $rows);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/Excerpts.php | system/src/Grav/Common/Helpers/Excerpts.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use DOMDocument;
use DOMElement;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Markdown\Excerpts as ExcerptsObject;
use Grav\Common\Page\Medium\Link;
use Grav\Common\Page\Medium\Medium;
use function is_array;
/**
* Class Excerpts
* @package Grav\Common\Helpers
*/
class Excerpts
{
/**
* Process Grav image media URL from HTML tag
*
* @param string $html HTML tag e.g. `<img src="image.jpg" />`
* @param PageInterface|null $page Page, defaults to the current page object
* @return string Returns final HTML string
*/
public static function processImageHtml($html, PageInterface $page = null)
{
$excerpt = static::getExcerptFromHtml($html, 'img');
if (null === $excerpt) {
return '';
}
$original_src = $excerpt['element']['attributes']['src'];
$excerpt['element']['attributes']['href'] = $original_src;
$excerpt = static::processLinkExcerpt($excerpt, $page, 'image');
$excerpt['element']['attributes']['src'] = $excerpt['element']['attributes']['href'];
unset($excerpt['element']['attributes']['href']);
$excerpt = static::processImageExcerpt($excerpt, $page);
$excerpt['element']['attributes']['data-src'] = $original_src;
$html = static::getHtmlFromExcerpt($excerpt);
return $html;
}
/**
* Process Grav page link URL from HTML tag
*
* @param string $html HTML tag e.g. `<a href="../foo">Page Link</a>`
* @param PageInterface|null $page Page, defaults to the current page object
* @return string Returns final HTML string
*/
public static function processLinkHtml($html, PageInterface $page = null)
{
$excerpt = static::getExcerptFromHtml($html, 'a');
if (null === $excerpt) {
return '';
}
$original_href = $excerpt['element']['attributes']['href'];
$excerpt = static::processLinkExcerpt($excerpt, $page, 'link');
$excerpt['element']['attributes']['data-href'] = $original_href;
$html = static::getHtmlFromExcerpt($excerpt);
return $html;
}
/**
* Get an Excerpt array from a chunk of HTML
*
* @param string $html Chunk of HTML
* @param string $tag A tag, for example `img`
* @return array|null returns nested array excerpt
*/
public static function getExcerptFromHtml($html, $tag)
{
$doc = new DOMDocument('1.0', 'UTF-8');
$internalErrors = libxml_use_internal_errors(true);
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
libxml_use_internal_errors($internalErrors);
$elements = $doc->getElementsByTagName($tag);
$excerpt = null;
$inner = [];
foreach ($elements as $element) {
$attributes = [];
foreach ($element->attributes as $name => $value) {
$attributes[$name] = $value->value;
}
$excerpt = [
'element' => [
'name' => $element->tagName,
'attributes' => $attributes
]
];
foreach ($element->childNodes as $node) {
$inner[] = $doc->saveHTML($node);
}
$excerpt = array_merge_recursive($excerpt, ['element' => ['text' => implode('', $inner)]]);
}
return $excerpt;
}
/**
* Rebuild HTML tag from an excerpt array
*
* @param array $excerpt
* @return string
*/
public static function getHtmlFromExcerpt($excerpt)
{
$element = $excerpt['element'];
$html = '<'.$element['name'];
if (isset($element['attributes'])) {
foreach ($element['attributes'] as $name => $value) {
if ($value === null) {
continue;
}
$html .= ' '.$name.'="'.$value.'"';
}
}
if (isset($element['text'])) {
$html .= '>';
$html .= is_array($element['text']) ? static::getHtmlFromExcerpt(['element' => $element['text']]) : $element['text'];
$html .= '</'.$element['name'].'>';
} else {
$html .= ' />';
}
return $html;
}
/**
* Process a Link excerpt
*
* @param array $excerpt
* @param PageInterface|null $page Page, defaults to the current page object
* @param string $type
* @return mixed
*/
public static function processLinkExcerpt($excerpt, PageInterface $page = null, $type = 'link')
{
$excerpts = new ExcerptsObject($page);
return $excerpts->processLinkExcerpt($excerpt, $type);
}
/**
* Process an image excerpt
*
* @param array $excerpt
* @param PageInterface|null $page Page, defaults to the current page object
* @return array
*/
public static function processImageExcerpt(array $excerpt, PageInterface $page = null)
{
$excerpts = new ExcerptsObject($page);
return $excerpts->processImageExcerpt($excerpt);
}
/**
* Process media actions
*
* @param Medium $medium
* @param string|array $url
* @param PageInterface|null $page Page, defaults to the current page object
* @return Medium|Link
*/
public static function processMediaActions($medium, $url, PageInterface $page = null)
{
$excerpts = new ExcerptsObject($page);
return $excerpts->processMediaActions($medium, $url);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/Truncator.php | system/src/Grav/Common/Helpers/Truncator.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use DOMText;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMWordsIterator;
use DOMLettersIterator;
use function in_array;
use function strlen;
/**
* This file is part of https://github.com/Bluetel-Solutions/twig-truncate-extension
*
* Copyright (c) 2015 Bluetel Solutions developers@bluetel.co.uk
* Copyright (c) 2015 Alex Wilson ajw@bluetel.co.uk
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Truncator
{
/**
* Safely truncates HTML by a given number of words.
*
* @param string $html Input HTML.
* @param int $limit Limit to how many words we preserve.
* @param string $ellipsis String to use as ellipsis (if any).
* @return string Safe truncated HTML.
*/
public static function truncateWords($html, $limit = 0, $ellipsis = '')
{
if ($limit <= 0) {
return $html;
}
$doc = self::htmlToDomDocument($html);
$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);
// Iterate over words.
$words = new DOMWordsIterator($container);
$truncated = false;
foreach ($words as $word) {
// If we have exceeded the limit, we delete the remainder of the content.
if ($words->key() >= $limit) {
// Grab current position.
$currentWordPosition = $words->currentWordPosition();
$curNode = $currentWordPosition[0];
$offset = $currentWordPosition[1];
$words = $currentWordPosition[2];
$curNode->nodeValue = substr(
$curNode->nodeValue,
0,
$words[$offset][1] + strlen($words[$offset][0])
);
self::removeProceedingNodes($curNode, $container);
if (!empty($ellipsis)) {
self::insertEllipsis($curNode, $ellipsis);
}
$truncated = true;
break;
}
}
// Return original HTML if not truncated.
if ($truncated) {
$html = self::getCleanedHtml($doc, $container);
}
return $html;
}
/**
* Safely truncates HTML by a given number of letters.
*
* @param string $html Input HTML.
* @param int $limit Limit to how many letters we preserve.
* @param string $ellipsis String to use as ellipsis (if any).
* @return string Safe truncated HTML.
*/
public static function truncateLetters($html, $limit = 0, $ellipsis = '')
{
if ($limit <= 0) {
return $html;
}
$doc = self::htmlToDomDocument($html);
$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);
// Iterate over letters.
$letters = new DOMLettersIterator($container);
$truncated = false;
foreach ($letters as $letter) {
// If we have exceeded the limit, we want to delete the remainder of this document.
if ($letters->key() >= $limit) {
$currentText = $letters->currentTextPosition();
$currentText[0]->nodeValue = mb_substr($currentText[0]->nodeValue, 0, $currentText[1] + 1);
self::removeProceedingNodes($currentText[0], $container);
if (!empty($ellipsis)) {
self::insertEllipsis($currentText[0], $ellipsis);
}
$truncated = true;
break;
}
}
// Return original HTML if not truncated.
if ($truncated) {
$html = self::getCleanedHtml($doc, $container);
}
return $html;
}
/**
* Builds a DOMDocument object from a string containing HTML.
*
* @param string $html HTML to load
* @return DOMDocument Returns a DOMDocument object.
*/
public static function htmlToDomDocument($html)
{
if (!$html) {
$html = '';
}
// Transform multibyte entities which otherwise display incorrectly.
$html = mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, ~0], 'UTF-8');
// Internal errors enabled as HTML5 not fully supported.
libxml_use_internal_errors(true);
// Instantiate new DOMDocument object, and then load in UTF-8 HTML.
$dom = new DOMDocument();
$dom->encoding = 'UTF-8';
$dom->loadHTML("<div>$html</div>");
return $dom;
}
/**
* Removes all nodes after the current node.
*
* @param DOMNode|DOMElement $domNode
* @param DOMNode|DOMElement $topNode
* @return void
*/
private static function removeProceedingNodes($domNode, $topNode)
{
/** @var DOMNode|null $nextNode */
$nextNode = $domNode->nextSibling;
if ($nextNode !== null) {
self::removeProceedingNodes($nextNode, $topNode);
$domNode->parentNode->removeChild($nextNode);
} else {
//scan upwards till we find a sibling
$curNode = $domNode->parentNode;
while ($curNode !== $topNode) {
if ($curNode->nextSibling !== null) {
$curNode = $curNode->nextSibling;
self::removeProceedingNodes($curNode, $topNode);
$curNode->parentNode->removeChild($curNode);
break;
}
$curNode = $curNode->parentNode;
}
}
}
/**
* Clean extra code
*
* @param DOMDocument $doc
* @param DOMNode $container
* @return string
*/
private static function getCleanedHTML(DOMDocument $doc, DOMNode $container)
{
while ($doc->firstChild) {
$doc->removeChild($doc->firstChild);
}
while ($container->firstChild) {
$doc->appendChild($container->firstChild);
}
return trim($doc->saveHTML());
}
/**
* Inserts an ellipsis
*
* @param DOMNode|DOMElement $domNode Element to insert after.
* @param string $ellipsis Text used to suffix our document.
* @return void
*/
private static function insertEllipsis($domNode, $ellipsis)
{
$avoid = array('a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5'); //html tags to avoid appending the ellipsis to
if ($domNode->parentNode->parentNode !== null && in_array($domNode->parentNode->nodeName, $avoid, true)) {
// Append as text node to parent instead
$textNode = new DOMText($ellipsis);
/** @var DOMNode|null $nextSibling */
$nextSibling = $domNode->parentNode->parentNode->nextSibling;
if ($nextSibling) {
$domNode->parentNode->parentNode->insertBefore($textNode, $domNode->parentNode->parentNode->nextSibling);
} else {
$domNode->parentNode->parentNode->appendChild($textNode);
}
} else {
// Append to current node
$domNode->nodeValue = rtrim($domNode->nodeValue) . $ellipsis;
}
}
/**
* @param string $text
* @param int $length
* @param string $ending
* @param bool $exact
* @param bool $considerHtml
* @return string
*/
public function truncate(
$text,
$length = 100,
$ending = '...',
$exact = false,
$considerHtml = true
) {
if ($considerHtml) {
// if the plain text is shorter than the maximum length, return the whole text
if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
return $text;
}
// splits all html-tags to scanable lines
preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
$total_length = strlen($ending);
$truncate = '';
$open_tags = [];
foreach ($lines as $line_matchings) {
// if there is any html-tag in this line, handle it and add it (uncounted) to the output
if (!empty($line_matchings[1])) {
// if it's an "empty element" with or without xhtml-conform closing slash
if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
// do nothing
// if tag is a closing tag
} elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
// delete tag from $open_tags list
$pos = array_search($tag_matchings[1], $open_tags);
if ($pos !== false) {
unset($open_tags[$pos]);
}
// if tag is an opening tag
} elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
// add tag to the beginning of $open_tags list
array_unshift($open_tags, strtolower($tag_matchings[1]));
}
// add html-tag to $truncate'd text
$truncate .= $line_matchings[1];
}
// calculate the length of the plain text part of the line; handle entities as one character
$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
if ($total_length+$content_length> $length) {
// the number of characters which are left
$left = $length - $total_length;
$entities_length = 0;
// search for html entities
if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
// calculate the real length of all entities in the legal range
foreach ($entities[0] as $entity) {
if ($entity[1]+1-$entities_length <= $left) {
$left--;
$entities_length += strlen($entity[0]);
} else {
// no more characters left
break;
}
}
}
$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
// maximum lenght is reached, so get off the loop
break;
} else {
$truncate .= $line_matchings[2];
$total_length += $content_length;
}
// if the maximum length is reached, get off the loop
if ($total_length>= $length) {
break;
}
}
} else {
if (strlen($text) <= $length) {
return $text;
}
$truncate = substr($text, 0, $length - strlen($ending));
}
// if the words shouldn't be cut in the middle...
if (!$exact) {
// ...search the last occurance of a space...
$spacepos = strrpos($truncate, ' ');
if (false !== $spacepos) {
// ...and cut the text in this position
$truncate = substr($truncate, 0, $spacepos);
}
}
// add the defined ending to the text
$truncate .= $ending;
if (isset($open_tags)) {
// close all unclosed html-tags
foreach ($open_tags as $tag) {
$truncate .= '</' . $tag . '>';
}
}
return $truncate;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/Exif.php | system/src/Grav/Common/Helpers/Exif.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use Grav\Common\Grav;
use PHPExif\Reader\Reader;
use RuntimeException;
use function function_exists;
/**
* Class Exif
* @package Grav\Common\Helpers
*/
class Exif
{
/** @var Reader */
public $reader;
/**
* Exif constructor.
* @throws RuntimeException
*/
public function __construct()
{
if (Grav::instance()['config']->get('system.media.auto_metadata_exif')) {
if (function_exists('exif_read_data') && class_exists(Reader::class)) {
$this->reader = Reader::factory(Reader::TYPE_NATIVE);
} else {
throw new RuntimeException('Please enable the Exif extension for PHP or disable Exif support in Grav system configuration');
}
}
}
/**
* @return Reader
*/
public function getReader()
{
return $this->reader;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/YamlLinter.php | system/src/Grav/Common/Helpers/YamlLinter.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use Exception;
use Grav\Common\Grav;
use Grav\Common\Utils;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use RocketTheme\Toolbox\File\MarkdownFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use Symfony\Component\Yaml\Yaml;
/**
* Class YamlLinter
* @package Grav\Common\Helpers
*/
class YamlLinter
{
/**
* @param string|null $folder
* @return array
*/
public static function lint(string $folder = null)
{
if (null !== $folder) {
$folder = $folder ?: GRAV_ROOT;
return static::recurseFolder($folder);
}
return array_merge(static::lintConfig(), static::lintPages(), static::lintBlueprints());
}
/**
* @return array
*/
public static function lintPages()
{
return static::recurseFolder('page://');
}
/**
* @return array
*/
public static function lintConfig()
{
return static::recurseFolder('config://');
}
/**
* @return array
*/
public static function lintBlueprints()
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$current_theme = Grav::instance()['config']->get('system.pages.theme');
$theme_path = 'themes://' . $current_theme . '/blueprints';
$locator->addPath('blueprints', '', [$theme_path]);
return static::recurseFolder('blueprints://');
}
/**
* @param string $path
* @param string $extensions
* @return array
*/
public static function recurseFolder($path, $extensions = '(md|yaml)')
{
$lint_errors = [];
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$flags = RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
if ($locator->isStream($path)) {
$directory = $locator->getRecursiveIterator($path, $flags);
} else {
$directory = new RecursiveDirectoryIterator($path, $flags);
}
$recursive = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
$iterator = new RegexIterator($recursive, '/^.+\.'.$extensions.'$/ui');
/** @var RecursiveDirectoryIterator $file */
foreach ($iterator as $filepath => $file) {
try {
Yaml::parse(static::extractYaml($filepath));
} catch (Exception $e) {
$lint_errors[str_replace(GRAV_ROOT, '', $filepath)] = $e->getMessage();
}
}
return $lint_errors;
}
/**
* @param string $path
* @return string
*/
protected static function extractYaml($path)
{
$extension = Utils::pathinfo($path, PATHINFO_EXTENSION);
if ($extension === 'md') {
$file = MarkdownFile::instance($path);
$contents = $file->frontmatter();
$file->free();
} else {
$contents = file_get_contents($path);
}
return $contents;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Helpers/Base32.php | system/src/Grav/Common/Helpers/Base32.php | <?php
/**
* @package Grav\Common\Helpers
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Helpers;
use function chr;
use function count;
use function ord;
use function strlen;
/**
* Class Base32
* @package Grav\Common\Helpers
*/
class Base32
{
/** @var string */
protected static $base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/** @var array */
protected static $base32Lookup = [
0xFF,0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, // '0', '1', '2', '3', '4', '5', '6', '7'
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // '8', '9', ':', ';', '<', '=', '>', '?'
0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G'
0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W'
0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_'
0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g'
0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w'
0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
];
/**
* Encode in Base32
*
* @param string $bytes
* @return string
*/
public static function encode($bytes)
{
$i = 0;
$index = 0;
$base32 = '';
$bytesLen = strlen($bytes);
while ($i < $bytesLen) {
$currByte = ord($bytes[$i]);
/* Is the current digit going to span a byte boundary? */
if ($index > 3) {
if (($i + 1) < $bytesLen) {
$nextByte = ord($bytes[$i+1]);
} else {
$nextByte = 0;
}
$digit = $currByte & (0xFF >> $index);
$index = ($index + 5) % 8;
$digit <<= $index;
$digit |= $nextByte >> (8 - $index);
$i++;
} else {
$digit = ($currByte >> (8 - ($index + 5))) & 0x1F;
$index = ($index + 5) % 8;
if ($index === 0) {
$i++;
}
}
$base32 .= self::$base32Chars[$digit];
}
return $base32;
}
/**
* Decode in Base32
*
* @param string $base32
* @return string
*/
public static function decode($base32)
{
$bytes = [];
$base32Len = strlen($base32);
$base32LookupLen = count(self::$base32Lookup);
for ($i = $base32Len * 5 / 8 - 1; $i >= 0; --$i) {
$bytes[] = 0;
}
for ($i = 0, $index = 0, $offset = 0; $i < $base32Len; $i++) {
$lookup = ord($base32[$i]) - ord('0');
/* Skip chars outside the lookup table */
if ($lookup < 0 || $lookup >= $base32LookupLen) {
continue;
}
$digit = self::$base32Lookup[$lookup];
/* If this digit is not in the table, ignore it */
if ($digit === 0xFF) {
continue;
}
if ($index <= 3) {
$index = ($index + 5) % 8;
if ($index === 0) {
$bytes[$offset] |= $digit;
$offset++;
if ($offset >= count($bytes)) {
break;
}
} else {
$bytes[$offset] |= $digit << (8 - $index);
}
} else {
$index = ($index + 5) % 8;
$bytes[$offset] |= ($digit >> $index);
$offset++;
if ($offset >= count($bytes)) {
break;
}
$bytes[$offset] |= $digit << (8 - $index);
}
}
$bites = '';
foreach ($bytes as $byte) {
$bites .= chr($byte);
}
return $bites;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Link.php | system/src/Grav/Common/Assets/Link.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class Link
* @package Grav\Common\Assets
*/
class Link extends BaseAsset
{
/**
* Css constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'link',
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
return '<link href="' . trim($this->asset) . $this->renderQueryString() . '"' . $this->renderAttributes() . $this->integrityHash($this->asset) . ">\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/JsModule.php | system/src/Grav/Common/Assets/JsModule.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class Js
* @package Grav\Common\Assets
*/
class JsModule extends BaseAsset
{
/**
* Js constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'js_module',
'attributes' => ['type' => 'module']
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
if (isset($this->attributes['loading']) && $this->attributes['loading'] === 'inline') {
$buffer = $this->gatherLinks([$this], self::JS_MODULE_ASSET);
return '<script' . $this->renderAttributes() . ">\n" . trim($buffer) . "\n</script>\n";
}
return '<script src="' . trim($this->asset) . $this->renderQueryString() . '"' . $this->renderAttributes() . $this->integrityHash($this->asset) . "></script>\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/InlineCss.php | system/src/Grav/Common/Assets/InlineCss.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class InlineCss
* @package Grav\Common\Assets
*/
class InlineCss extends BaseAsset
{
/**
* InlineCss constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'css',
'position' => 'after'
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
return '<style' . $this->renderAttributes(). ">\n" . trim($this->asset) . "\n</style>\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/InlineJs.php | system/src/Grav/Common/Assets/InlineJs.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class InlineJs
* @package Grav\Common\Assets
*/
class InlineJs extends BaseAsset
{
/**
* InlineJs constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'js',
'position' => 'after'
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
return '<script' . $this->renderAttributes(). ">\n" . trim($this->asset) . "\n</script>\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/BaseAsset.php | system/src/Grav/Common/Assets/BaseAsset.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Assets\Traits\AssetUtilsTrait;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Framework\Object\PropertyObject;
use RocketTheme\Toolbox\File\File;
use SplFileInfo;
/**
* Class BaseAsset
* @package Grav\Common\Assets
*/
abstract class BaseAsset extends PropertyObject
{
use AssetUtilsTrait;
protected const CSS_ASSET = 1;
protected const JS_ASSET = 2;
protected const JS_MODULE_ASSET = 3;
/** @var string|false */
protected $asset;
/** @var string */
protected $asset_type;
/** @var int */
protected $order;
/** @var string */
protected $group;
/** @var string */
protected $position;
/** @var int */
protected $priority;
/** @var array */
protected $attributes = [];
/** @var string */
protected $timestamp;
/** @var int|false */
protected $modified;
/** @var bool */
protected $remote;
/** @var string */
protected $query = '';
// Private Bits
/** @var bool */
private $css_rewrite = false;
/** @var bool */
private $css_minify = false;
/**
* @return string
*/
abstract function render();
/**
* BaseAsset constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_config = [
'group' => 'head',
'position' => 'pipeline',
'priority' => 10,
'modified' => null,
'asset' => null
];
// Merge base defaults
$elements = array_merge($base_config, $elements);
parent::__construct($elements, $key);
}
/**
* @param string|false $asset
* @param array $options
* @return $this|false
*/
public function init($asset, $options)
{
if (!$asset) {
return false;
}
$config = Grav::instance()['config'];
$uri = Grav::instance()['uri'];
// set attributes
foreach ($options as $key => $value) {
if ($this->hasProperty($key)) {
$this->setProperty($key, $value);
} else {
$this->attributes[$key] = $value;
}
}
// Force priority to be an int
$this->priority = (int) $this->priority;
// Do some special stuff for CSS/JS (not inline)
if (!Utils::startsWith($this->getType(), 'inline')) {
$this->base_url = rtrim($uri->rootUrl($config->get('system.absolute_urls')), '/') . '/';
$this->remote = static::isRemoteLink($asset);
// Move this to render?
if (!$this->remote) {
$asset_parts = parse_url($asset);
if (isset($asset_parts['query'])) {
$this->query = $asset_parts['query'];
unset($asset_parts['query']);
$asset = Uri::buildUrl($asset_parts);
}
$locator = Grav::instance()['locator'];
if ($locator->isStream($asset)) {
$path = $locator->findResource($asset, true);
} else {
$path = GRAV_WEBROOT . $asset;
}
// If local file is missing return
if ($path === false) {
return false;
}
$file = new SplFileInfo($path);
$asset = $this->buildLocalLink($file->getPathname());
$this->modified = $file->isFile() ? $file->getMTime() : false;
}
}
$this->asset = $asset;
return $this;
}
/**
* @return string|false
*/
public function getAsset()
{
return $this->asset;
}
/**
* @return bool
*/
public function getRemote()
{
return $this->remote;
}
/**
* @param string $position
* @return $this
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Receive asset location and return the SRI integrity hash
*
* @param string $input
* @return string
*/
public static function integrityHash($input)
{
$grav = Grav::instance();
$uri = $grav['uri'];
$assetsConfig = $grav['config']->get('system.assets');
if (!self::isRemoteLink($input) && !empty($assetsConfig['enable_asset_sri']) && $assetsConfig['enable_asset_sri']) {
$input = preg_replace('#^' . $uri->rootUrl() . '#', '', $input);
$asset = File::instance(GRAV_WEBROOT . $input);
if ($asset->exists()) {
$dataToHash = $asset->content();
$hash = hash('sha256', $dataToHash, true);
$hash_base64 = base64_encode($hash);
return ' integrity="sha256-' . $hash_base64 . '"';
}
}
return '';
}
/**
*
* Get the last modification time of asset
*
* @param string $asset the asset string reference
*
* @return string the last modifcation time or false on error
*/
// protected function getLastModificationTime($asset)
// {
// $file = GRAV_WEBROOT . $asset;
// if (Grav::instance()['locator']->isStream($asset)) {
// $file = $this->buildLocalLink($asset, true);
// }
//
// return file_exists($file) ? filemtime($file) : false;
// }
/**
*
* Build local links including grav asset shortcodes
*
* @param string $asset the asset string reference
*
* @return string|false the final link url to the asset
*/
protected function buildLocalLink($asset)
{
if ($asset) {
return $this->base_url . ltrim(Utils::replaceFirstOccurrence(GRAV_WEBROOT, '', $asset), '/');
}
return false;
}
/**
* Implements JsonSerializable interface.
*
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return ['type' => $this->getType(), 'elements' => $this->getElements()];
}
/**
* Placeholder for AssetUtilsTrait method
*
* @param string $file
* @param string $dir
* @param bool $local
* @return string
*/
protected function cssRewrite($file, $dir, $local)
{
return '';
}
/**
* Finds relative JS urls() and rewrites the URL with an absolute one
*
* @param string $file the css source file
* @param string $dir local relative path to the css file
* @param bool $local is this a local or remote asset
* @return string
*/
protected function jsRewrite($file, $dir, $local)
{
return '';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/BlockAssets.php | system/src/Grav/Common/Assets/BlockAssets.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Assets;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Framework\ContentBlock\HtmlBlock;
use function strlen;
/**
* Register block assets into Grav.
*/
class BlockAssets
{
/**
* @param HtmlBlock $block
* @return void
*/
public static function registerAssets(HtmlBlock $block): void
{
$grav = Grav::instance();
/** @var Assets $assets */
$assets = $grav['assets'];
$types = $block->getAssets();
foreach ($types as $type => $groups) {
switch ($type) {
case 'frameworks':
static::registerFrameworks($assets, $groups);
break;
case 'styles':
static::registerStyles($assets, $groups);
break;
case 'scripts':
static::registerScripts($assets, $groups);
break;
case 'links':
static::registerLinks($assets, $groups);
break;
case 'html':
static::registerHtml($assets, $groups);
break;
}
}
}
/**
* @param Assets $assets
* @param array $list
* @return void
*/
protected static function registerFrameworks(Assets $assets, array $list): void
{
if ($list) {
throw new \RuntimeException('Not Implemented');
}
}
/**
* @param Assets $assets
* @param array $groups
* @return void
*/
protected static function registerStyles(Assets $assets, array $groups): void
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
foreach ($groups as $group => $styles) {
foreach ($styles as $style) {
switch ($style[':type']) {
case 'file':
$options = [
'priority' => $style[':priority'],
'group' => $group,
'type' => $style['type'],
'media' => $style['media']
] + $style['element'];
$assets->addCss(static::getRelativeUrl($style['href'], $config->get('system.assets.css_pipeline')), $options);
break;
case 'inline':
$options = [
'priority' => $style[':priority'],
'group' => $group,
'type' => $style['type'],
] + $style['element'];
$assets->addInlineCss($style['content'], $options);
break;
}
}
}
}
/**
* @param Assets $assets
* @param array $groups
* @return void
*/
protected static function registerScripts(Assets $assets, array $groups): void
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
foreach ($groups as $group => $scripts) {
$group = $group === 'footer' ? 'bottom' : $group;
foreach ($scripts as $script) {
switch ($script[':type']) {
case 'file':
$options = [
'group' => $group,
'priority' => $script[':priority'],
'src' => $script['src'],
'type' => $script['type'],
'loading' => $script['loading'],
'defer' => $script['defer'],
'async' => $script['async'],
'handle' => $script['handle']
] + $script['element'];
$assets->addJs(static::getRelativeUrl($script['src'], $config->get('system.assets.js_pipeline')), $options);
break;
case 'inline':
$options = [
'priority' => $script[':priority'],
'group' => $group,
'type' => $script['type'],
'loading' => $script['loading']
] + $script['element'];
$assets->addInlineJs($script['content'], $options);
break;
}
}
}
}
/**
* @param Assets $assets
* @param array $groups
* @return void
*/
protected static function registerLinks(Assets $assets, array $groups): void
{
foreach ($groups as $group => $links) {
foreach ($links as $link) {
$href = $link['href'];
$options = [
'group' => $group,
'priority' => $link[':priority'],
'rel' => $link['rel'],
] + $link['element'];
$assets->addLink($href, $options);
}
}
}
/**
* @param Assets $assets
* @param array $groups
* @return void
*/
protected static function registerHtml(Assets $assets, array $groups): void
{
if ($groups) {
throw new \RuntimeException('Not Implemented');
}
}
/**
* @param string $url
* @param bool $pipeline
* @return string
*/
protected static function getRelativeUrl($url, $pipeline)
{
$grav = Grav::instance();
$base = rtrim($grav['base_url'], '/') ?: '/';
if (strpos($url, $base) === 0) {
if ($pipeline) {
// Remove file timestamp if CSS pipeline has been enabled.
$url = preg_replace('|[?#].*|', '', $url);
}
return substr($url, strlen($base) - 1);
}
return $url;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/InlineJsModule.php | system/src/Grav/Common/Assets/InlineJsModule.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class InlineJs
* @package Grav\Common\Assets
*/
class InlineJsModule extends BaseAsset
{
/**
* InlineJs constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'js_module',
'attributes' => ['type' => 'module'],
'position' => 'after'
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
return '<script' . $this->renderAttributes(). ">\n" . trim($this->asset) . "\n</script>\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Css.php | system/src/Grav/Common/Assets/Css.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class Css
* @package Grav\Common\Assets
*/
class Css extends BaseAsset
{
/**
* Css constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'css',
'attributes' => [
'type' => 'text/css',
'rel' => 'stylesheet'
]
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
if (isset($this->attributes['loading']) && $this->attributes['loading'] === 'inline') {
$buffer = $this->gatherLinks([$this], self::CSS_ASSET);
return "<style>\n" . trim($buffer) . "\n</style>\n";
}
return '<link href="' . trim($this->asset) . $this->renderQueryString() . '"' . $this->renderAttributes() . $this->integrityHash($this->asset) . ">\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Js.php | system/src/Grav/Common/Assets/Js.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Utils;
/**
* Class Js
* @package Grav\Common\Assets
*/
class Js extends BaseAsset
{
/**
* Js constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
$base_options = [
'asset_type' => 'js',
];
$merged_attributes = Utils::arrayMergeRecursiveUnique($base_options, $elements);
parent::__construct($merged_attributes, $key);
}
/**
* @return string
*/
public function render()
{
if (isset($this->attributes['loading']) && $this->attributes['loading'] === 'inline') {
$buffer = $this->gatherLinks([$this], self::JS_ASSET);
return '<script' . $this->renderAttributes() . ">\n" . trim($buffer) . "\n</script>\n";
}
return '<script src="' . trim($this->asset) . $this->renderQueryString() . '"' . $this->renderAttributes() . $this->integrityHash($this->asset) . "></script>\n";
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Pipeline.php | system/src/Grav/Common/Assets/Pipeline.php | <?php
/**
* @package Grav\Common\Assets
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets;
use Grav\Common\Assets\Traits\AssetUtilsTrait;
use Grav\Common\Config\Config;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Framework\Object\PropertyObject;
use MatthiasMullie\Minify\CSS;
use MatthiasMullie\Minify\JS;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function array_key_exists;
/**
* Class Pipeline
* @package Grav\Common\Assets
*/
class Pipeline extends PropertyObject
{
use AssetUtilsTrait;
protected const CSS_ASSET = 1;
protected const JS_ASSET = 2;
protected const JS_MODULE_ASSET = 3;
/** @const Regex to match CSS urls */
protected const CSS_URL_REGEX = '{url\(([\'\"]?)(.*?)\1\)|(@import)\s+([\'\"])(.*?)\4}';
/** @const Regex to match JS imports */
protected const JS_IMPORT_REGEX = '{import.+from\s?[\'|\"](.+?)[\'|\"]}';
/** @const Regex to match CSS sourcemap comments */
protected const CSS_SOURCEMAP_REGEX = '{\/\*# (.*?) \*\/}';
protected const FIRST_FORWARDSLASH_REGEX = '{^\/{1}\w}';
// Following variables come from the configuration:
/** @var bool */
protected $css_minify = false;
/** @var bool */
protected $css_minify_windows = false;
/** @var bool */
protected $css_rewrite = false;
/** @var bool */
protected $css_pipeline_include_externals = true;
/** @var bool */
protected $js_minify = false;
/** @var bool */
protected $js_minify_windows = false;
/** @var bool */
protected $js_pipeline_include_externals = true;
/** @var string */
protected $assets_dir;
/** @var string */
protected $assets_url;
/** @var string */
protected $timestamp;
/** @var array */
protected $attributes;
/** @var string */
protected $query = '';
/** @var string */
protected $asset;
/**
* Pipeline constructor.
* @param array $elements
* @param string|null $key
*/
public function __construct(array $elements = [], ?string $key = null)
{
parent::__construct($elements, $key);
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
/** @var Config $config */
$config = Grav::instance()['config'];
/** @var Uri $uri */
$uri = Grav::instance()['uri'];
$this->base_url = rtrim($uri->rootUrl($config->get('system.absolute_urls')), '/') . '/';
$this->assets_dir = $locator->findResource('asset://');
if (!$this->assets_dir) {
// Attempt to create assets folder if it doesn't exist yet.
$this->assets_dir = $locator->findResource('asset://', true, true);
Folder::mkdir($this->assets_dir);
$locator->clearCache();
}
$this->assets_url = $locator->findResource('asset://', false);
}
/**
* Minify and concatenate CSS
*
* @param array $assets
* @param string $group
* @param array $attributes
* @return bool|string URL or generated content if available, else false
*/
public function renderCss($assets, $group, $attributes = [])
{
// temporary list of assets to pipeline
$inline_group = false;
if (array_key_exists('loading', $attributes) && $attributes['loading'] === 'inline') {
$inline_group = true;
unset($attributes['loading']);
}
// Store Attributes
$this->attributes = array_merge(['type' => 'text/css', 'rel' => 'stylesheet'], $attributes);
// Compute uid based on assets and timestamp
$json_assets = json_encode($assets);
$uid = md5($json_assets . (int)$this->css_minify . (int)$this->css_rewrite . $group);
$file = $uid . '.css';
$relative_path = "{$this->base_url}{$this->assets_url}/{$file}";
$filepath = "{$this->assets_dir}/{$file}";
if (file_exists($filepath)) {
$buffer = file_get_contents($filepath) . "\n";
} else {
//if nothing found get out of here!
if (empty($assets)) {
return false;
}
// Concatenate files
$buffer = $this->gatherLinks($assets, self::CSS_ASSET);
// Minify if required
if ($this->shouldMinify('css')) {
$minifier = new CSS();
$minifier->add($buffer);
$buffer = $minifier->minify();
}
// Write file
if (trim($buffer) !== '') {
file_put_contents($filepath, $buffer);
}
}
if ($inline_group) {
$output = "<style>\n" . $buffer . "\n</style>\n";
} else {
$this->asset = $relative_path;
$output = '<link href="' . $relative_path . $this->renderQueryString() . '"' . $this->renderAttributes() . BaseAsset::integrityHash($this->asset) . ">\n";
}
return $output;
}
/**
* Minify and concatenate JS files.
*
* @param array $assets
* @param string $group
* @param array $attributes
* @return bool|string URL or generated content if available, else false
*/
public function renderJs($assets, $group, $attributes = [], $type = self::JS_ASSET)
{
// temporary list of assets to pipeline
$inline_group = false;
if (array_key_exists('loading', $attributes) && $attributes['loading'] === 'inline') {
$inline_group = true;
unset($attributes['loading']);
}
// Store Attributes
$this->attributes = $attributes;
// Compute uid based on assets and timestamp
$json_assets = json_encode($assets);
$uid = md5($json_assets . $this->js_minify . $group);
$file = $uid . '.js';
$relative_path = "{$this->base_url}{$this->assets_url}/{$file}";
$filepath = "{$this->assets_dir}/{$file}";
if (file_exists($filepath)) {
$buffer = file_get_contents($filepath) . "\n";
} else {
//if nothing found get out of here!
if (empty($assets)) {
return false;
}
// Concatenate files
$buffer = $this->gatherLinks($assets, $type);
// Minify if required
if ($this->shouldMinify('js')) {
$minifier = new JS();
$minifier->add($buffer);
$buffer = $minifier->minify();
}
// Write file
if (trim($buffer) !== '') {
file_put_contents($filepath, $buffer);
}
}
if ($inline_group) {
$output = '<script' . $this->renderAttributes(). ">\n" . $buffer . "\n</script>\n";
} else {
$this->asset = $relative_path;
$output = '<script src="' . $relative_path . $this->renderQueryString() . '"' . $this->renderAttributes() . BaseAsset::integrityHash($this->asset) . "></script>\n";
}
return $output;
}
/**
* Minify and concatenate JS files.
*
* @param array $assets
* @param string $group
* @param array $attributes
* @return bool|string URL or generated content if available, else false
*/
public function renderJs_Module($assets, $group, $attributes = [])
{
$attributes['type'] = 'module';
return $this->renderJs($assets, $group, $attributes, self::JS_MODULE_ASSET);
}
/**
* Finds relative CSS urls() and rewrites the URL with an absolute one
*
* @param string $file the css source file
* @param string $dir , $local relative path to the css file
* @param bool $local is this a local or remote asset
* @return string
*/
protected function cssRewrite($file, $dir, $local)
{
// Strip any sourcemap comments
$file = preg_replace(self::CSS_SOURCEMAP_REGEX, '', $file);
// Find any css url() elements, grab the URLs and calculate an absolute path
// Then replace the old url with the new one
$file = (string)preg_replace_callback(self::CSS_URL_REGEX, function ($matches) use ($dir, $local) {
$isImport = count($matches) > 3 && $matches[3] === '@import';
if ($isImport) {
$old_url = $matches[5];
} else {
$old_url = $matches[2];
}
// Ensure link is not rooted to web server, a data URL, or to a remote host
if (preg_match(self::FIRST_FORWARDSLASH_REGEX, $old_url) || Utils::startsWith($old_url, 'data:') || $this->isRemoteLink($old_url)) {
return $matches[0];
}
// clean leading /
$old_url = Utils::normalizePath($dir . '/' . $old_url);
if (preg_match(self::FIRST_FORWARDSLASH_REGEX, $old_url)) {
$old_url = ltrim($old_url, '/');
}
$new_url = ($local ? $this->base_url : '') . $old_url;
if ($isImport) {
return str_replace($matches[5], $new_url, $matches[0]);
} else {
return str_replace($matches[2], $new_url, $matches[0]);
}
}, $file);
return $file;
}
/**
* Finds relative JS urls() and rewrites the URL with an absolute one
*
* @param string $file the css source file
* @param string $dir local relative path to the css file
* @param bool $local is this a local or remote asset
* @return string
*/
protected function jsRewrite($file, $dir, $local)
{
// Find any js import elements, grab the URLs and calculate an absolute path
// Then replace the old url with the new one
$file = (string)preg_replace_callback(self::JS_IMPORT_REGEX, function ($matches) use ($dir, $local) {
$old_url = $matches[1];
// Ensure link is not rooted to web server, a data URL, or to a remote host
if (preg_match(self::FIRST_FORWARDSLASH_REGEX, $old_url) || $this->isRemoteLink($old_url)) {
return $matches[0];
}
// clean leading /
$old_url = Utils::normalizePath($dir . '/' . $old_url);
$old_url = str_replace('/./', '/', $old_url);
if (preg_match(self::FIRST_FORWARDSLASH_REGEX, $old_url)) {
$old_url = ltrim($old_url, '/');
}
$new_url = ($local ? $this->base_url : '') . $old_url;
return str_replace($matches[1], $new_url, $matches[0]);
}, $file);
return $file;
}
/**
* @param string $type
* @return bool
*/
private function shouldMinify($type = 'css')
{
$check = $type . '_minify';
$win_check = $type . '_minify_windows';
$minify = (bool) $this->$check;
// If this is a Windows server, and minify_windows is false (default value) skip the
// minification process because it will cause Apache to die/crash due to insufficient
// ThreadStackSize in httpd.conf - See: https://bugs.php.net/bug.php?id=47689
if (stripos(php_uname('s'), 'WIN') === 0 && !$this->{$win_check}) {
$minify = false;
}
return $minify;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php | system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php | <?php
/**
* @package Grav\Common\Assets\Traits
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets\Traits;
use Grav\Common\Assets;
use function count;
use function is_array;
use function is_int;
/**
* Trait LegacyAssetsTrait
* @package Grav\Common\Assets\Traits
*/
trait LegacyAssetsTrait
{
/**
* @param array $args
* @param string $type
* @return array
*/
protected function unifyLegacyArguments($args, $type = Assets::CSS_TYPE)
{
// First argument is always the asset
array_shift($args);
if (count($args) === 0) {
return [];
}
// New options array format
if (count($args) === 1 && is_array($args[0])) {
return $args[0];
}
// Handle obscure case where options array is mixed with a priority
if (count($args) === 2 && is_array($args[0]) && is_int($args[1])) {
$arguments = $args[0];
$arguments['priority'] = $args[1];
return $arguments;
}
switch ($type) {
case (Assets::JS_TYPE):
$defaults = ['priority' => null, 'pipeline' => true, 'loading' => null, 'group' => null];
$arguments = $this->createArgumentsFromLegacy($args, $defaults);
break;
case (Assets::INLINE_JS_TYPE):
$defaults = ['priority' => null, 'group' => null, 'attributes' => null];
$arguments = $this->createArgumentsFromLegacy($args, $defaults);
// special case to handle old attributes being passed in
if (isset($arguments['attributes'])) {
$old_attributes = $arguments['attributes'];
if (is_array($old_attributes)) {
$arguments = array_merge($arguments, $old_attributes);
} else {
$arguments['type'] = $old_attributes;
}
}
unset($arguments['attributes']);
break;
case (Assets::INLINE_CSS_TYPE):
$defaults = ['priority' => null, 'group' => null];
$arguments = $this->createArgumentsFromLegacy($args, $defaults);
break;
default:
case (Assets::CSS_TYPE):
$defaults = ['priority' => null, 'pipeline' => true, 'group' => null, 'loading' => null];
$arguments = $this->createArgumentsFromLegacy($args, $defaults);
}
return $arguments;
}
/**
* @param array $args
* @param array $defaults
* @return array
*/
protected function createArgumentsFromLegacy(array $args, array $defaults)
{
// Remove arguments with old default values.
$arguments = [];
foreach ($args as $arg) {
$default = current($defaults);
if ($arg !== $default) {
$arguments[key($defaults)] = $arg;
}
next($defaults);
}
return $arguments;
}
/**
* Convenience wrapper for async loading of JavaScript
*
* @param string|array $asset
* @param int $priority
* @param bool $pipeline
* @param string $group name of the group
* @return Assets
* @deprecated Please use dynamic method with ['loading' => 'async'].
*/
public function addAsyncJs($asset, $priority = 10, $pipeline = true, $group = 'head')
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'async\']', E_USER_DEPRECATED);
return $this->addJs($asset, $priority, $pipeline, 'async', $group);
}
/**
* Convenience wrapper for deferred loading of JavaScript
*
* @param string|array $asset
* @param int $priority
* @param bool $pipeline
* @param string $group name of the group
* @return Assets
* @deprecated Please use dynamic method with ['loading' => 'defer'].
*/
public function addDeferJs($asset, $priority = 10, $pipeline = true, $group = 'head')
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use dynamic method with [\'loading\' => \'defer\']', E_USER_DEPRECATED);
return $this->addJs($asset, $priority, $pipeline, 'defer', $group);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php | system/src/Grav/Common/Assets/Traits/TestingAssetsTrait.php | <?php
/**
* @package Grav\Common\Assets\Traits
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets\Traits;
use FilesystemIterator;
use Grav\Common\Grav;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use function strlen;
/**
* Trait TestingAssetsTrait
* @package Grav\Common\Assets\Traits
*/
trait TestingAssetsTrait
{
/**
* Determines if an asset exists as a collection, CSS or JS reference
*
* @param string $asset
* @return bool
*/
public function exists($asset)
{
return isset($this->collections[$asset]) || isset($this->assets_css[$asset]) || isset($this->assets_js[$asset]);
}
/**
* Return the array of all the registered collections
*
* @return array
*/
public function getCollections()
{
return $this->collections;
}
/**
* Set the array of collections explicitly
*
* @param array $collections
* @return $this
*/
public function setCollection($collections)
{
$this->collections = $collections;
return $this;
}
/**
* Return the array of all the registered CSS assets
* If a $key is provided, it will try to return only that asset
* else it will return null
*
* @param string|null $key the asset key
* @return array
*/
public function getCss($key = null)
{
if (null !== $key) {
$asset_key = md5($key);
return $this->assets_css[$asset_key] ?? null;
}
return $this->assets_css;
}
/**
* Return the array of all the registered JS assets
* If a $key is provided, it will try to return only that asset
* else it will return null
*
* @param string|null $key the asset key
* @return array
*/
public function getJs($key = null)
{
if (null !== $key) {
$asset_key = md5($key);
return $this->assets_js[$asset_key] ?? null;
}
return $this->assets_js;
}
/**
* Set the whole array of CSS assets
*
* @param array $css
* @return $this
*/
public function setCss($css)
{
$this->assets_css = $css;
return $this;
}
/**
* Set the whole array of JS assets
*
* @param array $js
* @return $this
*/
public function setJs($js)
{
$this->assets_js = $js;
return $this;
}
/**
* Removes an item from the CSS array if set
*
* @param string $key The asset key
* @return $this
*/
public function removeCss($key)
{
$asset_key = md5($key);
if (isset($this->assets_css[$asset_key])) {
unset($this->assets_css[$asset_key]);
}
return $this;
}
/**
* Removes an item from the JS array if set
*
* @param string $key The asset key
* @return $this
*/
public function removeJs($key)
{
$asset_key = md5($key);
if (isset($this->assets_js[$asset_key])) {
unset($this->assets_js[$asset_key]);
}
return $this;
}
/**
* Sets the state of CSS Pipeline
*
* @param bool $value
* @return $this
*/
public function setCssPipeline($value)
{
$this->css_pipeline = (bool)$value;
return $this;
}
/**
* Sets the state of JS Pipeline
*
* @param bool $value
* @return $this
*/
public function setJsPipeline($value)
{
$this->js_pipeline = (bool)$value;
return $this;
}
/**
* Reset all assets.
*
* @return $this
*/
public function reset()
{
$this->resetCss();
$this->resetJs();
$this->setCssPipeline(false);
$this->setJsPipeline(false);
$this->order = [];
return $this;
}
/**
* Reset JavaScript assets.
*
* @return $this
*/
public function resetJs()
{
$this->assets_js = [];
return $this;
}
/**
* Reset CSS assets.
*
* @return $this
*/
public function resetCss()
{
$this->assets_css = [];
return $this;
}
/**
* Explicitly set's a timestamp for assets
*
* @param string|int $value
*/
public function setTimestamp($value)
{
$this->timestamp = $value;
}
/**
* Get the timestamp for assets
*
* @param bool $include_join
* @return string|null
*/
public function getTimestamp($include_join = true)
{
if ($this->timestamp) {
return $include_join ? '?' . $this->timestamp : $this->timestamp;
}
return null;
}
/**
* Add all assets matching $pattern within $directory.
*
* @param string $directory Relative to the Grav root path, or a stream identifier
* @param string $pattern (regex)
* @return $this
*/
public function addDir($directory, $pattern = self::DEFAULT_REGEX)
{
$root_dir = GRAV_ROOT;
// Check if $directory is a stream.
if (strpos($directory, '://')) {
$directory = Grav::instance()['locator']->findResource($directory, null);
}
// Get files
$files = $this->rglob($root_dir . DIRECTORY_SEPARATOR . $directory, $pattern, $root_dir . '/');
// No luck? Nothing to do
if (!$files) {
return $this;
}
// Add CSS files
if ($pattern === self::CSS_REGEX) {
foreach ($files as $file) {
$this->addCss($file);
}
return $this;
}
// Add JavaScript files
if ($pattern === self::JS_REGEX) {
foreach ($files as $file) {
$this->addJs($file);
}
return $this;
}
// Add JavaScript Module files
if ($pattern === self::JS_MODULE_REGEX) {
foreach ($files as $file) {
$this->addJsModule($file);
}
return $this;
}
// Unknown pattern.
foreach ($files as $asset) {
$this->add($asset);
}
return $this;
}
/**
* Add all JavaScript assets within $directory
*
* @param string $directory Relative to the Grav root path, or a stream identifier
* @return $this
*/
public function addDirJs($directory)
{
return $this->addDir($directory, self::JS_REGEX);
}
/**
* Add all CSS assets within $directory
*
* @param string $directory Relative to the Grav root path, or a stream identifier
* @return $this
*/
public function addDirCss($directory)
{
return $this->addDir($directory, self::CSS_REGEX);
}
/**
* Recursively get files matching $pattern within $directory.
*
* @param string $directory
* @param string $pattern (regex)
* @param string|null $ltrim Will be trimmed from the left of the file path
* @return array
*/
protected function rglob($directory, $pattern, $ltrim = null)
{
$iterator = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
$directory,
FilesystemIterator::SKIP_DOTS
)), $pattern);
$offset = strlen($ltrim);
$files = [];
foreach ($iterator as $file) {
$files[] = substr($file->getPathname(), $offset);
}
return $files;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php | system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php | <?php
/**
* @package Grav\Common\Assets\Traits
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Assets\Traits;
use Closure;
use Grav\Common\Grav;
use Grav\Common\Utils;
use function dirname;
use function in_array;
use function is_array;
/**
* Trait AssetUtilsTrait
* @package Grav\Common\Assets\Traits
*/
trait AssetUtilsTrait
{
/**
* @var Closure|null
*
* Closure used by the pipeline to fetch assets.
*
* Useful when file_get_contents() function is not available in your PHP
* installation or when you want to apply any kind of preprocessing to
* your assets before they get pipelined.
*
* The closure will receive as the only parameter a string with the path/URL of the asset and
* it should return the content of the asset file as a string.
*/
protected $fetch_command;
/** @var string */
protected $base_url;
/**
* Determine whether a link is local or remote.
* Understands both "http://" and "https://" as well as protocol agnostic links "//"
*
* @param string $link
* @return bool
*/
public static function isRemoteLink($link)
{
$base = Grav::instance()['uri']->rootUrl(true);
// Sanity check for local URLs with absolute URL's enabled
if (Utils::startsWith($link, $base)) {
return false;
}
return (0 === strpos($link, 'http://') || 0 === strpos($link, 'https://') || 0 === strpos($link, '//'));
}
/**
* Download and concatenate the content of several links.
*
* @param array $assets
* @param int $type
* @return string
*/
protected function gatherLinks(array $assets, int $type = self::CSS_ASSET): string
{
$buffer = '';
foreach ($assets as $asset) {
$local = true;
$link = $asset->getAsset();
$relative_path = $link;
if (static::isRemoteLink($link)) {
$local = false;
if (0 === strpos($link, '//')) {
$link = 'http:' . $link;
}
$relative_dir = dirname($relative_path);
} else {
// Fix to remove relative dir if grav is in one
if (($this->base_url !== '/') && Utils::startsWith($relative_path, $this->base_url)) {
$base_url = '#' . preg_quote($this->base_url, '#') . '#';
$relative_path = ltrim(preg_replace($base_url, '/', $link, 1), '/');
}
$relative_dir = dirname($relative_path);
$link = GRAV_ROOT . '/' . $relative_path;
}
// TODO: looks like this is not being used.
$file = $this->fetch_command instanceof Closure ? @$this->fetch_command->__invoke($link) : @file_get_contents($link);
// No file found, skip it...
if ($file === false) {
continue;
}
// Double check last character being
if ($type === self::JS_ASSET || $type === self::JS_MODULE_ASSET) {
$file = rtrim($file, ' ;') . ';';
}
// If this is CSS + the file is local + rewrite enabled
if ($type === self::CSS_ASSET && $this->css_rewrite) {
$file = $this->cssRewrite($file, $relative_dir, $local);
}
if ($type === self::JS_MODULE_ASSET) {
$file = $this->jsRewrite($file, $relative_dir, $local);
}
$file = rtrim($file) . PHP_EOL;
$buffer .= $file;
}
// Pull out @imports and move to top
if ($type === self::CSS_ASSET) {
$buffer = $this->moveImports($buffer);
}
return $buffer;
}
/**
* Moves @import statements to the top of the file per the CSS specification
*
* @param string $file the file containing the combined CSS files
* @return string the modified file with any @imports at the top of the file
*/
protected function moveImports($file)
{
$regex = '{@import.*?["\']([^"\']+)["\'].*?;}';
$imports = [];
$file = (string)preg_replace_callback($regex, static function ($matches) use (&$imports) {
$imports[] = $matches[0];
return '';
}, $file);
return implode("\n", $imports) . "\n\n" . $file;
}
/**
*
* Build an HTML attribute string from an array.
*
* @return string
*/
protected function renderAttributes()
{
$html = '';
$no_key = ['loading'];
foreach ($this->attributes as $key => $value) {
if ($value === null) {
continue;
}
if (is_numeric($key)) {
$key = $value;
}
if (is_array($value)) {
$value = implode(' ', $value);
}
if (in_array($key, $no_key, true)) {
$element = htmlentities($value, ENT_QUOTES, 'UTF-8', false);
} else {
$element = $key . '="' . htmlentities($value, ENT_QUOTES, 'UTF-8', false) . '"';
}
$html .= ' ' . $element;
}
return $html;
}
/**
* Render Querystring
*
* @param string|null $asset
* @return string
*/
protected function renderQueryString($asset = null)
{
$querystring = '';
$asset = $asset ?? $this->asset;
$attributes = $this->attributes;
if (!empty($this->query)) {
if (Utils::contains($asset, '?')) {
$querystring .= '&' . $this->query;
} else {
$querystring .= '?' . $this->query;
}
}
if ($this->timestamp) {
if ($querystring || Utils::contains($asset, '?')) {
$querystring .= '&' . $this->timestamp;
} else {
$querystring .= '?' . $this->timestamp;
}
}
return $querystring;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TwigClockworkDataSource.php | system/src/Grav/Common/Twig/TwigClockworkDataSource.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Clockwork\DataSource\DataSource;
use Clockwork\Request\Request;
use Twig\Environment;
use Twig\Extension\ProfilerExtension;
use Twig\Profiler\Profile;
/**
* Class TwigClockworkDataSource
* @package Grav\Common\Twig
*/
class TwigClockworkDataSource extends DataSource
{
/** @var Environment */
protected $twig;
/** @var Profile */
protected $profile;
// Create a new data source, takes Twig instance as an argument
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
/**
* Register the Twig profiler extension
*/
public function listenToEvents(): void
{
$this->twig->addExtension(new ProfilerExtension($this->profile = new Profile()));
}
/**
* Adds rendered views to the request
*
* @param Request $request
* @return Request
*/
public function resolve(Request $request)
{
$timeline = (new TwigClockworkDumper())->dump($this->profile);
$request->viewsData = array_merge($request->viewsData, $timeline->finalize());
return $request;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TwigClockworkDumper.php | system/src/Grav/Common/Twig/TwigClockworkDumper.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Clockwork\Request\Timeline\Timeline;
use Twig\Profiler\Profile;
/**
* Class TwigClockworkDumper
* @package Grav\Common\Twig
*/
class TwigClockworkDumper
{
protected $lastId = 1;
/**
* Dumps a profile into a new rendered views timeline
*
* @param Profile $profile
* @return Timeline
*/
public function dump(Profile $profile)
{
$timeline = new Timeline;
$this->dumpProfile($profile, $timeline);
return $timeline;
}
/**
* @param Profile $profile
* @param Timeline $timeline
* @param null $parent
*/
public function dumpProfile(Profile $profile, Timeline $timeline, $parent = null)
{
$id = $this->lastId++;
if ($profile->isRoot()) {
$name = $profile->getName();
} elseif ($profile->isTemplate()) {
$name = $profile->getTemplate();
} else {
$name = $profile->getTemplate() . '::' . $profile->getType() . '(' . $profile->getName() . ')';
}
foreach ($profile as $p) {
$this->dumpProfile($p, $timeline, $id);
}
$data = $profile->__serialize();
$timeline->event($name, [
'name' => $id,
'start' => $data[3]['wt'] ?? null,
'end' => $data[4]['wt'] ?? null,
'data' => [
'data' => [],
'memoryUsage' => $data[4]['mu'] ?? null,
'parent' => $parent
]
]);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Twig.php | system/src/Grav/Common/Twig/Twig.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Config\Config;
use Grav\Common\Language\Language;
use Grav\Common\Language\LanguageCodes;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Security;
use Grav\Common\Twig\Exception\TwigException;
use Grav\Common\Twig\Extension\FilesystemExtension;
use Grav\Common\Twig\Extension\GravExtension;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RocketTheme\Toolbox\Event\Event;
use RuntimeException;
use Twig\Cache\FilesystemCache;
use Twig\DeferredExtension\DeferredExtension;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\CoreExtension;
use Twig\Extension\DebugExtension;
use Twig\Extension\StringLoaderExtension;
use Twig\Loader\ArrayLoader;
use Twig\Loader\ChainLoader;
use Twig\Loader\ExistsLoaderInterface;
use Twig\Loader\FilesystemLoader;
use Twig\Profiler\Profile;
use Twig\TwigFilter;
use Twig\TwigFunction;
use function function_exists;
use function in_array;
use function is_array;
/**
* Class Twig
* @package Grav\Common\Twig
*/
class Twig
{
/** @var Environment */
public $twig;
/** @var array */
public $twig_vars = [];
/** @var array */
public $twig_paths;
/** @var string */
public $template;
/** @var array */
public $plugins_hooked_nav = [];
/** @var array */
public $plugins_quick_tray = [];
/** @var array */
public $plugins_hooked_dashboard_widgets_top = [];
/** @var array */
public $plugins_hooked_dashboard_widgets_main = [];
/** @var Grav */
protected $grav;
/** @var FilesystemLoader */
protected $loader;
/** @var ArrayLoader */
protected $loaderArray;
/** @var bool */
protected $autoescape;
/** @var Profile */
protected $profile;
/**
* Constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
$this->twig_paths = [];
}
/**
* Twig initialization that sets the twig loader chain, then the environment, then extensions
* and also the base set of twig vars
*
* @return $this
*/
public function init()
{
if (null === $this->twig) {
/** @var Config $config */
$config = $this->grav['config'];
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
/** @var Language $language */
$language = $this->grav['language'];
$active_language = $language->getActive();
// handle language templates if available
if ($language->enabled()) {
$lang_templates = $locator->findResource('theme://templates/' . ($active_language ?: $language->getDefault()));
if ($lang_templates) {
$this->twig_paths[] = $lang_templates;
}
}
$this->twig_paths = array_merge($this->twig_paths, $locator->findResources('theme://templates'));
$this->grav->fireEvent('onTwigTemplatePaths');
// Add Grav core templates location
$core_templates = array_merge($locator->findResources('system://templates'), $locator->findResources('system://templates/testing'));
$this->twig_paths = array_merge($this->twig_paths, $core_templates);
$this->loader = new FilesystemLoader($this->twig_paths);
// Register all other prefixes as namespaces in twig
foreach ($locator->getPaths('theme') as $prefix => $_) {
if ($prefix === '') {
continue;
}
$twig_paths = [];
// handle language templates if available
if ($language->enabled()) {
$lang_templates = $locator->findResource('theme://'.$prefix.'templates/' . ($active_language ?: $language->getDefault()));
if ($lang_templates) {
$twig_paths[] = $lang_templates;
}
}
$twig_paths = array_merge($twig_paths, $locator->findResources('theme://'.$prefix.'templates'));
$namespace = trim($prefix, '/');
$this->loader->setPaths($twig_paths, $namespace);
}
$this->grav->fireEvent('onTwigLoader');
$this->loaderArray = new ArrayLoader([]);
$loader_chain = new ChainLoader([$this->loaderArray, $this->loader]);
$params = $config->get('system.twig');
if (!empty($params['cache'])) {
$cachePath = $locator->findResource('cache://twig', true, true);
$params['cache'] = new FilesystemCache($cachePath, FilesystemCache::FORCE_BYTECODE_INVALIDATION);
}
if (!$config->get('system.strict_mode.twig_compat', false)) {
// Force autoescape on for all files if in strict mode.
$params['autoescape'] = 'html';
} elseif (!empty($this->autoescape)) {
$params['autoescape'] = $this->autoescape ? 'html' : false;
}
if (empty($params['autoescape'])) {
user_error('Grav 2.0 will have Twig auto-escaping forced on (can be emulated by turning off \'system.strict_mode.twig_compat\' setting in your configuration)', E_USER_DEPRECATED);
}
$this->twig = new TwigEnvironment($loader_chain, $params);
$this->twig->registerUndefinedFunctionCallback(function (string $name) use ($config) {
$allowed = $config->get('system.twig.safe_functions');
if (is_array($allowed) && in_array($name, $allowed, true) && function_exists($name)) {
return new TwigFunction($name, $name);
}
if ($config->get('system.twig.undefined_functions')) {
if (function_exists($name)) {
if (!Utils::isDangerousFunction($name)) {
user_error("PHP function {$name}() was used as Twig function. This is deprecated in Grav 1.7. Please add it to system configuration: `system.twig.safe_functions`", E_USER_DEPRECATED);
return new TwigFunction($name, $name);
}
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addException(new RuntimeException("Blocked potentially dangerous PHP function {$name}() being used as Twig function. If you really want to use it, please add it to system configuration: `system.twig.safe_functions`"));
}
return new TwigFunction($name, static function () {});
}
return false;
});
$this->twig->registerUndefinedFilterCallback(function (string $name) use ($config) {
$allowed = $config->get('system.twig.safe_filters');
if (is_array($allowed) && in_array($name, $allowed, true) && function_exists($name)) {
return new TwigFilter($name, $name);
}
if ($config->get('system.twig.undefined_filters')) {
if (function_exists($name)) {
if (!Utils::isDangerousFunction($name)) {
user_error("PHP function {$name}() used as Twig filter. This is deprecated in Grav 1.7. Please add it to system configuration: `system.twig.safe_filters`", E_USER_DEPRECATED);
return new TwigFilter($name, $name);
}
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addException(new RuntimeException("Blocked potentially dangerous PHP function {$name}() being used as Twig filter. If you really want to use it, please add it to system configuration: `system.twig.safe_filters`"));
}
return new TwigFilter($name, static function () {});
}
return false;
});
$this->grav->fireEvent('onTwigInitialized');
// set default date format if set in config
if ($config->get('system.pages.dateformat.long')) {
/** @var CoreExtension $extension */
$extension = $this->twig->getExtension(CoreExtension::class);
$extension->setDateFormat($config->get('system.pages.dateformat.long'));
}
// enable the debug extension if required
if ($config->get('system.twig.debug')) {
$this->twig->addExtension(new DebugExtension());
}
$this->twig->addExtension(new GravExtension());
$this->twig->addExtension(new FilesystemExtension());
$this->twig->addExtension(new DeferredExtension());
$this->twig->addExtension(new StringLoaderExtension());
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addTwigProfiler($this->twig);
$this->grav->fireEvent('onTwigExtensions');
/** @var Pages $pages */
$pages = $this->grav['pages'];
// Set some standard variables for twig
$this->twig_vars += [
'config' => $config,
'system' => $config->get('system'),
'theme' => $config->get('theme'),
'site' => $config->get('site'),
'uri' => $this->grav['uri'],
'assets' => $this->grav['assets'],
'taxonomy' => $this->grav['taxonomy'],
'browser' => $this->grav['browser'],
'base_dir' => GRAV_ROOT,
'home_url' => $pages->homeUrl($active_language),
'base_url' => $pages->baseUrl($active_language),
'base_url_absolute' => $pages->baseUrl($active_language, true),
'base_url_relative' => $pages->baseUrl($active_language, false),
'base_url_simple' => $this->grav['base_url'],
'theme_dir' => $locator->findResource('theme://'),
'theme_url' => $this->grav['base_url'] . '/' . $locator->findResource('theme://', false),
'html_lang' => $this->grav['language']->getActive() ?: $config->get('site.default_lang', 'en'),
'language_codes' => new LanguageCodes,
];
}
return $this;
}
/**
* @return Environment
*/
public function twig()
{
return $this->twig;
}
/**
* @return FilesystemLoader
*/
public function loader()
{
return $this->loader;
}
/**
* @return Profile
*/
public function profile()
{
return $this->profile;
}
/**
* Adds or overrides a template.
*
* @param string $name The template name
* @param string $template The template source
*/
public function setTemplate($name, $template)
{
$this->loaderArray->setTemplate($name, $template);
}
/**
* Twig process that renders a page item. It supports two variations:
* 1) Handles modular pages by rendering a specific page based on its modular twig template
* 2) Renders individual page items for twig processing before the site rendering
*
* @param PageInterface $item The page item to render
* @param string|null $content Optional content override
*
* @return string The rendered output
*/
public function processPage(PageInterface $item, $content = null)
{
$content = $content ?? $item->content();
$content = Security::cleanDangerousTwig($content);
// override the twig header vars for local resolution
$this->grav->fireEvent('onTwigPageVariables', new Event(['page' => $item]));
$twig_vars = $this->twig_vars;
$twig_vars['page'] = $item;
$twig_vars['media'] = $item->media();
$twig_vars['header'] = $item->header();
$local_twig = clone $this->twig;
$output = '';
try {
if ($item->isModule()) {
$twig_vars['content'] = $content;
$template = $this->getPageTwigTemplate($item);
$output = $content = $local_twig->render($template, $twig_vars);
}
// Process in-page Twig
if ($item->shouldProcess('twig')) {
$name = '@Page:' . $item->path();
$this->setTemplate($name, $content);
$output = $local_twig->render($name, $twig_vars);
}
} catch (LoaderError $e) {
throw new RuntimeException($e->getRawMessage(), 400, $e);
}
return $output;
}
/**
* Process a Twig template directly by using a template name
* and optional array of variables
*
* @param string $template template to render with
* @param array $vars Optional variables
*
* @return string
*/
public function processTemplate($template, $vars = [])
{
// override the twig header vars for local resolution
$this->grav->fireEvent('onTwigTemplateVariables');
$vars += $this->twig_vars;
try {
$output = $this->twig->render($template, $vars);
} catch (LoaderError $e) {
throw new RuntimeException($e->getRawMessage(), 404, $e);
}
return $output;
}
/**
* Process a Twig template directly by using a Twig string
* and optional array of variables
*
* @param string $string string to render.
* @param array $vars Optional variables
*
* @return string
*/
public function processString($string, array $vars = [])
{
// override the twig header vars for local resolution
$this->grav->fireEvent('onTwigStringVariables');
$vars += $this->twig_vars;
$string = Security::cleanDangerousTwig($string);
$name = '@Var:' . $string;
$this->setTemplate($name, $string);
try {
$output = $this->twig->render($name, $vars);
} catch (LoaderError $e) {
throw new RuntimeException($e->getRawMessage(), 404, $e);
}
return $output;
}
/**
* Twig process that renders the site layout. This is the main twig process that renders the overall
* page and handles all the layout for the site display.
*
* @param string|null $format Output format (defaults to HTML).
* @param array $vars
* @return string the rendered output
* @throws RuntimeException
*/
public function processSite($format = null, array $vars = [])
{
try {
$grav = $this->grav;
// set the page now it's been processed
$grav->fireEvent('onTwigSiteVariables');
/** @var Pages $pages */
$pages = $grav['pages'];
/** @var PageInterface $page */
$page = $grav['page'];
$content = Security::cleanDangerousTwig($page->content());
$twig_vars = $this->twig_vars;
$twig_vars['theme'] = $grav['config']->get('theme');
$twig_vars['pages'] = $pages->root();
$twig_vars['page'] = $page;
$twig_vars['header'] = $page->header();
$twig_vars['media'] = $page->media();
$twig_vars['content'] = $content;
// determine if params are set, if so disable twig cache
$params = $grav['uri']->params(null, true);
if (!empty($params)) {
$this->twig->setCache(false);
}
// Get Twig template layout
$template = $this->getPageTwigTemplate($page, $format);
$page->templateFormat($format);
$output = $this->twig->render($template, $vars + $twig_vars);
} catch (LoaderError $e) {
throw new RuntimeException($e->getMessage(), 400, $e);
} catch (RuntimeError $e) {
$prev = $e->getPrevious();
if ($prev instanceof TwigException) {
$code = $prev->getCode() ?: 500;
// Fire onPageNotFound event.
$event = new Event([
'page' => $page,
'code' => $code,
'message' => $prev->getMessage(),
'exception' => $prev,
'route' => $grav['route'],
'request' => $grav['request']
]);
$event = $grav->fireEvent("onDisplayErrorPage.{$code}", $event);
$newPage = $event['page'];
if ($newPage && $newPage !== $page) {
unset($grav['page']);
$grav['page'] = $newPage;
return $this->processSite($newPage->templateFormat(), $vars);
}
}
throw $e;
}
return $output;
}
/**
* Wraps the FilesystemLoader addPath method (should be used only in `onTwigLoader()` event
* @param string $template_path
* @param string $namespace
* @throws LoaderError
*/
public function addPath($template_path, $namespace = '__main__')
{
$this->loader->addPath($template_path, $namespace);
}
/**
* Wraps the FilesystemLoader prependPath method (should be used only in `onTwigLoader()` event
* @param string $template_path
* @param string $namespace
* @throws LoaderError
*/
public function prependPath($template_path, $namespace = '__main__')
{
$this->loader->prependPath($template_path, $namespace);
}
/**
* Simple helper method to get the twig template if it has already been set, else return
* the one being passed in
* NOTE: Modular pages that are injected should not use this pre-set template as it's usually set at the page level
*
* @param string $template the template name
* @return string the template name
*/
public function template(string $template): string
{
if (isset($this->template)) {
$template = $this->template;
unset($this->template);
}
return $template;
}
/**
* @param PageInterface $page
* @param string|null $format
* @return string
*/
public function getPageTwigTemplate($page, &$format = null)
{
$template = $page->template();
$default = $page->isModule() ? 'modular/default' : 'default';
$extension = $format ?: $page->templateFormat();
$twig_extension = $extension ? '.'. $extension .TWIG_EXT : TEMPLATE_EXT;
$template_file = $this->template($template . $twig_extension);
// TODO: no longer needed in Twig 3.
/** @var ExistsLoaderInterface $loader */
$loader = $this->twig->getLoader();
if ($loader->exists($template_file)) {
// template.xxx.twig
$page_template = $template_file;
} elseif ($twig_extension !== TEMPLATE_EXT && $loader->exists($template . TEMPLATE_EXT)) {
// template.html.twig
$page_template = $template . TEMPLATE_EXT;
$format = 'html';
} elseif ($loader->exists($default . $twig_extension)) {
// default.xxx.twig
$page_template = $default . $twig_extension;
} else {
// default.html.twig
$page_template = $default . TEMPLATE_EXT;
$format = 'html';
}
return $page_template;
}
/**
* Overrides the autoescape setting
*
* @param bool $state
* @return void
* @deprecated 1.5 Auto-escape should always be turned on to protect against XSS issues (can be disabled per template file).
*/
public function setAutoescape($state)
{
if (!$state) {
user_error(__CLASS__ . '::' . __FUNCTION__ . '(false) is deprecated since Grav 1.5', E_USER_DEPRECATED);
}
$this->autoescape = (bool) $state;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TwigEnvironment.php | system/src/Grav/Common/Twig/TwigEnvironment.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Loader\ExistsLoaderInterface;
use Twig\Loader\LoaderInterface;
use Twig\Template;
use Twig\TemplateWrapper;
/**
* Class TwigEnvironment
* @package Grav\Common\Twig
*/
class TwigEnvironment extends Environment
{
use WriteCacheFileTrait;
/**
* @inheritDoc
*/
public function resolveTemplate($names)
{
if (!\is_array($names)) {
$names = [$names];
}
$count = \count($names);
foreach ($names as $name) {
if ($name instanceof Template) {
return $name;
}
if ($name instanceof TemplateWrapper) {
return $name;
}
// Optimization: Avoid throwing an exception when it would be ignored anyway.
if (1 !== $count) {
/** @var LoaderInterface|ExistsLoaderInterface $loader */
$loader = $this->getLoader();
if (!$loader->exists($name)) {
continue;
}
}
// Throws LoaderError: Unable to find template "%s".
return $this->loadTemplate($name);
}
throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/WriteCacheFileTrait.php | system/src/Grav/Common/Twig/WriteCacheFileTrait.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use function dirname;
/**
* Trait WriteCacheFileTrait
* @package Grav\Common\Twig
*/
trait WriteCacheFileTrait
{
/** @var bool */
protected static $umask;
/**
* This exists so template cache files use the same
* group between apache and cli
*
* @param string $file
* @param string $content
* @return void
*/
protected function writeCacheFile($file, $content)
{
if (empty($file)) {
return;
}
if (!isset(self::$umask)) {
self::$umask = Grav::instance()['config']->get('system.twig.umask_fix', false);
}
if (self::$umask) {
$dir = dirname($file);
if (!is_dir($dir)) {
$old = umask(0002);
Folder::create($dir);
umask($old);
}
parent::writeCacheFile($file, $content);
chmod($file, 0775);
} else {
parent::writeCacheFile($file, $content);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.