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
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpConnectionProviderTest.php
src/Ftp/FtpConnectionProviderTest.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use League\Flysystem\AdapterTestUtilities\RetryOnTestException; use PHPUnit\Framework\TestCase; use function ftp_close; /** * @group ftp */ class FtpConnectionProviderTest extends TestCase { use RetryOnTestException; /** * @var FtpConnectionProvider */ private $connectionProvider; protected function setUp(): void { $this->retryOnException(UnableToConnectToFtpHost::class); } /** * @before */ public function setupConnectionProvider(): void { $this->connectionProvider = new FtpConnectionProvider(); } /** * @after */ public function resetFunctionMocks(): void { reset_function_mocks(); } /** * @test */ public function connecting_successfully(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'utf8' => true, 'passive' => true, 'ignorePassiveAddress' => true, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); $this->runScenario(function () use ($options) { $connection = $this->connectionProvider->createConnection($options); $this->assertTrue(ftp_close($connection)); }); } /** * @test */ public function not_being_able_to_enable_uft8_mode(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'utf8' => true, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); mock_function('ftp_raw', ['Error']); $this->expectException(UnableToEnableUtf8Mode::class); $this->runScenario(function () use ($options) { $this->connectionProvider->createConnection($options); }); } /** * @test */ public function uft8_mode_already_active_by_server(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'utf8' => true, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); mock_function('ftp_raw', ['202 UTF8 mode is always enabled. No need to send this command.']); $this->expectNotToPerformAssertions(); $this->runScenario(function () use ($options) { $this->connectionProvider->createConnection($options); }); } /** * @test */ public function not_being_able_to_ignore_the_passive_address(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'ignorePassiveAddress' => true, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); mock_function('ftp_set_option', false); $this->expectException(UnableToSetFtpOption::class); $this->runScenario(function () use ($options) { $this->connectionProvider->createConnection($options); }); } /** * @test */ public function not_being_able_to_make_the_connection_passive(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'utf8' => true, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); mock_function('ftp_pasv', false); $this->expectException(UnableToMakeConnectionPassive::class); $this->runScenario(function () use ($options) { $this->connectionProvider->createConnection($options); }); } /** * @test */ public function not_being_able_to_connect(): void { $this->dontRetryOnException(); $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 313131, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); $this->expectException(UnableToConnectToFtpHost::class); $this->connectionProvider->createConnection($options); } /** * @test */ public function not_being_able_to_connect_over_ssl(): void { $this->dontRetryOnException(); $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'ssl' => true, 'port' => 313131, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'pass', ]); $this->expectException(UnableToConnectToFtpHost::class); $this->connectionProvider->createConnection($options); } /** * @test */ public function not_being_able_to_authenticate(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'root' => '/home/foo/upload', 'username' => 'foo', 'password' => 'lolnope', ]); $this->expectException(UnableToAuthenticate::class); $this->retryOnException(UnableToConnectToFtpHost::class); $this->runScenario(function () use ($options) { $this->connectionProvider->createConnection($options); }); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpAdapterTestCase.php
src/Ftp/FtpAdapterTestCase.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use Generator; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\Config; use League\Flysystem\FileAttributes; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToWriteFile; use League\Flysystem\Visibility; use function iterator_to_array; /** * @group ftp * * @codeCoverageIgnore */ abstract class FtpAdapterTestCase extends FilesystemAdapterTestCase { protected function setUp(): void { parent::setUp(); $this->retryOnException(UnableToConnectToFtpHost::class); } protected static ConnectivityCheckerThatCanFail $connectivityChecker; protected static ?StubConnectionProvider $connectionProvider; /** * @after */ public function resetFunctionMocks(): void { reset_function_mocks(); } public static function clearFilesystemAdapterCache(): void { parent::clearFilesystemAdapterCache(); static::$connectionProvider = null; } /** * @test */ public function using_empty_string_for_root(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'root' => '', 'username' => 'foo', 'password' => 'pass', ]); $this->runScenario(function () use ($options) { $adapter = new FtpAdapter($options); $adapter->write('dirname1/dirname2/path.txt', 'contents', new Config()); $adapter->write('dirname1/dirname2/path.txt', 'contents', new Config()); $this->assertTrue($adapter->fileExists('dirname1/dirname2/path.txt')); $this->assertSame('contents', $adapter->read('dirname1/dirname2/path.txt')); }); } /** * @test */ public function reconnecting_after_failure(): void { $this->runScenario(function () { $adapter = $this->adapter(); static::$connectivityChecker->failNextCall(); $contents = iterator_to_array($adapter->listContents('', false)); $this->assertIsArray($contents); }); } /** * @test * * @see https://github.com/thephpleague/flysystem/issues/1522 */ public function reading_a_file_twice_for_issue_1522(): void { $this->givenWeHaveAnExistingFile('some/nested/path.txt', 'this is it'); $this->runScenario(function () { $adapter = $this->adapter(); self::assertEquals('this is it', $adapter->read('some/nested/path.txt')); self::assertEquals('this is it', $adapter->read('some/nested/path.txt')); self::assertEquals('this is it', $adapter->read('some/nested/path.txt')); }); } /** * @test * * @dataProvider scenariosCausingWriteFailure */ public function failing_to_write_a_file(callable $scenario): void { $this->runScenario(function () use ($scenario) { $scenario(); }); $this->expectException(UnableToWriteFile::class); $this->runScenario(function () { $this->adapter()->write('some/path.txt', 'contents', new Config([ Config::OPTION_VISIBILITY => Visibility::PUBLIC, Config::OPTION_DIRECTORY_VISIBILITY => Visibility::PUBLIC ])); }); } public static function scenariosCausingWriteFailure(): Generator { yield "Not being able to create the parent directory" => [function () { mock_function('ftp_mkdir', false); }]; yield "Not being able to set the parent directory visibility" => [function () { mock_function('ftp_chmod', false); }]; yield "Not being able to write the file" => [function () { mock_function('ftp_fput', false); }]; yield "Not being able to set the visibility" => [function () { mock_function('ftp_chmod', true, false); }]; } /** * @test * * @dataProvider scenariosCausingDirectoryDeleteFailure */ public function scenarios_causing_directory_deletion_to_fail(callable $scenario): void { $this->runScenario($scenario); $this->givenWeHaveAnExistingFile('some/nested/path.txt'); $this->expectException(UnableToDeleteDirectory::class); $this->runScenario(function () { $this->adapter()->deleteDirectory('some'); }); } public static function scenariosCausingDirectoryDeleteFailure(): Generator { yield "ftp_delete failure" => [function () { mock_function('ftp_delete', false); }]; yield "ftp_rmdir failure" => [function () { mock_function('ftp_rmdir', false); }]; } /** * @test * * @dataProvider scenariosCausingCopyFailure */ public function failing_to_copy(callable $scenario): void { $this->givenWeHaveAnExistingFile('path.txt'); $scenario(); $this->expectException(UnableToCopyFile::class); $this->runScenario(function () { $this->adapter()->copy('path.txt', 'new/path.txt', new Config()); }); } /** * @test */ public function failing_to_move_because_creating_the_directory_fails(): void { $this->givenWeHaveAnExistingFile('path.txt'); mock_function('ftp_mkdir', false); $this->expectException(UnableToMoveFile::class); $this->runScenario(function () { $this->adapter()->move('path.txt', 'new/path.txt', new Config()); }); } public static function scenariosCausingCopyFailure(): Generator { yield "failing to read" => [function () { mock_function('ftp_fget', false); }]; yield "failing to write" => [function () { mock_function('ftp_fput', false); }]; } /** * @test */ public function failing_to_delete_a_file(): void { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); mock_function('ftp_delete', false); $this->expectException(UnableToDeleteFile::class); $this->runScenario(function () { $this->adapter()->delete('path.txt'); }); } /** * @test */ public function formatting_a_directory_listing_with_a_total_indicator(): void { $response = [ 'total 1', '-rw-r--r-- 1 ftp ftp 409 Aug 19 09:01 file1.txt', ]; mock_function('ftp_rawlist', $response); $this->runScenario(function () { $adapter = $this->adapter(); $contents = iterator_to_array($adapter->listContents('/', false), false); $this->assertCount(1, $contents); $this->assertContainsOnlyInstancesOf(FileAttributes::class, $contents); }); } /** * @test * * @runInSeparateProcess */ public function receiving_a_windows_listing(): void { $response = [ '2015-05-23 12:09 <DIR> dir1', '05-23-15 12:09PM 684 file2.txt', ]; mock_function('ftp_rawlist', $response); $this->runScenario(function () { $adapter = $this->adapter(); $contents = iterator_to_array($adapter->listContents('/', false), false); $this->assertCount(2, $contents); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $contents); }); } /** * @test */ public function receiving_an_invalid_windows_listing(): void { $response = [ '05-23-15 12:09PM file2.txt', ]; mock_function('ftp_rawlist', $response); $this->expectException(InvalidListResponseReceived::class); $this->runScenario(function () { $adapter = $this->adapter(); iterator_to_array($adapter->listContents('/', false), false); }); } /** * @test */ public function getting_an_invalid_listing_response_for_unix_listings(): void { $response = [ 'total 1', '-rw-r--r-- 1 ftp 409 Aug 19 09:01 file1.txt', ]; mock_function('ftp_rawlist', $response); $this->expectException(InvalidListResponseReceived::class); $this->runScenario(function () { $adapter = $this->adapter(); iterator_to_array($adapter->listContents('/', false), false); }); } /** * @test */ public function failing_to_get_the_file_size_of_a_directory(): void { $adapter = $this->adapter(); $this->runScenario(function () use ($adapter) { $adapter->createDirectory('directory_name', new Config()); }); $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () use ($adapter) { $adapter->fileSize('directory_name'); }); } /** * @test */ public function formatting_non_manual_recursive_listings(): void { $response = [ 'drwxr-xr-x 4 ftp ftp 4096 Nov 24 13:58 .', 'drwxr-xr-x 16 ftp ftp 4096 Sep 2 13:01 ..', 'drwxr-xr-x 2 ftp ftp 4096 Oct 13 2012 cgi-bin', 'drwxr-xr-x 2 ftp ftp 4096 Nov 24 13:59 folder', '-rw-r--r-- 1 ftp ftp 409 Oct 13 2012 index.html', '', 'somewhere/cgi-bin:', 'drwxr-xr-x 2 ftp ftp 4096 Oct 13 2012 .', 'drwxr-xr-x 4 ftp ftp 4096 Nov 24 13:58 ..', '', 'somewhere/folder:', 'drwxr-xr-x 2 ftp ftp 4096 Nov 24 13:59 .', 'drwxr-xr-x 4 ftp ftp 4096 Nov 24 13:58 ..', '-rw-r--r-- 1 ftp ftp 0 Nov 24 13:59 dummy.txt', ]; mock_function('ftp_rawlist', $response); $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'timestampsOnUnixListingsEnabled' => true, 'recurseManually' => false, 'root' => '/home/foo/upload/', 'username' => 'foo', 'password' => 'pass', ]); $this->runScenario(function () use ($options) { $adapter = new FtpAdapter($options); $contents = iterator_to_array($adapter->listContents('somewhere', true), false); $this->assertCount(4, $contents); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $contents); }); } /** * @test */ public function filenames_and_dirnames_with_spaces_are_supported(): void { $this->givenWeHaveAnExistingFile('some dirname/file name.txt'); $this->runScenario(function () { $adapter = $this->adapter(); $this->assertTrue($adapter->fileExists('some dirname/file name.txt')); $contents = iterator_to_array($adapter->listContents('', true)); $this->assertCount(2, $contents); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $contents); }); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpdAdapterTest.php
src/Ftp/FtpdAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use League\Flysystem\FilesystemAdapter; /** * @group ftpd */ class FtpdAdapterTest extends FtpAdapterTestCase { protected static function createFilesystemAdapter(): FilesystemAdapter { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2122, 'timestampsOnUnixListingsEnabled' => true, 'root' => '/', 'username' => 'foo', 'password' => 'pass', ]); static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker()); return new FtpAdapter($options, null, static::$connectivityChecker); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpAdapter.php
src/Ftp/FtpAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use DateTime; use Generator; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UnixVisibility\PortableVisibilityConverter; use League\Flysystem\UnixVisibility\VisibilityConverter; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use Throwable; use function array_map; use function error_clear_last; use function error_get_last; use function ftp_chdir; use function ftp_close; use function is_string; class FtpAdapter implements FilesystemAdapter { private const SYSTEM_TYPE_WINDOWS = 'windows'; private const SYSTEM_TYPE_UNIX = 'unix'; private ConnectionProvider $connectionProvider; private ConnectivityChecker $connectivityChecker; /** * @var resource|false|\FTP\Connection */ private mixed $connection = false; private PathPrefixer $prefixer; private VisibilityConverter $visibilityConverter; private ?bool $isPureFtpdServer = null; private ?bool $useRawListOptions; private ?string $systemType; private MimeTypeDetector $mimeTypeDetector; private ?string $rootDirectory = null; public function __construct( private FtpConnectionOptions $connectionOptions, ?ConnectionProvider $connectionProvider = null, ?ConnectivityChecker $connectivityChecker = null, ?VisibilityConverter $visibilityConverter = null, ?MimeTypeDetector $mimeTypeDetector = null, private bool $detectMimeTypeUsingPath = false, ) { $this->systemType = $this->connectionOptions->systemType(); $this->connectionProvider = $connectionProvider ?? new FtpConnectionProvider(); $this->connectivityChecker = $connectivityChecker ?? new NoopCommandConnectivityChecker(); $this->visibilityConverter = $visibilityConverter ?? new PortableVisibilityConverter(); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); $this->useRawListOptions = $connectionOptions->useRawListOptions(); } /** * Disconnect FTP connection on destruct. */ public function __destruct() { $this->disconnect(); } /** * @return resource */ private function connection() { start: if ( ! $this->hasFtpConnection()) { $this->connection = $this->connectionProvider->createConnection($this->connectionOptions); $this->rootDirectory = $this->resolveConnectionRoot($this->connection); $this->prefixer = new PathPrefixer($this->rootDirectory); return $this->connection; } if ($this->connectivityChecker->isConnected($this->connection) === false) { $this->connection = false; goto start; } ftp_chdir($this->connection, $this->rootDirectory); return $this->connection; } public function disconnect(): void { if ($this->hasFtpConnection()) { @ftp_close($this->connection); } $this->connection = false; } private function isPureFtpdServer(): bool { if ($this->isPureFtpdServer !== null) { return $this->isPureFtpdServer; } $response = ftp_raw($this->connection, 'HELP'); return $this->isPureFtpdServer = stripos(implode(' ', $response), 'Pure-FTPd') !== false; } private function isServerSupportingListOptions(): bool { if ($this->useRawListOptions !== null) { return $this->useRawListOptions; } $response = ftp_raw($this->connection, 'SYST'); $syst = implode(' ', $response); return $this->useRawListOptions = stripos($syst, 'FileZilla') === false && stripos($syst, 'L8') === false; } public function fileExists(string $path): bool { try { $this->fileSize($path); return true; } catch (UnableToRetrieveMetadata $exception) { return false; } } public function write(string $path, string $contents, Config $config): void { try { $writeStream = fopen('php://temp', 'w+b'); fwrite($writeStream, $contents); rewind($writeStream); $this->writeStream($path, $writeStream, $config); } finally { isset($writeStream) && is_resource($writeStream) && fclose($writeStream); } } public function writeStream(string $path, $contents, Config $config): void { try { $this->ensureParentDirectoryExists($path, $config->get(Config::OPTION_DIRECTORY_VISIBILITY)); } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, 'creating parent directory failed', $exception); } $location = $this->prefixer()->prefixPath($path); if ( ! ftp_fput($this->connection(), $location, $contents, $this->connectionOptions->transferMode())) { throw UnableToWriteFile::atLocation($path, 'writing the file failed'); } if ( ! $visibility = $config->get(Config::OPTION_VISIBILITY)) { return; } try { $this->setVisibility($path, $visibility); } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, 'setting visibility failed', $exception); } } public function read(string $path): string { $readStream = $this->readStream($path); $contents = stream_get_contents($readStream); fclose($readStream); return $contents; } public function readStream(string $path) { $location = $this->prefixer()->prefixPath($path); $stream = fopen('php://temp', 'w+b'); $result = @ftp_fget($this->connection(), $stream, $location, $this->connectionOptions->transferMode()); if ( ! $result) { fclose($stream); throw UnableToReadFile::fromLocation($path, error_get_last()['message'] ?? ''); } rewind($stream); return $stream; } public function delete(string $path): void { $connection = $this->connection(); $this->deleteFile($path, $connection); } /** * @param resource $connection */ private function deleteFile(string $path, $connection): void { $location = $this->prefixer()->prefixPath($path); $success = @ftp_delete($connection, $location); if ($success === false && ftp_size($connection, $location) !== -1) { throw UnableToDeleteFile::atLocation($path, 'the file still exists'); } } public function deleteDirectory(string $path): void { /** @var StorageAttributes[] $contents */ $contents = $this->listContents($path, true); $connection = $this->connection(); $directories = [$path]; foreach ($contents as $item) { if ($item->isDir()) { $directories[] = $item->path(); continue; } try { $this->deleteFile($item->path(), $connection); } catch (Throwable $exception) { throw UnableToDeleteDirectory::atLocation($path, 'unable to delete child', $exception); } } rsort($directories); foreach ($directories as $directory) { if ( ! @ftp_rmdir($connection, $this->prefixer()->prefixPath($directory))) { throw UnableToDeleteDirectory::atLocation($path, "Could not delete directory $directory"); } } } public function createDirectory(string $path, Config $config): void { $this->ensureDirectoryExists($path, $config->get(Config::OPTION_DIRECTORY_VISIBILITY, $config->get(Config::OPTION_VISIBILITY))); } public function setVisibility(string $path, string $visibility): void { $location = $this->prefixer()->prefixPath($path); $mode = $this->visibilityConverter->forFile($visibility); if ( ! @ftp_chmod($this->connection(), $mode, $location)) { $message = error_get_last()['message'] ?? ''; throw UnableToSetVisibility::atLocation($path, $message); } } private function fetchMetadata(string $path, string $type): FileAttributes { $location = $this->prefixer()->prefixPath($path); if ($this->isPureFtpdServer) { $location = $this->escapePath($location); } $object = @ftp_raw($this->connection(), 'STAT ' . $location); if (empty($object) || count($object) < 3 || str_starts_with($object[1], "ftpd:")) { throw UnableToRetrieveMetadata::create($path, $type, error_get_last()['message'] ?? ''); } $attributes = $this->normalizeObject($object[1], ''); if ( ! $attributes instanceof FileAttributes) { throw UnableToRetrieveMetadata::create( $path, $type, 'expected file, ' . ($attributes instanceof DirectoryAttributes ? 'directory found' : 'nothing found') ); } return $attributes; } public function mimeType(string $path): FileAttributes { try { $mimetype = $this->detectMimeTypeUsingPath ? $this->mimeTypeDetector->detectMimeTypeFromPath($path) : $this->mimeTypeDetector->detectMimeType($path, $this->read($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::mimeType($path, $exception->getMessage(), $exception); } if ($mimetype === null) { throw UnableToRetrieveMetadata::mimeType($path, 'Unknown.'); } return new FileAttributes($path, null, null, null, $mimetype); } public function lastModified(string $path): FileAttributes { $location = $this->prefixer()->prefixPath($path); $connection = $this->connection(); $lastModified = @ftp_mdtm($connection, $location); if ($lastModified < 0) { throw UnableToRetrieveMetadata::lastModified($path); } return new FileAttributes($path, null, null, $lastModified); } public function visibility(string $path): FileAttributes { return $this->fetchMetadata($path, FileAttributes::ATTRIBUTE_VISIBILITY); } public function fileSize(string $path): FileAttributes { $location = $this->prefixer()->prefixPath($path); $connection = $this->connection(); $fileSize = @ftp_size($connection, $location); if ($fileSize < 0) { throw UnableToRetrieveMetadata::fileSize($path, error_get_last()['message'] ?? ''); } return new FileAttributes($path, $fileSize); } public function listContents(string $path, bool $deep): iterable { $path = ltrim($path, '/'); $path = $path === '' ? $path : trim($path, '/') . '/'; if ($deep && $this->connectionOptions->recurseManually()) { yield from $this->listDirectoryContentsRecursive($path); } else { $location = $this->prefixer()->prefixPath($path); $options = $deep ? '-alnR' : '-aln'; $listing = $this->ftpRawlist($options, $location); yield from $this->normalizeListing($listing, $path); } } private function normalizeListing(array $listing, string $prefix = ''): Generator { $base = $prefix; foreach ($listing as $item) { if ($item === '' || preg_match('#.* \.(\.)?$|^total#', $item)) { continue; } if (preg_match('#^.*:$#', $item)) { $base = preg_replace('~^\./*|:$~', '', $item); continue; } yield $this->normalizeObject($item, $base); } } private function normalizeObject(string $item, string $base): StorageAttributes { $this->systemType === null && $this->systemType = $this->detectSystemType($item); if ($this->systemType === self::SYSTEM_TYPE_UNIX) { return $this->normalizeUnixObject($item, $base); } return $this->normalizeWindowsObject($item, $base); } private function detectSystemType(string $item): string { return preg_match( '/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item ) ? self::SYSTEM_TYPE_WINDOWS : self::SYSTEM_TYPE_UNIX; } private function normalizeWindowsObject(string $item, string $base): StorageAttributes { $item = preg_replace('#\s+#', ' ', trim($item), 3); $parts = explode(' ', $item, 4); if (count($parts) !== 4) { throw new InvalidListResponseReceived("Metadata can't be parsed from item '$item' , not enough parts."); } [$date, $time, $size, $name] = $parts; $path = $base === '' ? $name : rtrim($base, '/') . '/' . $name; if ($size === '<DIR>') { return new DirectoryAttributes($path); } // Check for the correct date/time format $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i'; $dt = DateTime::createFromFormat($format, $date . $time); $lastModified = $dt ? $dt->getTimestamp() : (int) strtotime("$date $time"); return new FileAttributes($path, (int) $size, null, $lastModified); } private function normalizeUnixObject(string $item, string $base): StorageAttributes { $item = preg_replace('#\s+#', ' ', trim($item), 7); $parts = explode(' ', $item, 9); if (count($parts) !== 9) { throw new InvalidListResponseReceived("Metadata can't be parsed from item '$item' , not enough parts."); } [$permissions, /* $number */, /* $owner */, /* $group */, $size, $month, $day, $timeOrYear, $name] = $parts; $isDirectory = $this->listingItemIsDirectory($permissions); $permissions = $this->normalizePermissions($permissions); $path = $base === '' ? $name : rtrim($base, '/') . '/' . $name; $lastModified = $this->connectionOptions->timestampsOnUnixListingsEnabled() ? $this->normalizeUnixTimestamp( $month, $day, $timeOrYear ) : null; if ($isDirectory) { return new DirectoryAttributes( $path, $this->visibilityConverter->inverseForDirectory($permissions), $lastModified ); } $visibility = $this->visibilityConverter->inverseForFile($permissions); return new FileAttributes($path, (int) $size, $visibility, $lastModified); } private function listingItemIsDirectory(string $permissions): bool { return str_starts_with($permissions, 'd'); } private function normalizeUnixTimestamp(string $month, string $day, string $timeOrYear): int { if (is_numeric($timeOrYear)) { $year = $timeOrYear; $hour = '00'; $minute = '00'; } else { $year = date('Y'); [$hour, $minute] = explode(':', $timeOrYear); } $dateTime = DateTime::createFromFormat('Y-M-j-G:i:s', "$year-$month-$day-$hour:$minute:00"); return $dateTime->getTimestamp(); } private function normalizePermissions(string $permissions): int { // remove the type identifier $permissions = substr($permissions, 1); // map the string rights to the numeric counterparts $map = ['-' => '0', 'r' => '4', 'w' => '2', 'x' => '1']; $permissions = strtr($permissions, $map); // split up the permission groups $parts = str_split($permissions, 3); // convert the groups $mapper = static function ($part) { return array_sum(array_map(static function ($p) { return (int) $p; }, str_split($part))); }; // converts to decimal number return octdec(implode('', array_map($mapper, $parts))); } private function listDirectoryContentsRecursive(string $directory): Generator { $location = $this->prefixer()->prefixPath($directory); $listing = $this->ftpRawlist('-aln', $location); /** @var StorageAttributes[] $listing */ $listing = $this->normalizeListing($listing, $directory); foreach ($listing as $item) { yield $item; if ( ! $item->isDir()) { continue; } $children = $this->listDirectoryContentsRecursive($item->path()); foreach ($children as $child) { yield $child; } } } private function ftpRawlist(string $options, string $path): array { $path = rtrim($path, '/') . '/'; $connection = $this->connection(); if ($this->isPureFtpdServer()) { $path = str_replace(' ', '\ ', $path); $path = $this->escapePath($path); } if ( ! $this->isServerSupportingListOptions()) { $options = ''; } return ftp_rawlist($connection, ($options ? $options . ' ' : '') . $path, stripos($options, 'R') !== false) ?: []; } public function move(string $source, string $destination, Config $config): void { try { $this->ensureParentDirectoryExists($destination, $config->get(Config::OPTION_DIRECTORY_VISIBILITY)); } catch (Throwable $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } $sourceLocation = $this->prefixer()->prefixPath($source); $destinationLocation = $this->prefixer()->prefixPath($destination); $connection = $this->connection(); if ( ! @ftp_rename($connection, $sourceLocation, $destinationLocation)) { throw UnableToMoveFile::because(error_get_last()['message'] ?? 'reason unknown', $source, $destination); } } public function copy(string $source, string $destination, Config $config): void { try { $readStream = $this->readStream($source); $visibility = $config->get(Config::OPTION_VISIBILITY); if ($visibility === null && $config->get(Config::OPTION_RETAIN_VISIBILITY, true)) { $config = $config->withSetting(Config::OPTION_VISIBILITY, $this->visibility($source)->visibility()); } $this->writeStream($destination, $readStream, $config); } catch (Throwable $exception) { if (isset($readStream) && is_resource($readStream)) { @fclose($readStream); } throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } private function ensureParentDirectoryExists(string $path, ?string $visibility): void { $dirname = dirname($path); if ($dirname === '' || $dirname === '.') { return; } $this->ensureDirectoryExists($dirname, $visibility); } private function ensureDirectoryExists(string $dirname, ?string $visibility): void { $connection = $this->connection(); $dirPath = ''; $parts = explode('/', trim($dirname, '/')); $mode = $visibility ? $this->visibilityConverter->forDirectory($visibility) : false; foreach ($parts as $part) { $dirPath .= '/' . $part; $location = $this->prefixer()->prefixPath($dirPath); if (@ftp_chdir($connection, $location)) { continue; } error_clear_last(); $result = @ftp_mkdir($connection, $location); if ($result === false) { $errorMessage = error_get_last()['message'] ?? 'unable to create the directory'; throw UnableToCreateDirectory::atLocation($dirPath, $errorMessage); } if ($mode !== false && @ftp_chmod($connection, $mode, $location) === false) { throw UnableToCreateDirectory::atLocation( $dirPath, 'unable to chmod the directory: ' . (error_get_last()['message'] ?? 'reason unknown'), ); } } } private function escapePath(string $path): string { return str_replace(['*', '[', ']'], ['\\*', '\\[', '\\]'], $path); } /** * @return bool */ private function hasFtpConnection(): bool { return $this->connection instanceof \FTP\Connection || is_resource($this->connection); } public function directoryExists(string $path): bool { $location = $this->prefixer()->prefixPath($path); $connection = $this->connection(); return @ftp_chdir($connection, $location) === true; } /** * @param resource|\FTP\Connection $connection */ private function resolveConnectionRoot($connection): string { $root = $this->connectionOptions->root(); error_clear_last(); if ($root !== '' && @ftp_chdir($connection, $root) !== true) { throw UnableToResolveConnectionRoot::itDoesNotExist($root, error_get_last()['message'] ?? ''); } error_clear_last(); $pwd = @ftp_pwd($connection); if ( ! is_string($pwd)) { throw UnableToResolveConnectionRoot::couldNotGetCurrentDirectory(error_get_last()['message'] ?? ''); } return $pwd; } /** * @return PathPrefixer */ private function prefixer(): PathPrefixer { if ($this->rootDirectory === null) { $this->connection(); } return $this->prefixer; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToMakeConnectionPassive.php
src/Ftp/UnableToMakeConnectionPassive.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use RuntimeException; class UnableToMakeConnectionPassive extends RuntimeException implements FtpConnectionException { }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpConnectionProvider.php
src/Ftp/FtpConnectionProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use const FTP_USEPASVADDRESS; use function error_clear_last; use function error_get_last; class FtpConnectionProvider implements ConnectionProvider { /** * @return resource * * @throws FtpConnectionException */ public function createConnection(FtpConnectionOptions $options) { $connection = $this->createConnectionResource( $options->host(), $options->port(), $options->timeout(), $options->ssl() ); try { $this->authenticate($options, $connection); $this->enableUtf8Mode($options, $connection); $this->ignorePassiveAddress($options, $connection); $this->makeConnectionPassive($options, $connection); } catch (FtpConnectionException $exception) { @ftp_close($connection); throw $exception; } return $connection; } /** * @return resource */ private function createConnectionResource(string $host, int $port, int $timeout, bool $ssl) { error_clear_last(); $connection = $ssl ? @ftp_ssl_connect($host, $port, $timeout) : @ftp_connect($host, $port, $timeout); if ($connection === false) { throw UnableToConnectToFtpHost::forHost($host, $port, $ssl, error_get_last()['message'] ?? ''); } return $connection; } /** * @param resource $connection */ private function authenticate(FtpConnectionOptions $options, $connection): void { if ( ! @ftp_login($connection, $options->username(), $options->password())) { throw new UnableToAuthenticate(); } } /** * @param resource $connection */ private function enableUtf8Mode(FtpConnectionOptions $options, $connection): void { if ( ! $options->utf8()) { return; } $response = @ftp_raw($connection, "OPTS UTF8 ON"); if ( ! in_array(substr($response[0], 0, 3), ['200', '202'])) { throw new UnableToEnableUtf8Mode( 'Could not set UTF-8 mode for connection: ' . $options->host() . '::' . $options->port() ); } } /** * @param resource $connection */ private function ignorePassiveAddress(FtpConnectionOptions $options, $connection): void { $ignorePassiveAddress = $options->ignorePassiveAddress(); if ( ! is_bool($ignorePassiveAddress) || ! defined('FTP_USEPASVADDRESS')) { return; } if ( ! @ftp_set_option($connection, FTP_USEPASVADDRESS, ! $ignorePassiveAddress)) { throw UnableToSetFtpOption::whileSettingOption('FTP_USEPASVADDRESS'); } } /** * @param resource $connection */ private function makeConnectionPassive(FtpConnectionOptions $options, $connection): void { if ( ! @ftp_pasv($connection, $options->passive())) { throw new UnableToMakeConnectionPassive( 'Could not set passive mode for connection: ' . $options->host() . '::' . $options->port() ); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpAdapterTest.php
src/Ftp/FtpAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use League\Flysystem\FilesystemAdapter; use function mock_function; use function reset_function_mocks; /** * @group ftp */ class FtpAdapterTest extends FtpAdapterTestCase { protected static function createFilesystemAdapter(): FilesystemAdapter { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'timestampsOnUnixListingsEnabled' => true, 'root' => '/home/foo/upload/', 'username' => 'foo', 'password' => 'pass', ]); static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker()); static::$connectionProvider = new StubConnectionProvider(new FtpConnectionProvider()); return new FtpAdapter( $options, static::$connectionProvider, static::$connectivityChecker, ); } /** * @test */ public function disconnect_after_destruct(): void { /** @var FtpAdapter $adapter */ $adapter = $this->adapter(); $reflection = new \ReflectionObject($adapter); $adapter->fileExists('foo.txt'); $reflectionProperty = $reflection->getProperty('connection'); $reflectionProperty->setAccessible(true); $connection = $reflectionProperty->getValue($adapter); unset($reflection); $this->assertTrue(false !== ftp_pwd($connection)); $adapter->__destruct(); static::clearFilesystemAdapterCache(); $this->assertFalse((new NoopCommandConnectivityChecker())->isConnected($connection)); } /** * @test */ public function it_can_disconnect(): void { /** @var FtpAdapter $adapter */ $adapter = $this->adapter(); $this->assertFalse($adapter->fileExists('not-existing.file')); self::assertTrue(static::$connectivityChecker->isConnected(static::$connectionProvider->connection)); $adapter->disconnect(); self::assertFalse(static::$connectivityChecker->isConnected(static::$connectionProvider->connection)); } /** * @test */ public function not_being_able_to_resolve_connection_root(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'timestampsOnUnixListingsEnabled' => true, 'root' => '/invalid/root', 'username' => 'foo', 'password' => 'pass', ]); $adapter = new FtpAdapter($options); $this->expectExceptionObject(UnableToResolveConnectionRoot::itDoesNotExist('/invalid/root')); $adapter->delete('something'); } /** * @test */ public function not_being_able_to_resolve_connection_root_pwd(): void { $options = FtpConnectionOptions::fromArray([ 'host' => 'localhost', 'port' => 2121, 'timestampsOnUnixListingsEnabled' => true, 'root' => '/home/foo/upload/', 'username' => 'foo', 'password' => 'pass', ]); $this->expectExceptionObject(UnableToResolveConnectionRoot::couldNotGetCurrentDirectory()); mock_function('ftp_pwd', false); $adapter = new FtpAdapter($options); $adapter->delete('something'); } protected function tearDown(): void { reset_function_mocks(); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpConnectionOptions.php
src/Ftp/FtpConnectionOptions.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use const FTP_BINARY; class FtpConnectionOptions { public function __construct( private string $host, private string $root, private string $username, private string $password, private int $port = 21, private bool $ssl = false, private int $timeout = 90, private bool $utf8 = false, private bool $passive = true, private int $transferMode = FTP_BINARY, private ?string $systemType = null, private ?bool $ignorePassiveAddress = null, private bool $enableTimestampsOnUnixListings = false, private bool $recurseManually = false, private ?bool $useRawListOptions = null, ) { } public function host(): string { return $this->host; } public function root(): string { return $this->root; } public function username(): string { return $this->username; } public function password(): string { return $this->password; } public function port(): int { return $this->port; } public function ssl(): bool { return $this->ssl; } public function timeout(): int { return $this->timeout; } public function utf8(): bool { return $this->utf8; } public function passive(): bool { return $this->passive; } public function transferMode(): int { return $this->transferMode; } public function systemType(): ?string { return $this->systemType; } public function ignorePassiveAddress(): ?bool { return $this->ignorePassiveAddress; } public function timestampsOnUnixListingsEnabled(): bool { return $this->enableTimestampsOnUnixListings; } public function recurseManually(): bool { return $this->recurseManually; } public function useRawListOptions(): ?bool { return $this->useRawListOptions; } public static function fromArray(array $options): FtpConnectionOptions { return new FtpConnectionOptions( $options['host'] ?? 'invalid://host-not-set', $options['root'] ?? '', $options['username'] ?? 'invalid://username-not-set', $options['password'] ?? 'invalid://password-not-set', $options['port'] ?? 21, $options['ssl'] ?? false, $options['timeout'] ?? 90, $options['utf8'] ?? false, $options['passive'] ?? true, $options['transferMode'] ?? FTP_BINARY, $options['systemType'] ?? null, $options['ignorePassiveAddress'] ?? null, $options['timestampsOnUnixListingsEnabled'] ?? false, $options['recurseManually'] ?? true, $options['useRawListOptions'] ?? null, ); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/FtpConnectionException.php
src/Ftp/FtpConnectionException.php
<?php declare(strict_types=1); namespace League\Flysystem\Ftp; use League\Flysystem\FilesystemException; interface FtpConnectionException extends FilesystemException { }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AwsS3V3/VisibilityConverter.php
src/AwsS3V3/VisibilityConverter.php
<?php declare(strict_types=1); namespace League\Flysystem\AwsS3V3; interface VisibilityConverter { public function visibilityToAcl(string $visibility): string; public function aclToVisibility(array $grants): string; public function defaultForDirectories(): string; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AwsS3V3/PortableVisibilityConverter.php
src/AwsS3V3/PortableVisibilityConverter.php
<?php declare(strict_types=1); namespace League\Flysystem\AwsS3V3; use League\Flysystem\Visibility; class PortableVisibilityConverter implements VisibilityConverter { private const PUBLIC_GRANTEE_URI = 'http://acs.amazonaws.com/groups/global/AllUsers'; private const PUBLIC_GRANTS_PERMISSION = 'READ'; private const PUBLIC_ACL = 'public-read'; private const PRIVATE_ACL = 'private'; public function __construct(private string $defaultForDirectories = Visibility::PUBLIC) { } public function visibilityToAcl(string $visibility): string { if ($visibility === Visibility::PUBLIC) { return self::PUBLIC_ACL; } return self::PRIVATE_ACL; } public function aclToVisibility(array $grants): string { foreach ($grants as $grant) { $granteeUri = $grant['Grantee']['URI'] ?? null; $permission = $grant['Permission'] ?? null; if ($granteeUri === self::PUBLIC_GRANTEE_URI && $permission === self::PUBLIC_GRANTS_PERMISSION) { return Visibility::PUBLIC; } } return Visibility::PRIVATE; } public function defaultForDirectories(): string { return $this->defaultForDirectories; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AwsS3V3/AwsS3V3Adapter.php
src/AwsS3V3/AwsS3V3Adapter.php
<?php declare(strict_types=1); namespace League\Flysystem\AwsS3V3; use Aws\Api\DateTimeResult; use Aws\S3\S3ClientInterface; use DateTimeInterface; use Generator; use League\Flysystem\ChecksumAlgoIsNotSupported; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\FilesystemOperationFailed; use League\Flysystem\PathPrefixer; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCheckDirectoryExistence; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToGeneratePublicUrl; use League\Flysystem\UnableToGenerateTemporaryUrl; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToProvideChecksum; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use League\Flysystem\UrlGeneration\TemporaryUrlGenerator; use League\Flysystem\Visibility; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use Psr\Http\Message\StreamInterface; use Throwable; use function trim; class AwsS3V3Adapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator { /** * @var string[] */ public const AVAILABLE_OPTIONS = [ 'ACL', 'CacheControl', 'ContentDisposition', 'ContentEncoding', 'ContentLength', 'ContentType', 'Expires', 'GrantFullControl', 'GrantRead', 'GrantReadACP', 'GrantWriteACP', 'Metadata', 'MetadataDirective', 'RequestPayer', 'SSECustomerAlgorithm', 'SSECustomerKey', 'SSECustomerKeyMD5', 'SSEKMSKeyId', 'ServerSideEncryption', 'StorageClass', 'Tagging', 'WebsiteRedirectLocation', 'ChecksumAlgorithm', 'CopySourceSSECustomerAlgorithm', 'CopySourceSSECustomerKey', 'CopySourceSSECustomerKeyMD5', ]; /** * @var string[] */ public const MUP_AVAILABLE_OPTIONS = [ 'add_content_md5', 'before_upload', 'concurrency', 'mup_threshold', 'params', 'part_size', ]; /** * @var string[] */ private const EXTRA_METADATA_FIELDS = [ 'Metadata', 'StorageClass', 'ETag', 'VersionId', ]; private PathPrefixer $prefixer; private VisibilityConverter $visibility; private MimeTypeDetector $mimeTypeDetector; public function __construct( private S3ClientInterface $client, private string $bucket, string $prefix = '', ?VisibilityConverter $visibility = null, ?MimeTypeDetector $mimeTypeDetector = null, private array $options = [], private bool $streamReads = true, private array $forwardedOptions = self::AVAILABLE_OPTIONS, private array $metadataFields = self::EXTRA_METADATA_FIELDS, private array $multipartUploadOptions = self::MUP_AVAILABLE_OPTIONS, ) { $this->prefixer = new PathPrefixer($prefix); $this->visibility = $visibility ?? new PortableVisibilityConverter(); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); } public function fileExists(string $path): bool { try { return $this->client->doesObjectExistV2($this->bucket, $this->prefixer->prefixPath($path), false, $this->options); } catch (Throwable $exception) { throw UnableToCheckFileExistence::forLocation($path, $exception); } } public function directoryExists(string $path): bool { try { $prefix = $this->prefixer->prefixDirectoryPath($path); $options = ['Bucket' => $this->bucket, 'Prefix' => $prefix, 'MaxKeys' => 1, 'Delimiter' => '/']; $command = $this->client->getCommand('ListObjectsV2', $options); $result = $this->client->execute($command); return $result->hasKey('Contents') || $result->hasKey('CommonPrefixes'); } catch (Throwable $exception) { throw UnableToCheckDirectoryExistence::forLocation($path, $exception); } } public function write(string $path, string $contents, Config $config): void { $this->upload($path, $contents, $config); } /** * @param string $path * @param string|resource $body * @param Config $config */ private function upload(string $path, $body, Config $config): void { $key = $this->prefixer->prefixPath($path); $options = $this->createOptionsFromConfig($config); $acl = $options['params']['ACL'] ?? $this->determineAcl($config); $shouldDetermineMimetype = ! array_key_exists('ContentType', $options['params']); if ($shouldDetermineMimetype && $mimeType = $this->mimeTypeDetector->detectMimeType($key, $body)) { $options['params']['ContentType'] = $mimeType; } try { $this->client->upload($this->bucket, $key, $body, $acl, $options); } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } private function determineAcl(Config $config): string { $visibility = (string) $config->get(Config::OPTION_VISIBILITY, Visibility::PRIVATE); return $this->visibility->visibilityToAcl($visibility); } private function createOptionsFromConfig(Config $config): array { $config = $config->withDefaults($this->options); $options = ['params' => []]; if ($mimetype = $config->get('mimetype')) { $options['params']['ContentType'] = $mimetype; } foreach ($this->forwardedOptions as $option) { $value = $config->get($option, '__NOT_SET__'); if ($value !== '__NOT_SET__') { $options['params'][$option] = $value; } } foreach ($this->multipartUploadOptions as $option) { $value = $config->get($option, '__NOT_SET__'); if ($value !== '__NOT_SET__') { $options[$option] = $value; } } return $options; } public function writeStream(string $path, $contents, Config $config): void { $this->upload($path, $contents, $config); } public function read(string $path): string { $body = $this->readObject($path, false); return (string) $body->getContents(); } public function readStream(string $path) { /** @var resource $resource */ $resource = $this->readObject($path, true)->detach(); return $resource; } public function delete(string $path): void { $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)]; $command = $this->client->getCommand('DeleteObject', $arguments); try { $this->client->execute($command); } catch (Throwable $exception) { throw UnableToDeleteFile::atLocation($path, '', $exception); } } public function deleteDirectory(string $path): void { $prefix = $this->prefixer->prefixPath($path); $prefix = ltrim(rtrim($prefix, '/') . '/', '/'); try { $this->client->deleteMatchingObjects($this->bucket, $prefix); } catch (Throwable $exception) { throw UnableToDeleteDirectory::atLocation($path, '', $exception); } } public function createDirectory(string $path, Config $config): void { $defaultVisibility = $config->get(Config::OPTION_DIRECTORY_VISIBILITY, $this->visibility->defaultForDirectories()); $config = $config->withDefaults([Config::OPTION_VISIBILITY => $defaultVisibility]); $this->upload(rtrim($path, '/') . '/', '', $config); } public function setVisibility(string $path, string $visibility): void { $arguments = [ 'Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path), 'ACL' => $this->visibility->visibilityToAcl($visibility), ]; $command = $this->client->getCommand('PutObjectAcl', $arguments); try { $this->client->execute($command); } catch (Throwable $exception) { throw UnableToSetVisibility::atLocation($path, '', $exception); } } public function visibility(string $path): FileAttributes { $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)]; $command = $this->client->getCommand('GetObjectAcl', $arguments); try { $result = $this->client->execute($command); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::visibility($path, '', $exception); } $visibility = $this->visibility->aclToVisibility((array) $result->get('Grants')); return new FileAttributes($path, null, $visibility); } private function fetchFileMetadata(string $path, string $type): FileAttributes { $arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)]; $command = $this->client->getCommand('HeadObject', $arguments); try { $result = $this->client->execute($command); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::create($path, $type, '', $exception); } $attributes = $this->mapS3ObjectMetadata($result->toArray(), $path); if ( ! $attributes instanceof FileAttributes) { throw UnableToRetrieveMetadata::create($path, $type, ''); } return $attributes; } private function mapS3ObjectMetadata(array $metadata, string $path): StorageAttributes { if (substr($path, -1) === '/') { return new DirectoryAttributes(rtrim($path, '/')); } $mimetype = $metadata['ContentType'] ?? null; $fileSize = $metadata['ContentLength'] ?? $metadata['Size'] ?? null; $fileSize = $fileSize === null ? null : (int) $fileSize; $dateTime = $metadata['LastModified'] ?? null; $lastModified = $dateTime instanceof DateTimeResult ? $dateTime->getTimeStamp() : null; return new FileAttributes( $path, $fileSize, null, $lastModified, $mimetype, $this->extractExtraMetadata($metadata) ); } private function extractExtraMetadata(array $metadata): array { $extracted = []; foreach ($this->metadataFields as $field) { if (isset($metadata[$field]) && $metadata[$field] !== '') { $extracted[$field] = $metadata[$field]; } } return $extracted; } public function mimeType(string $path): FileAttributes { $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_MIME_TYPE); if ($attributes->mimeType() === null) { throw UnableToRetrieveMetadata::mimeType($path); } return $attributes; } public function lastModified(string $path): FileAttributes { $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_LAST_MODIFIED); if ($attributes->lastModified() === null) { throw UnableToRetrieveMetadata::lastModified($path); } return $attributes; } public function fileSize(string $path): FileAttributes { $attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_FILE_SIZE); if ($attributes->fileSize() === null) { throw UnableToRetrieveMetadata::fileSize($path); } return $attributes; } public function listContents(string $path, bool $deep): iterable { $prefix = trim($this->prefixer->prefixPath($path), '/'); $prefix = $prefix === '' ? '' : $prefix . '/'; $options = ['Bucket' => $this->bucket, 'Prefix' => $prefix]; if ($deep === false) { $options['Delimiter'] = '/'; } $listing = $this->retrievePaginatedListing($options); foreach ($listing as $item) { $key = $item['Key'] ?? $item['Prefix']; if ($key === $prefix) { continue; } yield $this->mapS3ObjectMetadata($item, $this->prefixer->stripPrefix($key)); } } private function retrievePaginatedListing(array $options): Generator { $resultPaginator = $this->client->getPaginator('ListObjectsV2', $options + $this->options); foreach ($resultPaginator as $result) { yield from ($result->get('CommonPrefixes') ?? []); yield from ($result->get('Contents') ?? []); } } public function move(string $source, string $destination, Config $config): void { if ($source === $destination) { return; } try { $this->copy($source, $destination, $config); $this->delete($source); } catch (FilesystemOperationFailed $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } } public function copy(string $source, string $destination, Config $config): void { if ($source === $destination) { return; } try { $visibility = $config->get(Config::OPTION_VISIBILITY); if ($visibility === null && $config->get(Config::OPTION_RETAIN_VISIBILITY, true)) { $visibility = $this->visibility($source)->visibility(); } } catch (Throwable $exception) { throw UnableToCopyFile::fromLocationTo( $source, $destination, $exception ); } $options = $this->createOptionsFromConfig($config); $options['MetadataDirective'] = $config->get('MetadataDirective', 'COPY'); try { $this->client->copy( $this->bucket, $this->prefixer->prefixPath($source), $this->bucket, $this->prefixer->prefixPath($destination), $this->visibility->visibilityToAcl($visibility ?: 'private'), $options, ); } catch (Throwable $exception) { throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } private function readObject(string $path, bool $wantsStream): StreamInterface { $options = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)]; if ($wantsStream && $this->streamReads && ! isset($this->options['@http']['stream'])) { $options['@http']['stream'] = true; } $command = $this->client->getCommand('GetObject', $options + $this->options); try { return $this->client->execute($command)->get('Body'); } catch (Throwable $exception) { throw UnableToReadFile::fromLocation($path, '', $exception); } } public function publicUrl(string $path, Config $config): string { $location = $this->prefixer->prefixPath($path); try { return $this->client->getObjectUrl($this->bucket, $location); } catch (Throwable $exception) { throw UnableToGeneratePublicUrl::dueToError($path, $exception); } } public function checksum(string $path, Config $config): string { $algo = $config->get('checksum_algo', 'etag'); if ($algo !== 'etag') { throw new ChecksumAlgoIsNotSupported(); } try { $metadata = $this->fetchFileMetadata($path, 'checksum')->extraMetadata(); } catch (UnableToRetrieveMetadata $exception) { throw new UnableToProvideChecksum($exception->reason(), $path, $exception); } if ( ! isset($metadata['ETag'])) { throw new UnableToProvideChecksum('ETag header not available.', $path); } return trim($metadata['ETag'], '"'); } public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string { try { $options = $config->get('get_object_options', []); $command = $this->client->getCommand('GetObject', [ 'Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path), ] + $options); $presignedRequestOptions = $config->get('presigned_request_options', []); $request = $this->client->createPresignedRequest($command, $expiresAt, $presignedRequestOptions); return (string) $request->getUri(); } catch (Throwable $exception) { throw UnableToGenerateTemporaryUrl::dueToError($path, $exception); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AwsS3V3/AwsS3V3AdapterTest.php
src/AwsS3V3/AwsS3V3AdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\AwsS3V3; use Aws\Result; use Aws\S3\S3Client; use Aws\S3\S3ClientInterface; use Exception; use Generator; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\ChecksumAlgoIsNotSupported; use League\Flysystem\Config; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToWriteFile; use League\Flysystem\Visibility; use RuntimeException; use function getenv; use function iterator_to_array; /** * @group aws */ class AwsS3V3AdapterTest extends FilesystemAdapterTestCase { /** * @var bool */ private $shouldCleanUp = false; /** * @var string */ private static $adapterPrefix = 'test-prefix'; /** * @var S3ClientInterface|null */ private static $s3Client; /** * @var S3ClientStub */ private static $stubS3Client; public static function setUpBeforeClass(): void { static::$adapterPrefix = getenv('FLYSYSTEM_AWS_S3_PREFIX') ?: 'ci/' . bin2hex(random_bytes(10)); } protected function tearDown(): void { if ( ! $this->shouldCleanUp) { return; } $adapter = $this->adapter(); $adapter->deleteDirectory('/'); /** @var StorageAttributes[] $listing */ $listing = $adapter->listContents('', false); foreach ($listing as $item) { if ($item->isFile()) { $adapter->delete($item->path()); } else { $adapter->deleteDirectory($item->path()); } } self::$adapter = null; } protected function setUp(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('AWS does not support this anymore.'); } parent::setUp(); } private static function s3Client(): S3ClientInterface { if (static::$s3Client instanceof S3ClientInterface) { return static::$s3Client; } $key = getenv('FLYSYSTEM_AWS_S3_KEY'); $secret = getenv('FLYSYSTEM_AWS_S3_SECRET'); $bucket = getenv('FLYSYSTEM_AWS_S3_BUCKET'); $region = getenv('FLYSYSTEM_AWS_S3_REGION') ?: 'eu-central-1'; if ( ! $key || ! $secret || ! $bucket) { self::markTestSkipped('No AWS credentials present for testing.'); } $options = ['version' => 'latest', 'credentials' => compact('key', 'secret'), 'region' => $region]; return static::$s3Client = new S3Client($options); } /** * @test */ public function writing_with_a_specific_mime_type(): void { $adapter = $this->adapter(); $adapter->write('some/path.txt', 'contents', new Config(['ContentType' => 'text/plain+special'])); $mimeType = $adapter->mimeType('some/path.txt')->mimeType(); $this->assertEquals('text/plain+special', $mimeType); } /** * @test */ public function writing_a_file_with_explicit_mime_type(): void { $adapter = $this->adapter(); $adapter->write('some/path.txt', 'contents', new Config(['mimetype' => 'text/plain+special'])); $mimeType = $adapter->mimeType('some/path.txt')->mimeType(); $this->assertEquals('text/plain+special', $mimeType); } /** * @test * * @see https://github.com/thephpleague/flysystem-aws-s3-v3/issues/291 */ public function issue_291(): void { $adapter = $this->adapter(); $adapter->createDirectory('directory', new Config()); $listing = iterator_to_array($adapter->listContents('directory', true)); self::assertCount(0, $listing); } /** * @test */ public function listing_contents_recursive(): void { $adapter = $this->adapter(); $adapter->write('something/0/here.txt', 'contents', new Config()); $adapter->write('something/1/also/here.txt', 'contents', new Config()); $contents = iterator_to_array($adapter->listContents('', true)); $this->assertCount(2, $contents); $this->assertContainsOnlyInstancesOf(FileAttributes::class, $contents); /** @var FileAttributes $file */ $file = $contents[0]; $this->assertEquals('something/0/here.txt', $file->path()); /** @var FileAttributes $file */ $file = $contents[1]; $this->assertEquals('something/1/also/here.txt', $file->path()); } /** * @test */ public function failing_to_delete_while_moving(): void { $adapter = $this->adapter(); $adapter->write('source.txt', 'contents to be copied', new Config()); static::$stubS3Client->failOnNextCopy(); $this->expectException(UnableToMoveFile::class); $adapter->move('source.txt', 'destination.txt', new Config()); } /** * @test * * @see https://github.com/thephpleague/flysystem-aws-s3-v3/issues/287 */ public function issue_287(): void { $adapter = $this->adapter(); $adapter->write('KmFVvKqo/QLMExy2U/620ff60c8a154.pdf', 'pdf content', new Config()); self::assertTrue($adapter->directoryExists('KmFVvKqo')); } /** * @test */ public function failing_to_write_a_file(): void { $adapter = $this->adapter(); static::$stubS3Client->throwDuringUpload(new RuntimeException('Oh no')); $this->expectException(UnableToWriteFile::class); $adapter->write('path.txt', 'contents', new Config()); } /** * @test */ public function failing_to_delete_a_file(): void { $adapter = $this->adapter(); static::$stubS3Client->throwExceptionWhenExecutingCommand('DeleteObject'); $this->expectException(UnableToDeleteFile::class); $adapter->delete('path.txt'); } /** * @test */ public function fetching_unknown_mime_type_of_a_file(): void { $this->adapter(); $result = new Result([ 'Key' => static::$adapterPrefix . '/unknown-mime-type.md5', ]); static::$stubS3Client->stageResultForCommand('HeadObject', $result); parent::fetching_unknown_mime_type_of_a_file(); } /** * @test * * @dataProvider dpFailingMetadataGetters */ public function failing_to_retrieve_metadata(Exception $exception, string $getterName): void { $adapter = $this->adapter(); $result = new Result([ 'Key' => static::$adapterPrefix . '/filename.txt', ]); static::$stubS3Client->stageResultForCommand('HeadObject', $result); $this->expectExceptionObject($exception); $adapter->{$getterName}('filename.txt'); } public static function dpFailingMetadataGetters(): iterable { yield "mimeType" => [UnableToRetrieveMetadata::mimeType('filename.txt'), 'mimeType']; yield "lastModified" => [UnableToRetrieveMetadata::lastModified('filename.txt'), 'lastModified']; yield "fileSize" => [UnableToRetrieveMetadata::fileSize('filename.txt'), 'fileSize']; } /** * @test */ public function failing_to_check_for_file_existence(): void { $adapter = $this->adapter(); static::$stubS3Client->throw500ExceptionWhenExecutingCommand('HeadObject'); $this->expectException(UnableToCheckFileExistence::class); $adapter->fileExists('something-that-does-exist.txt'); } /** * @test * * @dataProvider casesWhereHttpStreamingInfluencesSeekability */ public function streaming_reads_are_not_seekable_and_non_streaming_are(bool $streaming, bool $seekable): void { if (getenv('COMPOSER_OPTS') === '--prefer-lowest') { $this->markTestSkipped('The SDK does not support streaming in low versions.'); } $adapter = $this->useAdapter($this->createFilesystemAdapter($streaming)); $this->givenWeHaveAnExistingFile('path.txt'); $resource = $adapter->readStream('path.txt'); $metadata = stream_get_meta_data($resource); fclose($resource); $this->assertEquals($seekable, $metadata['seekable']); } public static function casesWhereHttpStreamingInfluencesSeekability(): Generator { yield "not streaming reads have seekable stream" => [false, true]; yield "streaming reads have non-seekable stream" => [true, false]; } /** * @test * * @dataProvider casesWhereHttpStreamingInfluencesSeekability */ public function configuring_http_streaming_via_options(bool $streaming): void { $adapter = $this->useAdapter($this->createFilesystemAdapter($streaming, ['@http' => ['stream' => false]])); $this->givenWeHaveAnExistingFile('path.txt'); $resource = $adapter->readStream('path.txt'); $metadata = stream_get_meta_data($resource); fclose($resource); $this->assertTrue($metadata['seekable']); } /** * @test * * @dataProvider casesWhereHttpStreamingInfluencesSeekability */ public function use_globally_configured_options(bool $streaming): void { $adapter = $this->useAdapter($this->createFilesystemAdapter($streaming, ['ContentType' => 'text/plain+special'])); $this->givenWeHaveAnExistingFile('path.txt'); $mimeType = $adapter->mimeType('path.txt')->mimeType(); $this->assertSame('text/plain+special', $mimeType); } /** * @test */ public function moving_with_updated_metadata(): void { $adapter = $this->adapter(); $adapter->write('source.txt', 'contents to be moved', new Config(['ContentType' => 'text/plain'])); $mimeTypeSource = $adapter->mimeType('source.txt')->mimeType(); $this->assertSame('text/plain', $mimeTypeSource); $adapter->move('source.txt', 'destination.txt', new Config( ['ContentType' => 'text/plain+special', 'MetadataDirective' => 'REPLACE'] )); $mimeTypeDestination = $adapter->mimeType('destination.txt')->mimeType(); $this->assertSame('text/plain+special', $mimeTypeDestination); } /** * @test */ public function moving_without_updated_metadata(): void { $adapter = $this->adapter(); $adapter->write('source.txt', 'contents to be moved', new Config(['ContentType' => 'text/plain'])); $mimeTypeSource = $adapter->mimeType('source.txt')->mimeType(); $this->assertSame('text/plain', $mimeTypeSource); $adapter->move('source.txt', 'destination.txt', new Config( ['ContentType' => 'text/plain+special'] )); $mimeTypeDestination = $adapter->mimeType('destination.txt')->mimeType(); $this->assertSame('text/plain', $mimeTypeDestination); } /** * @test */ public function copying_with_updated_metadata(): void { $adapter = $this->adapter(); $adapter->write('source.txt', 'contents to be moved', new Config(['ContentType' => 'text/plain'])); $mimeTypeSource = $adapter->mimeType('source.txt')->mimeType(); $this->assertSame('text/plain', $mimeTypeSource); $adapter->copy('source.txt', 'destination.txt', new Config( ['ContentType' => 'text/plain+special', 'MetadataDirective' => 'REPLACE'] )); $mimeTypeDestination = $adapter->mimeType('destination.txt')->mimeType(); $this->assertSame('text/plain+special', $mimeTypeDestination); } /** * @test */ public function setting_acl_via_options(): void { $adapter = $this->adapter(); $prefixer = new PathPrefixer(static::$adapterPrefix); $prefixedPath = $prefixer->prefixPath('path.txt'); $adapter->write('path.txt', 'contents', new Config(['ACL' => 'bucket-owner-full-control'])); $arguments = ['Bucket' => getenv('FLYSYSTEM_AWS_S3_BUCKET'), 'Key' => $prefixedPath]; $command = static::$s3Client->getCommand('GetObjectAcl', $arguments); $response = static::$s3Client->execute($command)->toArray(); $permission = $response['Grants'][0]['Permission']; self::assertEquals('FULL_CONTROL', $permission); } /** * @test */ public function moving_a_file_with_visibility(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->move('source.txt', 'destination.txt', new Config([Config::OPTION_VISIBILITY => Visibility::PRIVATE])); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals(Visibility::PRIVATE, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function specifying_a_custom_checksum_algo_is_not_supported(): void { /** @var AwsS3V3Adapter $adapter */ $adapter = $this->adapter(); $this->expectException(ChecksumAlgoIsNotSupported::class); $adapter->checksum('something', new Config(['checksum_algo' => 'md5'])); } /** * @test */ public function copying_a_file_with_visibility(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->copy('source.txt', 'destination.txt', new Config([Config::OPTION_VISIBILITY => Visibility::PRIVATE])); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals(Visibility::PRIVATE, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } protected static function createFilesystemAdapter(bool $streaming = true, array $options = []): FilesystemAdapter { static::$stubS3Client = new S3ClientStub(static::s3Client()); /** @var string $bucket */ $bucket = getenv('FLYSYSTEM_AWS_S3_BUCKET'); $prefix = static::$adapterPrefix; return new AwsS3V3Adapter(static::$stubS3Client, $bucket, $prefix, null, null, $options, $streaming); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AwsS3V3/S3ClientStub.php
src/AwsS3V3/S3ClientStub.php
<?php declare(strict_types=1); namespace League\Flysystem\AwsS3V3; use Aws\Command; use Aws\CommandInterface; use Aws\ResultInterface; use Aws\S3\Exception\S3Exception; use Aws\S3\S3ClientInterface; use Aws\S3\S3ClientTrait; use GuzzleHttp\Psr7\Response; use Throwable; use function GuzzleHttp\Promise\promise_for; /** * @codeCoverageIgnore */ class S3ClientStub implements S3ClientInterface { use S3ClientTrait; /** * @var S3ClientInterface */ private $actualClient; /** * @var S3Exception[] */ private $stagedExceptions = []; /** * @var ResultInterface[] */ private $stagedResult = []; /** * @var Throwable|null */ private $exceptionForUpload = null; public function __construct(S3ClientInterface $client) { return $this->actualClient = $client; } public function throwDuringUpload(Throwable $throwable): void { $this->exceptionForUpload = $throwable; } public function upload($bucket, $key, $body, $acl = 'private', array $options = []) { if ($this->exceptionForUpload instanceof Throwable) { $throwable = $this->exceptionForUpload; $this->exceptionForUpload = null; throw $throwable; } return $this->actualClient->upload($bucket, $key, $body, $acl, $options); } public function failOnNextCopy(): void { $this->throwExceptionWhenExecutingCommand('CopyObject'); } public function throwExceptionWhenExecutingCommand(string $commandName, ?S3Exception $exception = null): void { $this->stagedExceptions[$commandName] = $exception ?? new S3Exception($commandName, new Command($commandName)); } public function throw500ExceptionWhenExecutingCommand(string $commandName): void { $response = new Response(500); $exception = new S3Exception($commandName, new Command($commandName), compact('response')); $this->throwExceptionWhenExecutingCommand($commandName, $exception); } public function stageResultForCommand(string $commandName, ResultInterface $result): void { $this->stagedResult[$commandName] = $result; } public function execute(CommandInterface $command) { return $this->executeAsync($command)->wait(); } public function getCommand($name, array $args = []) { return $this->actualClient->getCommand($name, $args); } public function getHandlerList() { return $this->actualClient->getHandlerList(); } public function getIterator($name, array $args = []) { return $this->actualClient->getIterator($name, $args); } public function __call($name, array $arguments) { return $this->actualClient->__call($name, $arguments); } public function executeAsync(CommandInterface $command) { $name = $command->getName(); if (array_key_exists($name, $this->stagedExceptions)) { $exception = $this->stagedExceptions[$name]; unset($this->stagedExceptions[$name]); throw $exception; } if (array_key_exists($name, $this->stagedResult)) { $result = $this->stagedResult[$name]; unset($this->stagedResult[$name]); return promise_for($result); } return $this->actualClient->executeAsync($command); } public function getCredentials() { return $this->actualClient->getCredentials(); } public function getRegion() { return $this->actualClient->getRegion(); } public function getEndpoint() { return $this->actualClient->getEndpoint(); } public function getApi() { return $this->actualClient->getApi(); } public function getConfig($option = null) { return $this->actualClient->getConfig($option); } public function getPaginator($name, array $args = []) { return $this->actualClient->getPaginator($name, $args); } public function waitUntil($name, array $args = []) { $this->actualClient->waitUntil($name, $args); } public function getWaiter($name, array $args = []) { return $this->actualClient->getWaiter($name, $args); } public function createPresignedRequest(CommandInterface $command, $expires, array $options = []) { return $this->actualClient->createPresignedRequest($command, $expires, $options); } public function getObjectUrl($bucket, $key) { return $this->actualClient->getObjectUrl($bucket, $key); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/UrlPrefixingClientStub.php
src/WebDAV/UrlPrefixingClientStub.php
<?php declare(strict_types=1); namespace League\Flysystem\WebDAV; use Sabre\DAV\Client; class UrlPrefixingClientStub extends Client { /** * @param string $url */ public function propFind($url, array $properties, $depth = 0): array { $response = parent::propFind($url, $properties, $depth); if ($depth === 0) { return $response; } $formatted = []; foreach ($response as $path => $object) { $formatted['https://domain.tld/' . ltrim($path, '/')] = $object; } return $formatted; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/WebDAVAdapter.php
src/WebDAV/WebDAVAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\WebDAV; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\UnableToCheckDirectoryExistence; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use RuntimeException; use Sabre\DAV\Client; use Sabre\DAV\Xml\Property\ResourceType; use Sabre\HTTP\ClientHttpException; use Sabre\HTTP\Request; use Throwable; use function array_key_exists; use function array_shift; use function dirname; use function explode; use function fclose; use function implode; use function parse_url; use function rawurldecode; class WebDAVAdapter implements FilesystemAdapter, PublicUrlGenerator { public const ON_VISIBILITY_THROW_ERROR = 'throw'; public const ON_VISIBILITY_IGNORE = 'ignore'; public const FIND_PROPERTIES = [ '{DAV:}displayname', '{DAV:}getcontentlength', '{DAV:}getcontenttype', '{DAV:}getlastmodified', '{DAV:}iscollection', '{DAV:}resourcetype', ]; private PathPrefixer $prefixer; public function __construct( private Client $client, string $prefix = '', private string $visibilityHandling = self::ON_VISIBILITY_THROW_ERROR, private bool $manualCopy = false, private bool $manualMove = false, ) { $this->prefixer = new PathPrefixer($prefix); } public function fileExists(string $path): bool { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $properties = $this->client->propFind($location, ['{DAV:}resourcetype', '{DAV:}iscollection']); return ! $this->propsIsDirectory($properties); } catch (Throwable $exception) { if ($exception instanceof ClientHttpException && $exception->getHttpStatus() === 404) { return false; } throw UnableToCheckFileExistence::forLocation($path, $exception); } } protected function encodePath(string $path): string { $parts = explode('/', $path); foreach ($parts as $i => $part) { $parts[$i] = rawurlencode($part); } return implode('/', $parts); } public function directoryExists(string $path): bool { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $properties = $this->client->propFind($location, ['{DAV:}resourcetype', '{DAV:}iscollection']); return $this->propsIsDirectory($properties); } catch (Throwable $exception) { if ($exception instanceof ClientHttpException && $exception->getHttpStatus() === 404) { return false; } throw UnableToCheckDirectoryExistence::forLocation($path, $exception); } } public function write(string $path, string $contents, Config $config): void { $this->upload($path, $contents); } public function writeStream(string $path, $contents, Config $config): void { $this->upload($path, $contents); } /** * @param resource|string $contents */ private function upload(string $path, mixed $contents): void { $this->createParentDirFor($path); $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $response = $this->client->request('PUT', $location, $contents); $statusCode = $response['statusCode']; if ($statusCode < 200 || $statusCode >= 300) { throw new RuntimeException('Unexpected status code received: ' . $statusCode); } } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } public function read(string $path): string { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $response = $this->client->request('GET', $location); if ($response['statusCode'] !== 200) { throw new RuntimeException('Unexpected response code for GET: ' . $response['statusCode']); } return $response['body']; } catch (Throwable $exception) { throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception); } } public function readStream(string $path) { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $url = $this->client->getAbsoluteUrl($location); $request = new Request('GET', $url); $response = $this->client->send($request); $status = $response->getStatus(); if ($status !== 200) { throw new RuntimeException('Unexpected response code for GET: ' . $status); } return $response->getBodyAsStream(); } catch (Throwable $exception) { throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception); } } public function delete(string $path): void { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $response = $this->client->request('DELETE', $location); $statusCode = $response['statusCode']; if ($statusCode !== 404 && ($statusCode < 200 || $statusCode >= 300)) { throw new RuntimeException('Unexpected status code received while deleting file: ' . $statusCode); } } catch (Throwable $exception) { if ( ! ($exception instanceof ClientHttpException && $exception->getCode() === 404)) { throw UnableToDeleteFile::atLocation($path, $exception->getMessage(), $exception); } } } public function deleteDirectory(string $path): void { $location = $this->encodePath($this->prefixer->prefixDirectoryPath($path)); try { $statusCode = $this->client->request('DELETE', $location)['statusCode']; if ($statusCode !== 404 && ($statusCode < 200 || $statusCode >= 300)) { throw new RuntimeException('Unexpected status code received while deleting file: ' . $statusCode); } } catch (Throwable $exception) { if ( ! ($exception instanceof ClientHttpException && $exception->getCode() === 404)) { throw UnableToDeleteDirectory::atLocation($path, $exception->getMessage(), $exception); } } } public function createDirectory(string $path, Config $config): void { $parts = explode('/', $this->prefixer->prefixDirectoryPath($path)); $directoryParts = []; foreach ($parts as $directory) { if ($directory === '.' || $directory === '') { return; } $directoryParts[] = $directory; $directoryPath = implode('/', $directoryParts); $location = $this->encodePath($directoryPath) . '/'; if ($this->directoryExists($this->prefixer->stripDirectoryPrefix($directoryPath))) { continue; } try { $response = $this->client->request('MKCOL', $location); } catch (Throwable $exception) { throw UnableToCreateDirectory::dueToFailure($path, $exception); } if ($response['statusCode'] === 405) { continue; } if ($response['statusCode'] !== 201) { throw UnableToCreateDirectory::atLocation($path, 'Failed to create directory at: ' . $location); } } } public function setVisibility(string $path, string $visibility): void { if ($this->visibilityHandling === self::ON_VISIBILITY_THROW_ERROR) { throw UnableToSetVisibility::atLocation($path, 'WebDAV does not support this operation.'); } } public function visibility(string $path): FileAttributes { throw UnableToRetrieveMetadata::visibility($path, 'WebDAV does not support this operation.'); } public function mimeType(string $path): FileAttributes { $mimeType = (string) $this->propFind($path, 'mime_type', '{DAV:}getcontenttype'); return new FileAttributes($path, mimeType: $mimeType); } public function lastModified(string $path): FileAttributes { $lastModified = $this->propFind($path, 'last_modified', '{DAV:}getlastmodified'); return new FileAttributes($path, lastModified: strtotime($lastModified)); } public function fileSize(string $path): FileAttributes { $fileSize = (int) $this->propFind($path, 'file_size', '{DAV:}getcontentlength'); return new FileAttributes($path, fileSize: $fileSize); } public function listContents(string $path, bool $deep): iterable { $location = $this->encodePath($this->prefixer->prefixDirectoryPath($path)); $response = $this->client->propFind($location, self::FIND_PROPERTIES, 1); // This is the directory itself, the files are subsequent entries. array_shift($response); foreach ($response as $path => $object) { $path = (string) parse_url(rawurldecode($path), PHP_URL_PATH); $path = $this->prefixer->stripPrefix($path); $object = $this->normalizeObject($object); if ($this->propsIsDirectory($object)) { yield new DirectoryAttributes($path, lastModified: $object['last_modified'] ?? null); if ( ! $deep) { continue; } foreach ($this->listContents($path, true) as $child) { yield $child; } } else { yield new FileAttributes( $path, fileSize: $object['file_size'] ?? null, lastModified: $object['last_modified'] ?? null, mimeType: $object['mime_type'] ?? null, ); } } } private function normalizeObject(array $object): array { $mapping = [ '{DAV:}getcontentlength' => 'file_size', '{DAV:}getcontenttype' => 'mime_type', 'content-length' => 'file_size', 'content-type' => 'mime_type', ]; foreach ($mapping as $from => $to) { if (array_key_exists($from, $object)) { $object[$to] = $object[$from]; } } array_key_exists('file_size', $object) && $object['file_size'] = (int) $object['file_size']; if (array_key_exists('{DAV:}getlastmodified', $object)) { $object['last_modified'] = strtotime($object['{DAV:}getlastmodified']); } return $object; } public function move(string $source, string $destination, Config $config): void { if ($source === $destination) { return; } if ($this->manualMove) { $this->manualMove($source, $destination); return; } $this->createParentDirFor($destination); $location = $this->encodePath($this->prefixer->prefixPath($source)); $newLocation = $this->encodePath($this->prefixer->prefixPath($destination)); try { $response = $this->client->request('MOVE', $location, null, [ 'Destination' => $this->client->getAbsoluteUrl($newLocation), ]); if ($response['statusCode'] < 200 || $response['statusCode'] >= 300) { throw new RuntimeException('MOVE command returned unexpected status code: ' . $response['statusCode'] . "\n{$response['body']}"); } } catch (Throwable $e) { throw UnableToMoveFile::fromLocationTo($source, $destination, $e); } } private function manualMove(string $source, string $destination): void { try { $handle = $this->readStream($source); $this->writeStream($destination, $handle, new Config()); @fclose($handle); $this->delete($source); } catch (Throwable $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } } public function copy(string $source, string $destination, Config $config): void { if ($source === $destination) { return; } if ($this->manualCopy) { $this->manualCopy($source, $destination); return; } $this->createParentDirFor($destination); $location = $this->encodePath($this->prefixer->prefixPath($source)); $newLocation = $this->encodePath($this->prefixer->prefixPath($destination)); try { $response = $this->client->request('COPY', $location, null, [ 'Destination' => $this->client->getAbsoluteUrl($newLocation), ]); if ($response['statusCode'] < 200 || $response['statusCode'] >= 300) { throw new RuntimeException('COPY command returned unexpected status code: ' . $response['statusCode']); } } catch (Throwable $e) { throw UnableToCopyFile::fromLocationTo($source, $destination, $e); } } private function manualCopy(string $source, string $destination): void { try { $handle = $this->readStream($source); $this->writeStream($destination, $handle, new Config()); @fclose($handle); } catch (Throwable $exception) { throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } private function propsIsDirectory(array $properties): bool { if (isset($properties['{DAV:}resourcetype'])) { /** @var ResourceType $resourceType */ $resourceType = $properties['{DAV:}resourcetype']; return $resourceType->is('{DAV:}collection'); } return isset($properties['{DAV:}iscollection']) && $properties['{DAV:}iscollection'] === '1'; } private function createParentDirFor(string $path): void { $dirname = dirname($path); if ($this->directoryExists($dirname)) { return; } $this->createDirectory($dirname, new Config()); } private function propFind(string $path, string $section, string $property): mixed { $location = $this->encodePath($this->prefixer->prefixPath($path)); try { $result = $this->client->propFind($location, [$property]); if ( ! array_key_exists($property, $result)) { throw new RuntimeException('Invalid response, missing key: ' . $property); } return $result[$property]; } catch (Throwable $exception) { throw UnableToRetrieveMetadata::create($path, $section, $exception->getMessage(), $exception); } } public function publicUrl(string $path, Config $config): string { return $this->client->getAbsoluteUrl($this->encodePath($this->prefixer->prefixPath($path))); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/ByteMarkWebDAVServerTest.php
src/WebDAV/ByteMarkWebDAVServerTest.php
<?php declare(strict_types=1); namespace League\Flysystem\WebDAV; use League\Flysystem\FilesystemAdapter; class ByteMarkWebDAVServerTest extends WebDAVAdapterTestCase { protected static function createFilesystemAdapter(): FilesystemAdapter { if (($_ENV['TEST_WEBDAV'] ?? '') !== 'YES') { self::markTestSkipped('Library regression'); } $client = new UrlPrefixingClientStub(['baseUri' => 'http://localhost:4080/', 'userName' => 'alice', 'password' => 'secret1234']); return new WebDAVAdapter($client, manualCopy: true, manualMove: true); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/WebDAVAdapterTestCase.php
src/WebDAV/WebDAVAdapterTestCase.php
<?php declare(strict_types=1); namespace League\Flysystem\WebDAV; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\Config; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\Visibility; use Sabre\DAV\Client; abstract class WebDAVAdapterTestCase extends FilesystemAdapterTestCase { /** * @test */ public function setting_visibility(): void { $adapter = $this->adapter(); $this->givenWeHaveAnExistingFile('some/file.txt'); $this->expectException(UnableToSetVisibility::class); $adapter->setVisibility('some/file.txt', Visibility::PRIVATE); } /** * @test */ public function overwriting_a_file(): void { $this->runScenario(function () { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $contents = $adapter->read('path.txt'); $this->assertEquals('new contents', $contents); }); } /** * @test */ public function creating_a_directory_with_leading_and_trailing_slashes(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->createDirectory('/some/directory/', new Config()); self::assertTrue($adapter->directoryExists('/some/directory/')); }); } /** * @test */ public function copying_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config() ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function copying_a_file_again(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config() ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function moving_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config() ); $adapter->move('source.txt', 'destination.txt', new Config()); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function moving_a_file_that_does_not_exist(): void { $this->expectException(UnableToMoveFile::class); $this->runScenario(function () { $this->adapter()->move('source.txt', 'destination.txt', new Config()); }); } /** * @test */ public function part_of_prefix_already_exists(): void { $this->runScenario(function () { $config = new Config(); $adapter1 = new WebDAVAdapter( new Client(['baseUri' => 'http://localhost:4040/']), 'directory1/prefix1', ); $adapter1->createDirectory('folder1', $config); self::assertTrue($adapter1->directoryExists('/folder1')); $adapter2 = new WebDAVAdapter( new Client(['baseUri' => 'http://localhost:4040/']), 'directory1/prefix2', ); $adapter2->createDirectory('folder2', $config); self::assertTrue($adapter2->directoryExists('/folder2')); }); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/SabreServerTest.php
src/WebDAV/SabreServerTest.php
<?php declare(strict_types=1); namespace League\Flysystem\WebDAV; use League\Flysystem\FilesystemAdapter; use Sabre\DAV\Client; class SabreServerTest extends WebDAVAdapterTestCase { protected static function createFilesystemAdapter(): FilesystemAdapter { $client = new Client(['baseUri' => 'http://localhost:4040/']); return new WebDAVAdapter($client, 'directory/prefix'); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WebDAV/resources/server.php
src/WebDAV/resources/server.php
<?php use Sabre\DAV\FS\Directory; use Sabre\DAV\Server; include __DIR__ . '/../../../vendor/autoload.php'; error_reporting(E_ALL ^ E_DEPRECATED); $rootPath = __DIR__ . '/data'; if ( ! is_dir($rootPath)) { mkdir($rootPath); } $rootDirectory = new Directory($rootPath); $server = new Server($rootDirectory); $server->addPlugin(new Sabre\DAV\Browser\Plugin()); if (strpos($_SERVER['REQUEST_URI'], 'unknown-mime-type.md5') === false) { $guesser = new Sabre\DAV\Browser\GuessContentType(); $guesser->extensionMap['svg'] = 'image/svg+xml'; $server->addPlugin($guesser); } $server->start();
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/ShardedPrefixPublicUrlGenerator.php
src/UrlGeneration/ShardedPrefixPublicUrlGenerator.php
<?php namespace League\Flysystem\UrlGeneration; use InvalidArgumentException; use League\Flysystem\Config; use League\Flysystem\PathPrefixer; use function array_map; use function count; use function crc32; final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator { /** @var PathPrefixer[] */ private array $prefixes; private int $count; /** * @param string[] $prefixes */ public function __construct(array $prefixes) { $this->count = count($prefixes); if ($this->count === 0) { throw new InvalidArgumentException('At least one prefix is required.'); } $this->prefixes = array_map(static fn (string $prefix) => new PathPrefixer($prefix, '/'), $prefixes); } public function publicUrl(string $path, Config $config): string { $index = abs(crc32($path)) % $this->count; return $this->prefixes[$index]->prefixPath($path); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/ChainedPublicUrlGeneratorTest.php
src/UrlGeneration/ChainedPublicUrlGeneratorTest.php
<?php namespace League\Flysystem\UrlGeneration; use League\Flysystem\Config; use League\Flysystem\UnableToGeneratePublicUrl; use PHPUnit\Framework\TestCase; final class ChainedPublicUrlGeneratorTest extends TestCase { /** * @test */ public function can_generate_url_for_supported_generator(): void { $generator = new ChainedPublicUrlGenerator([ new class() implements PublicUrlGenerator { public function publicUrl(string $path, Config $config): string { throw new UnableToGeneratePublicUrl('not supported', $path); } }, new PrefixPublicUrlGenerator('/prefix'), ]); $this->assertSame('/prefix/some/path', $generator->publicUrl('some/path', new Config())); } /** * @test */ public function no_supported_generator_found_throws_exception(): void { $generator = new ChainedPublicUrlGenerator([ new class() implements PublicUrlGenerator { public function publicUrl(string $path, Config $config): string { throw new UnableToGeneratePublicUrl('not supported', $path); } }, ]); $this->expectException(UnableToGeneratePublicUrl::class); $this->expectExceptionMessage('Unable to generate public url for some/path: No supported public url generator found.'); $generator->publicUrl('some/path', new Config()); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/PrefixPublicUrlGenerator.php
src/UrlGeneration/PrefixPublicUrlGenerator.php
<?php declare(strict_types=1); namespace League\Flysystem\UrlGeneration; use League\Flysystem\Config; use League\Flysystem\PathPrefixer; class PrefixPublicUrlGenerator implements PublicUrlGenerator { private PathPrefixer $prefixer; public function __construct(string $urlPrefix) { $this->prefixer = new PathPrefixer($urlPrefix, '/'); } public function publicUrl(string $path, Config $config): string { return $this->prefixer->prefixPath($path); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/ChainedPublicUrlGenerator.php
src/UrlGeneration/ChainedPublicUrlGenerator.php
<?php declare(strict_types=1); namespace League\Flysystem\UrlGeneration; use League\Flysystem\Config; use League\Flysystem\UnableToGeneratePublicUrl; final class ChainedPublicUrlGenerator implements PublicUrlGenerator { /** * @param PublicUrlGenerator[] $generators */ public function __construct(private iterable $generators) { } public function publicUrl(string $path, Config $config): string { foreach ($this->generators as $generator) { try { return $generator->publicUrl($path, $config); } catch (UnableToGeneratePublicUrl) { } } throw new UnableToGeneratePublicUrl('No supported public url generator found.', $path); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/PublicUrlGenerator.php
src/UrlGeneration/PublicUrlGenerator.php
<?php declare(strict_types=1); namespace League\Flysystem\UrlGeneration; use League\Flysystem\Config; use League\Flysystem\UnableToGeneratePublicUrl; interface PublicUrlGenerator { /** * @throws UnableToGeneratePublicUrl */ public function publicUrl(string $path, Config $config): string; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UrlGeneration/TemporaryUrlGenerator.php
src/UrlGeneration/TemporaryUrlGenerator.php
<?php declare(strict_types=1); namespace League\Flysystem\UrlGeneration; use DateTimeInterface; use League\Flysystem\Config; use League\Flysystem\UnableToGenerateTemporaryUrl; interface TemporaryUrlGenerator { /** * @throws UnableToGenerateTemporaryUrl */ public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GridFS/GridFSAdapterTest.php
src/GridFS/GridFSAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\GridFS; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase as TestCase; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToWriteFile; use MongoDB\Client; use MongoDB\Database; use function getenv; /** * @group gridfs * * @method GridFSAdapter adapter() */ class GridFSAdapterTest extends TestCase { /** * @var string */ private static $adapterPrefix = 'test-prefix'; public static function tearDownAfterClass(): void { self::getDatabase()->drop(); parent::tearDownAfterClass(); } /** * @test */ public function fetching_contains_extra_metadata(): void { $adapter = $this->adapter(); $this->runScenario(function () use ($adapter) { $this->givenWeHaveAnExistingFile('file.txt'); $fileAttributes = $adapter->lastModified('file.txt'); $extra = $fileAttributes->extraMetadata(); $this->assertArrayHasKey('_id', $extra); $this->assertArrayHasKey('filename', $extra); }); } /** * @test */ public function fetching_last_modified_of_a_directory(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = $this->adapter(); $this->runScenario(function () use ($adapter) { $adapter->createDirectory('path', new Config()); $adapter->lastModified('path/'); }); } /** * @test */ public function fetching_mime_type_of_a_directory(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = $this->adapter(); $this->runScenario(function () use ($adapter) { $adapter->createDirectory('path', new Config()); $adapter->mimeType('path/'); }); } /** * @test */ public function reading_a_file_with_trailing_slash(): void { $this->expectException(UnableToReadFile::class); $this->adapter()->read('foo/'); } /** * @test */ public function reading_a_file_stream_with_trailing_slash(): void { $this->expectException(UnableToReadFile::class); $this->adapter()->readStream('foo/'); } /** * @test */ public function writing_a_file_with_trailing_slash(): void { $this->expectException(UnableToWriteFile::class); $this->adapter()->write('foo/', 'contents', new Config()); } /** * @test */ public function writing_a_file_stream_with_trailing_slash(): void { $this->expectException(UnableToWriteFile::class); $writeStream = stream_with_contents('contents'); $this->adapter()->writeStream('foo/', $writeStream, new Config()); } /** * @test */ public function writing_a_file_with_a_invalid_stream(): void { $this->expectException(UnableToWriteFile::class); // @phpstan-ignore argument.type $this->adapter()->writeStream('file.txt', 'foo', new Config()); } /** * @test */ public function delete_a_file_with_trailing_slash(): void { $this->expectException(UnableToDeleteFile::class); $this->adapter()->delete('foo/'); } /** * @test */ public function reading_last_revision(): void { $this->runScenario( function () { $this->givenWeHaveAnExistingFile('file.txt', 'version 1'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 2'); $this->assertSame('version 2', $this->adapter()->read('file.txt')); } ); } /** * @testWith [false] * [true] * * @test */ public function listing_contents_last_revision(bool $deep): void { $this->runScenario( function () use ($deep) { $this->givenWeHaveAnExistingFile('file.txt', 'version 1'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 2'); $files = $this->adapter()->listContents('', $deep); $files = iterator_to_array($files); $this->assertCount(1, $files); $file = $files[0]; $this->assertInstanceOf(FileAttributes::class, $file); $this->assertSame('file.txt', $file->path()); } ); } /** * @test */ public function listing_contents_directory_with_multiple_files(): void { $this->runScenario( function () { $this->givenWeHaveAnExistingFile('some/file-1.txt'); $this->givenWeHaveAnExistingFile('some/file-2.txt'); $this->givenWeHaveAnExistingFile('some/other/file-1.txt'); $files = $this->adapter()->listContents('', false); $files = iterator_to_array($files); $this->assertCount(1, $files); $file = $files[0]; $this->assertInstanceOf(DirectoryAttributes::class, $file); $this->assertSame('some', $file->path()); } ); } /** * @test */ public function delete_all_revisions(): void { $this->runScenario( function () { $this->givenWeHaveAnExistingFile('file.txt', 'version 1'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 2'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 3'); $this->adapter()->delete('file.txt'); $this->assertFalse($this->adapter()->fileExists('file.txt'), 'File does not exist'); } ); } /** * @test */ public function move_all_revisions(): void { $this->runScenario( function () { $this->givenWeHaveAnExistingFile('file.txt', 'version 1'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 2'); usleep(1000); $this->givenWeHaveAnExistingFile('file.txt', 'version 3'); $this->adapter()->move('file.txt', 'destination.txt', new Config()); $this->assertFalse($this->adapter()->fileExists('file.txt')); $this->assertSame($this->adapter()->read('destination.txt'), 'version 3'); } ); } protected function tearDown(): void { self::getDatabase()->selectGridFSBucket()->drop(); parent::tearDown(); } protected static function createFilesystemAdapter(): FilesystemAdapter { $bucket = self::getDatabase()->selectGridFSBucket(); $prefix = getenv('FLYSYSTEM_MONGODB_PREFIX') ?: self::$adapterPrefix; return new GridFSAdapter($bucket, $prefix); } private static function getDatabase(): Database { $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1:27017/'; $client = new Client($uri); return $client->selectDatabase(getenv('MONGODB_DATABASE') ?: 'flysystem_tests'); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GridFS/GridFSAdapter.php
src/GridFS/GridFSAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\GridFS; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; use MongoDB\Driver\Exception\Exception; use MongoDB\GridFS\Bucket; use MongoDB\GridFS\Exception\FileNotFoundException; /** * @phpstan-type GridFile array{_id:ObjectId, length:int, chunkSize:int, uploadDate:UTCDateTime, filename:string, metadata?:array{contentType?:string, flysystem_visibility?:string}} */ class GridFSAdapter implements FilesystemAdapter { private const METADATA_DIRECTORY = 'flysystem_directory'; private const METADATA_VISIBILITY = 'flysystem_visibility'; private const METADATA_MIMETYPE = 'contentType'; private const TYPEMAP_ARRAY = [ 'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'], 'codec' => null, ]; private Bucket $bucket; private PathPrefixer $prefixer; private MimeTypeDetector $mimeTypeDetector; public function __construct( Bucket $bucket, string $prefix = '', ?MimeTypeDetector $mimeTypeDetector = null, ) { $this->bucket = $bucket; $this->prefixer = new PathPrefixer($prefix); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); } public function fileExists(string $path): bool { $file = $this->findFile($path); return $file !== null; } public function directoryExists(string $path): bool { // A directory exists if at least one file exists with a path starting with the directory name $files = $this->listContents($path, true); foreach ($files as $file) { return true; } return false; } public function write(string $path, string $contents, Config $config): void { if (str_ends_with($path, '/')) { throw UnableToWriteFile::atLocation($path, 'file path cannot end with a slash'); } $filename = $this->prefixer->prefixPath($path); $options = [ 'metadata' => $config->get('metadata', []), ]; if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $options['metadata'][self::METADATA_VISIBILITY] = $visibility; } if (($mimeType = $config->get('mimetype')) || ($mimeType = $this->mimeTypeDetector->detectMimeType($path, $contents))) { $options['metadata'][self::METADATA_MIMETYPE] = $mimeType; } try { $stream = $this->bucket->openUploadStream($filename, $options); fwrite($stream, $contents); fclose($stream); } catch (Exception $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } public function writeStream(string $path, $contents, Config $config): void { if (str_ends_with($path, '/')) { throw UnableToWriteFile::atLocation($path, 'file path cannot end with a slash'); } $filename = $this->prefixer->prefixPath($path); $options = []; if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $options['metadata'][self::METADATA_VISIBILITY] = $visibility; } if (($mimetype = $config->get('mimetype')) || ($mimetype = $this->mimeTypeDetector->detectMimeTypeFromPath($path))) { $options['metadata'][self::METADATA_MIMETYPE] = $mimetype; } try { $this->bucket->uploadFromStream($filename, $contents, $options); } catch (Exception $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } public function read(string $path): string { $stream = $this->readStream($path); try { return stream_get_contents($stream); } finally { fclose($stream); } } public function readStream(string $path) { if (str_ends_with($path, '/')) { throw UnableToReadFile::fromLocation($path, 'file path cannot end with a slash'); } try { $filename = $this->prefixer->prefixPath($path); return $this->bucket->openDownloadStreamByName($filename); } catch (FileNotFoundException $exception) { throw UnableToReadFile::fromLocation($path, 'file does not exist', $exception); } catch (Exception $exception) { throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception); } } /** * Delete all revisions of the file name, starting with the oldest, * no-op if the file does not exist. * * @throws UnableToDeleteFile */ public function delete(string $path): void { if (str_ends_with($path, '/')) { throw UnableToDeleteFile::atLocation($path, 'file path cannot end with a slash'); } $filename = $this->prefixer->prefixPath($path); try { $this->findAndDelete(['filename' => $filename]); } catch (Exception $exception) { throw UnableToDeleteFile::atLocation($path, $exception->getMessage(), $exception); } } public function deleteDirectory(string $path): void { $prefixedPath = $this->prefixer->prefixDirectoryPath($path); try { $this->findAndDelete(['filename' => new Regex('^' . preg_quote($prefixedPath))]); } catch (Exception $exception) { throw UnableToDeleteDirectory::atLocation($path, $exception->getMessage(), $exception); } } public function createDirectory(string $path, Config $config): void { $dirname = $this->prefixer->prefixDirectoryPath($path); $options = [ 'metadata' => $config->get('metadata', []) + [self::METADATA_DIRECTORY => true], ]; if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $options['metadata'][self::METADATA_VISIBILITY] = $visibility; } try { $stream = $this->bucket->openUploadStream($dirname, $options); fwrite($stream, ''); fclose($stream); } catch (Exception $exception) { throw UnableToCreateDirectory::atLocation($path, $exception->getMessage(), $exception); } } public function setVisibility(string $path, string $visibility): void { $file = $this->findFile($path); if ($file === null) { throw UnableToSetVisibility::atLocation($path, 'file does not exist'); } try { $this->bucket->getFilesCollection()->updateOne( ['_id' => $file['_id']], ['$set' => ['metadata.' . self::METADATA_VISIBILITY => $visibility]], ); } catch (Exception $exception) { throw UnableToSetVisibility::atLocation($path, $exception->getMessage(), $exception); } } public function visibility(string $path): FileAttributes { $file = $this->findFile($path); if ($file === null) { throw UnableToRetrieveMetadata::mimeType($path, 'file does not exist'); } return $this->mapFileAttributes($file); } public function fileSize(string $path): FileAttributes { if (str_ends_with($path, '/')) { throw UnableToRetrieveMetadata::fileSize($path, 'file path cannot end with a slash'); } $file = $this->findFile($path); if ($file === null) { throw UnableToRetrieveMetadata::fileSize($path, 'file does not exist'); } return $this->mapFileAttributes($file); } public function mimeType(string $path): FileAttributes { if (str_ends_with($path, '/')) { throw UnableToRetrieveMetadata::mimeType($path, 'file path cannot end with a slash'); } $file = $this->findFile($path); if ($file === null) { throw UnableToRetrieveMetadata::mimeType($path, 'file does not exist'); } $attributes = $this->mapFileAttributes($file); if ($attributes->mimeType() === null) { throw UnableToRetrieveMetadata::mimeType($path, 'unknown'); } return $attributes; } public function lastModified(string $path): FileAttributes { if (str_ends_with($path, '/')) { throw UnableToRetrieveMetadata::lastModified($path, 'file path cannot end with a slash'); } $file = $this->findFile($path); if ($file === null) { throw UnableToRetrieveMetadata::lastModified($path, 'file does not exist'); } return $this->mapFileAttributes($file); } public function listContents(string $path, bool $deep): iterable { $path = $this->prefixer->prefixDirectoryPath($path); $pathdeep = 0; // Get the last revision of each file, using the index on the files collection $pipeline = [['$sort' => ['filename' => 1, 'uploadDate' => 1]]]; if ($path !== '') { $pathdeep = substr_count($path, '/'); // Exclude files that do not start with the expected path $pipeline[] = ['$match' => ['filename' => new Regex('^' . preg_quote($path))]]; } if ($deep === false) { $pipeline[] = ['$addFields' => ['splitpath' => ['$split' => ['$filename', '/']]]]; $pipeline[] = ['$group' => [ // The same name could be used as a filename and as part of the path of other files '_id' => [ 'basename' => ['$arrayElemAt' => ['$splitpath', $pathdeep]], 'isDir' => ['$ne' => [['$size' => '$splitpath'], $pathdeep + 1]], ], // Get the metadata of the last revision of each file 'file' => ['$last' => '$$ROOT'], // The "lastModified" date is the date of the last uploaded file in the directory 'uploadDate' => ['$max' => '$uploadDate'], ]]; $files = $this->bucket->getFilesCollection()->aggregate($pipeline, self::TYPEMAP_ARRAY); foreach ($files as $file) { if ($file['_id']['isDir']) { yield new DirectoryAttributes( $this->prefixer->stripDirectoryPrefix($path . $file['_id']['basename']), null, $file['uploadDate']->toDateTime()->getTimestamp(), ); } else { yield $this->mapFileAttributes($file['file']); } } } else { // Get the metadata of the last revision of each file $pipeline[] = ['$group' => [ '_id' => '$filename', 'file' => ['$first' => '$$ROOT'], ]]; $files = $this->bucket->getFilesCollection()->aggregate($pipeline, self::TYPEMAP_ARRAY); foreach ($files as $file) { $file = $file['file']; if (str_ends_with($file['filename'], '/')) { // Empty files with a trailing slash are markers for directories, only for Flysystem yield new DirectoryAttributes( $this->prefixer->stripDirectoryPrefix($file['filename']), $file['metadata'][self::METADATA_VISIBILITY] ?? null, $file['uploadDate']->toDateTime()->getTimestamp(), $file, ); } else { yield $this->mapFileAttributes($file); } } } } public function move(string $source, string $destination, Config $config): void { if ($source === $destination) { return; } if ($this->fileExists($destination)) { $this->delete($destination); } try { $result = $this->bucket->getFilesCollection()->updateMany( ['filename' => $this->prefixer->prefixPath($source)], ['$set' => ['filename' => $this->prefixer->prefixPath($destination)]], ); if ($result->getModifiedCount() === 0) { throw UnableToMoveFile::because('file does not exist', $source, $destination); } } catch (Exception $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } } public function copy(string $source, string $destination, Config $config): void { $file = $this->findFile($source); if ($file === null) { throw UnableToCopyFile::fromLocationTo( $source, $destination, ); } $options = []; if (($visibility = $config->get(Config::OPTION_VISIBILITY)) || $visibility = $file['metadata'][self::METADATA_VISIBILITY] ?? null) { $options['metadata'][self::METADATA_VISIBILITY] = $visibility; } if (($mimetype = $config->get('mimetype')) || $mimetype = $file['metadata'][self::METADATA_MIMETYPE] ?? null) { $options['metadata'][self::METADATA_MIMETYPE] = $mimetype; } try { $stream = $this->bucket->openDownloadStream($file['_id']); $this->bucket->uploadFromStream($this->prefixer->prefixPath($destination), $stream, $options); } catch (Exception $exception) { throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } /** * Get the last revision of the file name. * * @return GridFile|null */ private function findFile(string $path): ?array { $filename = $this->prefixer->prefixPath($path); $files = $this->bucket->find( ['filename' => $filename], ['sort' => ['uploadDate' => -1], 'limit' => 1] + self::TYPEMAP_ARRAY, ); return $files->toArray()[0] ?? null; } /** * @param GridFile $file */ private function mapFileAttributes(array $file): FileAttributes { return new FileAttributes( $this->prefixer->stripPrefix($file['filename']), $file['length'], $file['metadata'][self::METADATA_VISIBILITY] ?? null, $file['uploadDate']->toDateTime()->getTimestamp(), $file['metadata'][self::METADATA_MIMETYPE] ?? null, $file, ); } /** * @throws Exception */ private function findAndDelete(array $filter): void { $files = $this->bucket->find( $filter, ['sort' => ['uploadDate' => 1], 'projection' => ['_id' => 1]] + self::TYPEMAP_ARRAY, ); foreach ($files as $file) { try { $this->bucket->delete($file['_id']); } catch (FileNotFoundException) { // Ignore error due to race condition } } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Local/LocalFilesystemAdapterTest.php
src/Local/LocalFilesystemAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\Local; use const LOCK_EX; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\Config; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemAdapter; use League\Flysystem\StorageAttributes; use League\Flysystem\SymbolicLinkEncountered; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UnixVisibility\PortableVisibilityConverter; use League\Flysystem\UnixVisibility\VisibilityConverter; use League\Flysystem\Visibility; use League\MimeTypeDetection\EmptyExtensionToMimeTypeMap; use League\MimeTypeDetection\ExtensionMimeTypeDetector; use League\MimeTypeDetection\FinfoMimeTypeDetector; use Traversable; use function file_get_contents; use function file_put_contents; use function fileperms; use function is_resource; use function iterator_to_array; use function mkdir; use function strnatcasecmp; use function symlink; use function usort; /** * @group local */ class LocalFilesystemAdapterTest extends FilesystemAdapterTestCase { public const ROOT = __DIR__ . '/test-root'; protected function setUp(): void { reset_function_mocks(); delete_directory(static::ROOT); } protected function tearDown(): void { reset_function_mocks(); delete_directory(static::ROOT); } /** * @test */ public function creating_a_local_filesystem_creates_a_root_directory(): void { new LocalFilesystemAdapter(static::ROOT); $this->assertDirectoryExists(static::ROOT); } /** * @test */ public function creating_a_local_filesystem_does_not_create_a_root_directory_when_constructed_with_lazy_root_creation(): void { new LocalFilesystemAdapter(static::ROOT, lazyRootCreation: true); $this->assertDirectoryDoesNotExist(static::ROOT); } /** * @test */ public function not_being_able_to_create_a_root_directory_results_in_an_exception(): void { $this->expectException(UnableToCreateDirectory::class); new LocalFilesystemAdapter('/cannot-create/this-directory/'); } /** * @test * * @see https://github.com/thephpleague/flysystem/issues/1442 */ public function falling_back_to_extension_lookup_when_finding_mime_type_of_empty_file(): void { $this->givenWeHaveAnExistingFile('something.csv', ''); $mimeType = $this->adapter()->mimeType('something.csv'); self::assertEquals('text/csv', $mimeType->mimeType()); } /** * @test */ public function writing_a_file(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('/file.txt', 'contents', new Config()); $this->assertFileExists(static::ROOT . '/file.txt'); $contents = file_get_contents(static::ROOT . '/file.txt'); $this->assertEquals('contents', $contents); } /** * @test */ public function writing_a_file_with_a_stream(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $stream = stream_with_contents('contents'); $adapter->writeStream('/file.txt', $stream, new Config()); fclose($stream); $this->assertFileExists(static::ROOT . '/file.txt'); $contents = file_get_contents(static::ROOT . '/file.txt'); $this->assertEquals('contents', $contents); } /** * @test * * @see https://github.com/thephpleague/flysystem/issues/1606 */ public function deleting_a_file_during_contents_listing(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, visibility: new class() implements VisibilityConverter { private VisibilityConverter $visibility; public function __construct() { $this->visibility = new PortableVisibilityConverter(); } public function forFile(string $visibility): int { return $this->visibility->forFile($visibility); } public function forDirectory(string $visibility): int { return $this->visibility->forDirectory($visibility); } public function inverseForFile(int $visibility): string { unlink(LocalFilesystemAdapterTest::ROOT . '/file-1.txt'); return $this->visibility->inverseForFile($visibility); } public function inverseForDirectory(int $visibility): string { return $this->visibility->inverseForDirectory($visibility); } public function defaultForDirectories(): int { return $this->visibility->defaultForDirectories(); } }); $filesystem = new Filesystem($adapter); $filesystem->write('/file-1.txt', 'something'); $listing = $filesystem->listContents('/')->toArray(); self::assertCount(0, $listing); } /** * @test */ public function writing_a_file_with_a_stream_and_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $stream = stream_with_contents('something'); $adapter->writeStream('/file.txt', $stream, new Config(['visibility' => Visibility::PRIVATE])); fclose($stream); $this->assertFileContains(static::ROOT . '/file.txt', 'something'); $this->assertFileHasPermissions(static::ROOT . '/file.txt', 0600); } /** * @test */ public function writing_a_file_with_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, new PortableVisibilityConverter()); $adapter->write('/file.txt', 'contents', new Config(['visibility' => 'private'])); $this->assertFileContains(static::ROOT . '/file.txt', 'contents'); $this->assertFileHasPermissions(static::ROOT . '/file.txt', 0600); } /** * @test */ public function failing_to_set_visibility(): void { $this->expectException(UnableToSetVisibility::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->setVisibility('/file.txt', Visibility::PUBLIC); } /** * @test */ public function failing_to_write_a_file(): void { $this->expectException(UnableToWriteFile::class); (new LocalFilesystemAdapter('/'))->write('/cannot-create-a-file-here', 'contents', new Config()); } /** * @test */ public function failing_to_write_a_file_using_a_stream(): void { $this->expectException(UnableToWriteFile::class); try { $stream = stream_with_contents('something'); (new LocalFilesystemAdapter('/'))->writeStream('/cannot-create-a-file-here', $stream, new Config()); } finally { isset($stream) && is_resource($stream) && fclose($stream); } } /** * @test */ public function deleting_a_file(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); file_put_contents(static::ROOT . '/file.txt', 'contents'); $adapter->delete('/file.txt'); $this->assertFileDoesNotExist(static::ROOT . '/file.txt'); } /** * @test */ public function deleting_a_file_that_does_not_exist(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->delete('/file.txt'); $this->assertTrue(true); } /** * @test */ public function deleting_a_file_that_cannot_be_deleted(): void { $this->givenWeHaveAnExistingFile('here.txt'); mock_function('unlink', false); $this->expectException(UnableToDeleteFile::class); $this->adapter()->delete('here.txt'); } /** * @test */ public function checking_if_a_file_exists(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('/file.txt', 'contents', new Config); $this->assertTrue($adapter->fileExists('/file.txt')); } /** * @test */ public function checking_if_a_file_exists_that_does_not_exsist(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $this->assertFalse($adapter->fileExists('/file.txt')); } /** * @test */ public function listing_contents(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('directory/filename.txt', 'content', new Config()); $adapter->write('filename.txt', 'content', new Config()); /** @var Traversable $contentListing */ $contentListing = $adapter->listContents('/', false); $contents = iterator_to_array($contentListing); $this->assertCount(2, $contents); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $contents); } /** * @test */ public function listing_contents_recursively(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('directory/filename.txt', 'content', new Config()); $adapter->write('filename.txt', 'content', new Config()); /** @var Traversable $contentListing */ $contentListing = $adapter->listContents('/', true); $contents = iterator_to_array($contentListing); $this->assertCount(3, $contents); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $contents); } /** * @test */ public function listing_a_non_existing_directory(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); /** @var Traversable $contentListing */ $contentListing = $adapter->listContents('/directory/', false); $contents = iterator_to_array($contentListing); $this->assertCount(0, $contents); } /** * @test */ public function listing_directory_contents_with_link_skipping(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, null, LOCK_EX, LocalFilesystemAdapter::SKIP_LINKS); $adapter->write('/file.txt', 'content', new Config()); symlink(static::ROOT . '/file.txt', static::ROOT . '/link.txt'); /** @var Traversable $contentListing */ $contentListing = $adapter->listContents('/', true); $contents = iterator_to_array($contentListing); $this->assertCount(1, $contents); } /** * @test */ public function listing_directory_contents_with_disallowing_links(): void { $this->expectException(SymbolicLinkEncountered::class); $adapter = new LocalFilesystemAdapter(static::ROOT, null, LOCK_EX, LocalFilesystemAdapter::DISALLOW_LINKS); file_put_contents(static::ROOT . '/file.txt', 'content'); symlink(static::ROOT . '/file.txt', static::ROOT . '/link.txt'); /** @var Traversable $contentListing */ $contentListing = $adapter->listContents('/', true); iterator_to_array($contentListing); } /** * @test */ public function retrieving_visibility_while_listing_directory_contents(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->createDirectory('public', new Config(['visibility' => 'public'])); $adapter->createDirectory('private', new Config(['visibility' => 'private'])); $adapter->write('public/private.txt', 'private', new Config(['visibility' => 'private'])); $adapter->write('private/public.txt', 'public', new Config(['visibility' => 'public'])); /** @var Traversable<StorageAttributes> $contentListing */ $contentListing = $adapter->listContents('/', true); $listing = iterator_to_array($contentListing); usort($listing, function (StorageAttributes $a, StorageAttributes $b) { return strnatcasecmp($a->path(), $b->path()); }); /** * @var StorageAttributes $publicDirectoryAttributes * @var StorageAttributes $privateFileAttributes * @var StorageAttributes $privateDirectoryAttributes * @var StorageAttributes $publicFileAttributes */ [$privateDirectoryAttributes, $publicFileAttributes, $publicDirectoryAttributes, $privateFileAttributes] = $listing; $this->assertEquals('public', $publicDirectoryAttributes->visibility()); $this->assertEquals('private', $privateFileAttributes->visibility()); $this->assertEquals('private', $privateDirectoryAttributes->visibility()); $this->assertEquals('public', $publicFileAttributes->visibility()); } /** * @test */ public function deleting_a_directory(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); mkdir(static::ROOT . '/directory/subdir/', 0744, true); $this->assertDirectoryExists(static::ROOT . '/directory/subdir/'); file_put_contents(static::ROOT . '/directory/subdir/file.txt', 'content'); symlink(static::ROOT . '/directory/subdir/file.txt', static::ROOT . '/directory/subdir/link.txt'); $adapter->deleteDirectory('directory/subdir'); $this->assertDirectoryDoesNotExist(static::ROOT . '/directory/subdir/'); $adapter->deleteDirectory('directory'); $this->assertDirectoryDoesNotExist(static::ROOT . '/directory/'); } /** * @test */ public function deleting_directories_with_other_directories_in_it(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('a/b/c/d/e.txt', 'contents', new Config()); $adapter->deleteDirectory('a/b'); $this->assertDirectoryExists(static::ROOT . '/a'); $this->assertDirectoryDoesNotExist(static::ROOT . '/a/b'); } /** * @test */ public function deleting_a_non_existing_directory(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->deleteDirectory('/non-existing-directory/'); $this->assertTrue(true); } /** * @test */ public function not_being_able_to_delete_a_directory(): void { $this->expectException(UnableToDeleteDirectory::class); mock_function('rmdir', false); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->createDirectory('/etc/', new Config()); $adapter->deleteDirectory('/etc/'); } /** * @test */ public function not_being_able_to_delete_a_sub_directory(): void { $this->expectException(UnableToDeleteDirectory::class); mock_function('rmdir', false); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->createDirectory('/etc/subdirectory/', new Config()); $adapter->deleteDirectory('/etc/'); } /** * @test */ public function creating_a_directory(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->createDirectory('public', new Config(['visibility' => 'public'])); $this->assertDirectoryExists(static::ROOT . '/public'); $this->assertFileHasPermissions(static::ROOT . '/public', 0755); $adapter->createDirectory('private', new Config(['visibility' => 'private'])); $this->assertDirectoryExists(static::ROOT . '/private'); $this->assertFileHasPermissions(static::ROOT . '/private', 0700); $adapter->createDirectory('also_private', new Config(['directory_visibility' => 'private'])); $this->assertDirectoryExists(static::ROOT . '/also_private'); $this->assertFileHasPermissions(static::ROOT . '/also_private', 0700); } /** * @test */ public function not_being_able_to_create_a_directory(): void { $this->expectException(UnableToCreateDirectory::class); $adapter = new LocalFilesystemAdapter('/'); $adapter->createDirectory('/something/', new Config()); } /** * @test */ public function creating_a_directory_is_idempotent(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->createDirectory('/something/', new Config(['visibility' => 'private'])); $this->assertFileHasPermissions(static::ROOT . '/something', 0700); $adapter->createDirectory('/something/', new Config(['visibility' => 'public'])); $this->assertFileHasPermissions(static::ROOT . '/something', 0755); } /** * @test */ public function retrieving_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('public.txt', 'contents', new Config(['visibility' => 'public'])); $this->assertEquals('public', $adapter->visibility('public.txt')->visibility()); $adapter->write('private.txt', 'contents', new Config(['visibility' => 'private'])); $this->assertEquals('private', $adapter->visibility('private.txt')->visibility()); } /** * @test */ public function not_being_able_to_retrieve_visibility(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->visibility('something.txt'); } /** * @test */ public function moving_a_file(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('first.txt', 'contents', new Config()); $this->assertFileExists(static::ROOT . '/first.txt'); $adapter->move('first.txt', 'second.txt', new Config()); $this->assertFileExists(static::ROOT . '/second.txt'); $this->assertFileDoesNotExist(static::ROOT . '/first.txt'); } /** * @test */ public function moving_a_file_with_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, new PortableVisibilityConverter()); $adapter->write('first.txt', 'contents', new Config()); $this->assertFileExists(static::ROOT . '/first.txt'); $this->assertFileHasPermissions(static::ROOT . '/first.txt', 0644); $adapter->move('first.txt', 'second.txt', new Config(['visibility' => 'private'])); $this->assertFileExists(static::ROOT . '/second.txt'); $this->assertFileHasPermissions(static::ROOT . '/second.txt', 0600); } /** * @test */ public function not_being_able_to_move_a_file(): void { $this->expectException(UnableToMoveFile::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->move('first.txt', 'second.txt', new Config()); } /** * @test */ public function copying_a_file(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('first.txt', 'contents', new Config()); $adapter->copy('first.txt', 'second.txt', new Config()); $this->assertFileExists(static::ROOT . '/second.txt'); $this->assertFileExists(static::ROOT . '/first.txt'); } /** * @test */ public function copying_a_file_with_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, new PortableVisibilityConverter()); $adapter->write('first.txt', 'contents', new Config()); $adapter->copy('first.txt', 'second.txt', new Config(['visibility' => 'private'])); $this->assertFileExists(static::ROOT . '/first.txt'); $this->assertFileHasPermissions(static::ROOT . '/first.txt', 0644); $this->assertFileExists(static::ROOT . '/second.txt'); $this->assertFileHasPermissions(static::ROOT . '/second.txt', 0600); } /** * @test */ public function copying_a_file_retaining_visibility(): void { $adapter = new LocalFilesystemAdapter(static::ROOT, new PortableVisibilityConverter()); $adapter->write('first.txt', 'contents', new Config(['visibility' => 'private'])); $adapter->copy('first.txt', 'retain.txt', new Config()); $adapter->copy('first.txt', 'do-not-retain.txt', new Config(['retain_visibility' => false])); $this->assertFileExists(static::ROOT . '/first.txt'); $this->assertFileHasPermissions(static::ROOT . '/first.txt', 0600); $this->assertFileExists(static::ROOT . '/retain.txt'); $this->assertFileHasPermissions(static::ROOT . '/retain.txt', 0600); $this->assertFileExists(static::ROOT . '/do-not-retain.txt'); $this->assertFileHasPermissions(static::ROOT . '/do-not-retain.txt', 0644); } /** * @test */ public function not_being_able_to_copy_a_file(): void { $this->expectException(UnableToCopyFile::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->copy('first.txt', 'second.txt', new Config()); } /** * @test */ public function getting_mimetype(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write( 'flysystem.svg', (string) file_get_contents(__DIR__ . '/../AdapterTestUtilities/test_files/flysystem.svg'), new Config() ); $this->assertStringStartsWith('image/svg+xml', $adapter->mimeType('flysystem.svg')->mimeType()); } /** * @test */ public function failing_to_get_the_mimetype(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write( 'file.unknown', '', new Config() ); $this->expectException(UnableToRetrieveMetadata::class); $adapter->mimeType('file.unknown'); } /** * @test */ public function allowing_inconclusive_mime_type(): void { $adapter = new LocalFilesystemAdapter( location: static::ROOT, useInconclusiveMimeTypeFallback: true, ); $adapter->write( 'file.unknown', '', new Config() ); $this->assertEquals('application/x-empty', $adapter->mimeType('file.unknown')->mimeType()); } /** * @test */ public function fetching_unknown_mime_type_of_a_file(): void { $this->useAdapter(new LocalFilesystemAdapter(self::ROOT, null, LOCK_EX, LocalFilesystemAdapter::DISALLOW_LINKS, new ExtensionMimeTypeDetector(new EmptyExtensionToMimeTypeMap()))); parent::fetching_unknown_mime_type_of_a_file(); } /** * @test */ public function not_being_able_to_get_mimetype(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = new LocalFilesystemAdapter( location: static::ROOT, mimeTypeDetector: new FinfoMimeTypeDetector(), ); $adapter->mimeType('flysystem.svg'); } /** * @test */ public function getting_last_modified(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('first.txt', 'contents', new Config()); mock_function('filemtime', $now = time()); $lastModified = $adapter->lastModified('first.txt')->lastModified(); $this->assertEquals($now, $lastModified); } /** * @test */ public function not_being_able_to_get_last_modified(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->lastModified('first.txt'); } /** * @test */ public function getting_file_size(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('first.txt', 'contents', new Config()); $fileSize = $adapter->fileSize('first.txt'); $this->assertEquals(8, $fileSize->fileSize()); } /** * @test */ public function not_being_able_to_get_file_size(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->fileSize('first.txt'); } /** * @test */ public function reading_a_file(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('path.txt', 'contents', new Config()); $contents = $adapter->read('path.txt'); $this->assertEquals('contents', $contents); } /** * @test */ public function not_being_able_to_read_a_file(): void { $this->expectException(UnableToReadFile::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->read('path.txt'); } /** * @test */ public function reading_a_stream(): void { $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->write('path.txt', 'contents', new Config()); $contents = $adapter->readStream('path.txt'); $this->assertIsResource($contents); $fileContents = stream_get_contents($contents); fclose($contents); $this->assertEquals('contents', $fileContents); } /** * @test */ public function not_being_able_to_stream_read_a_file(): void { $this->expectException(UnableToReadFile::class); $adapter = new LocalFilesystemAdapter(static::ROOT); $adapter->readStream('path.txt'); } /* ////////////////////// // These are the utils // ////////////////////// */ /** * @param string $file * @param int $expectedPermissions */ private function assertFileHasPermissions(string $file, int $expectedPermissions): void { clearstatcache(false, $file); $permissions = fileperms($file) & 0777; $this->assertEquals($expectedPermissions, $permissions); } /** * @param string $file * @param string $expectedContents */ private function assertFileContains(string $file, string $expectedContents): void { $this->assertFileExists($file); $contents = file_get_contents($file); $this->assertEquals($expectedContents, $contents); } protected static function createFilesystemAdapter(): FilesystemAdapter { return new LocalFilesystemAdapter(static::ROOT); } /** * @test */ public function get_checksum_with_specified_algo(): void { /** @var LocalFilesystemAdapter $adapter */ $adapter = $this->adapter(); $adapter->write('path.txt', 'foobar', new Config()); $checksum = $adapter->checksum('path.txt', new Config(['checksum_algo' => 'crc32c'])); $this->assertSame('0d5f5c7f', $checksum); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Local/FallbackMimeTypeDetector.php
src/Local/FallbackMimeTypeDetector.php
<?php declare(strict_types=1); namespace League\Flysystem\Local; use League\MimeTypeDetection\MimeTypeDetector; use function in_array; class FallbackMimeTypeDetector implements MimeTypeDetector { private const INCONCLUSIVE_MIME_TYPES = [ 'application/x-empty', 'text/plain', 'text/x-asm', 'application/octet-stream', 'inode/x-empty', ]; public function __construct( private MimeTypeDetector $detector, private array $inconclusiveMimetypes = self::INCONCLUSIVE_MIME_TYPES, private bool $useInconclusiveMimeTypeFallback = false, ) { } public function detectMimeType(string $path, $contents): ?string { return $this->detector->detectMimeType($path, $contents); } public function detectMimeTypeFromBuffer(string $contents): ?string { return $this->detector->detectMimeTypeFromBuffer($contents); } public function detectMimeTypeFromPath(string $path): ?string { return $this->detector->detectMimeTypeFromPath($path); } public function detectMimeTypeFromFile(string $path): ?string { $mimeType = $this->detector->detectMimeTypeFromFile($path); if ($mimeType !== null && ! in_array($mimeType, $this->inconclusiveMimetypes)) { return $mimeType; } return $this->detector->detectMimeTypeFromPath($path) ?? ($this->useInconclusiveMimeTypeFallback ? $mimeType : null); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Local/LocalFilesystemAdapter.php
src/Local/LocalFilesystemAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\Local; use const DIRECTORY_SEPARATOR; use const LOCK_EX; use DirectoryIterator; use FilesystemIterator; use Generator; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\SymbolicLinkEncountered; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToProvideChecksum; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UnixVisibility\PortableVisibilityConverter; use League\Flysystem\UnixVisibility\VisibilityConverter; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; use Throwable; use function chmod; use function clearstatcache; use function dirname; use function error_clear_last; use function error_get_last; use function file_exists; use function file_put_contents; use function hash_file; use function is_dir; use function is_file; use function mkdir; use function rename; class LocalFilesystemAdapter implements FilesystemAdapter, ChecksumProvider { /** * @var int */ public const SKIP_LINKS = 0001; /** * @var int */ public const DISALLOW_LINKS = 0002; private PathPrefixer $prefixer; private VisibilityConverter $visibility; private MimeTypeDetector $mimeTypeDetector; private string $rootLocation; /** * @var bool */ private $rootLocationIsSetup = false; public function __construct( string $location, ?VisibilityConverter $visibility = null, private int $writeFlags = LOCK_EX, private int $linkHandling = self::DISALLOW_LINKS, ?MimeTypeDetector $mimeTypeDetector = null, bool $lazyRootCreation = false, bool $useInconclusiveMimeTypeFallback = false, ) { $this->prefixer = new PathPrefixer($location, DIRECTORY_SEPARATOR); $visibility ??= new PortableVisibilityConverter(); $this->visibility = $visibility; $this->rootLocation = $location; $this->mimeTypeDetector = $mimeTypeDetector ?? new FallbackMimeTypeDetector( detector: new FinfoMimeTypeDetector(), useInconclusiveMimeTypeFallback: $useInconclusiveMimeTypeFallback, ); if ( ! $lazyRootCreation) { $this->ensureRootDirectoryExists(); } } private function ensureRootDirectoryExists(): void { if ($this->rootLocationIsSetup) { return; } $this->ensureDirectoryExists($this->rootLocation, $this->visibility->defaultForDirectories()); $this->rootLocationIsSetup = true; } public function write(string $path, string $contents, Config $config): void { $this->writeToFile($path, $contents, $config); } public function writeStream(string $path, $contents, Config $config): void { $this->writeToFile($path, $contents, $config); } /** * @param resource|string $contents */ private function writeToFile(string $path, $contents, Config $config): void { $prefixedLocation = $this->prefixer->prefixPath($path); $this->ensureRootDirectoryExists(); $this->ensureDirectoryExists( dirname($prefixedLocation), $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY)) ); error_clear_last(); if (@file_put_contents($prefixedLocation, $contents, $this->writeFlags) === false) { throw UnableToWriteFile::atLocation($path, error_get_last()['message'] ?? ''); } if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $this->setVisibility($path, (string) $visibility); } } public function delete(string $path): void { $location = $this->prefixer->prefixPath($path); if ( ! file_exists($location)) { return; } error_clear_last(); if ( ! @unlink($location)) { throw UnableToDeleteFile::atLocation($location, error_get_last()['message'] ?? ''); } } public function deleteDirectory(string $prefix): void { $location = $this->prefixer->prefixPath($prefix); if ( ! is_dir($location)) { return; } $contents = $this->listDirectoryRecursively($location, RecursiveIteratorIterator::CHILD_FIRST); /** @var SplFileInfo $file */ foreach ($contents as $file) { if ( ! $this->deleteFileInfoObject($file)) { throw UnableToDeleteDirectory::atLocation($prefix, "Unable to delete file at " . $file->getPathname()); } } unset($contents); if ( ! @rmdir($location)) { throw UnableToDeleteDirectory::atLocation($prefix, error_get_last()['message'] ?? ''); } } private function listDirectoryRecursively( string $path, int $mode = RecursiveIteratorIterator::SELF_FIRST ): Generator { if ( ! is_dir($path)) { return; } yield from new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), $mode ); } protected function deleteFileInfoObject(SplFileInfo $file): bool { switch ($file->getType()) { case 'dir': return @rmdir((string) $file->getRealPath()); case 'link': return @unlink((string) $file->getPathname()); default: return @unlink((string) $file->getRealPath()); } } public function listContents(string $path, bool $deep): iterable { $location = $this->prefixer->prefixPath($path); if ( ! is_dir($location)) { return; } /** @var SplFileInfo[] $iterator */ $iterator = $deep ? $this->listDirectoryRecursively($location) : $this->listDirectory($location); foreach ($iterator as $fileInfo) { $pathName = $fileInfo->getPathname(); try { if ($fileInfo->isLink()) { if ($this->linkHandling & self::SKIP_LINKS) { continue; } throw SymbolicLinkEncountered::atLocation($pathName); } $path = $this->prefixer->stripPrefix($pathName); $lastModified = $fileInfo->getMTime(); $isDirectory = $fileInfo->isDir(); $permissions = octdec(substr(sprintf('%o', $fileInfo->getPerms()), -4)); $visibility = $isDirectory ? $this->visibility->inverseForDirectory($permissions) : $this->visibility->inverseForFile($permissions); yield $isDirectory ? new DirectoryAttributes(str_replace('\\', '/', $path), $visibility, $lastModified) : new FileAttributes( str_replace('\\', '/', $path), $fileInfo->getSize(), $visibility, $lastModified ); } catch (Throwable $exception) { if (file_exists($pathName)) { throw $exception; } } } } public function move(string $source, string $destination, Config $config): void { $sourcePath = $this->prefixer->prefixPath($source); $destinationPath = $this->prefixer->prefixPath($destination); $this->ensureRootDirectoryExists(); $this->ensureDirectoryExists( dirname($destinationPath), $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY)) ); error_clear_last(); if ( ! @rename($sourcePath, $destinationPath)) { throw UnableToMoveFile::because(error_get_last()['message'] ?? 'unknown reason', $source, $destination); } if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $this->setVisibility($destination, (string) $visibility); } } public function copy(string $source, string $destination, Config $config): void { $sourcePath = $this->prefixer->prefixPath($source); $destinationPath = $this->prefixer->prefixPath($destination); $this->ensureRootDirectoryExists(); $this->ensureDirectoryExists( dirname($destinationPath), $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY)) ); error_clear_last(); if ($sourcePath !== $destinationPath && ! @copy($sourcePath, $destinationPath)) { throw UnableToCopyFile::because(error_get_last()['message'] ?? 'unknown', $source, $destination); } $visibility = $config->get( Config::OPTION_VISIBILITY, $config->get(Config::OPTION_RETAIN_VISIBILITY, true) ? $this->visibility($source)->visibility() : null, ); if ($visibility) { $this->setVisibility($destination, (string) $visibility); } } public function read(string $path): string { $location = $this->prefixer->prefixPath($path); error_clear_last(); $contents = @file_get_contents($location); if ($contents === false) { throw UnableToReadFile::fromLocation($path, error_get_last()['message'] ?? ''); } return $contents; } public function readStream(string $path) { $location = $this->prefixer->prefixPath($path); error_clear_last(); $contents = @fopen($location, 'rb'); if ($contents === false) { throw UnableToReadFile::fromLocation($path, error_get_last()['message'] ?? ''); } return $contents; } protected function ensureDirectoryExists(string $dirname, int $visibility): void { if (is_dir($dirname)) { return; } error_clear_last(); if ( ! @mkdir($dirname, $visibility, true)) { $mkdirError = error_get_last(); } clearstatcache(true, $dirname); if ( ! is_dir($dirname)) { $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : ''; throw UnableToCreateDirectory::atLocation($dirname, $errorMessage); } } public function fileExists(string $location): bool { $location = $this->prefixer->prefixPath($location); clearstatcache(); return is_file($location); } public function directoryExists(string $location): bool { $location = $this->prefixer->prefixPath($location); clearstatcache(); return is_dir($location); } public function createDirectory(string $path, Config $config): void { $this->ensureRootDirectoryExists(); $location = $this->prefixer->prefixPath($path); $visibility = $config->get(Config::OPTION_VISIBILITY, $config->get(Config::OPTION_DIRECTORY_VISIBILITY)); $permissions = $this->resolveDirectoryVisibility($visibility); if (is_dir($location)) { $this->setPermissions($location, $permissions); return; } error_clear_last(); if ( ! @mkdir($location, $permissions, true)) { throw UnableToCreateDirectory::atLocation($path, error_get_last()['message'] ?? ''); } } public function setVisibility(string $path, string $visibility): void { $path = $this->prefixer->prefixPath($path); $visibility = is_dir($path) ? $this->visibility->forDirectory($visibility) : $this->visibility->forFile( $visibility ); $this->setPermissions($path, $visibility); } public function visibility(string $path): FileAttributes { $location = $this->prefixer->prefixPath($path); clearstatcache(false, $location); error_clear_last(); $fileperms = @fileperms($location); if ($fileperms === false) { throw UnableToRetrieveMetadata::visibility($path, error_get_last()['message'] ?? ''); } $permissions = $fileperms & 0777; $visibility = $this->visibility->inverseForFile($permissions); return new FileAttributes($path, null, $visibility); } private function resolveDirectoryVisibility(?string $visibility): int { return $visibility === null ? $this->visibility->defaultForDirectories() : $this->visibility->forDirectory( $visibility ); } public function mimeType(string $path): FileAttributes { $location = $this->prefixer->prefixPath($path); error_clear_last(); if ( ! is_file($location)) { throw UnableToRetrieveMetadata::mimeType($location, 'No such file exists.'); } $mimeType = $this->mimeTypeDetector->detectMimeTypeFromFile($location); if ($mimeType === null) { throw UnableToRetrieveMetadata::mimeType($path, error_get_last()['message'] ?? ''); } return new FileAttributes($path, null, null, null, $mimeType); } public function lastModified(string $path): FileAttributes { $location = $this->prefixer->prefixPath($path); clearstatcache(); error_clear_last(); $lastModified = @filemtime($location); if ($lastModified === false) { throw UnableToRetrieveMetadata::lastModified($path, error_get_last()['message'] ?? ''); } return new FileAttributes($path, null, null, $lastModified); } public function fileSize(string $path): FileAttributes { $location = $this->prefixer->prefixPath($path); clearstatcache(); error_clear_last(); if (is_file($location) && ($fileSize = @filesize($location)) !== false) { return new FileAttributes($path, $fileSize); } throw UnableToRetrieveMetadata::fileSize($path, error_get_last()['message'] ?? ''); } public function checksum(string $path, Config $config): string { $algo = $config->get('checksum_algo', 'md5'); $location = $this->prefixer->prefixPath($path); error_clear_last(); $checksum = @hash_file($algo, $location); if ($checksum === false) { throw new UnableToProvideChecksum(error_get_last()['message'] ?? '', $path); } return $checksum; } private function listDirectory(string $location): Generator { $iterator = new DirectoryIterator($location); foreach ($iterator as $item) { if ($item->isDot()) { continue; } yield $item; } } private function setPermissions(string $location, int $visibility): void { error_clear_last(); if ( ! @chmod($location, $visibility)) { $extraMessage = error_get_last()['message'] ?? ''; throw UnableToSetVisibility::atLocation($this->prefixer->stripPrefix($location), $extraMessage); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AdapterTestUtilities/RetryOnTestException.php
src/AdapterTestUtilities/RetryOnTestException.php
<?php declare(strict_types=1); namespace League\Flysystem\AdapterTestUtilities; use const PHP_EOL; use const STDOUT; use League\Flysystem\FilesystemException; use Throwable; /** * @codeCoverageIgnore */ trait RetryOnTestException { /** * @var string */ protected $exceptionTypeToRetryOn; /** * @var int */ protected $timeoutForExceptionRetry = 2; protected function retryOnException(string $className, int $timout = 2): void { $this->exceptionTypeToRetryOn = $className; $this->timeoutForExceptionRetry = $timout; } protected function retryScenarioOnException(string $className, callable $scenario, int $timeout = 2): void { $this->retryOnException($className, $timeout); $this->runScenario($scenario); } protected function dontRetryOnException(): void { $this->exceptionTypeToRetryOn = null; } /** * @internal * * @throws Throwable */ protected function runSetup(callable $scenario): void { $previousException = $this->exceptionTypeToRetryOn; $previousTimeout = $this->timeoutForExceptionRetry; $this->retryOnException(FilesystemException::class); try { $this->runScenario($scenario); } finally { $this->exceptionTypeToRetryOn = $previousException; $this->timeoutForExceptionRetry = $previousTimeout; } } protected function runScenario(callable $scenario): void { if ($this->exceptionTypeToRetryOn === null) { $scenario(); return; } $firstTryAt = \time(); $lastTryAt = $firstTryAt + 60; while (time() <= $lastTryAt) { try { $scenario(); return; } catch (Throwable $exception) { if ( ! $exception instanceof $this->exceptionTypeToRetryOn) { throw $exception; } fwrite(STDOUT, 'Retrying ...' . PHP_EOL); sleep($this->timeoutForExceptionRetry); } } $this->exceptionTypeToRetryOn = null; if (isset($exception) && $exception instanceof Throwable) { throw $exception; } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AdapterTestUtilities/ExceptionThrowingFilesystemAdapter.php
src/AdapterTestUtilities/ExceptionThrowingFilesystemAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\AdapterTestUtilities; use League\Flysystem\Config; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\FilesystemOperationFailed; class ExceptionThrowingFilesystemAdapter implements FilesystemAdapter { /** * @var FilesystemAdapter */ private $adapter; /** * @var array<string, FilesystemOperationFailed> */ private $stagedExceptions = []; public function __construct(FilesystemAdapter $adapter) { $this->adapter = $adapter; } public function stageException(string $method, string $path, FilesystemOperationFailed $exception): void { $this->stagedExceptions[join('@', [$method, $path])] = $exception; } private function throwStagedException(string $method, $path): void { $method = preg_replace('~.+::~', '', $method); $key = join('@', [$method, $path]); if ( ! array_key_exists($key, $this->stagedExceptions)) { return; } $exception = $this->stagedExceptions[$key]; unset($this->stagedExceptions[$key]); throw $exception; } public function fileExists(string $path): bool { $this->throwStagedException(__METHOD__, $path); return $this->adapter->fileExists($path); } public function write(string $path, string $contents, Config $config): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->write($path, $contents, $config); } public function writeStream(string $path, $contents, Config $config): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->writeStream($path, $contents, $config); } public function read(string $path): string { $this->throwStagedException(__METHOD__, $path); return $this->adapter->read($path); } public function readStream(string $path) { $this->throwStagedException(__METHOD__, $path); return $this->adapter->readStream($path); } public function delete(string $path): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->delete($path); } public function deleteDirectory(string $path): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->deleteDirectory($path); } public function createDirectory(string $path, Config $config): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->createDirectory($path, $config); } public function setVisibility(string $path, string $visibility): void { $this->throwStagedException(__METHOD__, $path); $this->adapter->setVisibility($path, $visibility); } public function visibility(string $path): FileAttributes { $this->throwStagedException(__METHOD__, $path); return $this->adapter->visibility($path); } public function mimeType(string $path): FileAttributes { $this->throwStagedException(__METHOD__, $path); return $this->adapter->mimeType($path); } public function lastModified(string $path): FileAttributes { $this->throwStagedException(__METHOD__, $path); return $this->adapter->lastModified($path); } public function fileSize(string $path): FileAttributes { $this->throwStagedException(__METHOD__, $path); return $this->adapter->fileSize($path); } public function listContents(string $path, bool $deep): iterable { $this->throwStagedException(__METHOD__, $path); return $this->adapter->listContents($path, $deep); } public function move(string $source, string $destination, Config $config): void { $this->throwStagedException(__METHOD__, $source); $this->adapter->move($source, $destination, $config); } public function copy(string $source, string $destination, Config $config): void { $this->throwStagedException(__METHOD__, $source); $this->adapter->copy($source, $destination, $config); } public function directoryExists(string $path): bool { $this->throwStagedException(__METHOD__, $path); return $this->adapter->directoryExists($path); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AdapterTestUtilities/FilesystemAdapterTestCase.php
src/AdapterTestUtilities/FilesystemAdapterTestCase.php
<?php declare(strict_types=1); namespace League\Flysystem\AdapterTestUtilities; use const PHP_EOL; use DateInterval; use DateTimeImmutable; use Generator; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToProvideChecksum; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use League\Flysystem\UrlGeneration\TemporaryUrlGenerator; use League\Flysystem\Visibility; use PHPUnit\Framework\TestCase; use Throwable; use function file_get_contents; use function is_resource; use function iterator_to_array; /** * @codeCoverageIgnore */ abstract class FilesystemAdapterTestCase extends TestCase { use RetryOnTestException; /** * @var FilesystemAdapter */ protected static $adapter; /** * @var bool */ protected $isUsingCustomAdapter = false; public static function clearFilesystemAdapterCache(): void { static::$adapter = null; } abstract protected static function createFilesystemAdapter(): FilesystemAdapter; public function adapter(): FilesystemAdapter { if ( ! static::$adapter instanceof FilesystemAdapter) { static::$adapter = static::createFilesystemAdapter(); } return static::$adapter; } public static function tearDownAfterClass(): void { self::clearFilesystemAdapterCache(); } protected function setUp(): void { parent::setUp(); $this->adapter(); } protected function useAdapter(FilesystemAdapter $adapter): FilesystemAdapter { static::$adapter = $adapter; $this->isUsingCustomAdapter = true; return $adapter; } /** * @after */ public function cleanupAdapter(): void { $this->clearCustomAdapter(); $this->clearStorage(); } public function clearStorage(): void { reset_function_mocks(); try { $adapter = $this->adapter(); } catch (Throwable $exception) { /* * Setting up the filesystem adapter failed. This is OK at this stage. * The exception will have been shown to the user when trying to run * a test. We expect an exception to be thrown when tests are marked as * skipped when a filesystem adapter cannot be constructed. */ return; } $this->runSetup(function () use ($adapter) { /** @var StorageAttributes $item */ foreach ($adapter->listContents('', false) as $item) { if ($item->isDir()) { $adapter->deleteDirectory($item->path()); } else { $adapter->delete($item->path()); } } }); } public function clearCustomAdapter(): void { if ($this->isUsingCustomAdapter) { $this->isUsingCustomAdapter = false; self::clearFilesystemAdapterCache(); } } /** * @test */ public function writing_and_reading_with_string(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'contents', new Config()); $fileExists = $adapter->fileExists('path.txt'); $contents = $adapter->read('path.txt'); $this->assertTrue($fileExists); $this->assertEquals('contents', $contents); }); } /** * @test */ public function writing_a_file_with_a_stream(): void { $this->runScenario(function () { $adapter = $this->adapter(); $writeStream = stream_with_contents('contents'); $adapter->writeStream('path.txt', $writeStream, new Config([ Config::OPTION_VISIBILITY => Visibility::PUBLIC, ])); if (is_resource($writeStream)) { fclose($writeStream); } $fileExists = $adapter->fileExists('path.txt'); $this->assertTrue($fileExists); }); } /** * @test * * @dataProvider filenameProvider */ public function writing_and_reading_files_with_special_path(string $path): void { $this->runScenario(function () use ($path) { $adapter = $this->adapter(); $adapter->write($path, 'contents', new Config()); $contents = $adapter->read($path); $this->assertEquals('contents', $contents); }); } public static function filenameProvider(): Generator { yield "a path with square brackets in filename 1" => ["some/file[name].txt"]; yield "a path with square brackets in filename 2" => ["some/file[0].txt"]; yield "a path with square brackets in filename 3" => ["some/file[10].txt"]; yield "a path with square brackets in dirname 1" => ["some[name]/file.txt"]; yield "a path with square brackets in dirname 2" => ["some[0]/file.txt"]; yield "a path with square brackets in dirname 3" => ["some[10]/file.txt"]; yield "a path with curly brackets in filename 1" => ["some/file{name}.txt"]; yield "a path with curly brackets in filename 2" => ["some/file{0}.txt"]; yield "a path with curly brackets in filename 3" => ["some/file{10}.txt"]; yield "a path with curly brackets in dirname 1" => ["some{name}/filename.txt"]; yield "a path with curly brackets in dirname 2" => ["some{0}/filename.txt"]; yield "a path with curly brackets in dirname 3" => ["some{10}/filename.txt"]; yield "a path with space in dirname" => ["some dir/filename.txt"]; yield "a path with space in filename" => ["somedir/file name.txt"]; } /** * @test */ public function writing_a_file_with_an_empty_stream(): void { $this->runScenario(function () { $adapter = $this->adapter(); $writeStream = stream_with_contents(''); $adapter->writeStream('path.txt', $writeStream, new Config()); if (is_resource($writeStream)) { fclose($writeStream); } $fileExists = $adapter->fileExists('path.txt'); $this->assertTrue($fileExists); $contents = $adapter->read('path.txt'); $this->assertEquals('', $contents); }); } /** * @test */ public function listing_a_directory_named_0(): void { $this->givenWeHaveAnExistingFile('0/path.txt'); $this->givenWeHaveAnExistingFile('1/path.txt'); $this->runScenario(function () { $listing = iterator_to_array($this->adapter()->listContents('0', false)); $this->assertCount(1, $listing); }); } /** * @test */ public function reading_a_file(): void { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $this->runScenario(function () { $contents = $this->adapter()->read('path.txt'); $this->assertEquals('contents', $contents); }); } /** * @test */ public function reading_a_file_with_a_stream(): void { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $this->runScenario(function () { $readStream = $this->adapter()->readStream('path.txt'); $contents = stream_get_contents($readStream); $this->assertIsResource($readStream); $this->assertEquals('contents', $contents); fclose($readStream); }); } /** * @test */ public function overwriting_a_file(): void { $this->runScenario(function () { $this->givenWeHaveAnExistingFile('path.txt', 'contents', ['visibility' => Visibility::PUBLIC]); $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config(['visibility' => Visibility::PRIVATE])); $contents = $adapter->read('path.txt'); $this->assertEquals('new contents', $contents); $visibility = $adapter->visibility('path.txt')->visibility(); $this->assertEquals(Visibility::PRIVATE, $visibility); }); } /** * @test */ public function a_file_exists_only_when_it_is_written_and_not_deleted(): void { $this->runScenario(function () { $adapter = $this->adapter(); // does not exist before creation self::assertFalse($adapter->fileExists('path.txt')); // a file exists after creation $this->givenWeHaveAnExistingFile('path.txt'); self::assertTrue($adapter->fileExists('path.txt')); // a file no longer exists after creation $adapter->delete('path.txt'); self::assertFalse($adapter->fileExists('path.txt')); }); } /** * @test */ public function listing_contents_shallow(): void { $this->runScenario(function () { $this->givenWeHaveAnExistingFile('some/0-path.txt', 'contents'); $this->givenWeHaveAnExistingFile('some/1-nested/path.txt', 'contents'); $listing = $this->adapter()->listContents('some', false); /** @var StorageAttributes[] $items */ $items = iterator_to_array($listing); $this->assertInstanceOf(Generator::class, $listing); $this->assertContainsOnlyInstancesOf(StorageAttributes::class, $items); $this->assertCount(2, $items, $this->formatIncorrectListingCount($items)); // Order of entries is not guaranteed [$fileIndex, $directoryIndex] = $items[0]->isFile() ? [0, 1] : [1, 0]; $this->assertEquals('some/0-path.txt', $items[$fileIndex]->path()); $this->assertEquals('some/1-nested', $items[$directoryIndex]->path()); $this->assertTrue($items[$fileIndex]->isFile()); $this->assertTrue($items[$directoryIndex]->isDir()); }); } /** * @test */ public function checking_if_a_non_existing_directory_exists(): void { $this->runScenario(function () { $adapter = $this->adapter(); self::assertFalse($adapter->directoryExists('this-does-not-exist.php')); }); } /** * @test */ public function checking_if_a_directory_exists_after_writing_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $this->givenWeHaveAnExistingFile('existing-directory/file.txt'); self::assertTrue($adapter->directoryExists('existing-directory')); }); } /** * @test */ public function checking_if_a_directory_exists_after_creating_it(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->createDirectory('explicitly-created-directory', new Config()); self::assertTrue($adapter->directoryExists('explicitly-created-directory')); $adapter->deleteDirectory('explicitly-created-directory'); $l = iterator_to_array($adapter->listContents('/', false), false); self::assertEquals([], $l); self::assertFalse($adapter->directoryExists('explicitly-created-directory')); }); } /** * @test */ public function listing_contents_recursive(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->createDirectory('path', new Config()); $adapter->write('path/file.txt', 'string', new Config()); $listing = $adapter->listContents('', true); /** @var StorageAttributes[] $items */ $items = iterator_to_array($listing); $this->assertCount(2, $items, $this->formatIncorrectListingCount($items)); }); } protected function formatIncorrectListingCount(array $items): string { $message = "Incorrect number of items returned.\nThe listing contains:\n\n"; /** @var StorageAttributes $item */ foreach ($items as $item) { $message .= "- {$item->path()}\n"; } return $message . PHP_EOL; } protected function givenWeHaveAnExistingFile(string $path, string $contents = 'contents', array $config = []): void { $this->runSetup(function () use ($path, $contents, $config) { $this->adapter()->write($path, $contents, new Config($config)); }); } /** * @test */ public function fetching_file_size(): void { $adapter = $this->adapter(); $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $this->runScenario(function () use ($adapter) { $attributes = $adapter->fileSize('path.txt'); $this->assertInstanceOf(FileAttributes::class, $attributes); $this->assertEquals(8, $attributes->fileSize()); }); } /** * @test */ public function setting_visibility(): void { $this->runScenario(function () { $adapter = $this->adapter(); $this->givenWeHaveAnExistingFile('path.txt', 'contents', [Config::OPTION_VISIBILITY => Visibility::PUBLIC]); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('path.txt')->visibility()); $adapter->setVisibility('path.txt', Visibility::PRIVATE); $this->assertEquals(Visibility::PRIVATE, $adapter->visibility('path.txt')->visibility()); $adapter->setVisibility('path.txt', Visibility::PUBLIC); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('path.txt')->visibility()); }); } /** * @test */ public function fetching_file_size_of_a_directory(): void { $this->expectException(UnableToRetrieveMetadata::class); $adapter = $this->adapter(); $this->runScenario(function () use ($adapter) { $adapter->createDirectory('path', new Config()); $adapter->fileSize('path/'); }); } /** * @test */ public function fetching_file_size_of_non_existing_file(): void { $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () { $this->adapter()->fileSize('non-existing-file.txt'); }); } /** * @test */ public function fetching_last_modified_of_non_existing_file(): void { $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () { $this->adapter()->lastModified('non-existing-file.txt'); }); } /** * @test */ public function fetching_visibility_of_non_existing_file(): void { $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () { $this->adapter()->visibility('non-existing-file.txt'); }); } /** * @test */ public function fetching_the_mime_type_of_an_svg_file(): void { $this->runScenario(function () { $this->givenWeHaveAnExistingFile('file.svg', file_get_contents(__DIR__ . '/test_files/flysystem.svg')); $mimetype = $this->adapter()->mimeType('file.svg')->mimeType(); $this->assertStringStartsWith('image/svg+xml', $mimetype); }); } /** * @test */ public function fetching_mime_type_of_non_existing_file(): void { $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () { $this->adapter()->mimeType('non-existing-file.txt'); }); } /** * @test */ public function fetching_unknown_mime_type_of_a_file(): void { $this->givenWeHaveAnExistingFile( 'unknown-mime-type.md5', file_get_contents(__DIR__ . '/test_files/unknown-mime-type.md5') ); $this->expectException(UnableToRetrieveMetadata::class); $this->runScenario(function () { $this->adapter()->mimeType('unknown-mime-type.md5'); }); } /** * @test */ public function listing_a_toplevel_directory(): void { $this->givenWeHaveAnExistingFile('path1.txt'); $this->givenWeHaveAnExistingFile('path2.txt'); $this->runScenario(function () { $contents = iterator_to_array($this->adapter()->listContents('', true)); $this->assertCount(2, $contents); }); } /** * @test */ public function writing_and_reading_with_streams(): void { $this->runScenario(function () { $writeStream = stream_with_contents('contents'); $adapter = $this->adapter(); $adapter->writeStream('path.txt', $writeStream, new Config()); if (is_resource($writeStream)) { fclose($writeStream); }; $readStream = $adapter->readStream('path.txt'); $this->assertIsResource($readStream); $contents = stream_get_contents($readStream); fclose($readStream); $this->assertEquals('contents', $contents); }); } /** * @test */ public function setting_visibility_on_a_file_that_does_not_exist(): void { $this->expectException(UnableToSetVisibility::class); $this->runScenario(function () { $this->adapter()->setVisibility('this-path-does-not-exists.txt', Visibility::PRIVATE); }); } /** * @test */ public function copying_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('text/plain', $adapter->mimeType('destination.txt')->mimeType()); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function copying_a_file_that_does_not_exist(): void { $this->expectException(UnableToCopyFile::class); $this->runScenario(function () { $this->adapter()->copy('source.txt', 'destination.txt', new Config()); }); } /** * @test */ public function copying_a_file_again(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function moving_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->move('source.txt', 'destination.txt', new Config()); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('text/plain', $adapter->mimeType('destination.txt')->mimeType()); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function file_exists_on_directory_is_false(): void { $this->runScenario(function () { $adapter = $this->adapter(); $this->assertFalse($adapter->directoryExists('test')); $adapter->createDirectory('test', new Config()); $this->assertTrue($adapter->directoryExists('test')); $this->assertFalse($adapter->fileExists('test')); }); } /** * @test */ public function directory_exists_on_file_is_false(): void { $this->runScenario(function () { $adapter = $this->adapter(); $this->assertFalse($adapter->fileExists('test.txt')); $adapter->write('test.txt', 'content', new Config()); $this->assertTrue($adapter->fileExists('test.txt')); $this->assertFalse($adapter->directoryExists('test.txt')); }); } /** * @test */ public function reading_a_file_that_does_not_exist(): void { $this->expectException(UnableToReadFile::class); $this->runScenario(function () { $this->adapter()->read('path.txt'); }); } /** * @test */ public function moving_a_file_that_does_not_exist(): void { $this->expectException(UnableToMoveFile::class); $this->runScenario(function () { $this->adapter()->move('source.txt', 'destination.txt', new Config()); }); } /** * @test */ public function trying_to_delete_a_non_existing_file(): void { $adapter = $this->adapter(); $adapter->delete('path.txt'); $fileExists = $adapter->fileExists('path.txt'); $this->assertFalse($fileExists); } /** * @test */ public function checking_if_files_exist(): void { $this->runScenario(function () { $adapter = $this->adapter(); $fileExistsBefore = $adapter->fileExists('some/path.txt'); $adapter->write('some/path.txt', 'contents', new Config()); $fileExistsAfter = $adapter->fileExists('some/path.txt'); $this->assertFalse($fileExistsBefore); $this->assertTrue($fileExistsAfter); }); } /** * @test */ public function fetching_last_modified(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'contents', new Config()); $attributes = $adapter->lastModified('path.txt'); $this->assertInstanceOf(FileAttributes::class, $attributes); $this->assertIsInt($attributes->lastModified()); $this->assertTrue($attributes->lastModified() > time() - 30); $this->assertTrue($attributes->lastModified() < time() + 30); }); } /** * @test */ public function failing_to_read_a_non_existing_file_into_a_stream(): void { $this->expectException(UnableToReadFile::class); $this->adapter()->readStream('something.txt'); } /** * @test */ public function failing_to_read_a_non_existing_file(): void { $this->expectException(UnableToReadFile::class); $this->adapter()->read('something.txt'); } /** * @test */ public function creating_a_directory(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->createDirectory('creating_a_directory/path', new Config()); // Creating a directory should be idempotent. $adapter->createDirectory('creating_a_directory/path', new Config()); $contents = iterator_to_array($adapter->listContents('creating_a_directory', false)); $this->assertCount(1, $contents, $this->formatIncorrectListingCount($contents)); /** @var DirectoryAttributes $directory */ $directory = $contents[0]; $this->assertInstanceOf(DirectoryAttributes::class, $directory); $this->assertEquals('creating_a_directory/path', $directory->path()); $adapter->deleteDirectory('creating_a_directory/path'); }); } /** * @test */ public function copying_a_file_with_collision(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $adapter->write('new-path.txt', 'contents', new Config()); $adapter->copy('path.txt', 'new-path.txt', new Config()); $contents = $adapter->read('new-path.txt'); $this->assertEquals('new contents', $contents); }); } /** * @test */ public function moving_a_file_with_collision(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $adapter->write('new-path.txt', 'contents', new Config()); $adapter->move('path.txt', 'new-path.txt', new Config()); $oldFileExists = $adapter->fileExists('path.txt'); $this->assertFalse($oldFileExists); $contents = $adapter->read('new-path.txt'); $this->assertEquals('new contents', $contents); }); } /** * @test */ public function copying_a_file_with_same_destination(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $adapter->copy('path.txt', 'path.txt', new Config()); $contents = $adapter->read('path.txt'); $this->assertEquals('new contents', $contents); }); } /** * @test */ public function moving_a_file_with_same_destination(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $adapter->move('path.txt', 'path.txt', new Config()); $contents = $adapter->read('path.txt'); $this->assertEquals('new contents', $contents); }); } protected function assertFileExistsAtPath(string $path): void { $this->runScenario(function () use ($path) { $fileExists = $this->adapter()->fileExists($path); $this->assertTrue($fileExists); }); } /** * @test */ public function generating_a_public_url(): void { $adapter = $this->adapter(); if ( ! $adapter instanceof PublicUrlGenerator) { $this->markTestSkipped('Adapter does not supply public URls'); } $adapter->write('some/path.txt', 'public contents', new Config(['visibility' => 'public'])); $url = $adapter->publicUrl('some/path.txt', new Config()); $contents = file_get_contents($url); self::assertEquals('public contents', $contents); } /** * @test */ public function generating_a_temporary_url(): void { $adapter = $this->adapter(); if ( ! $adapter instanceof TemporaryUrlGenerator) { $this->markTestSkipped('Adapter does not supply temporary URls'); } $adapter->write('some/private.txt', 'public contents', new Config(['visibility' => 'private'])); $expiresAt = (new DateTimeImmutable())->add(DateInterval::createFromDateString('1 minute')); $url = $adapter->temporaryUrl('some/private.txt', $expiresAt, new Config()); $contents = file_get_contents($url); self::assertEquals('public contents', $contents); } /** * @test */ public function get_checksum(): void { $adapter = $this->adapter(); if ( ! $adapter instanceof ChecksumProvider) { $this->markTestSkipped('Adapter does not supply providing checksums'); } $adapter->write('path.txt', 'foobar', new Config()); $this->assertSame('3858f62230ac3c915f300c664312c63f', $adapter->checksum('path.txt', new Config())); } /** * @test */ public function cannot_get_checksum_for_non_existent_file(): void { $adapter = $this->adapter(); if ( ! $adapter instanceof ChecksumProvider) { $this->markTestSkipped('Adapter does not supply providing checksums'); } $this->expectException(UnableToProvideChecksum::class); $adapter->checksum('path.txt', new Config()); } /** * @test */ public function cannot_get_checksum_for_directory(): void { $adapter = $this->adapter(); if ( ! $adapter instanceof ChecksumProvider) { $this->markTestSkipped('Adapter does not supply providing checksums'); } $adapter->createDirectory('dir', new Config()); $this->expectException(UnableToProvideChecksum::class); $adapter->checksum('dir', new Config()); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AdapterTestUtilities/test-functions.php
src/AdapterTestUtilities/test-functions.php
<?php declare(strict_types=1); function return_mocked_value(string $name) { return array_shift($_ENV['__FM:RETURNS:' . $name]); } function reset_function_mocks() { foreach (array_keys($_ENV) as $name) { if (is_string($name) && substr($name, 0, 5) === '__FM:') { unset($_ENV[$name]); } } } function mock_function(string $name, ...$returns) { $_ENV['__FM:FUNC_IS_MOCKED:' . $name] = 'yes'; $_ENV['__FM:RETURNS:' . $name] = $returns; } function is_mocked(string $name) { return ($_ENV['__FM:FUNC_IS_MOCKED:' . $name] ?? 'no') === 'yes'; } function stream_with_contents(string $contents) { $stream = fopen('php://temp', 'w+b'); fwrite($stream, $contents); rewind($stream); return $stream; } function delete_directory(string $dir): void { if ( ! is_dir($dir)) { return; } foreach ((array) scandir($dir) as $file) { if ('.' === $file || '..' === $file) { continue; } if (is_dir("$dir/$file")) { delete_directory("$dir/$file"); } else { unlink("$dir/$file"); } } rmdir($dir); }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AdapterTestUtilities/ToxiproxyManagement.php
src/AdapterTestUtilities/ToxiproxyManagement.php
<?php declare(strict_types=1); namespace League\Flysystem\AdapterTestUtilities; use GuzzleHttp\Client; /** * This class provides a client for the HTTP API provided by the proxy that simulates network issues. * * @see https://github.com/shopify/toxiproxy#http-api * * @phpstan-type RegisteredProxies 'ftp'|'sftp'|'ftpd' * @phpstan-type StreamDirection 'upstream'|'downstream' * @phpstan-type Type 'latency'|'bandwidth'|'slow_close'|'timeout'|'reset_peer'|'slicer'|'limit_data' * @phpstan-type Attributes array{latency?: int, jitter?: int, rate?: int, delay?: int} * @phpstan-type Toxic array{name?: string, type: Type, stream?: StreamDirection, toxicity?: float, attributes: Attributes} */ final class ToxiproxyManagement { /** @var Client */ private $apiClient; public function __construct(Client $apiClient) { $this->apiClient = $apiClient; } public static function forServer(string $apiUri = 'http://localhost:8474'): self { return new self( new Client( [ 'base_uri' => $apiUri, 'base_url' => $apiUri, // Compatibility with older versions of Guzzle ] ) ); } public function removeAllToxics(): void { $this->apiClient->post('/reset'); } /** * Simulates a peer reset on the client->server direction. * * @param RegisteredProxies $proxyName */ public function resetPeerOnRequest( string $proxyName, int $timeoutInMilliseconds ): void { $configuration = [ 'type' => 'reset_peer', 'stream' => 'upstream', 'attributes' => ['timeout' => $timeoutInMilliseconds], ]; $this->addToxic($proxyName, $configuration); } /** * Registers a network toxic for the given proxy. * * @param RegisteredProxies $proxyName * @param Toxic $configuration */ private function addToxic(string $proxyName, array $configuration): void { $this->apiClient->post('/proxies/' . $proxyName . '/toxics', ['json' => $configuration]); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/UnableToCreateParentDirectory.php
src/ZipArchive/UnableToCreateParentDirectory.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use RuntimeException; class UnableToCreateParentDirectory extends RuntimeException implements ZipArchiveException { public static function atLocation(string $location, string $reason = ''): UnableToCreateParentDirectory { return new UnableToCreateParentDirectory( rtrim("Unable to create the parent directory ($location): $reason", ' :') ); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/StubZipArchiveProvider.php
src/ZipArchive/StubZipArchiveProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use ZipArchive; class StubZipArchiveProvider implements ZipArchiveProvider { private FilesystemZipArchiveProvider $provider; /** * @var StubZipArchive */ private $archive; public function __construct(private string $filename, int $localDirectoryPermissions = 0700) { $this->provider = new FilesystemZipArchiveProvider($filename, $localDirectoryPermissions); } public function createZipArchive(): ZipArchive { if ( ! $this->archive instanceof StubZipArchive) { $zipArchive = $this->provider->createZipArchive(); $zipArchive->close(); unset($zipArchive); $this->archive = new StubZipArchive(); } $this->archive->open($this->filename, ZipArchive::CREATE); return $this->archive; } public function stubbedZipArchive(): StubZipArchive { $this->createZipArchive(); return $this->archive; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/FilesystemZipArchiveProvider.php
src/ZipArchive/FilesystemZipArchiveProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use ZipArchive; class FilesystemZipArchiveProvider implements ZipArchiveProvider { /** * @var bool */ private $parentDirectoryCreated = false; public function __construct(private string $filename, private int $localDirectoryPermissions = 0700) { } public function createZipArchive(): ZipArchive { if ($this->parentDirectoryCreated !== true) { $this->parentDirectoryCreated = true; $this->createParentDirectoryForZipArchive($this->filename); } return $this->openZipArchive(); } private function createParentDirectoryForZipArchive(string $fullPath): void { $dirname = dirname($fullPath); if (is_dir($dirname) || @mkdir($dirname, $this->localDirectoryPermissions, true)) { return; } if ( ! is_dir($dirname)) { throw UnableToCreateParentDirectory::atLocation($fullPath, error_get_last()['message'] ?? ''); } } private function openZipArchive(): ZipArchive { $archive = new ZipArchive(); $success = $archive->open($this->filename, ZipArchive::CREATE); if ($success !== true) { throw UnableToOpenZipArchive::atLocation($this->filename, $archive->getStatusString() ?: ''); } return $archive; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/PrefixedRootZipArchiveAdapterTest.php
src/ZipArchive/PrefixedRootZipArchiveAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; /** * @group zip */ final class PrefixedRootZipArchiveAdapterTest extends ZipArchiveAdapterTestCase { protected static function getRoot(): string { return '/prefixed-path'; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/ZipArchiveProvider.php
src/ZipArchive/ZipArchiveProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use ZipArchive; interface ZipArchiveProvider { public function createZipArchive(): ZipArchive; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/NoRootPrefixZipArchiveAdapterTest.php
src/ZipArchive/NoRootPrefixZipArchiveAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; /** * @group zip */ final class NoRootPrefixZipArchiveAdapterTest extends ZipArchiveAdapterTestCase { protected static function getRoot(): string { return '/'; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/StubZipArchive.php
src/ZipArchive/StubZipArchive.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use ZipArchive; class StubZipArchive extends ZipArchive { private bool $failNextDirectoryCreation = false; private bool $failNextWrite = false; private bool $failNextDeleteName = false; private bool $failWhenSettingVisibility = false; private bool $failWhenDeletingAnIndex = false; public function failNextDirectoryCreation(): void { $this->failNextDirectoryCreation = true; } /** * @param string $dirname * @param int $flags * * @return bool */ public function addEmptyDir($dirname, $flags = 0): bool { if ($this->failNextDirectoryCreation) { $this->failNextDirectoryCreation = false; return false; } return parent::addEmptyDir($dirname); } public function failNextWrite(): void { $this->failNextWrite = true; } /** * @param string $localname * @param string $contents * @param int $flags * * @return bool */ public function addFromString($localname, $contents, $flags = 0): bool { if ($this->failNextWrite) { $this->failNextWrite = false; return false; } return parent::addFromString($localname, $contents); } public function failNextDeleteName(): void { $this->failNextDeleteName = true; } /** * @return bool */ public function deleteName($name): bool { if ($this->failNextDeleteName) { $this->failNextDeleteName = false; return false; } return parent::deleteName($name); } public function failWhenSettingVisibility(): void { $this->failWhenSettingVisibility = true; } public function setExternalAttributesName($name, $opsys, $attr, $flags = null): bool { if ($this->failWhenSettingVisibility) { $this->failWhenSettingVisibility = false; return false; } return parent::setExternalAttributesName($name, $opsys, $attr); } public function failWhenDeletingAnIndex(): void { $this->failWhenDeletingAnIndex = true; } public function deleteIndex($index): bool { if ($this->failWhenDeletingAnIndex) { $this->failWhenDeletingAnIndex = false; return false; } return parent::deleteIndex($index); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/ZipArchiveAdapterTestCase.php
src/ZipArchive/ZipArchiveAdapterTestCase.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use Generator; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\Config; use League\Flysystem\FilesystemAdapter; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\Visibility; use function iterator_to_array; /** * @group zip */ abstract class ZipArchiveAdapterTestCase extends FilesystemAdapterTestCase { private const ARCHIVE = __DIR__ . '/test.zip'; /** * @var StubZipArchiveProvider */ private static $archiveProvider; protected function setUp(): void { static::$adapter = static::createFilesystemAdapter(); static::removeZipArchive(); parent::setUp(); } public static function tearDownAfterClass(): void { static::removeZipArchive(); } protected function tearDown(): void { static::removeZipArchive(); } protected static function createFilesystemAdapter(): FilesystemAdapter { static::$archiveProvider = new StubZipArchiveProvider(self::ARCHIVE); return new ZipArchiveAdapter(self::$archiveProvider, static::getRoot()); } abstract protected static function getRoot(): string; /** * @test */ public function not_being_able_to_create_the_parent_directory(): void { $this->expectException(UnableToCreateParentDirectory::class); (new ZipArchiveAdapter(new StubZipArchiveProvider('/no-way/this/will/work'))) ->write('haha', 'lol', new Config()); } /** * @test */ public function not_being_able_to_write_a_file_because_the_parent_directory_could_not_be_created(): void { self::$archiveProvider->stubbedZipArchive()->failNextDirectoryCreation(); $this->expectException(UnableToWriteFile::class); $this->adapter()->write('directoryName/is-here/filename.txt', 'contents', new Config()); } /** * @test * * @dataProvider scenariosThatCauseWritesToFail */ public function scenarios_that_cause_writing_a_file_to_fail(callable $scenario): void { $this->runScenario($scenario); $this->expectException(UnableToWriteFile::class); $this->runScenario(function () { $handle = stream_with_contents('contents'); $this->adapter()->writeStream('some/path.txt', $handle, new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC])); is_resource($handle) && @fclose($handle); }); } public static function scenariosThatCauseWritesToFail(): Generator { yield "writing a file fails when writing" => [function () { static::$archiveProvider->stubbedZipArchive()->failNextWrite(); }]; yield "writing a file fails when setting visibility" => [function () { static::$archiveProvider->stubbedZipArchive()->failWhenSettingVisibility(); }]; yield "writing a file fails to get the stream contents" => [function () { mock_function('stream_get_contents', false); }]; } /** * @test */ public function failing_to_delete_a_file(): void { $this->givenWeHaveAnExistingFile('path.txt'); static::$archiveProvider->stubbedZipArchive()->failNextDeleteName(); $this->expectException(UnableToDeleteFile::class); $this->adapter()->delete('path.txt'); } /** * @test */ public function deleting_a_directory(): void { $this->givenWeHaveAnExistingFile('a.txt'); $this->givenWeHaveAnExistingFile('one/a.txt'); $this->givenWeHaveAnExistingFile('one/b.txt'); $this->givenWeHaveAnExistingFile('two/a.txt'); $items = iterator_to_array($this->adapter()->listContents('', true)); $this->assertCount(6, $items); $this->adapter()->deleteDirectory('one'); $items = iterator_to_array($this->adapter()->listContents('', true)); $this->assertCount(3, $items); } /** * @test */ public function deleting_a_prefixed_directory(): void { $this->givenWeHaveAnExistingFile('a.txt'); $this->givenWeHaveAnExistingFile('/one/a.txt'); $this->givenWeHaveAnExistingFile('one/b.txt'); $this->givenWeHaveAnExistingFile('two/a.txt'); $items = iterator_to_array($this->adapter()->listContents('', true)); $this->assertCount(6, $items); $this->adapter()->deleteDirectory('one'); $items = iterator_to_array($this->adapter()->listContents('', true)); $this->assertCount(3, $items); } /** * @test */ public function list_root_directory(): void { $this->givenWeHaveAnExistingFile('a.txt'); $this->givenWeHaveAnExistingFile('one/a.txt'); $this->givenWeHaveAnExistingFile('one/b.txt'); $this->givenWeHaveAnExistingFile('two/a.txt'); $this->assertCount(6, iterator_to_array($this->adapter()->listContents('', true))); $this->assertCount(3, iterator_to_array($this->adapter()->listContents('', false))); } /** * @test */ public function failing_to_create_a_directory(): void { static::$archiveProvider->stubbedZipArchive()->failNextDirectoryCreation(); $this->expectException(UnableToCreateDirectory::class); $this->adapter()->createDirectory('somewhere', new Config); } /** * @test */ public function failing_to_create_a_directory_because_setting_visibility_fails(): void { static::$archiveProvider->stubbedZipArchive()->failWhenSettingVisibility(); $this->expectException(UnableToCreateDirectory::class); $this->adapter()->createDirectory('somewhere', new Config([Config::OPTION_DIRECTORY_VISIBILITY => Visibility::PRIVATE])); } /** * @test */ public function failing_to_delete_a_directory(): void { static::$archiveProvider->stubbedZipArchive()->failWhenDeletingAnIndex(); $this->givenWeHaveAnExistingFile('here/path.txt'); $this->expectException(UnableToDeleteDirectory::class); $this->adapter()->deleteDirectory('here'); } /** * @test */ public function setting_visibility_on_a_directory(): void { $adapter = $this->adapter(); $adapter->createDirectory('pri-dir', new Config([Config::OPTION_DIRECTORY_VISIBILITY => Visibility::PRIVATE])); $adapter->createDirectory('pub-dir', new Config([Config::OPTION_DIRECTORY_VISIBILITY => Visibility::PUBLIC])); $this->expectNotToPerformAssertions(); } /** * @test */ public function failing_to_move_a_file(): void { $this->givenWeHaveAnExistingFile('somewhere/here.txt'); static::$archiveProvider->stubbedZipArchive()->failNextDirectoryCreation(); $this->expectException(UnableToMoveFile::class); $this->adapter()->move('somewhere/here.txt', 'to-here/path.txt', new Config); } /** * @test */ public function failing_to_copy_a_file(): void { $this->givenWeHaveAnExistingFile('here.txt'); static::$archiveProvider->stubbedZipArchive()->failNextWrite(); $this->expectException(UnableToCopyFile::class); $this->adapter()->copy('here.txt', 'here.txt', new Config); } /** * @test */ public function failing_to_set_visibility_because_the_file_does_not_exist(): void { $this->expectException(UnableToSetVisibility::class); $this->adapter()->setVisibility('path.txt', Visibility::PUBLIC); } /** * @test */ public function deleting_a_directory_with_files_in_it(): void { $this->givenWeHaveAnExistingFile('nested/path-a.txt'); $this->givenWeHaveAnExistingFile('nested/path-b.txt'); $this->adapter()->deleteDirectory('nested'); $listing = iterator_to_array($this->adapter()->listContents('', true)); self::assertEquals([], $listing); } /** * @test */ public function failing_to_set_visibility_because_setting_it_fails(): void { $this->givenWeHaveAnExistingFile('path.txt'); static::$archiveProvider->stubbedZipArchive()->failWhenSettingVisibility(); $this->expectException(UnableToSetVisibility::class); $this->adapter()->setVisibility('path.txt', Visibility::PUBLIC); } /** * @test * * @fixme Move to FilesystemAdapterTestCase once all adapters pass */ public function moving_a_file_and_overwriting(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be moved', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->write( 'destination.txt', 'contents to be overwritten', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->move('source.txt', 'destination.txt', new Config()); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('contents to be moved', $adapter->read('destination.txt')); }); } protected static function removeZipArchive(): void { if ( ! file_exists(self::ARCHIVE)) { return; } unlink(self::ARCHIVE); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/UnableToOpenZipArchive.php
src/ZipArchive/UnableToOpenZipArchive.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use RuntimeException; final class UnableToOpenZipArchive extends RuntimeException implements ZipArchiveException { public static function atLocation(string $location, string $reason = ''): self { return new self(rtrim(sprintf( 'Unable to open file at location: %s. %s', $location, $reason ))); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/ZipArchiveAdapter.php
src/ZipArchive/ZipArchiveAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use Generator; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UnixVisibility\PortableVisibilityConverter; use League\Flysystem\UnixVisibility\VisibilityConverter; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use Throwable; use ZipArchive; use function fclose; use function fopen; use function rewind; use function stream_copy_to_stream; final class ZipArchiveAdapter implements FilesystemAdapter { private PathPrefixer $pathPrefixer; private MimeTypeDetector$mimeTypeDetector; private VisibilityConverter $visibility; public function __construct( private ZipArchiveProvider $zipArchiveProvider, string $root = '', ?MimeTypeDetector $mimeTypeDetector = null, ?VisibilityConverter $visibility = null, private bool $detectMimeTypeUsingPath = false, ) { $this->pathPrefixer = new PathPrefixer(ltrim($root, '/')); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); $this->visibility = $visibility ?? new PortableVisibilityConverter(); } public function fileExists(string $path): bool { $archive = $this->zipArchiveProvider->createZipArchive(); $fileExists = $archive->locateName($this->pathPrefixer->prefixPath($path)) !== false; $archive->close(); return $fileExists; } public function write(string $path, string $contents, Config $config): void { try { $this->ensureParentDirectoryExists($path, $config); } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, 'creating parent directory failed', $exception); } $archive = $this->zipArchiveProvider->createZipArchive(); $prefixedPath = $this->pathPrefixer->prefixPath($path); if ( ! $archive->addFromString($prefixedPath, $contents)) { throw UnableToWriteFile::atLocation($path, 'writing the file failed'); } $archive->close(); $archive = $this->zipArchiveProvider->createZipArchive(); $visibility = $config->get(Config::OPTION_VISIBILITY); $visibilityResult = $visibility === null || $this->setVisibilityAttribute($prefixedPath, $visibility, $archive); $archive->close(); if ($visibilityResult === false) { throw UnableToWriteFile::atLocation($path, 'setting visibility failed'); } } public function writeStream(string $path, $contents, Config $config): void { $contents = stream_get_contents($contents); if ($contents === false) { throw UnableToWriteFile::atLocation($path, 'Could not get contents of given resource.'); } $this->write($path, $contents, $config); } public function read(string $path): string { $archive = $this->zipArchiveProvider->createZipArchive(); $contents = $archive->getFromName($this->pathPrefixer->prefixPath($path)); $statusString = $archive->getStatusString(); $archive->close(); if ($contents === false) { throw UnableToReadFile::fromLocation($path, $statusString); } return $contents; } public function readStream(string $path) { $archive = $this->zipArchiveProvider->createZipArchive(); $resource = $archive->getStream($this->pathPrefixer->prefixPath($path)); if ($resource === false) { $status = $archive->getStatusString(); $archive->close(); throw UnableToReadFile::fromLocation($path, $status); } $stream = fopen('php://temp', 'w+b'); stream_copy_to_stream($resource, $stream); rewind($stream); fclose($resource); return $stream; } public function delete(string $path): void { $prefixedPath = $this->pathPrefixer->prefixPath($path); $zipArchive = $this->zipArchiveProvider->createZipArchive(); $success = $zipArchive->locateName($prefixedPath) === false || $zipArchive->deleteName($prefixedPath); $statusString = $zipArchive->getStatusString(); $zipArchive->close(); if ( ! $success) { throw UnableToDeleteFile::atLocation($path, $statusString); } } public function deleteDirectory(string $path): void { $archive = $this->zipArchiveProvider->createZipArchive(); $prefixedPath = $this->pathPrefixer->prefixDirectoryPath($path); for ($i = $archive->numFiles; $i > 0; $i--) { if (($stats = $archive->statIndex($i)) === false) { continue; } $itemPath = $stats['name']; if ( ! str_starts_with($itemPath, $prefixedPath)) { continue; } if ( ! $archive->deleteIndex($i)) { $statusString = $archive->getStatusString(); $archive->close(); throw UnableToDeleteDirectory::atLocation($path, $statusString); } } $archive->deleteName($prefixedPath); $archive->close(); } public function createDirectory(string $path, Config $config): void { try { $this->ensureDirectoryExists($path, $config); } catch (Throwable $exception) { throw UnableToCreateDirectory::dueToFailure($path, $exception); } } public function directoryExists(string $path): bool { $archive = $this->zipArchiveProvider->createZipArchive(); $location = $this->pathPrefixer->prefixDirectoryPath($path); return $archive->statName($location) !== false; } public function setVisibility(string $path, string $visibility): void { $archive = $this->zipArchiveProvider->createZipArchive(); $location = $this->pathPrefixer->prefixPath($path); $stats = $archive->statName($location) ?: $archive->statName($location . '/'); if ($stats === false) { $statusString = $archive->getStatusString(); $archive->close(); throw UnableToSetVisibility::atLocation($path, $statusString); } if ( ! $this->setVisibilityAttribute($stats['name'], $visibility, $archive)) { $statusString1 = $archive->getStatusString(); $archive->close(); throw UnableToSetVisibility::atLocation($path, $statusString1); } $archive->close(); } public function visibility(string $path): FileAttributes { $opsys = null; $attr = null; $archive = $this->zipArchiveProvider->createZipArchive(); $archive->getExternalAttributesName( $this->pathPrefixer->prefixPath($path), $opsys, $attr ); $archive->close(); if ($opsys !== ZipArchive::OPSYS_UNIX || $attr === null) { throw UnableToRetrieveMetadata::visibility($path); } return new FileAttributes( $path, null, $this->visibility->inverseForFile($attr >> 16) ); } public function mimeType(string $path): FileAttributes { try { $mimetype = $this->detectMimeTypeUsingPath ? $this->mimeTypeDetector->detectMimeTypeFromPath($path) : $this->mimeTypeDetector->detectMimeType($path, $this->read($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::mimeType($path, $exception->getMessage(), $exception); } if ($mimetype === null) { throw UnableToRetrieveMetadata::mimeType($path, 'Unknown.'); } return new FileAttributes($path, null, null, null, $mimetype); } public function lastModified(string $path): FileAttributes { $zipArchive = $this->zipArchiveProvider->createZipArchive(); $stats = $zipArchive->statName($this->pathPrefixer->prefixPath($path)); $statusString = $zipArchive->getStatusString(); $zipArchive->close(); if ($stats === false) { throw UnableToRetrieveMetadata::lastModified($path, $statusString); } return new FileAttributes($path, null, null, $stats['mtime']); } public function fileSize(string $path): FileAttributes { $archive = $this->zipArchiveProvider->createZipArchive(); $stats = $archive->statName($this->pathPrefixer->prefixPath($path)); $statusString = $archive->getStatusString(); $archive->close(); if ($stats === false) { throw UnableToRetrieveMetadata::fileSize($path, $statusString); } if ($this->isDirectoryPath($stats['name'])) { throw UnableToRetrieveMetadata::fileSize($path, 'It\'s a directory.'); } return new FileAttributes($path, $stats['size'], null, null); } public function listContents(string $path, bool $deep): iterable { $archive = $this->zipArchiveProvider->createZipArchive(); $location = $this->pathPrefixer->prefixDirectoryPath($path); $items = []; for ($i = 0; $i < $archive->numFiles; $i++) { $stats = $archive->statIndex($i); // @codeCoverageIgnoreStart if ($stats === false) { continue; } // @codeCoverageIgnoreEnd $itemPath = $stats['name']; if ( $location === $itemPath || ($deep && $location !== '' && ! str_starts_with($itemPath, $location)) || ($deep === false && ! $this->isAtRootDirectory($location, $itemPath)) ) { continue; } $items[] = $this->isDirectoryPath($itemPath) ? new DirectoryAttributes( $this->pathPrefixer->stripDirectoryPrefix($itemPath), null, $stats['mtime'] ) : new FileAttributes( $this->pathPrefixer->stripPrefix($itemPath), $stats['size'], null, $stats['mtime'] ); } $archive->close(); return $this->yieldItemsFrom($items); } private function yieldItemsFrom(array $items): Generator { yield from $items; } public function move(string $source, string $destination, Config $config): void { try { $this->ensureParentDirectoryExists($destination, $config); } catch (Throwable $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } $archive = $this->zipArchiveProvider->createZipArchive(); if ($archive->locateName($this->pathPrefixer->prefixPath($destination)) !== false) { if ($source === $destination) { //update the config of the file $this->copy($source, $destination, $config); return; } $this->delete($destination); $this->copy($source, $destination, $config); $this->delete($source); return; } $renamed = $archive->renameName( $this->pathPrefixer->prefixPath($source), $this->pathPrefixer->prefixPath($destination) ); if ($renamed === false) { throw UnableToMoveFile::fromLocationTo($source, $destination); } } public function copy(string $source, string $destination, Config $config): void { try { $readStream = $this->readStream($source); $this->writeStream($destination, $readStream, $config); } catch (Throwable $exception) { if (isset($readStream)) { @fclose($readStream); } throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } private function ensureParentDirectoryExists(string $path, Config $config): void { $dirname = dirname($path); if ($dirname === '' || $dirname === '.') { return; } $this->ensureDirectoryExists($dirname, $config); } private function ensureDirectoryExists(string $dirname, Config $config): void { $visibility = $config->get(Config::OPTION_DIRECTORY_VISIBILITY); $archive = $this->zipArchiveProvider->createZipArchive(); $prefixedDirname = $this->pathPrefixer->prefixDirectoryPath($dirname); $parts = array_filter(explode('/', trim($prefixedDirname, '/'))); $dirPath = ''; foreach ($parts as $part) { $dirPath .= $part . '/'; $info = $archive->statName($dirPath); if ($info === false && $archive->addEmptyDir($dirPath) === false) { throw UnableToCreateDirectory::atLocation($dirname); } if ($visibility === null) { continue; } if ( ! $this->setVisibilityAttribute($dirPath, $visibility, $archive)) { $archive->close(); throw UnableToCreateDirectory::atLocation($dirname, 'Unable to set visibility.'); } } $archive->close(); } private function isDirectoryPath(string $path): bool { return str_ends_with($path, '/'); } private function isAtRootDirectory(string $directoryRoot, string $path): bool { $dirname = dirname($path); if ('' === $directoryRoot && '.' === $dirname) { return true; } return $directoryRoot === (rtrim($dirname, '/') . '/'); } private function setVisibilityAttribute(string $statsName, string $visibility, ZipArchive $archive): bool { $visibility = $this->isDirectoryPath($statsName) ? $this->visibility->forDirectory($visibility) : $this->visibility->forFile($visibility); return $archive->setExternalAttributesName($statsName, ZipArchive::OPSYS_UNIX, $visibility << 16); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ZipArchive/ZipArchiveException.php
src/ZipArchive/ZipArchiveException.php
<?php declare(strict_types=1); namespace League\Flysystem\ZipArchive; use League\Flysystem\FilesystemException; interface ZipArchiveException extends FilesystemException { }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathPrefixing/PathPrefixedAdapter.php
src/PathPrefixing/PathPrefixedAdapter.php
<?php namespace League\Flysystem\PathPrefixing; use DateTimeInterface; use Generator; use League\Flysystem\CalculateChecksumFromStream; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\UnableToCheckDirectoryExistence; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToGeneratePublicUrl; use League\Flysystem\UnableToGenerateTemporaryUrl; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use League\Flysystem\UrlGeneration\TemporaryUrlGenerator; use Throwable; class PathPrefixedAdapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator { use CalculateChecksumFromStream; private PathPrefixer $prefix; public function __construct(private FilesystemAdapter $adapter, string $prefix) { if ($prefix === '') { throw new \InvalidArgumentException('The prefix must not be empty.'); } $this->prefix = new PathPrefixer($prefix); } public function read(string $location): string { try { return $this->adapter->read($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToReadFile::fromLocation($location, $previous->getMessage(), $previous); } } public function readStream(string $location) { try { return $this->adapter->readStream($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToReadFile::fromLocation($location, $previous->getMessage(), $previous); } } public function listContents(string $location, bool $deep): Generator { foreach ($this->adapter->listContents($this->prefix->prefixPath($location), $deep) as $attributes) { yield $attributes->withPath($this->prefix->stripPrefix($attributes->path())); } } public function fileExists(string $location): bool { try { return $this->adapter->fileExists($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToCheckFileExistence::forLocation($location, $previous); } } public function directoryExists(string $location): bool { try { return $this->adapter->directoryExists($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToCheckDirectoryExistence::forLocation($location, $previous); } } public function lastModified(string $path): FileAttributes { try { return $this->adapter->lastModified($this->prefix->prefixPath($path)); } catch (Throwable $previous) { throw UnableToRetrieveMetadata::lastModified($path, $previous->getMessage(), $previous); } } public function fileSize(string $path): FileAttributes { try { return $this->adapter->fileSize($this->prefix->prefixPath($path)); } catch (Throwable $previous) { throw UnableToRetrieveMetadata::fileSize($path, $previous->getMessage(), $previous); } } public function mimeType(string $path): FileAttributes { try { return $this->adapter->mimeType($this->prefix->prefixPath($path)); } catch (Throwable $previous) { throw UnableToRetrieveMetadata::mimeType($path, $previous->getMessage(), $previous); } } public function visibility(string $path): FileAttributes { try { return $this->adapter->visibility($this->prefix->prefixPath($path)); } catch (Throwable $previous) { throw UnableToRetrieveMetadata::visibility($path, $previous->getMessage(), $previous); } } public function write(string $location, string $contents, Config $config): void { try { $this->adapter->write($this->prefix->prefixPath($location), $contents, $config); } catch (Throwable $previous) { throw UnableToWriteFile::atLocation($location, $previous->getMessage(), $previous); } } public function writeStream(string $location, $contents, Config $config): void { try { $this->adapter->writeStream($this->prefix->prefixPath($location), $contents, $config); } catch (Throwable $previous) { throw UnableToWriteFile::atLocation($location, $previous->getMessage(), $previous); } } public function setVisibility(string $path, string $visibility): void { try { $this->adapter->setVisibility($this->prefix->prefixPath($path), $visibility); } catch (Throwable $previous) { throw UnableToSetVisibility::atLocation($path, $previous->getMessage(), $previous); } } public function delete(string $location): void { try { $this->adapter->delete($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToDeleteFile::atLocation($location, $previous->getMessage(), $previous); } } public function deleteDirectory(string $location): void { try { $this->adapter->deleteDirectory($this->prefix->prefixPath($location)); } catch (Throwable $previous) { throw UnableToDeleteDirectory::atLocation($location, $previous->getMessage(), $previous); } } public function createDirectory(string $location, Config $config): void { try { $this->adapter->createDirectory($this->prefix->prefixPath($location), $config); } catch (Throwable $previous) { throw UnableToCreateDirectory::atLocation($location, $previous->getMessage(), $previous); } } public function move(string $source, string $destination, Config $config): void { try { $this->adapter->move($this->prefix->prefixPath($source), $this->prefix->prefixPath($destination), $config); } catch (Throwable $previous) { throw UnableToMoveFile::fromLocationTo($source, $destination, $previous); } } public function copy(string $source, string $destination, Config $config): void { try { $this->adapter->copy($this->prefix->prefixPath($source), $this->prefix->prefixPath($destination), $config); } catch (Throwable $previous) { throw UnableToCopyFile::fromLocationTo($source, $destination, $previous); } } public function publicUrl(string $path, Config $config): string { if ( ! $this->adapter instanceof PublicUrlGenerator) { throw UnableToGeneratePublicUrl::noGeneratorConfigured($path); } return $this->adapter->publicUrl($this->prefix->prefixPath($path), $config); } public function checksum(string $path, Config $config): string { if ($this->adapter instanceof ChecksumProvider) { return $this->adapter->checksum($this->prefix->prefixPath($path), $config); } return $this->calculateChecksumFromStream($path, $config); } public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string { if ( ! $this->adapter instanceof TemporaryUrlGenerator) { throw UnableToGenerateTemporaryUrl::noGeneratorConfigured($path); } return $this->adapter->temporaryUrl($this->prefix->prefixPath($path), $expiresAt, $config); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathPrefixing/PathPrefixedAdapterTest.php
src/PathPrefixing/PathPrefixedAdapterTest.php
<?php namespace League\Flysystem\PathPrefixing; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\InMemory\InMemoryFilesystemAdapter; use League\Flysystem\UnableToGeneratePublicUrl; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use League\Flysystem\Visibility; use PHPUnit\Framework\TestCase; use function iterator_to_array; class PathPrefixedAdapterTest extends TestCase { public function testPrefix(): void { $adapter = new InMemoryFilesystemAdapter(); $prefix = new PathPrefixedAdapter($adapter, 'foo'); $prefix->write('foo.txt', 'bla', new Config); static::assertTrue($prefix->fileExists('foo.txt')); static::assertFalse($prefix->directoryExists('foo.txt')); static::assertTrue($adapter->fileExists('foo/foo.txt')); static::assertFalse($adapter->directoryExists('foo/foo.txt')); static::assertSame('bla', $prefix->read('foo.txt')); static::assertSame('bla', stream_get_contents($prefix->readStream('foo.txt'))); static::assertSame('text/plain', $prefix->mimeType('foo.txt')->mimeType()); static::assertSame(3, $prefix->fileSize('foo.txt')->fileSize()); static::assertSame(Visibility::PUBLIC, $prefix->visibility('foo.txt')->visibility()); $prefix->setVisibility('foo.txt', Visibility::PRIVATE); static::assertSame(Visibility::PRIVATE, $prefix->visibility('foo.txt')->visibility()); static::assertEqualsWithDelta($prefix->lastModified('foo.txt')->lastModified(), time(), 2); $prefix->copy('foo.txt', 'bla.txt', new Config); static::assertTrue($prefix->fileExists('bla.txt')); $prefix->createDirectory('dir', new Config()); static::assertTrue($prefix->directoryExists('dir')); static::assertFalse($prefix->directoryExists('dir2')); $prefix->deleteDirectory('dir'); static::assertFalse($prefix->directoryExists('dir')); $prefix->move('bla.txt', 'bla2.txt', new Config()); static::assertFalse($prefix->fileExists('bla.txt')); static::assertTrue($prefix->fileExists('bla2.txt')); $prefix->delete('bla2.txt'); static::assertFalse($prefix->fileExists('bla2.txt')); $prefix->createDirectory('test', new Config()); $files = iterator_to_array($prefix->listContents('', true)); static::assertCount(2, $files); } public function testWriteStream(): void { $adapter = new InMemoryFilesystemAdapter(); $prefix = new PathPrefixedAdapter($adapter, 'foo'); $tmpFile = sys_get_temp_dir() . '/' . uniqid('test', true); file_put_contents($tmpFile, 'test'); $prefix->writeStream('a.txt', fopen($tmpFile, 'rb'), new Config()); static::assertTrue($prefix->fileExists('a.txt')); static::assertSame('test', $prefix->read('a.txt')); static::assertSame('test', stream_get_contents($prefix->readStream('a.txt'))); unlink($tmpFile); } public function testEmptyPrefix(): void { static::expectException(\InvalidArgumentException::class); new PathPrefixedAdapter(new InMemoryFilesystemAdapter(), ''); } /** * @test */ public function generating_a_public_url(): void { $adapter = new class() extends InMemoryFilesystemAdapter implements PublicUrlGenerator { public function publicUrl(string $path, Config $config): string { return 'memory://' . ltrim($path, '/'); } }; $prefixedAdapter = new PathPrefixedAdapter($adapter, 'prefix'); $url = $prefixedAdapter->publicUrl('/path.txt', new Config()); self::assertEquals('memory://prefix/path.txt', $url); } /** * @test */ public function calculate_checksum_using_decorated_adapter(): void { $adapter = new class() extends InMemoryFilesystemAdapter implements ChecksumProvider { public function checksum(string $path, Config $config): string { return hash('md5', $this->read($path)); } }; $prefixedAdapter = new PathPrefixedAdapter($adapter, 'prefix'); $prefixedAdapter->write('foo.txt', 'bla', new Config); self::assertEquals('128ecf542a35ac5270a87dc740918404', $prefixedAdapter->checksum('foo.txt', new Config())); } /** * @test */ public function calculate_checksum_using_current_adapter(): void { $adapter = new InMemoryFilesystemAdapter(); $prefixedAdapter = new PathPrefixedAdapter($adapter, 'prefix'); $prefixedAdapter->write('foo.txt', 'bla', new Config); self::assertEquals('128ecf542a35ac5270a87dc740918404', hash('md5', 'bla')); self::assertEquals('128ecf542a35ac5270a87dc740918404', $prefixedAdapter->checksum('foo.txt', new Config())); } /** * @test */ public function failing_to_generate_a_public_url(): void { $prefixedAdapter = new PathPrefixedAdapter(new InMemoryFilesystemAdapter(), 'prefix'); $this->expectException(UnableToGeneratePublicUrl::class); $prefixedAdapter->publicUrl('/path.txt', new Config()); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AzureBlobStorage/AzureBlobStorageAdapterTest.php
src/AzureBlobStorage/AzureBlobStorageAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\AzureBlobStorage; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase as TestCase; use League\Flysystem\Config; use League\Flysystem\FilesystemAdapter; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\Visibility; use MicrosoftAzure\Storage\Blob\BlobRestProxy; use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings; use function getenv; /** * @group azure */ class AzureBlobStorageAdapterTest extends TestCase { const CONTAINER_NAME = 'flysystem'; protected static function createFilesystemAdapter(): FilesystemAdapter { $dsn = getenv('FLYSYSTEM_AZURE_DSN'); if (empty($dsn)) { self::markTestSkipped('FLYSYSTEM_AZURE_DSN is not provided.'); } $client = BlobRestProxy::createBlobService($dsn); $serviceSettings = StorageServiceSettings::createFromConnectionString($dsn); return new AzureBlobStorageAdapter( $client, self::CONTAINER_NAME, 'ci', serviceSettings: $serviceSettings, ); } /** * @test */ public function overwriting_a_file(): void { $this->runScenario( function () { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $adapter = $this->adapter(); $adapter->write('path.txt', 'new contents', new Config()); $contents = $adapter->read('path.txt'); $this->assertEquals('new contents', $contents); } ); } /** * @test */ public function setting_visibility(): void { self::markTestSkipped('Azure does not support visibility'); } /** * @test */ public function failing_to_set_visibility(): void { self::markTestSkipped('Azure does not support visibility'); } /** * @test */ public function failing_to_check_visibility(): void { self::markTestSkipped('Azure does not support visibility'); } public function fetching_unknown_mime_type_of_a_file(): void { $this->markTestSkipped('This adapter always returns a mime-type'); } public function listing_contents_recursive(): void { $this->markTestSkipped('This adapter does not support creating directories'); } /** * @test */ public function copying_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function moving_a_file(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->move('source.txt', 'destination.txt', new Config()); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function copying_a_file_again(): void { $this->runScenario(function () { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be copied', new Config() ); $adapter->copy('source.txt', 'destination.txt', new Config()); $this->assertTrue($adapter->fileExists('source.txt')); $this->assertTrue($adapter->fileExists('destination.txt')); $this->assertEquals('contents to be copied', $adapter->read('destination.txt')); }); } /** * @test */ public function setting_visibility_can_be_ignored_not_supported(): void { $this->givenWeHaveAnExistingFile('some-file.md'); $this->expectNotToPerformAssertions(); $client = BlobRestProxy::createBlobService(getenv('FLYSYSTEM_AZURE_DSN')); $adapter = new AzureBlobStorageAdapter($client, self::CONTAINER_NAME, 'ci', null, 50000, AzureBlobStorageAdapter::ON_VISIBILITY_IGNORE); $adapter->setVisibility('some-file.md', 'public'); } /** * @test */ public function setting_visibility_causes_errors(): void { $this->givenWeHaveAnExistingFile('some-file.md'); $adapter = $this->adapter(); $this->expectException(UnableToSetVisibility::class); $adapter->setVisibility('some-file.md', 'public'); } /** * @test */ public function checking_if_a_directory_exists_after_creating_it(): void { $this->markTestSkipped('This adapter does not support creating directories'); } /** * @test */ public function setting_visibility_on_a_file_that_does_not_exist(): void { $this->markTestSkipped('This adapter does not support visibility'); } /** * @test */ public function creating_a_directory(): void { $this->markTestSkipped('This adapter does not support creating directories'); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AzureBlobStorage/AzureBlobStorageAdapter.php
src/AzureBlobStorage/AzureBlobStorageAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\AzureBlobStorage; use DateTime; use DateTimeInterface; use League\Flysystem\ChecksumAlgoIsNotSupported; use League\Flysystem\ChecksumProvider; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\PathPrefixer; use League\Flysystem\UnableToCheckDirectoryExistence; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToDeleteDirectory; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToGenerateTemporaryUrl; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToProvideChecksum; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UrlGeneration\PublicUrlGenerator; use League\Flysystem\UrlGeneration\TemporaryUrlGenerator; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use MicrosoftAzure\Storage\Blob\BlobRestProxy; use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper; use MicrosoftAzure\Storage\Blob\Models\BlobProperties; use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions; use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions; use MicrosoftAzure\Storage\Common\Exceptions\ServiceException; use MicrosoftAzure\Storage\Common\Internal\Resources; use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings; use MicrosoftAzure\Storage\Common\Models\ContinuationToken; use Throwable; use function base64_decode; use function bin2hex; use function stream_get_contents; class AzureBlobStorageAdapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator { /** @var string[] */ private const META_OPTIONS = [ 'CacheControl', 'ContentType', 'Metadata', 'ContentLanguage', 'ContentEncoding', ]; const ON_VISIBILITY_THROW_ERROR = 'throw'; const ON_VISIBILITY_IGNORE = 'ignore'; private MimeTypeDetector $mimeTypeDetector; private PathPrefixer $prefixer; public function __construct( private BlobRestProxy $client, private string $container, string $prefix = '', ?MimeTypeDetector $mimeTypeDetector = null, private int $maxResultsForContentsListing = 5000, private string $visibilityHandling = self::ON_VISIBILITY_THROW_ERROR, private ?StorageServiceSettings $serviceSettings = null, ) { $this->prefixer = new PathPrefixer($prefix); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); } public function copy(string $source, string $destination, Config $config): void { $resolvedDestination = $this->prefixer->prefixPath($destination); $resolvedSource = $this->prefixer->prefixPath($source); try { $this->client->copyBlob( $this->container, $resolvedDestination, $this->container, $resolvedSource ); } catch (Throwable $throwable) { throw UnableToCopyFile::fromLocationTo($source, $destination, $throwable); } } public function delete(string $path): void { $location = $this->prefixer->prefixPath($path); try { $this->client->deleteBlob($this->container, $location); } catch (Throwable $exception) { if ($exception instanceof ServiceException && $exception->getCode() === 404) { return; } throw UnableToDeleteFile::atLocation($path, $exception->getMessage(), $exception); } } public function read(string $path): string { $response = $this->readStream($path); return stream_get_contents($response); } public function readStream(string $path) { $location = $this->prefixer->prefixPath($path); try { $response = $this->client->getBlob($this->container, $location); return $response->getContentStream(); } catch (Throwable $exception) { throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception); } } public function listContents(string $path, bool $deep = false): iterable { $resolved = $this->prefixer->prefixDirectoryPath($path); $options = new ListBlobsOptions(); $options->setPrefix($resolved); $options->setMaxResults($this->maxResultsForContentsListing); if ($deep === false) { $options->setDelimiter('/'); } do { $response = $this->client->listBlobs($this->container, $options); foreach ($response->getBlobPrefixes() as $blobPrefix) { yield new DirectoryAttributes($this->prefixer->stripDirectoryPrefix($blobPrefix->getName())); } foreach ($response->getBlobs() as $blob) { yield $this->normalizeBlobProperties( $this->prefixer->stripPrefix($blob->getName()), $blob->getProperties() ); } $continuationToken = $response->getContinuationToken(); $options->setContinuationToken($continuationToken); } while ($continuationToken instanceof ContinuationToken); } public function fileExists(string $path): bool { $resolved = $this->prefixer->prefixPath($path); try { return $this->fetchMetadata($resolved) !== null; } catch (Throwable $exception) { if ($exception instanceof ServiceException && $exception->getCode() === 404) { return false; } throw UnableToCheckFileExistence::forLocation($path, $exception); } } public function directoryExists(string $path): bool { $resolved = $this->prefixer->prefixDirectoryPath($path); $options = new ListBlobsOptions(); $options->setPrefix($resolved); $options->setMaxResults(1); try { $listResults = $this->client->listBlobs($this->container, $options); return count($listResults->getBlobs()) > 0; } catch (Throwable $exception) { throw UnableToCheckDirectoryExistence::forLocation($path, $exception); } } public function deleteDirectory(string $path): void { $resolved = $this->prefixer->prefixDirectoryPath($path); $options = new ListBlobsOptions(); $options->setPrefix($resolved); try { start: $listResults = $this->client->listBlobs($this->container, $options); foreach ($listResults->getBlobs() as $blob) { $this->client->deleteBlob($this->container, $blob->getName()); } $continuationToken = $listResults->getContinuationToken(); if ($continuationToken instanceof ContinuationToken) { $options->setContinuationToken($continuationToken); goto start; } } catch (Throwable $exception) { throw UnableToDeleteDirectory::atLocation($path, $exception->getMessage(), $exception); } } public function createDirectory(string $path, Config $config): void { // this is not supported by Azure } public function setVisibility(string $path, string $visibility): void { if ($this->visibilityHandling === self::ON_VISIBILITY_THROW_ERROR) { throw UnableToSetVisibility::atLocation($path, 'Azure does not support this operation.'); } } public function visibility(string $path): FileAttributes { throw UnableToRetrieveMetadata::visibility($path, 'Azure does not support visibility'); } public function mimeType(string $path): FileAttributes { try { return $this->fetchMetadata($this->prefixer->prefixPath($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::mimeType($path, $exception->getMessage(), $exception); } } public function lastModified(string $path): FileAttributes { try { return $this->fetchMetadata($this->prefixer->prefixPath($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::lastModified($path, $exception->getMessage(), $exception); } } public function fileSize(string $path): FileAttributes { try { return $this->fetchMetadata($this->prefixer->prefixPath($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::fileSize($path, $exception->getMessage(), $exception); } } public function move(string $source, string $destination, Config $config): void { try { $this->copy($source, $destination, $config); $this->delete($source); } catch (Throwable $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } } public function write(string $path, string $contents, Config $config): void { $this->upload($path, $contents, $config); } public function writeStream(string $path, $contents, Config $config): void { $this->upload($path, $contents, $config); } /** * @param string|resource $contents */ private function upload(string $destination, $contents, Config $config): void { $resolved = $this->prefixer->prefixPath($destination); try { $options = $this->getOptionsFromConfig($config); if (empty($options->getContentType())) { $options->setContentType($this->mimeTypeDetector->detectMimeType($resolved, $contents)); } $this->client->createBlockBlob( $this->container, $resolved, $contents, $options ); } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($destination, $exception->getMessage(), $exception); } } private function fetchMetadata(string $path): FileAttributes { return $this->normalizeBlobProperties( $path, $this->client->getBlobProperties($this->container, $path)->getProperties() ); } private function getOptionsFromConfig(Config $config): CreateBlockBlobOptions { $options = new CreateBlockBlobOptions(); foreach (self::META_OPTIONS as $option) { $setting = $config->get($option, '___NOT__SET___'); if ($setting === '___NOT__SET___') { continue; } call_user_func([$options, "set$option"], $setting); } $mimeType = $config->get('mimetype'); if ($mimeType !== null) { $options->setContentType($mimeType); } return $options; } private function normalizeBlobProperties(string $path, BlobProperties $properties): FileAttributes { return new FileAttributes( $path, $properties->getContentLength(), null, $properties->getLastModified()->getTimestamp(), $properties->getContentType(), ['md5_checksum' => $properties->getContentMD5()] ); } public function publicUrl(string $path, Config $config): string { $location = $this->prefixer->prefixPath($path); return $this->client->getBlobUrl($this->container, $location); } public function checksum(string $path, Config $config): string { $algo = $config->get('checksum_algo', 'md5'); if ($algo !== 'md5') { throw new ChecksumAlgoIsNotSupported(); } try { $metadata = $this->fetchMetadata($this->prefixer->prefixPath($path)); $checksum = $metadata->extraMetadata()['md5_checksum'] ?? '__not_specified'; } catch (Throwable $exception) { throw new UnableToProvideChecksum($exception->getMessage(), $path, $exception); } if ($checksum === '__not_specified') { throw new UnableToProvideChecksum('No checksum provided in metadata', $path); } return bin2hex(base64_decode($checksum)); } public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string { if ( ! $this->serviceSettings instanceof StorageServiceSettings) { throw UnableToGenerateTemporaryUrl::noGeneratorConfigured( $path, 'The $serviceSettings constructor parameter must be set to generate temporary URLs.', ); } try { $sas = new BlobSharedAccessSignatureHelper($this->serviceSettings->getName(), $this->serviceSettings->getKey()); $baseUrl = $this->publicUrl($path, $config); $resourceName = $this->container . '/' . ltrim($this->prefixer->prefixPath($path), '/'); $token = $sas->generateBlobServiceSharedAccessSignatureToken( Resources::RESOURCE_TYPE_BLOB, $resourceName, 'r', // read DateTime::createFromInterface($expiresAt), $config->get('signed_start', ''), $config->get('signed_ip', ''), $config->get('signed_protocol', 'https'), $config->get('signed_identifier', ''), $config->get('cache_control', ''), $config->get('content_disposition', $config->get('content_deposition', '')), $config->get('content_encoding', ''), $config->get('content_language', ''), $config->get('content_type', ''), ); return "$baseUrl?$token"; } catch (Throwable $exception) { throw UnableToGenerateTemporaryUrl::dueToError($path, $exception); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/UnableToEstablishAuthenticityOfHost.php
src/PhpseclibV3/UnableToEstablishAuthenticityOfHost.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\FilesystemException; use RuntimeException; class UnableToEstablishAuthenticityOfHost extends RuntimeException implements FilesystemException { public static function becauseTheAuthenticityCantBeEstablished(string $host): UnableToEstablishAuthenticityOfHost { return new UnableToEstablishAuthenticityOfHost("The authenticity of host $host can't be established."); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SftpStub.php
src/PhpseclibV3/SftpStub.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; /** * @internal This is only used for testing purposes. */ class SftpStub extends SFTP { /** * @var array<string,bool> */ private array $tripWires = []; public function failOnChmod(string $filename): void { $key = $this->formatTripKey('chmod', $filename); $this->tripWires[$key] = true; } /** * @param int $mode * @param string $filename * @param bool $recursive * * @return bool|mixed */ public function chmod($mode, $filename, $recursive = false) { $key = $this->formatTripKey('chmod', $filename); $shouldTrip = $this->tripWires[$key] ?? false; if ($shouldTrip) { unset($this->tripWires[$key]); return false; } return parent::chmod($mode, $filename, $recursive); } public function failOnPut(string $filename): void { $key = $this->formatTripKey('put', $filename); $this->tripWires[$key] = true; } /** * @param string $remote_file * @param resource|string $data * @param int $mode * @param int $start * @param int $local_start * @param null $progressCallback * * @return bool */ public function put( $remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $local_start = -1, $progressCallback = null ) { $key = $this->formatTripKey('put', $remote_file); $shouldTrip = $this->tripWires[$key] ?? false; if ($shouldTrip) { return false; } return parent::put($remote_file, $data, $mode, $start, $local_start, $progressCallback); } /** * @param array<int,mixed> $arguments * * @return string */ private function formatTripKey(...$arguments): string { $key = ''; foreach ($arguments as $argument) { $key .= var_export($argument, true); } return $key; } public function resetTripWires(): void { $this->tripWires = []; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/UnableToConnectToSftpHost.php
src/PhpseclibV3/UnableToConnectToSftpHost.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\FilesystemException; use RuntimeException; use Throwable; class UnableToConnectToSftpHost extends RuntimeException implements FilesystemException { public static function atHostname(string $host, ?Throwable $previous = null): UnableToConnectToSftpHost { return new UnableToConnectToSftpHost("Unable to connect to host: $host", 0, $previous); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SftpAdapter.php
src/PhpseclibV3/SftpAdapter.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\Config; use League\Flysystem\DirectoryAttributes; use League\Flysystem\FileAttributes; use League\Flysystem\FilesystemAdapter; use League\Flysystem\FilesystemException; use League\Flysystem\PathPrefixer; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToCheckDirectoryExistence; use League\Flysystem\UnableToCheckFileExistence; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; use League\Flysystem\UnixVisibility\PortableVisibilityConverter; use League\Flysystem\UnixVisibility\VisibilityConverter; use League\MimeTypeDetection\FinfoMimeTypeDetector; use League\MimeTypeDetection\MimeTypeDetector; use phpseclib3\Net\SFTP; use Throwable; use function rtrim; class SftpAdapter implements FilesystemAdapter { private VisibilityConverter $visibilityConverter; private PathPrefixer $prefixer; private MimeTypeDetector $mimeTypeDetector; public function __construct( private ConnectionProvider $connectionProvider, string $root, ?VisibilityConverter $visibilityConverter = null, ?MimeTypeDetector $mimeTypeDetector = null, private bool $detectMimeTypeUsingPath = false, private bool $disconnectOnDestruct = false, ) { $this->prefixer = new PathPrefixer($root); $this->visibilityConverter = $visibilityConverter ?? new PortableVisibilityConverter(); $this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector(); } public function fileExists(string $path): bool { $location = $this->prefixer->prefixPath($path); try { return $this->connectionProvider->provideConnection()->is_file($location); } catch (Throwable $exception) { throw UnableToCheckFileExistence::forLocation($path, $exception); } } public function disconnect(): void { $this->connectionProvider->disconnect(); } public function directoryExists(string $path): bool { $location = $this->prefixer->prefixDirectoryPath($path); try { return $this->connectionProvider->provideConnection()->is_dir($location); } catch (Throwable $exception) { throw UnableToCheckDirectoryExistence::forLocation($path, $exception); } } /** * @param string $path * @param string|resource $contents * @param Config $config * * @throws FilesystemException */ private function upload(string $path, $contents, Config $config): void { $this->ensureParentDirectoryExists($path, $config); $connection = $this->connectionProvider->provideConnection(); $location = $this->prefixer->prefixPath($path); if ( ! $connection->put($location, $contents, SFTP::SOURCE_STRING)) { throw UnableToWriteFile::atLocation($path, 'not able to write the file'); } if ($visibility = $config->get(Config::OPTION_VISIBILITY)) { $this->setVisibility($path, $visibility); } } private function ensureParentDirectoryExists(string $path, Config $config): void { $parentDirectory = dirname($path); if ($parentDirectory === '' || $parentDirectory === '.') { return; } /** @var string $visibility */ $visibility = $config->get(Config::OPTION_DIRECTORY_VISIBILITY); $this->makeDirectory($parentDirectory, $visibility); } private function makeDirectory(string $directory, ?string $visibility): void { $location = $this->prefixer->prefixPath($directory); $connection = $this->connectionProvider->provideConnection(); if ($connection->is_dir($location)) { return; } $mode = $visibility ? $this->visibilityConverter->forDirectory( $visibility ) : $this->visibilityConverter->defaultForDirectories(); if ( ! $connection->mkdir($location, $mode, true) && ! $connection->is_dir($location)) { throw UnableToCreateDirectory::atLocation($directory); } } public function write(string $path, string $contents, Config $config): void { try { $this->upload($path, $contents, $config); } catch (UnableToWriteFile $exception) { throw $exception; } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } public function writeStream(string $path, $contents, Config $config): void { try { $this->upload($path, $contents, $config); } catch (UnableToWriteFile $exception) { throw $exception; } catch (Throwable $exception) { throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception); } } public function read(string $path): string { $location = $this->prefixer->prefixPath($path); $connection = $this->connectionProvider->provideConnection(); $contents = $connection->get($location); if ( ! is_string($contents)) { throw UnableToReadFile::fromLocation($path); } return $contents; } public function readStream(string $path) { $location = $this->prefixer->prefixPath($path); $connection = $this->connectionProvider->provideConnection(); /** @var resource $readStream */ $readStream = fopen('php://temp', 'w+'); if ( ! $connection->get($location, $readStream)) { fclose($readStream); throw UnableToReadFile::fromLocation($path); } rewind($readStream); return $readStream; } public function delete(string $path): void { $location = $this->prefixer->prefixPath($path); $connection = $this->connectionProvider->provideConnection(); $connection->delete($location); } public function deleteDirectory(string $path): void { $location = rtrim($this->prefixer->prefixPath($path), '/') . '/'; $connection = $this->connectionProvider->provideConnection(); $connection->delete($location); $connection->rmdir($location); } public function createDirectory(string $path, Config $config): void { $this->makeDirectory($path, $config->get(Config::OPTION_DIRECTORY_VISIBILITY, $config->get(Config::OPTION_VISIBILITY))); } public function setVisibility(string $path, string $visibility): void { $location = $this->prefixer->prefixPath($path); $connection = $this->connectionProvider->provideConnection(); $mode = $this->visibilityConverter->forFile($visibility); if ( ! $connection->chmod($mode, $location, false)) { throw UnableToSetVisibility::atLocation($path); } } private function fetchFileMetadata(string $path, string $type): FileAttributes { $location = $this->prefixer->prefixPath($path); $connection = $this->connectionProvider->provideConnection(); $stat = $connection->stat($location); if ( ! is_array($stat)) { throw UnableToRetrieveMetadata::create($path, $type); } $attributes = $this->convertListingToAttributes($path, $stat); if ( ! $attributes instanceof FileAttributes) { throw UnableToRetrieveMetadata::create($path, $type, 'path is not a file'); } return $attributes; } public function mimeType(string $path): FileAttributes { try { $mimetype = $this->detectMimeTypeUsingPath ? $this->mimeTypeDetector->detectMimeTypeFromPath($path) : $this->mimeTypeDetector->detectMimeType($path, $this->read($path)); } catch (Throwable $exception) { throw UnableToRetrieveMetadata::mimeType($path, $exception->getMessage(), $exception); } if ($mimetype === null) { throw UnableToRetrieveMetadata::mimeType($path, 'Unknown.'); } return new FileAttributes($path, null, null, null, $mimetype); } public function lastModified(string $path): FileAttributes { return $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_LAST_MODIFIED); } public function fileSize(string $path): FileAttributes { return $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_FILE_SIZE); } public function visibility(string $path): FileAttributes { return $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_VISIBILITY); } public function listContents(string $path, bool $deep): iterable { $connection = $this->connectionProvider->provideConnection(); $location = $this->prefixer->prefixPath(rtrim($path, '/')) . '/'; $listing = $connection->rawlist($location, false); if (false === $listing) { return; } foreach ($listing as $filename => $attributes) { if ($filename === '.' || $filename === '..') { continue; } // Ensure numeric keys are strings. $filename = (string) $filename; $path = $this->prefixer->stripPrefix($location . ltrim($filename, '/')); $attributes = $this->convertListingToAttributes($path, $attributes); yield $attributes; if ($deep && $attributes->isDir()) { foreach ($this->listContents($attributes->path(), true) as $child) { yield $child; } } } } private function convertListingToAttributes(string $path, array $attributes): StorageAttributes { $permissions = $attributes['mode'] & 0777; $lastModified = $attributes['mtime'] ?? null; if (($attributes['type'] ?? null) === NET_SFTP_TYPE_DIRECTORY) { return new DirectoryAttributes( ltrim($path, '/'), $this->visibilityConverter->inverseForDirectory($permissions), $lastModified ); } return new FileAttributes( $path, $attributes['size'], $this->visibilityConverter->inverseForFile($permissions), $lastModified ); } public function move(string $source, string $destination, Config $config): void { $sourceLocation = $this->prefixer->prefixPath($source); $destinationLocation = $this->prefixer->prefixPath($destination); $connection = $this->connectionProvider->provideConnection(); try { $this->ensureParentDirectoryExists($destination, $config); } catch (Throwable $exception) { throw UnableToMoveFile::fromLocationTo($source, $destination, $exception); } if ($sourceLocation === $destinationLocation) { return; } if ($connection->rename($sourceLocation, $destinationLocation)) { return; } // Overwrite existing file / dir if ($connection->is_file($destinationLocation)) { $this->delete($destination); if ($connection->rename($sourceLocation, $destinationLocation)) { return; } } throw UnableToMoveFile::fromLocationTo($source, $destination); } public function copy(string $source, string $destination, Config $config): void { try { $readStream = $this->readStream($source); $visibility = $config->get(Config::OPTION_VISIBILITY); if ($visibility === null && $config->get(Config::OPTION_RETAIN_VISIBILITY, true)) { $config = $config->withSetting(Config::OPTION_VISIBILITY, $this->visibility($source)->visibility()); } $this->writeStream($destination, $readStream, $config); } catch (Throwable $exception) { if (isset($readStream) && is_resource($readStream)) { @fclose($readStream); } throw UnableToCopyFile::fromLocationTo($source, $destination, $exception); } } public function __destruct() { if ($this->disconnectOnDestruct) { $this->connectionProvider->disconnect(); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/ConnectionProvider.php
src/PhpseclibV3/ConnectionProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; /** * @method void disconnect() */ interface ConnectionProvider { public function provideConnection(): SFTP; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SftpConnectionProviderTest.php
src/PhpseclibV3/SftpConnectionProviderTest.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; use PHPUnit\Framework\TestCase; use Throwable; use function base64_decode; use function class_exists; use function explode; use function getenv; use function hash; use function implode; use function is_a; use function sleep; use function str_split; /** * @group sftp * @group sftp-connection * @group phpseclib3 */ class SftpConnectionProviderTest extends TestCase { const KEX_ACCEPTED_BY_DEFAULT_OPENSSH_BUT_DISABLED_IN_EDDSA_ONLY = 'diffie-hellman-group14-sha256'; public static function setUpBeforeClass(): void { if ( ! class_exists(SFTP::class)) { self::markTestIncomplete("No phpseclib v3 installed"); } } /** * @test */ public function giving_up_after_5_connection_failures(): void { $this->expectException(UnableToConnectToSftpHost::class); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2222, 'timeout' => 10, 'connectivityChecker' => new FixatedConnectivityChecker(5), ] ); $provider->provideConnection(); } /** * @test */ public function trying_until_5_tries(): void { $provider = SftpConnectionProvider::fromArray([ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2222, 'timeout' => 10, 'connectivityChecker' => new FixatedConnectivityChecker(4), ]); $connection = $provider->provideConnection(); $sameConnection = $provider->provideConnection(); $this->assertInstanceOf(SFTP::class, $connection); $this->assertSame($connection, $sameConnection); } /** * @test */ public function authenticating_with_a_private_key(): void { $provider = SftpConnectionProvider::fromArray([ 'host' => 'localhost', 'username' => 'bar', 'privateKey' => __DIR__ . '/../../test_files/sftp/id_rsa', 'passphrase' => 'secret', 'port' => 2222, ]); $connection = null; $this->runWithRetries(function () use (&$connection, $provider) { $connection = $provider->provideConnection(); }); $this->assertInstanceOf(SFTP::class, $connection); } /** * @test */ public function authenticating_with_an_invalid_private_key(): void { $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'bar', 'privateKey' => __DIR__ . '/../../test_files/sftp/users.conf', 'port' => 2222, ] ); $this->expectException(UnableToLoadPrivateKey::class); $this->runWithRetries(fn () => $provider->provideConnection(), UnableToLoadPrivateKey::class); } /** * @test */ public function authenticating_with_an_ssh_agent(): void { if (getenv('COMPOSER_OPTS') === false) { $this->markTestSkipped('Test is not run locally'); } $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'bar', 'useAgent' => true, 'port' => 2222, ] ); $connection = null; $this->runWithRetries(function () use ($provider, &$connection) { $connection = $provider->provideConnection(); }); $this->assertInstanceOf(SFTP::class, $connection); } /** * @test */ public function failing_to_authenticating_with_an_ssh_agent(): void { $this->expectException(UnableToAuthenticate::class); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'useAgent' => true, 'port' => 2222, ] ); $provider->provideConnection(); } /** * @test */ public function authenticating_with_a_private_key_and_falling_back_to_password(): void { $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'privateKey' => __DIR__ . '/../../test_files/sftp/id_rsa', 'passphrase' => 'secret', 'port' => 2222, ] ); $connection = null; $this->runWithRetries(function () use ($provider, &$connection) { $connection = $provider->provideConnection(); }); $this->assertInstanceOf(SFTP::class, $connection); } /** * @test */ public function not_being_able_to_authenticate_with_a_private_key(): void { $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'privateKey' => __DIR__ . '/../../test_files/sftp/unknown.key', 'passphrase' => 'secret', 'port' => 2222, ] ); $this->expectExceptionObject(UnableToAuthenticate::withPrivateKey()); $this->runWithRetries(fn () => $provider->provideConnection(), UnableToAuthenticate::class); } /** * @test */ public function verifying_a_fingerprint(): void { $key = file_get_contents(__DIR__ . '/../../test_files/sftp/ssh_host_ed25519_key.pub'); $fingerPrint = $this->computeFingerPrint($key); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2222, 'hostFingerprint' => $fingerPrint, ] ); $connection = null; $this->runWithRetries(function () use ($provider, &$connection) { $connection = $provider->provideConnection(); }); $this->assertInstanceOf(SFTP::class, $connection); } /** * @test */ public function providing_an_invalid_fingerprint(): void { $this->expectException(UnableToEstablishAuthenticityOfHost::class); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2222, 'hostFingerprint' => 'invalid:fingerprint', ] ); $this->runWithRetries(fn () => $provider->provideConnection(), UnableToEstablishAuthenticityOfHost::class); } /** * @test */ public function providing_an_invalid_password(): void { $this->expectException(UnableToAuthenticate::class); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'lol', 'port' => 2222, ] ); $this->runWithRetries(fn () => $provider->provideConnection(), UnableToAuthenticate::class); } /** * @test */ public function retries_several_times_until_failure(): void { $connectivityChecker = new class implements ConnectivityChecker { /** @var int */ public $calls = 0; public function isConnected(SFTP $connection): bool { ++$this->calls; return false; } }; $maxTries = 2; $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'bar', 'privateKey' => __DIR__ . '/../../test_files/sftp/id_rsa', 'passphrase' => 'secret', 'port' => 8222, 'maxTries' => $maxTries, 'timeout' => 1, 'connectivityChecker' => $connectivityChecker, ] ); $this->expectException(UnableToConnectToSftpHost::class); try { $provider->provideConnection(); } finally { self::assertSame($maxTries + 1, $connectivityChecker->calls); } } /** * @test */ public function authenticate_with_supported_preferred_kex_algorithm_succeeds(): void { $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2222, 'preferredAlgorithms' => [ 'kex' => [self::KEX_ACCEPTED_BY_DEFAULT_OPENSSH_BUT_DISABLED_IN_EDDSA_ONLY], ], ] ); $this->runWithRetries(fn () => $this->assertInstanceOf(SFTP::class, $provider->provideConnection())); $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2223, 'preferredAlgorithms' => [ 'kex' => ['curve25519-sha256'], ], ] ); $this->runWithRetries(fn () => $this->assertInstanceOf(SFTP::class, $provider->provideConnection())); } /** * @test */ public function authenticate_with_unsupported_preferred_kex_algorithm_failes(): void { $provider = SftpConnectionProvider::fromArray( [ 'host' => 'localhost', 'username' => 'foo', 'password' => 'pass', 'port' => 2223, 'preferredAlgorithms' => [ 'kex' => [self::KEX_ACCEPTED_BY_DEFAULT_OPENSSH_BUT_DISABLED_IN_EDDSA_ONLY], ], ] ); $this->expectException(UnableToConnectToSftpHost::class); $provider->provideConnection(); } private function computeFingerPrint(string $publicKey): string { $content = explode(' ', $publicKey, 3); $algo = $content[0] === 'ssh-rsa' ? 'md5' : 'sha512'; return implode(':', str_split(hash($algo, base64_decode($content[1])), 2)); } /** * @param class-string<Throwable>|null $expected * * @throws Throwable */ public function runWithRetries(callable $scenario, ?string $expected = null): void { $tries = 0; start: try { $scenario(); } catch (Throwable $exception) { if (($expected === null || is_a($exception, $expected) === false) && $tries < 10) { $tries++; sleep($tries); goto start; } throw $exception; } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/UnableToLoadPrivateKey.php
src/PhpseclibV3/UnableToLoadPrivateKey.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\FilesystemException; use RuntimeException; use Throwable; class UnableToLoadPrivateKey extends RuntimeException implements FilesystemException { public function __construct(?string $message = 'Unable to load private key.', ?Throwable $previous = null) { parent::__construct($message ?? 'Unable to load private key.', 0, $previous); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SftpConnectionProvider.php
src/PhpseclibV3/SftpConnectionProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\FilesystemException; use phpseclib3\Crypt\Common\AsymmetricKey; use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Exception\NoKeyLoadedException; use phpseclib3\Net\SFTP; use phpseclib3\System\SSH\Agent; use Throwable; use function base64_decode; use function implode; use function str_split; class SftpConnectionProvider implements ConnectionProvider { /** * @var SFTP|null */ private $connection; /** * @var ConnectivityChecker */ private $connectivityChecker; public function __construct( private string $host, private string $username, private ?string $password = null, private ?string $privateKey = null, private ?string $passphrase = null, private int $port = 22, private bool $useAgent = false, private int $timeout = 10, private int $maxTries = 4, private ?string $hostFingerprint = null, ?ConnectivityChecker $connectivityChecker = null, private array $preferredAlgorithms = [], private bool $disableStatCache = true, ) { $this->connectivityChecker = $connectivityChecker ?? new SimpleConnectivityChecker(); } public function provideConnection(): SFTP { $tries = 0; start: $tries++; try { $connection = $this->connection instanceof SFTP ? $this->connection : $this->setupConnection(); } catch (Throwable $exception) { if ($tries <= $this->maxTries) { goto start; } if ($exception instanceof FilesystemException) { throw $exception; } throw UnableToConnectToSftpHost::atHostname($this->host, $exception); } if ( ! $this->connectivityChecker->isConnected($connection)) { $connection->disconnect(); $this->connection = null; if ($tries <= $this->maxTries) { goto start; } throw UnableToConnectToSftpHost::atHostname($this->host); } return $this->connection = $connection; } public function disconnect(): void { if ($this->connection) { $this->connection->disconnect(); $this->connection = null; } } private function setupConnection(): SFTP { $connection = new SFTP($this->host, $this->port, $this->timeout); $connection->setPreferredAlgorithms($this->preferredAlgorithms); $this->disableStatCache && $connection->disableStatCache(); try { $this->checkFingerprint($connection); $this->authenticate($connection); } catch (Throwable $exception) { $connection->disconnect(); throw $exception; } return $connection; } private function checkFingerprint(SFTP $connection): void { if ( ! $this->hostFingerprint) { return; } $publicKey = $connection->getServerPublicHostKey(); if ($publicKey === false) { throw UnableToEstablishAuthenticityOfHost::becauseTheAuthenticityCantBeEstablished($this->host); } $fingerprint = $this->getFingerprintFromPublicKey($publicKey); if (0 !== strcasecmp($this->hostFingerprint, $fingerprint)) { throw UnableToEstablishAuthenticityOfHost::becauseTheAuthenticityCantBeEstablished($this->host); } } private function getFingerprintFromPublicKey(string $publicKey): string { $content = explode(' ', $publicKey, 3); $algo = $content[0] === 'ssh-rsa' ? 'md5' : 'sha512'; return implode(':', str_split(hash($algo, base64_decode($content[1])), 2)); } private function authenticate(SFTP $connection): void { if ($this->privateKey !== null) { $this->authenticateWithPrivateKey($connection); } elseif ($this->useAgent) { $this->authenticateWithAgent($connection); } else { $this->authenticateWithUsernameAndPassword($connection); } } private function authenticateWithUsernameAndPassword(SFTP $connection): void { if ( ! $connection->login($this->username, $this->password)) { throw UnableToAuthenticate::withPassword($connection->getLastError()); } } public static function fromArray(array $options): SftpConnectionProvider { return new SftpConnectionProvider( $options['host'], $options['username'], $options['password'] ?? null, $options['privateKey'] ?? null, $options['passphrase'] ?? null, $options['port'] ?? 22, $options['useAgent'] ?? false, $options['timeout'] ?? 10, $options['maxTries'] ?? 4, $options['hostFingerprint'] ?? null, $options['connectivityChecker'] ?? null, $options['preferredAlgorithms'] ?? [], ); } private function authenticateWithPrivateKey(SFTP $connection): void { $privateKey = $this->loadPrivateKey(); if ($connection->login($this->username, $privateKey)) { return; } if ($this->password !== null && $connection->login($this->username, $this->password)) { return; } throw UnableToAuthenticate::withPrivateKey($connection->getLastError()); } private function loadPrivateKey(): AsymmetricKey { if (("---" !== substr($this->privateKey, 0, 3) || "PuTTY" !== substr($this->privateKey, 0, 5)) && is_file($this->privateKey)) { $this->privateKey = file_get_contents($this->privateKey); } try { if ($this->passphrase !== null) { return PublicKeyLoader::load($this->privateKey, $this->passphrase); } return PublicKeyLoader::load($this->privateKey); } catch (NoKeyLoadedException $exception) { throw new UnableToLoadPrivateKey(null, $exception); } } private function authenticateWithAgent(SFTP $connection): void { $agent = new Agent(); if ( ! $connection->login($this->username, $agent)) { throw UnableToAuthenticate::withSshAgent($connection->getLastError()); } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/FixatedConnectivityChecker.php
src/PhpseclibV3/FixatedConnectivityChecker.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; class FixatedConnectivityChecker implements ConnectivityChecker { /** * @var int */ private $succeedAfter; /** * @var int */ private $numberOfTimesChecked = 0; public function __construct(int $succeedAfter = 0) { $this->succeedAfter = $succeedAfter; } public function isConnected(SFTP $connection): bool { if ($this->numberOfTimesChecked >= $this->succeedAfter) { return true; } $this->numberOfTimesChecked++; return false; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/ConnectivityChecker.php
src/PhpseclibV3/ConnectivityChecker.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; interface ConnectivityChecker { public function isConnected(SFTP $connection): bool; }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/UnableToAuthenticate.php
src/PhpseclibV3/UnableToAuthenticate.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\FilesystemException; use RuntimeException; class UnableToAuthenticate extends RuntimeException implements FilesystemException { private ?string $connectionError; public function __construct(string $message, ?string $lastError = null) { parent::__construct($message); $this->connectionError = $lastError; } public static function withPassword(?string $lastError = null): UnableToAuthenticate { return new UnableToAuthenticate('Unable to authenticate using a password.', $lastError); } public static function withPrivateKey(?string $lastError = null): UnableToAuthenticate { return new UnableToAuthenticate('Unable to authenticate using a private key.', $lastError); } public static function withSshAgent(?string $lastError = null): UnableToAuthenticate { return new UnableToAuthenticate('Unable to authenticate using an SSH agent.', $lastError); } public function connectionError(): ?string { return $this->connectionError; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/StubSftpConnectionProvider.php
src/PhpseclibV3/StubSftpConnectionProvider.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; class StubSftpConnectionProvider implements ConnectionProvider { /** * @var SftpStub|null */ public $connection; public function __construct( private string $host, private string $username, private ?string $password = null, private int $port = 22 ) { } public function disconnect(): void { if ($this->connection) { $this->connection->disconnect(); } } public function provideConnection(): SFTP { if ( ! $this->connection instanceof SFTP || ! $this->connection->isConnected()) { $connection = new SftpStub($this->host, $this->port); $connection->login($this->username, $this->password); $this->connection = $connection; } return $this->connection; } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SftpAdapterTest.php
src/PhpseclibV3/SftpAdapterTest.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase; use League\Flysystem\Config; use League\Flysystem\FilesystemAdapter; use League\Flysystem\UnableToCopyFile; use League\Flysystem\UnableToCreateDirectory; use League\Flysystem\UnableToMoveFile; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToWriteFile; use League\Flysystem\Visibility; use phpseclib3\Net\SFTP; use function class_exists; /** * @group sftp * @group phpseclib3 */ class SftpAdapterTest extends FilesystemAdapterTestCase { public static function setUpBeforeClass(): void { if ( ! class_exists(SFTP::class)) { self::markTestIncomplete("No phpseclib v3 installed"); } } /** * @var StubSftpConnectionProvider */ private static $connectionProvider; /** * @var SftpStub */ private $connection; protected static function createFilesystemAdapter(): FilesystemAdapter { return new SftpAdapter( static::connectionProvider(), '/upload' ); } /** * @before */ public function setupConnectionProvider(): void { /** @var SftpStub $connection */ $connection = static::connectionProvider()->provideConnection(); $this->connection = $connection; $this->connection->resetTripWires(); } /** * @test */ public function failing_to_create_a_directory(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToCreateDirectory::class); $adapter->createDirectory('not-gonna-happen', new Config()); } /** * @test */ public function failing_to_write_a_file(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToWriteFile::class); $adapter->write('not-gonna-happen', 'na-ah', new Config()); } /** * @test */ public function failing_to_read_a_file(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToReadFile::class); $adapter->read('not-gonna-happen'); } /** * @test */ public function failing_to_read_a_file_as_a_stream(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToReadFile::class); $adapter->readStream('not-gonna-happen'); } /** * @test */ public function failing_to_write_a_file_using_streams(): void { $adapter = $this->adapterWithInvalidRoot(); $writeHandle = stream_with_contents('contents'); $this->expectException(UnableToWriteFile::class); try { $adapter->writeStream('not-gonna-happen', $writeHandle, new Config()); } finally { fclose($writeHandle); } } /** * @test */ public function detecting_mimetype(): void { $adapter = $this->adapter(); $adapter->write('file.svg', (string) file_get_contents(__DIR__ . '/../AdapterTestUtilities/test_files/flysystem.svg'), new Config()); $mimeType = $adapter->mimeType('file.svg'); $this->assertStringStartsWith('image/svg+xml', $mimeType->mimeType()); } /** * @test */ public function failing_to_chmod_when_writing(): void { $this->connection->failOnChmod('/upload/path.txt'); $adapter = $this->adapter(); $this->expectException(UnableToWriteFile::class); $adapter->write('path.txt', 'contents', new Config(['visibility' => 'public'])); } /** * @test */ public function failing_to_move_a_file_cause_the_parent_directory_cant_be_created(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToMoveFile::class); $adapter->move('path.txt', 'new-path.txt', new Config()); } /** * @test */ public function failing_to_copy_a_file(): void { $adapter = $this->adapterWithInvalidRoot(); $this->expectException(UnableToCopyFile::class); $adapter->copy('path.txt', 'new-path.txt', new Config()); } /** * @test */ public function failing_to_copy_a_file_because_writing_fails(): void { $this->givenWeHaveAnExistingFile('path.txt', 'contents'); $adapter = $this->adapter(); $this->connection->failOnPut('/upload/new-path.txt'); $this->expectException(UnableToCopyFile::class); $adapter->copy('path.txt', 'new-path.txt', new Config()); } /** * @test */ public function failing_to_chmod_when_writing_with_a_stream(): void { $writeStream = stream_with_contents('contents'); $this->connection->failOnChmod('/upload/path.txt'); $adapter = $this->adapter(); $this->expectException(UnableToWriteFile::class); try { $adapter->writeStream('path.txt', $writeStream, new Config(['visibility' => 'public'])); } finally { @fclose($writeStream); } } /** * @test */ public function list_contents_directory_does_not_exist(): void { $contents = $this->adapter()->listContents('/does_not_exist', false); $this->assertCount(0, iterator_to_array($contents)); } /** * @test */ public function it_can_proactively_close_a_connection(): void { /** @var SftpAdapter $adapter */ $adapter = $this->adapter(); self::assertFalse($adapter->fileExists('does not exists at all')); self::assertTrue(static::$connectionProvider->connection->isConnected()); $adapter->disconnect(); self::assertFalse(static::$connectionProvider->connection->isConnected()); } /** * @test * @fixme Move to FilesystemAdapterTestCase once all adapters pass */ public function moving_a_file_and_overwriting(): void { $this->runScenario(function() { $adapter = $this->adapter(); $adapter->write( 'source.txt', 'contents to be moved', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->write( 'destination.txt', 'contents to be overwritten', new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC]) ); $adapter->move('source.txt', 'destination.txt', new Config()); $this->assertFalse( $adapter->fileExists('source.txt'), 'After moving a file should no longer exist in the original location.' ); $this->assertTrue( $adapter->fileExists('destination.txt'), 'After moving, a file should be present at the new location.' ); $this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility()); $this->assertEquals('contents to be moved', $adapter->read('destination.txt')); }); } private static function connectionProvider(): StubSftpConnectionProvider { if ( ! static::$connectionProvider instanceof ConnectionProvider) { static::$connectionProvider = new StubSftpConnectionProvider('localhost', 'foo', 'pass', 2222); } return static::$connectionProvider; } /** * @return SftpAdapter */ private function adapterWithInvalidRoot(): SftpAdapter { $provider = static::connectionProvider(); return new SftpAdapter($provider, '/invalid'); } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV3/SimpleConnectivityChecker.php
src/PhpseclibV3/SimpleConnectivityChecker.php
<?php declare(strict_types=1); namespace League\Flysystem\PhpseclibV3; use phpseclib3\Net\SFTP; use Throwable; class SimpleConnectivityChecker implements ConnectivityChecker { public function __construct( private bool $usePing = false, ) { } public static function create(): SimpleConnectivityChecker { return new SimpleConnectivityChecker(); } public function withUsingPing(bool $usePing): SimpleConnectivityChecker { $clone = clone $this; $clone->usePing = $usePing; return $clone; } public function isConnected(SFTP $connection): bool { if ( ! $connection->isConnected()) { return false; } if ( ! $this->usePing) { return true; } try { return $connection->ping(); } catch (Throwable) { return false; } } }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/bin/tools.php
bin/tools.php
<?php include_once __DIR__ . '/../vendor/autoload.php'; function write_line(string $line) { fwrite(STDOUT, "{$line}\n"); } function panic(string $reason) { write_line('🚨 ' . $reason); exit(1); }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/bin/update-subsplit-closers.php
bin/update-subsplit-closers.php
<?php use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; include __DIR__ . '/../vendor/autoload.php'; $filesystem = new Filesystem(new LocalFilesystemAdapter(realpath(__DIR__ . '/../'))); $subsplits = json_decode($filesystem->read('config.subsplit-publish.json'), true); $workflowContents = $filesystem->read('bin/close-subsplit-prs.yml'); foreach ($subsplits['sub-splits'] as ['directory' => $subsplit]) { $workflowPath = $subsplit . '/.github/workflows/close-subsplit-prs.yaml'; $filesystem->write($workflowPath, $workflowContents); }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/bin/check-versions.php
bin/check-versions.php
<?php declare(strict_types=1); /** * This script check for composer dependency incompatibilities:. * * - All required dependencies of the extracted packages MUST be * present in the main composer.json's require(-dev) section. * - Dependency constraints of extracted packages may not exclude * the constraints of the main package and vice versa. * - The provided target release argument must be satisfiable by * all the extracted packages' core dependency constraint. */ use Composer\Semver\Comparator; use Composer\Semver\Semver; use Composer\Semver\VersionParser; use League\Flysystem\FileAttributes; use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; use League\Flysystem\StorageAttributes; include_once __DIR__ . '/tools.php'; function constraint_has_conflict(string $mainConstraint, string $packageConstraint): bool { $parser = new VersionParser(); $mainConstraint = $parser->parseConstraints($mainConstraint); $mainLowerBound = $mainConstraint->getLowerBound()->getVersion(); $mainUpperBound = $mainConstraint->getUpperBound()->getVersion(); $packageConstraint = $parser->parseConstraints($packageConstraint); $packageLowerBound = $packageConstraint->getLowerBound()->getVersion(); $packageUpperBound = $packageConstraint->getUpperBound()->getVersion(); if (Comparator::compare($mainUpperBound, '<=', $packageLowerBound)) { return true; } if (Comparator::compare($packageUpperBound, '<=', $mainLowerBound)) { return true; } return false; } if ( ! isset($argv[1])) { panic('No base version provided'); } write_line("🔎 Inspecting composer dependency incompatibilities."); $mainVersion = $argv[1]; $filesystem = new Filesystem(new LocalFilesystemAdapter(__DIR__ . '/../')); $mainComposer = $filesystem->read('composer.json'); /** @var string[] $otherComposers */ $otherComposers = $filesystem->listContents('src', true) ->filter(function (StorageAttributes $item) { return $item->isFile(); }) ->filter(function (FileAttributes $item) { return substr($item->path(), -5) === '.json'; }) ->map(function (FileAttributes $item) { return $item->path(); }) ->toArray(); $mainInformation = json_decode($mainComposer, true); foreach ($otherComposers as $composerFile) { $information = json_decode($filesystem->read($composerFile), true); foreach ($information['require'] as $dependency => $constraint) { if (str_starts_with($dependency, 'ext-') || $dependency === 'phpseclib/phpseclib') { continue; } if ($dependency === 'league/flysystem') { if ( ! Semver::satisfies($mainVersion, $constraint)) { panic("Composer file {$composerFile} does not allow league/flysystem:{$mainVersion}"); } else { write_line("Composer file {$composerFile} allows league/flysystem:{$mainVersion} with {$constraint}"); } continue; } $mainDependencyConstraint = $mainInformation['require'][$dependency] ?? $mainInformation['require-dev'][$dependency] ?? null; if ( ! is_string($mainDependencyConstraint)) { panic( "The main composer file does not depend on an adapter dependency.\n" . "Depedency {$dependency} from {$composerFile} is missing." ); } if (constraint_has_conflict($mainDependencyConstraint, $constraint)) { panic( "Package constraints are conflicting:\n\n" . "Package composer file: {$composerFile}\n" . "Dependency name: {$dependency}\n" . "Main constraint: {$mainDependencyConstraint}\n" . "Package constraint: {$constraint}" ); } } } write_line("✅ Composer dependencies are looking fine.");
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
thephpleague/flysystem
https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/bin/set-flysystem-version.php
bin/set-flysystem-version.php
<?php use League\Flysystem\FileAttributes; use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; use League\Flysystem\StorageAttributes; include_once __DIR__ . '/tools.php'; if ( ! isset($argv[1])) { panic('No base version provided'); } $mainVersion = $argv[1]; write_line("☝️ Setting all flysystem constraints to {$mainVersion}."); $filesystem = new Filesystem(new LocalFilesystemAdapter(__DIR__ . '/../')); /** @var string[] $otherComposers */ $composerFiles = $filesystem->listContents('src', true) ->filter(function (StorageAttributes $item) { return $item->isFile(); }) ->filter(function (FileAttributes $item) { return substr($item->path(), -5) === '.json'; }) ->map(function (FileAttributes $item) { return $item->path(); }) ->toArray(); foreach ($composerFiles as $composerFile) { $contents = $filesystem->read($composerFile); $mainVersionRegex = preg_quote($mainVersion, '~'); $updated = preg_replace('~("league/flysystem": "\\^[a-zA-Z0-9\\.-]+")~ms', '"league/flysystem": "^' . $mainVersion . '"', $contents); $filesystem->write($composerFile, $updated); }
php
MIT
5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277
2026-01-04T15:02:49.867552Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Dotenv.php
src/Dotenv.php
<?php declare(strict_types=1); namespace Dotenv; use Dotenv\Exception\InvalidPathException; use Dotenv\Loader\Loader; use Dotenv\Loader\LoaderInterface; use Dotenv\Parser\Parser; use Dotenv\Parser\ParserInterface; use Dotenv\Repository\Adapter\ArrayAdapter; use Dotenv\Repository\Adapter\PutenvAdapter; use Dotenv\Repository\RepositoryBuilder; use Dotenv\Repository\RepositoryInterface; use Dotenv\Store\StoreBuilder; use Dotenv\Store\StoreInterface; use Dotenv\Store\StringStore; class Dotenv { /** * The store instance. * * @var \Dotenv\Store\StoreInterface */ private $store; /** * The parser instance. * * @var \Dotenv\Parser\ParserInterface */ private $parser; /** * The loader instance. * * @var \Dotenv\Loader\LoaderInterface */ private $loader; /** * The repository instance. * * @var \Dotenv\Repository\RepositoryInterface */ private $repository; /** * Create a new dotenv instance. * * @param \Dotenv\Store\StoreInterface $store * @param \Dotenv\Parser\ParserInterface $parser * @param \Dotenv\Loader\LoaderInterface $loader * @param \Dotenv\Repository\RepositoryInterface $repository * * @return void */ public function __construct( StoreInterface $store, ParserInterface $parser, LoaderInterface $loader, RepositoryInterface $repository ) { $this->store = $store; $this->parser = $parser; $this->loader = $loader; $this->repository = $repository; } /** * Create a new dotenv instance. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function create(RepositoryInterface $repository, $paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $builder = $names === null ? StoreBuilder::createWithDefaultName() : StoreBuilder::createWithNoNames(); foreach ((array) $paths as $path) { $builder = $builder->addPath($path); } foreach ((array) $names as $name) { $builder = $builder->addName($name); } if ($shortCircuit) { $builder = $builder->shortCircuit(); } return new self($builder->fileEncoding($fileEncoding)->make(), new Parser(), new Loader(), $repository); } /** * Create a new mutable dotenv instance with default repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createMutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters()->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new mutable dotenv instance with default repository with the putenv adapter. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createUnsafeMutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters() ->addAdapter(PutenvAdapter::class) ->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new immutable dotenv instance with default repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createImmutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new immutable dotenv instance with default repository with the putenv adapter. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createUnsafeImmutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters() ->addAdapter(PutenvAdapter::class) ->immutable() ->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new dotenv instance with an array backed repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createArrayBacked($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) { $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Parse the given content and resolve nested variables. * * This method behaves just like load(), only without mutating your actual * environment. We do this by using an array backed repository. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return array<string, string|null> */ public static function parse(string $content) { $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); $phpdotenv = new self(new StringStore($content), new Parser(), new Loader(), $repository); return $phpdotenv->load(); } /** * Read and load environment file(s). * * @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException * * @return array<string, string|null> */ public function load() { $entries = $this->parser->parse($this->store->read()); return $this->loader->load($this->repository, $entries); } /** * Read and load environment file(s), silently failing if no files can be read. * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException * * @return array<string, string|null> */ public function safeLoad() { try { return $this->load(); } catch (InvalidPathException $e) { // suppressing exception return []; } } /** * Required ensures that the specified variables exist, and returns a new validator object. * * @param string|string[] $variables * * @return \Dotenv\Validator */ public function required($variables) { return (new Validator($this->repository, (array) $variables))->required(); } /** * Returns a new validator object that won't check if the specified variables exist. * * @param string|string[] $variables * * @return \Dotenv\Validator */ public function ifPresent($variables) { return new Validator($this->repository, (array) $variables); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Validator.php
src/Validator.php
<?php declare(strict_types=1); namespace Dotenv; use Dotenv\Exception\ValidationException; use Dotenv\Repository\RepositoryInterface; use Dotenv\Util\Regex; use Dotenv\Util\Str; class Validator { /** * The environment repository instance. * * @var \Dotenv\Repository\RepositoryInterface */ private $repository; /** * The variables to validate. * * @var string[] */ private $variables; /** * Create a new validator instance. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string[] $variables * * @return void */ public function __construct(RepositoryInterface $repository, array $variables) { $this->repository = $repository; $this->variables = $variables; } /** * Assert that each variable is present. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function required() { return $this->assert( static function (?string $value) { return $value !== null; }, 'is missing' ); } /** * Assert that each variable is not empty. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function notEmpty() { return $this->assertNullable( static function (string $value) { return Str::len(\trim($value)) > 0; }, 'is empty' ); } /** * Assert that each specified variable is an integer. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function isInteger() { return $this->assertNullable( static function (string $value) { return \ctype_digit($value); }, 'is not an integer' ); } /** * Assert that each specified variable is a boolean. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function isBoolean() { return $this->assertNullable( static function (string $value) { if ($value === '') { return false; } return \filter_var($value, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) !== null; }, 'is not a boolean' ); } /** * Assert that each variable is amongst the given choices. * * @param string[] $choices * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function allowedValues(array $choices) { return $this->assertNullable( static function (string $value) use ($choices) { return \in_array($value, $choices, true); }, \sprintf('is not one of [%s]', \implode(', ', $choices)) ); } /** * Assert that each variable matches the given regular expression. * * @param string $regex * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function allowedRegexValues(string $regex) { return $this->assertNullable( static function (string $value) use ($regex) { return Regex::matches($regex, $value)->success()->getOrElse(false); }, \sprintf('does not match "%s"', $regex) ); } /** * Assert that the callback returns true for each variable. * * @param callable(?string):bool $callback * @param string $message * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function assert(callable $callback, string $message) { $failing = []; foreach ($this->variables as $variable) { if ($callback($this->repository->get($variable)) === false) { $failing[] = \sprintf('%s %s', $variable, $message); } } if (\count($failing) > 0) { throw new ValidationException(\sprintf( 'One or more environment variables failed assertions: %s.', \implode(', ', $failing) )); } return $this; } /** * Assert that the callback returns true for each variable. * * Skip checking null variable values. * * @param callable(string):bool $callback * @param string $message * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function assertNullable(callable $callback, string $message) { return $this->assert( static function (?string $value) use ($callback) { if ($value === null) { return true; } return $callback($value); }, $message ); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/Value.php
src/Parser/Value.php
<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Str; final class Value { /** * The string representation of the parsed value. * * @var string */ private $chars; /** * The locations of the variables in the value. * * @var int[] */ private $vars; /** * Internal constructor for a value. * * @param string $chars * @param int[] $vars * * @return void */ private function __construct(string $chars, array $vars) { $this->chars = $chars; $this->vars = $vars; } /** * Create an empty value instance. * * @return \Dotenv\Parser\Value */ public static function blank() { return new self('', []); } /** * Create a new value instance, appending the characters. * * @param string $chars * @param bool $var * * @return \Dotenv\Parser\Value */ public function append(string $chars, bool $var) { return new self( $this->chars.$chars, $var ? \array_merge($this->vars, [Str::len($this->chars)]) : $this->vars ); } /** * Get the string representation of the parsed value. * * @return string */ public function getChars() { return $this->chars; } /** * Get the locations of the variables in the value. * * @return int[] */ public function getVars() { $vars = $this->vars; \rsort($vars); return $vars; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/Lexer.php
src/Parser/Lexer.php
<?php declare(strict_types=1); namespace Dotenv\Parser; final class Lexer { /** * The regex for each type of token. */ private const PATTERNS = [ '[\r\n]{1,1000}', '[^\S\r\n]{1,1000}', '\\\\', '\'', '"', '\\#', '\\$', '([^(\s\\\\\'"\\#\\$)]|\\(|\\)){1,1000}', ]; /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Convert content into a token stream. * * Multibyte string processing is not needed here, and nether is error * handling, for performance reasons. * * @param string $content * * @return \Generator<string> */ public static function lex(string $content) { static $regex; if ($regex === null) { $regex = '(('.\implode(')|(', self::PATTERNS).'))A'; } $offset = 0; while (isset($content[$offset])) { if (!\preg_match($regex, $content, $matches, 0, $offset)) { throw new \Error(\sprintf('Lexer encountered unexpected character [%s].', $content[$offset])); } $offset += \strlen($matches[0]); yield $matches[0]; } } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/Parser.php
src/Parser/Parser.php
<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Exception\InvalidFileException; use Dotenv\Util\Regex; use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Success; final class Parser implements ParserInterface { /** * Parse content into an entry array. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return \Dotenv\Parser\Entry[] */ public function parse(string $content) { return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static function () { return 'Could not split into separate lines.'; })->flatMap(static function (array $lines) { return self::process(Lines::process($lines)); })->mapError(static function (string $error) { throw new InvalidFileException(\sprintf('Failed to parse dotenv file. %s', $error)); })->success()->get(); } /** * Convert the raw entries into proper entries. * * @param string[] $entries * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[], string> */ private static function process(array $entries) { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[], string> */ return \array_reduce($entries, static function (Result $result, string $raw) { return $result->flatMap(static function (array $entries) use ($raw) { return EntryParser::parse($raw)->map(static function (Entry $entry) use ($entries) { /** @var \Dotenv\Parser\Entry[] */ return \array_merge($entries, [$entry]); }); }); }, Success::create([])); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/Lines.php
src/Parser/Lines.php
<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Regex; use Dotenv\Util\Str; final class Lines { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Process the array of lines of environment variables. * * This will produce an array of raw entries, one per variable. * * @param string[] $lines * * @return string[] */ public static function process(array $lines) { $output = []; $multiline = false; $multilineBuffer = []; foreach ($lines as $line) { [$multiline, $line, $multilineBuffer] = self::multilineProcess($multiline, $line, $multilineBuffer); if (!$multiline && !self::isCommentOrWhitespace($line)) { $output[] = $line; } } return $output; } /** * Used to make all multiline variable process. * * @param bool $multiline * @param string $line * @param string[] $buffer * * @return array{bool,string, string[]} */ private static function multilineProcess(bool $multiline, string $line, array $buffer) { $startsOnCurrentLine = $multiline ? false : self::looksLikeMultilineStart($line); // check if $line can be multiline variable if ($startsOnCurrentLine) { $multiline = true; } if ($multiline) { \array_push($buffer, $line); if (self::looksLikeMultilineStop($line, $startsOnCurrentLine)) { $multiline = false; $line = \implode("\n", $buffer); $buffer = []; } } return [$multiline, $line, $buffer]; } /** * Determine if the given line can be the start of a multiline variable. * * @param string $line * * @return bool */ private static function looksLikeMultilineStart(string $line) { return Str::pos($line, '="')->map(static function () use ($line) { return self::looksLikeMultilineStop($line, true) === false; })->getOrElse(false); } /** * Determine if the given line can be the start of a multiline variable. * * @param string $line * @param bool $started * * @return bool */ private static function looksLikeMultilineStop(string $line, bool $started) { if ($line === '"') { return true; } return Regex::occurrences('/(?=([^\\\\]"))/', \str_replace('\\\\', '', $line))->map(static function (int $count) use ($started) { return $started ? $count > 1 : $count >= 1; })->success()->getOrElse(false); } /** * Determine if the line in the file is a comment or whitespace. * * @param string $line * * @return bool */ private static function isCommentOrWhitespace(string $line) { $line = \trim($line); return $line === '' || (isset($line[0]) && $line[0] === '#'); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/ParserInterface.php
src/Parser/ParserInterface.php
<?php declare(strict_types=1); namespace Dotenv\Parser; interface ParserInterface { /** * Parse content into an entry array. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return \Dotenv\Parser\Entry[] */ public function parse(string $content); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/Entry.php
src/Parser/Entry.php
<?php declare(strict_types=1); namespace Dotenv\Parser; use PhpOption\Option; final class Entry { /** * The entry name. * * @var string */ private $name; /** * The entry value. * * @var \Dotenv\Parser\Value|null */ private $value; /** * Create a new entry instance. * * @param string $name * @param \Dotenv\Parser\Value|null $value * * @return void */ public function __construct(string $name, ?Value $value = null) { $this->name = $name; $this->value = $value; } /** * Get the entry name. * * @return string */ public function getName() { return $this->name; } /** * Get the entry value. * * @return \PhpOption\Option<\Dotenv\Parser\Value> */ public function getValue() { /** @var \PhpOption\Option<\Dotenv\Parser\Value> */ return Option::fromValue($this->value); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Parser/EntryParser.php
src/Parser/EntryParser.php
<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Regex; use Dotenv\Util\Str; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Success; final class EntryParser { private const INITIAL_STATE = 0; private const UNQUOTED_STATE = 1; private const SINGLE_QUOTED_STATE = 2; private const DOUBLE_QUOTED_STATE = 3; private const ESCAPE_SEQUENCE_STATE = 4; private const WHITESPACE_STATE = 5; private const COMMENT_STATE = 6; private const REJECT_STATES = [self::SINGLE_QUOTED_STATE, self::DOUBLE_QUOTED_STATE, self::ESCAPE_SEQUENCE_STATE]; /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Parse a raw entry into a proper entry. * * That is, turn a raw environment variable entry into a name and possibly * a value. We wrap the answer in a result type. * * @param string $entry * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry, string> */ public static function parse(string $entry) { return self::splitStringIntoParts($entry)->flatMap(static function (array $parts) { [$name, $value] = $parts; return self::parseName($name)->flatMap(static function (string $name) use ($value) { /** @var Result<Value|null, string> */ $parsedValue = $value === null ? Success::create(null) : self::parseValue($value); return $parsedValue->map(static function (?Value $value) use ($name) { return new Entry($name, $value); }); }); }); } /** * Split the compound string into parts. * * @param string $line * * @return \GrahamCampbell\ResultType\Result<array{string, string|null},string> */ private static function splitStringIntoParts(string $line) { /** @var array{string, string|null} */ $result = Str::pos($line, '=')->map(static function () use ($line) { return \array_map('trim', \explode('=', $line, 2)); })->getOrElse([$line, null]); if ($result[0] === '') { /** @var \GrahamCampbell\ResultType\Result<array{string, string|null},string> */ return Error::create(self::getErrorMessage('an unexpected equals', $line)); } /** @var \GrahamCampbell\ResultType\Result<array{string, string|null},string> */ return Success::create($result); } /** * Parse the given variable name. * * That is, strip the optional quotes and leading "export" from the * variable name. We wrap the answer in a result type. * * @param string $name * * @return \GrahamCampbell\ResultType\Result<string, string> */ private static function parseName(string $name) { if (Str::len($name) > 8 && Str::substr($name, 0, 6) === 'export' && \ctype_space(Str::substr($name, 6, 1))) { $name = \ltrim(Str::substr($name, 6)); } if (self::isQuotedName($name)) { $name = Str::substr($name, 1, -1); } if (!self::isValidName($name)) { /** @var \GrahamCampbell\ResultType\Result<string, string> */ return Error::create(self::getErrorMessage('an invalid name', $name)); } /** @var \GrahamCampbell\ResultType\Result<string, string> */ return Success::create($name); } /** * Is the given variable name quoted? * * @param string $name * * @return bool */ private static function isQuotedName(string $name) { if (Str::len($name) < 3) { return false; } $first = Str::substr($name, 0, 1); $last = Str::substr($name, -1, 1); return ($first === '"' && $last === '"') || ($first === '\'' && $last === '\''); } /** * Is the given variable name valid? * * @param string $name * * @return bool */ private static function isValidName(string $name) { return Regex::matches('~(*UTF8)\A[\p{Ll}\p{Lu}\p{M}\p{N}_.]+\z~', $name)->success()->getOrElse(false); } /** * Parse the given variable value. * * This has the effect of stripping quotes and comments, dealing with * special characters, and locating nested variables, but not resolving * them. Formally, we run a finite state automaton with an output tape: a * transducer. We wrap the answer in a result type. * * @param string $value * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value, string> */ private static function parseValue(string $value) { if (\trim($value) === '') { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value, string> */ return Success::create(Value::blank()); } return \array_reduce(\iterator_to_array(Lexer::lex($value)), static function (Result $data, string $token) { return $data->flatMap(static function (array $data) use ($token) { return self::processToken($data[1], $token)->map(static function (array $val) use ($data) { return [$data[0]->append($val[0], $val[1]), $val[2]]; }); }); }, Success::create([Value::blank(), self::INITIAL_STATE]))->flatMap(static function (array $result) { if (in_array($result[1], self::REJECT_STATES, true)) { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value, string> */ return Error::create('a missing closing quote'); } /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value, string> */ return Success::create($result[0]); })->mapError(static function (string $err) use ($value) { return self::getErrorMessage($err, $value); }); } /** * Process the given token. * * @param int $state * @param string $token * * @return \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ private static function processToken(int $state, string $token) { switch ($state) { case self::INITIAL_STATE: if ($token === '\'') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::SINGLE_QUOTED_STATE]); } elseif ($token === '"') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::DOUBLE_QUOTED_STATE]); } elseif ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, true, self::UNQUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::UNQUOTED_STATE]); } case self::UNQUOTED_STATE: if ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif (\ctype_space($token)) { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, true, self::UNQUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::UNQUOTED_STATE]); } case self::SINGLE_QUOTED_STATE: if ($token === '\'') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::SINGLE_QUOTED_STATE]); } case self::DOUBLE_QUOTED_STATE: if ($token === '"') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } elseif ($token === '\\') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::ESCAPE_SEQUENCE_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, true, self::DOUBLE_QUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } case self::ESCAPE_SEQUENCE_STATE: if ($token === '"' || $token === '\\') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } else { $first = Str::substr($token, 0, 1); if (\in_array($first, ['f', 'n', 'r', 't', 'v'], true)) { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create([\stripcslashes('\\'.$first).Str::substr($token, 1), false, self::DOUBLE_QUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Error::create('an unexpected escape sequence'); } } case self::WHITESPACE_STATE: if ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif (!\ctype_space($token)) { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Error::create('unexpected whitespace'); } else { /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } case self::COMMENT_STATE: /** @var \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> */ return Success::create(['', false, self::COMMENT_STATE]); default: throw new \Error('Parser entered invalid state.'); } } /** * Generate a friendly error message. * * @param string $cause * @param string $subject * * @return string */ private static function getErrorMessage(string $cause, string $subject) { return \sprintf( 'Encountered %s at [%s].', $cause, \strtok($subject, "\n") ); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Util/Regex.php
src/Util/Regex.php
<?php declare(strict_types=1); namespace Dotenv\Util; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Success; /** * @internal */ final class Regex { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Perform a preg match, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<bool, string> */ public static function matches(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { return @\preg_match($pattern, $subject) === 1; }, $subject); } /** * Perform a preg match all, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<int, string> */ public static function occurrences(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { return (int) @\preg_match_all($pattern, $subject); }, $subject); } /** * Perform a preg replace callback, wrapping up the result. * * @param string $pattern * @param callable(string[]): string $callback * @param string $subject * @param int|null $limit * * @return \GrahamCampbell\ResultType\Result<string, string> */ public static function replaceCallback(string $pattern, callable $callback, string $subject, ?int $limit = null) { return self::pregAndWrap(static function (string $subject) use ($pattern, $callback, $limit) { return (string) @\preg_replace_callback($pattern, $callback, $subject, $limit ?? -1); }, $subject); } /** * Perform a preg split, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<string[], string> */ public static function split(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { /** @var string[] */ return (array) @\preg_split($pattern, $subject); }, $subject); } /** * Perform a preg operation, wrapping up the result. * * @template V * * @param callable(string): V $operation * @param string $subject * * @return \GrahamCampbell\ResultType\Result<V, string> */ private static function pregAndWrap(callable $operation, string $subject) { $result = $operation($subject); if (\preg_last_error() !== \PREG_NO_ERROR) { /** @var \GrahamCampbell\ResultType\Result<V,string> */ return Error::create(\preg_last_error_msg()); } /** @var \GrahamCampbell\ResultType\Result<V,string> */ return Success::create($result); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Util/Str.php
src/Util/Str.php
<?php declare(strict_types=1); namespace Dotenv\Util; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Success; use PhpOption\Option; /** * @internal */ final class Str { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Convert a string to UTF-8 from the given encoding. * * @param string $input * @param string|null $encoding * * @return \GrahamCampbell\ResultType\Result<string, string> */ public static function utf8(string $input, ?string $encoding = null) { if ($encoding !== null && !\in_array($encoding, \mb_list_encodings(), true)) { /** @var \GrahamCampbell\ResultType\Result<string, string> */ return Error::create( \sprintf('Illegal character encoding [%s] specified.', $encoding) ); } $converted = $encoding === null ? @\mb_convert_encoding($input, 'UTF-8') : @\mb_convert_encoding($input, 'UTF-8', $encoding); if (!is_string($converted)) { /** @var \GrahamCampbell\ResultType\Result<string, string> */ return Error::create( \sprintf('Conversion from encoding [%s] failed.', $encoding ?? 'NULL') ); } /** * this is for support UTF-8 with BOM encoding * @see https://en.wikipedia.org/wiki/Byte_order_mark * @see https://github.com/vlucas/phpdotenv/issues/500 */ if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") { $converted = \substr($converted, 3); } /** @var \GrahamCampbell\ResultType\Result<string, string> */ return Success::create($converted); } /** * Search for a given substring of the input. * * @param string $haystack * @param string $needle * * @return \PhpOption\Option<int> */ public static function pos(string $haystack, string $needle) { /** @var \PhpOption\Option<int> */ return Option::fromValue(\mb_strpos($haystack, $needle, 0, 'UTF-8'), false); } /** * Grab the specified substring of the input. * * @param string $input * @param int $start * @param int|null $length * * @return string */ public static function substr(string $input, int $start, ?int $length = null) { return \mb_substr($input, $start, $length, 'UTF-8'); } /** * Compute the length of the given string. * * @param string $input * * @return int */ public static function len(string $input) { return \mb_strlen($input, 'UTF-8'); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Exception/InvalidEncodingException.php
src/Exception/InvalidEncodingException.php
<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidEncodingException extends InvalidArgumentException implements ExceptionInterface { // }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Exception/ExceptionInterface.php
src/Exception/ExceptionInterface.php
<?php declare(strict_types=1); namespace Dotenv\Exception; use Throwable; interface ExceptionInterface extends Throwable { // }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Exception/InvalidFileException.php
src/Exception/InvalidFileException.php
<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidFileException extends InvalidArgumentException implements ExceptionInterface { // }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Exception/ValidationException.php
src/Exception/ValidationException.php
<?php declare(strict_types=1); namespace Dotenv\Exception; use RuntimeException; final class ValidationException extends RuntimeException implements ExceptionInterface { // }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Exception/InvalidPathException.php
src/Exception/InvalidPathException.php
<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidPathException extends InvalidArgumentException implements ExceptionInterface { // }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Loader/Loader.php
src/Loader/Loader.php
<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Parser\Entry; use Dotenv\Parser\Value; use Dotenv\Repository\RepositoryInterface; final class Loader implements LoaderInterface { /** * Load the given entries into the repository. * * We'll substitute any nested variables, and send each variable to the * repository, with the effect of actually mutating the environment. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Entry[] $entries * * @return array<string, string|null> */ public function load(RepositoryInterface $repository, array $entries) { /** @var array<string, string|null> */ return \array_reduce($entries, static function (array $vars, Entry $entry) use ($repository) { $name = $entry->getName(); $value = $entry->getValue()->map(static function (Value $value) use ($repository) { return Resolver::resolve($repository, $value); }); if ($value->isDefined()) { $inner = $value->get(); if ($repository->set($name, $inner)) { return \array_merge($vars, [$name => $inner]); } } else { if ($repository->clear($name)) { return \array_merge($vars, [$name => null]); } } return $vars; }, []); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Loader/Resolver.php
src/Loader/Resolver.php
<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Parser\Value; use Dotenv\Repository\RepositoryInterface; use Dotenv\Util\Regex; use Dotenv\Util\Str; use PhpOption\Option; final class Resolver { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Resolve the nested variables in the given value. * * Replaces ${varname} patterns in the allowed positions in the variable * value by an existing environment variable. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Value $value * * @return string */ public static function resolve(RepositoryInterface $repository, Value $value) { return \array_reduce($value->getVars(), static function (string $s, int $i) use ($repository) { return Str::substr($s, 0, $i).self::resolveVariable($repository, Str::substr($s, $i)); }, $value->getChars()); } /** * Resolve a single nested variable. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string $str * * @return string */ private static function resolveVariable(RepositoryInterface $repository, string $str) { return Regex::replaceCallback( '/\A\${([a-zA-Z0-9_.]+)}/', static function (array $matches) use ($repository) { /** @var string */ return Option::fromValue($repository->get($matches[1]))->getOrElse($matches[0]); }, $str, 1 )->success()->getOrElse($str); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Loader/LoaderInterface.php
src/Loader/LoaderInterface.php
<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Repository\RepositoryInterface; interface LoaderInterface { /** * Load the given entries into the repository. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Entry[] $entries * * @return array<string, string|null> */ public function load(RepositoryInterface $repository, array $entries); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/StoreBuilder.php
src/Store/StoreBuilder.php
<?php declare(strict_types=1); namespace Dotenv\Store; use Dotenv\Store\File\Paths; final class StoreBuilder { /** * The of default name. */ private const DEFAULT_NAME = '.env'; /** * The paths to search within. * * @var string[] */ private $paths; /** * The file names to search for. * * @var string[] */ private $names; /** * Should file loading short circuit? * * @var bool */ private $shortCircuit; /** * The file encoding. * * @var string|null */ private $fileEncoding; /** * Create a new store builder instance. * * @param string[] $paths * @param string[] $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return void */ private function __construct(array $paths = [], array $names = [], bool $shortCircuit = false, ?string $fileEncoding = null) { $this->paths = $paths; $this->names = $names; $this->shortCircuit = $shortCircuit; $this->fileEncoding = $fileEncoding; } /** * Create a new store builder instance with no names. * * @return \Dotenv\Store\StoreBuilder */ public static function createWithNoNames() { return new self(); } /** * Create a new store builder instance with the default name. * * @return \Dotenv\Store\StoreBuilder */ public static function createWithDefaultName() { return new self([], [self::DEFAULT_NAME]); } /** * Creates a store builder with the given path added. * * @param string $path * * @return \Dotenv\Store\StoreBuilder */ public function addPath(string $path) { return new self(\array_merge($this->paths, [$path]), $this->names, $this->shortCircuit, $this->fileEncoding); } /** * Creates a store builder with the given name added. * * @param string $name * * @return \Dotenv\Store\StoreBuilder */ public function addName(string $name) { return new self($this->paths, \array_merge($this->names, [$name]), $this->shortCircuit, $this->fileEncoding); } /** * Creates a store builder with short circuit mode enabled. * * @return \Dotenv\Store\StoreBuilder */ public function shortCircuit() { return new self($this->paths, $this->names, true, $this->fileEncoding); } /** * Creates a store builder with the specified file encoding. * * @param string|null $fileEncoding * * @return \Dotenv\Store\StoreBuilder */ public function fileEncoding(?string $fileEncoding = null) { return new self($this->paths, $this->names, $this->shortCircuit, $fileEncoding); } /** * Creates a new store instance. * * @return \Dotenv\Store\StoreInterface */ public function make() { return new FileStore( Paths::filePaths($this->paths, $this->names), $this->shortCircuit, $this->fileEncoding ); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/StoreInterface.php
src/Store/StoreInterface.php
<?php declare(strict_types=1); namespace Dotenv\Store; interface StoreInterface { /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException * * @return string */ public function read(); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/FileStore.php
src/Store/FileStore.php
<?php declare(strict_types=1); namespace Dotenv\Store; use Dotenv\Exception\InvalidPathException; use Dotenv\Store\File\Reader; final class FileStore implements StoreInterface { /** * The file paths. * * @var string[] */ private $filePaths; /** * Should file loading short circuit? * * @var bool */ private $shortCircuit; /** * The file encoding. * * @var string|null */ private $fileEncoding; /** * Create a new file store instance. * * @param string[] $filePaths * @param bool $shortCircuit * @param string|null $fileEncoding * * @return void */ public function __construct(array $filePaths, bool $shortCircuit, ?string $fileEncoding = null) { $this->filePaths = $filePaths; $this->shortCircuit = $shortCircuit; $this->fileEncoding = $fileEncoding; } /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException * * @return string */ public function read() { if ($this->filePaths === []) { throw new InvalidPathException('At least one environment file path must be provided.'); } $contents = Reader::read($this->filePaths, $this->shortCircuit, $this->fileEncoding); if (\count($contents) > 0) { return \implode("\n", $contents); } throw new InvalidPathException( \sprintf('Unable to read any of the environment file(s) at [%s].', \implode(', ', $this->filePaths)) ); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/StringStore.php
src/Store/StringStore.php
<?php declare(strict_types=1); namespace Dotenv\Store; final class StringStore implements StoreInterface { /** * The file content. * * @var string */ private $content; /** * Create a new string store instance. * * @param string $content * * @return void */ public function __construct(string $content) { $this->content = $content; } /** * Read the content of the environment file(s). * * @return string */ public function read() { return $this->content; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/File/Reader.php
src/Store/File/Reader.php
<?php declare(strict_types=1); namespace Dotenv\Store\File; use Dotenv\Exception\InvalidEncodingException; use Dotenv\Util\Str; use PhpOption\Option; /** * @internal */ final class Reader { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Read the file(s), and return their raw content. * * We provide the file path as the key, and its content as the value. If * short circuit mode is enabled, then the returned array with have length * at most one. File paths that couldn't be read are omitted entirely. * * @param string[] $filePaths * @param bool $shortCircuit * @param string|null $fileEncoding * * @throws \Dotenv\Exception\InvalidEncodingException * * @return array<string, string> */ public static function read(array $filePaths, bool $shortCircuit = true, ?string $fileEncoding = null) { $output = []; foreach ($filePaths as $filePath) { $content = self::readFromFile($filePath, $fileEncoding); if ($content->isDefined()) { $output[$filePath] = $content->get(); if ($shortCircuit) { break; } } } return $output; } /** * Read the given file. * * @param string $path * @param string|null $encoding * * @throws \Dotenv\Exception\InvalidEncodingException * * @return \PhpOption\Option<string> */ private static function readFromFile(string $path, ?string $encoding = null) { /** @var Option<string> */ $content = Option::fromValue(@\file_get_contents($path), false); return $content->flatMap(static function (string $content) use ($encoding) { return Str::utf8($content, $encoding)->mapError(static function (string $error) { throw new InvalidEncodingException($error); })->success(); }); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Store/File/Paths.php
src/Store/File/Paths.php
<?php declare(strict_types=1); namespace Dotenv\Store\File; /** * @internal */ final class Paths { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Returns the full paths to the files. * * @param string[] $paths * @param string[] $names * * @return string[] */ public static function filePaths(array $paths, array $names) { $files = []; foreach ($paths as $path) { foreach ($names as $name) { $files[] = \rtrim($path, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.$name; } } return $files; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/RepositoryBuilder.php
src/Repository/RepositoryBuilder.php
<?php declare(strict_types=1); namespace Dotenv\Repository; use Dotenv\Repository\Adapter\AdapterInterface; use Dotenv\Repository\Adapter\EnvConstAdapter; use Dotenv\Repository\Adapter\GuardedWriter; use Dotenv\Repository\Adapter\ImmutableWriter; use Dotenv\Repository\Adapter\MultiReader; use Dotenv\Repository\Adapter\MultiWriter; use Dotenv\Repository\Adapter\ReaderInterface; use Dotenv\Repository\Adapter\ServerConstAdapter; use Dotenv\Repository\Adapter\WriterInterface; use InvalidArgumentException; use PhpOption\Some; use ReflectionClass; final class RepositoryBuilder { /** * The set of default adapters. */ private const DEFAULT_ADAPTERS = [ ServerConstAdapter::class, EnvConstAdapter::class, ]; /** * The set of readers to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface[] */ private $readers; /** * The set of writers to use. * * @var \Dotenv\Repository\Adapter\WriterInterface[] */ private $writers; /** * Are we immutable? * * @var bool */ private $immutable; /** * The variable name allow list. * * @var string[]|null */ private $allowList; /** * Create a new repository builder instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers * @param bool $immutable * @param string[]|null $allowList * * @return void */ private function __construct(array $readers = [], array $writers = [], bool $immutable = false, ?array $allowList = null) { $this->readers = $readers; $this->writers = $writers; $this->immutable = $immutable; $this->allowList = $allowList; } /** * Create a new repository builder instance with no adapters added. * * @return \Dotenv\Repository\RepositoryBuilder */ public static function createWithNoAdapters() { return new self(); } /** * Create a new repository builder instance with the default adapters added. * * @return \Dotenv\Repository\RepositoryBuilder */ public static function createWithDefaultAdapters() { $adapters = \iterator_to_array(self::defaultAdapters()); return new self($adapters, $adapters); } /** * Return the array of default adapters. * * @return \Generator<\Dotenv\Repository\Adapter\AdapterInterface> */ private static function defaultAdapters() { foreach (self::DEFAULT_ADAPTERS as $adapter) { $instance = $adapter::create(); if ($instance->isDefined()) { yield $instance->get(); } } } /** * Determine if the given name if of an adapterclass. * * @param string $name * * @return bool */ private static function isAnAdapterClass(string $name) { if (!\class_exists($name)) { return false; } return (new ReflectionClass($name))->implementsInterface(AdapterInterface::class); } /** * Creates a repository builder with the given reader added. * * Accepts either a reader instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. * * @param \Dotenv\Repository\Adapter\ReaderInterface|string $reader * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addReader($reader) { if (!(\is_string($reader) && self::isAnAdapterClass($reader)) && !($reader instanceof ReaderInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', ReaderInterface::class, AdapterInterface::class ) ); } $optional = Some::create($reader)->flatMap(static function ($reader) { return \is_string($reader) ? $reader::create() : Some::create($reader); }); $readers = \array_merge($this->readers, \iterator_to_array($optional)); return new self($readers, $this->writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with the given writer added. * * Accepts either a writer instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. * * @param \Dotenv\Repository\Adapter\WriterInterface|string $writer * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addWriter($writer) { if (!(\is_string($writer) && self::isAnAdapterClass($writer)) && !($writer instanceof WriterInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', WriterInterface::class, AdapterInterface::class ) ); } $optional = Some::create($writer)->flatMap(static function ($writer) { return \is_string($writer) ? $writer::create() : Some::create($writer); }); $writers = \array_merge($this->writers, \iterator_to_array($optional)); return new self($this->readers, $writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with the given adapter added. * * Accepts either an adapter instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. We will * add the adapter as both a reader and a writer. * * @param \Dotenv\Repository\Adapter\WriterInterface|string $adapter * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addAdapter($adapter) { if (!(\is_string($adapter) && self::isAnAdapterClass($adapter)) && !($adapter instanceof AdapterInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', WriterInterface::class, AdapterInterface::class ) ); } $optional = Some::create($adapter)->flatMap(static function ($adapter) { return \is_string($adapter) ? $adapter::create() : Some::create($adapter); }); $readers = \array_merge($this->readers, \iterator_to_array($optional)); $writers = \array_merge($this->writers, \iterator_to_array($optional)); return new self($readers, $writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with mutability enabled. * * @return \Dotenv\Repository\RepositoryBuilder */ public function immutable() { return new self($this->readers, $this->writers, true, $this->allowList); } /** * Creates a repository builder with the given allow list. * * @param string[]|null $allowList * * @return \Dotenv\Repository\RepositoryBuilder */ public function allowList(?array $allowList = null) { return new self($this->readers, $this->writers, $this->immutable, $allowList); } /** * Creates a new repository instance. * * @return \Dotenv\Repository\RepositoryInterface */ public function make() { $reader = new MultiReader($this->readers); $writer = new MultiWriter($this->writers); if ($this->immutable) { $writer = new ImmutableWriter($writer, $reader); } if ($this->allowList !== null) { $writer = new GuardedWriter($writer, $this->allowList); } return new AdapterRepository($reader, $writer); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/RepositoryInterface.php
src/Repository/RepositoryInterface.php
<?php declare(strict_types=1); namespace Dotenv\Repository; interface RepositoryInterface { /** * Determine if the given environment variable is defined. * * @param string $name * * @return bool */ public function has(string $name); /** * Get an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return string|null */ public function get(string $name); /** * Set an environment variable. * * @param string $name * @param string $value * * @throws \InvalidArgumentException * * @return bool */ public function set(string $name, string $value); /** * Clear an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return bool */ public function clear(string $name); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/AdapterRepository.php
src/Repository/AdapterRepository.php
<?php declare(strict_types=1); namespace Dotenv\Repository; use Dotenv\Repository\Adapter\ReaderInterface; use Dotenv\Repository\Adapter\WriterInterface; use InvalidArgumentException; final class AdapterRepository implements RepositoryInterface { /** * The reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * Create a new adapter repository instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * @param \Dotenv\Repository\Adapter\WriterInterface $writer * * @return void */ public function __construct(ReaderInterface $reader, WriterInterface $writer) { $this->reader = $reader; $this->writer = $writer; } /** * Determine if the given environment variable is defined. * * @param string $name * * @return bool */ public function has(string $name) { return '' !== $name && $this->reader->read($name)->isDefined(); } /** * Get an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return string|null */ public function get(string $name) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->reader->read($name)->getOrElse(null); } /** * Set an environment variable. * * @param string $name * @param string $value * * @throws \InvalidArgumentException * * @return bool */ public function set(string $name, string $value) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->writer->write($name, $value); } /** * Clear an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return bool */ public function clear(string $name) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->writer->delete($name); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ImmutableWriter.php
src/Repository/Adapter/ImmutableWriter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class ImmutableWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The inner reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The record of loaded variables. * * @var array<string, string> */ private $loaded; /** * Create a new immutable writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * * @return void */ public function __construct(WriterInterface $writer, ReaderInterface $reader) { $this->writer = $writer; $this->reader = $reader; $this->loaded = []; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { // Don't overwrite existing environment variables // Ruby's dotenv does this with `ENV[key] ||= value` if ($this->isExternallyDefined($name)) { return false; } // Set the value on the inner writer if (!$this->writer->write($name, $value)) { return false; } // Record that we have loaded the variable $this->loaded[$name] = ''; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { // Don't clear existing environment variables if ($this->isExternallyDefined($name)) { return false; } // Clear the value on the inner writer if (!$this->writer->delete($name)) { return false; } // Leave the variable as fair game unset($this->loaded[$name]); return true; } /** * Determine if the given variable is externally defined. * * That is, is it an "existing" variable. * * @param non-empty-string $name * * @return bool */ private function isExternallyDefined(string $name) { return $this->reader->read($name)->isDefined() && !isset($this->loaded[$name]); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ReplacingWriter.php
src/Repository/Adapter/ReplacingWriter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class ReplacingWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The inner reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The record of seen variables. * * @var array<string, string> */ private $seen; /** * Create a new replacement writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * * @return void */ public function __construct(WriterInterface $writer, ReaderInterface $reader) { $this->writer = $writer; $this->reader = $reader; $this->seen = []; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { if ($this->exists($name)) { return $this->writer->write($name, $value); } // succeed if nothing to do return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { if ($this->exists($name)) { return $this->writer->delete($name); } // succeed if nothing to do return true; } /** * Does the given environment variable exist. * * Returns true if it currently exists, or existed at any point in the past * that we are aware of. * * @param non-empty-string $name * * @return bool */ private function exists(string $name) { if (isset($this->seen[$name])) { return true; } if ($this->reader->read($name)->isDefined()) { $this->seen[$name] = ''; return true; } return false; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/PutenvAdapter.php
src/Repository/Adapter/PutenvAdapter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; final class PutenvAdapter implements AdapterInterface { /** * Create a new putenv adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { if (self::isSupported()) { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } return None::create(); } /** * Determines if the adapter is supported. * * @return bool */ private static function isSupported() { return \function_exists('getenv') && \function_exists('putenv'); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromValue(\getenv($name), false)->filter(static function ($value) { return \is_string($value); }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { \putenv("$name=$value"); return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { \putenv($name); return true; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false