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/WhitespacePathNormalizerTest.php | src/WhitespacePathNormalizerTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use PHPUnit\Framework\TestCase;
class WhitespacePathNormalizerTest extends TestCase
{
/**
* @var WhitespacePathNormalizer
*/
private $normalizer;
protected function setUp(): void
{
$this->normalizer = new WhitespacePathNormalizer();
}
/**
* @test
*
* @dataProvider pathProvider
*/
public function path_normalizing(string $input, string $expected): void
{
$result = $this->normalizer->normalizePath($input);
$double = $this->normalizer->normalizePath($this->normalizer->normalizePath($input));
$this->assertEquals($expected, $result);
$this->assertEquals($expected, $double);
}
/**
* @return array<array<string>>
*/
public static function pathProvider(): array
{
return [
['.', ''],
['/path/to/dir/.', 'path/to/dir'],
['/dirname/', 'dirname'],
['dirname/..', ''],
['dirname/../', ''],
['dirname./', 'dirname.'],
['dirname/./', 'dirname'],
['dirname/.', 'dirname'],
['./dir/../././', ''],
['/something/deep/../../dirname', 'dirname'],
['00004869/files/other/10-75..stl', '00004869/files/other/10-75..stl'],
['/dirname//subdir///subsubdir', 'dirname/subdir/subsubdir'],
['\dirname\\\\subdir\\\\\\subsubdir', 'dirname/subdir/subsubdir'],
['\\\\some\shared\\\\drive', 'some/shared/drive'],
['C:\dirname\\\\subdir\\\\\\subsubdir', 'C:/dirname/subdir/subsubdir'],
['C:\\\\dirname\subdir\\\\subsubdir', 'C:/dirname/subdir/subsubdir'],
['example/path/..txt', 'example/path/..txt'],
['\\example\\path.txt', 'example/path.txt'],
['\\example\\..\\path.txt', 'path.txt'],
];
}
/**
* @test
*
* @dataProvider invalidPathProvider
*/
public function guarding_against_path_traversal(string $input): void
{
$this->expectException(PathTraversalDetected::class);
$this->normalizer->normalizePath($input);
}
/**
* @test
*
* @dataProvider dpFunkyWhitespacePaths
*/
public function rejecting_funky_whitespace(string $path): void
{
self::expectException(CorruptedPathDetected::class);
$this->normalizer->normalizePath($path);
}
public static function dpFunkyWhitespacePaths(): iterable
{
return [["some\0/path.txt"], ["s\x09i.php"]];
}
/**
* @return array<array<string>>
*/
public static function invalidPathProvider(): array
{
return [
['something/../../../hehe'],
['/something/../../..'],
['..'],
['something\\..\\..'],
['\\something\\..\\..\\dirname'],
];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToGenerateTemporaryUrl.php | src/UnableToGenerateTemporaryUrl.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToGenerateTemporaryUrl extends RuntimeException implements FilesystemException
{
public function __construct(string $reason, string $path, ?Throwable $previous = null)
{
parent::__construct("Unable to generate temporary url for $path: $reason", 0, $previous);
}
public static function dueToError(string $path, Throwable $exception): static
{
return new static($exception->getMessage(), $path, $exception);
}
public static function noGeneratorConfigured(string $path, string $extraReason = ''): static
{
return new static('No generator was configured ' . $extraReason, $path);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/WhitespacePathNormalizer.php | src/WhitespacePathNormalizer.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
class WhitespacePathNormalizer implements PathNormalizer
{
public function normalizePath(string $path): string
{
$path = str_replace('\\', '/', $path);
$this->rejectFunkyWhiteSpace($path);
return $this->normalizeRelativePath($path);
}
private function rejectFunkyWhiteSpace(string $path): void
{
if (preg_match('#\p{C}+#u', $path)) {
throw CorruptedPathDetected::forPath($path);
}
}
private function normalizeRelativePath(string $path): string
{
$parts = [];
foreach (explode('/', $path) as $part) {
switch ($part) {
case '':
case '.':
break;
case '..':
if (empty($parts)) {
throw PathTraversalDetected::forPath($path);
}
array_pop($parts);
break;
default:
$parts[] = $part;
break;
}
}
return implode('/', $parts);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToDeleteDirectory.php | src/UnableToDeleteDirectory.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToDeleteDirectory extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location = '';
/**
* @var string
*/
private $reason;
public static function atLocation(
string $location,
string $reason = '',
?Throwable $previous = null
): UnableToDeleteDirectory {
$e = new static(rtrim("Unable to delete directory located at: {$location}. {$reason}"), 0, $previous);
$e->location = $location;
$e->reason = $reason;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_DELETE_DIRECTORY;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/DirectoryListing.php | src/DirectoryListing.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use ArrayIterator;
use Generator;
use IteratorAggregate;
use Traversable;
/**
* @template T
*/
class DirectoryListing implements IteratorAggregate
{
/**
* @param iterable<T> $listing
*/
public function __construct(private iterable $listing)
{
}
/**
* @param callable(T): bool $filter
*
* @return DirectoryListing<T>
*/
public function filter(callable $filter): DirectoryListing
{
$generator = (static function (iterable $listing) use ($filter): Generator {
foreach ($listing as $item) {
if ($filter($item)) {
yield $item;
}
}
})($this->listing);
return new DirectoryListing($generator);
}
/**
* @template R
*
* @param callable(T): R $mapper
*
* @return DirectoryListing<R>
*/
public function map(callable $mapper): DirectoryListing
{
$generator = (static function (iterable $listing) use ($mapper): Generator {
foreach ($listing as $item) {
yield $mapper($item);
}
})($this->listing);
return new DirectoryListing($generator);
}
/**
* @return DirectoryListing<T>
*/
public function sortByPath(): DirectoryListing
{
$listing = $this->toArray();
usort($listing, function (StorageAttributes $a, StorageAttributes $b) {
return $a->path() <=> $b->path();
});
return new DirectoryListing($listing);
}
/**
* @return Traversable<T>
*/
public function getIterator(): Traversable
{
return $this->listing instanceof Traversable
? $this->listing
: new ArrayIterator($this->listing);
}
/**
* @return T[]
*/
public function toArray(): array
{
return $this->listing instanceof Traversable
? iterator_to_array($this->listing, false)
: (array) $this->listing;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/StorageAttributes.php | src/StorageAttributes.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use ArrayAccess;
use JsonSerializable;
interface StorageAttributes extends JsonSerializable, ArrayAccess
{
public const ATTRIBUTE_PATH = 'path';
public const ATTRIBUTE_TYPE = 'type';
public const ATTRIBUTE_FILE_SIZE = 'file_size';
public const ATTRIBUTE_VISIBILITY = 'visibility';
public const ATTRIBUTE_LAST_MODIFIED = 'last_modified';
public const ATTRIBUTE_MIME_TYPE = 'mime_type';
public const ATTRIBUTE_EXTRA_METADATA = 'extra_metadata';
public const TYPE_FILE = 'file';
public const TYPE_DIRECTORY = 'dir';
public function path(): string;
public function type(): string;
public function visibility(): ?string;
public function lastModified(): ?int;
public static function fromArray(array $attributes): StorageAttributes;
public function isFile(): bool;
public function isDir(): bool;
public function withPath(string $path): StorageAttributes;
public function extraMetadata(): array;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToMoveFile.php | src/UnableToMoveFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToMoveFile extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $source;
/**
* @var string
*/
private $destination;
public static function sourceAndDestinationAreTheSame(string $source, string $destination): UnableToMoveFile
{
return UnableToMoveFile::because('Source and destination are the same', $source, $destination);
}
public function source(): string
{
return $this->source;
}
public function destination(): string
{
return $this->destination;
}
public static function fromLocationTo(
string $sourcePath,
string $destinationPath,
?Throwable $previous = null
): UnableToMoveFile {
$message = $previous?->getMessage() ?? "Unable to move file from $sourcePath to $destinationPath";
$e = new static($message, 0, $previous);
$e->source = $sourcePath;
$e->destination = $destinationPath;
return $e;
}
public static function because(
string $reason,
string $sourcePath,
string $destinationPath,
): UnableToMoveFile {
$message = "Unable to move file from $sourcePath to $destinationPath, because $reason";
$e = new static($message);
$e->source = $sourcePath;
$e->destination = $destinationPath;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_MOVE;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToCheckFileExistence.php | src/UnableToCheckFileExistence.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
class UnableToCheckFileExistence extends UnableToCheckExistence
{
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_FILE_EXISTS;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToGeneratePublicUrl.php | src/UnableToGeneratePublicUrl.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToGeneratePublicUrl extends RuntimeException implements FilesystemException
{
public function __construct(string $reason, string $path, ?Throwable $previous = null)
{
parent::__construct("Unable to generate public url for $path: $reason", 0, $previous);
}
public static function dueToError(string $path, Throwable $exception): static
{
return new static($exception->getMessage(), $path, $exception);
}
public static function noGeneratorConfigured(string $path, string $extraReason = ''): static
{
return new static('No generator was configured ' . $extraReason, $path);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ProxyArrayAccessToProperties.php | src/ProxyArrayAccessToProperties.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
/**
* @internal
*/
trait ProxyArrayAccessToProperties
{
private function formatPropertyName(string $offset): string
{
return str_replace('_', '', lcfirst(ucwords($offset, '_')));
}
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset): bool
{
$property = $this->formatPropertyName((string) $offset);
return isset($this->{$property});
}
/**
* @param mixed $offset
*
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
$property = $this->formatPropertyName((string) $offset);
return $this->{$property};
}
/**
* @param mixed $offset
* @param mixed $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value): void
{
throw new RuntimeException('Properties can not be manipulated');
}
/**
* @param mixed $offset
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset): void
{
throw new RuntimeException('Properties can not be manipulated');
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemOperationFailed.php | src/FilesystemOperationFailed.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
interface FilesystemOperationFailed extends FilesystemException
{
public const OPERATION_WRITE = 'WRITE';
public const OPERATION_UPDATE = 'UPDATE'; // not used
public const OPERATION_EXISTENCE_CHECK = 'EXISTENCE_CHECK';
public const OPERATION_DIRECTORY_EXISTS = 'DIRECTORY_EXISTS';
public const OPERATION_FILE_EXISTS = 'FILE_EXISTS';
public const OPERATION_CREATE_DIRECTORY = 'CREATE_DIRECTORY';
public const OPERATION_DELETE = 'DELETE';
public const OPERATION_DELETE_DIRECTORY = 'DELETE_DIRECTORY';
public const OPERATION_MOVE = 'MOVE';
public const OPERATION_RETRIEVE_METADATA = 'RETRIEVE_METADATA';
public const OPERATION_COPY = 'COPY';
public const OPERATION_READ = 'READ';
public const OPERATION_SET_VISIBILITY = 'SET_VISIBILITY';
public const OPERATION_LIST_CONTENTS = 'LIST_CONTENTS';
public function operation(): string;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ChecksumAlgoIsNotSupported.php | src/ChecksumAlgoIsNotSupported.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use InvalidArgumentException;
final class ChecksumAlgoIsNotSupported extends InvalidArgumentException
{
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathPrefixer.php | src/PathPrefixer.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use function rtrim;
use function strlen;
use function substr;
final class PathPrefixer
{
private string $prefix = '';
public function __construct(string $prefix, private string $separator = '/')
{
$this->prefix = rtrim($prefix, '\\/');
if ($this->prefix !== '' || $prefix === $separator) {
$this->prefix .= $separator;
}
}
public function prefixPath(string $path): string
{
return $this->prefix . ltrim($path, '\\/');
}
public function stripPrefix(string $path): string
{
/* @var string */
return substr($path, strlen($this->prefix));
}
public function stripDirectoryPrefix(string $path): string
{
return rtrim($this->stripPrefix($path), '\\/');
}
public function prefixDirectoryPath(string $path): string
{
$prefixedPath = $this->prefixPath(rtrim($path, '\\/'));
if ($prefixedPath === '' || substr($prefixedPath, -1) === $this->separator) {
return $prefixedPath;
}
return $prefixedPath . $this->separator;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/CorruptedPathDetected.php | src/CorruptedPathDetected.php | <?php
namespace League\Flysystem;
use RuntimeException;
final class CorruptedPathDetected extends RuntimeException implements FilesystemException
{
public static function forPath(string $path): CorruptedPathDetected
{
return new CorruptedPathDetected("Corrupted path detected: " . $path);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToResolveFilesystemMount.php | src/UnableToResolveFilesystemMount.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
class UnableToResolveFilesystemMount extends RuntimeException implements FilesystemException
{
public static function becauseTheSeparatorIsMissing(string $path): UnableToResolveFilesystemMount
{
return new UnableToResolveFilesystemMount("Unable to resolve the filesystem mount because the path ($path) is missing a separator (://).");
}
public static function becauseTheMountWasNotRegistered(string $mountIdentifier): UnableToResolveFilesystemMount
{
return new UnableToResolveFilesystemMount("Unable to resolve the filesystem mount because the mount ($mountIdentifier) was not registered.");
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InvalidStreamProvided.php | src/InvalidStreamProvided.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use InvalidArgumentException as BaseInvalidArgumentException;
class InvalidStreamProvided extends BaseInvalidArgumentException implements FilesystemException
{
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InvalidVisibilityProvided.php | src/InvalidVisibilityProvided.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use InvalidArgumentException;
use function var_export;
class InvalidVisibilityProvided extends InvalidArgumentException implements FilesystemException
{
public static function withVisibility(string $visibility, string $expectedMessage): InvalidVisibilityProvided
{
$provided = var_export($visibility, true);
$message = "Invalid visibility provided. Expected {$expectedMessage}, received {$provided}";
throw new InvalidVisibilityProvided($message);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToCopyFile.php | src/UnableToCopyFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToCopyFile extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $source;
/**
* @var string
*/
private $destination;
public function source(): string
{
return $this->source;
}
public function destination(): string
{
return $this->destination;
}
public static function fromLocationTo(
string $sourcePath,
string $destinationPath,
?Throwable $previous = null
): UnableToCopyFile {
$e = new static("Unable to copy file from $sourcePath to $destinationPath", 0 , $previous);
$e->source = $sourcePath;
$e->destination = $destinationPath;
return $e;
}
public static function sourceAndDestinationAreTheSame(string $source, string $destination): UnableToCopyFile
{
return UnableToCopyFile::because('Source and destination are the same', $source, $destination);
}
public static function because(string $reason, string $sourcePath, string $destinationPath): UnableToCopyFile
{
$e = new static("Unable to copy file from $sourcePath to $destinationPath, because $reason");
$e->source = $sourcePath;
$e->destination = $destinationPath;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_COPY;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/DirectoryAttributesTest.php | src/DirectoryAttributesTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use PHPUnit\Framework\TestCase;
/**
* @group core
*/
class DirectoryAttributesTest extends TestCase
{
/**
* @test
*/
public function exposing_some_values(): void
{
$attrs = new DirectoryAttributes('some/path');
$this->assertTrue($attrs->isDir());
$this->assertFalse($attrs->isFile());
$this->assertEquals(StorageAttributes::TYPE_DIRECTORY, $attrs->type());
$this->assertEquals('some/path', $attrs->path());
$this->assertNull($attrs->visibility());
}
/**
* @test
*/
public function exposing_visibility(): void
{
$attrs = new DirectoryAttributes('some/path', Visibility::PRIVATE);
$this->assertEquals(Visibility::PRIVATE, $attrs->visibility());
}
/**
* @test
*/
public function exposing_last_modified(): void
{
$attrs = new DirectoryAttributes('some/path', null, $timestamp = time());
$this->assertEquals($timestamp, $attrs->lastModified());
}
/**
* @test
*/
public function exposing_extra_meta_data(): void
{
$attrs = new DirectoryAttributes('some/path', null, null, ['key' => 'value']);
$this->assertEquals(['key' => 'value'], $attrs->extraMetadata());
}
/**
* @test
*/
public function serialization_capabilities(): void
{
$attrs = new DirectoryAttributes('some/path');
$payload = $attrs->jsonSerialize();
$attrsFromPayload = DirectoryAttributes::fromArray($payload);
$this->assertEquals($attrs, $attrsFromPayload);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathPrefixerTest.php | src/PathPrefixerTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use PHPUnit\Framework\TestCase;
class PathPrefixerTest extends TestCase
{
/**
* @test
*/
public function path_prefixing_with_a_prefix(): void
{
$prefixer = new PathPrefixer('prefix');
$prefixedPath = $prefixer->prefixPath('some/path.txt');
$this->assertEquals('prefix/some/path.txt', $prefixedPath);
}
/**
* @test
*/
public function path_stripping_with_a_prefix(): void
{
$prefixer = new PathPrefixer('prefix');
$strippedPath = $prefixer->stripPrefix('prefix/some/path.txt');
$this->assertEquals('some/path.txt', $strippedPath);
}
/**
* @test
*
* @dataProvider dpRootPaths
*/
public function an_absolute_root_path_is_supported(string $rootPath, string $separator, string $path, string $expectedPath): void
{
$prefixer = new PathPrefixer($rootPath, $separator);
$prefixedPath = $prefixer->prefixPath($path);
$this->assertEquals($expectedPath, $prefixedPath);
}
public static function dpRootPaths(): iterable
{
yield "unix-style root path" => ['/', '/', 'path.txt', '/path.txt'];
yield "windows-style root path" => ['\\', '\\', 'path.txt', '\\path.txt'];
}
/**
* @test
*/
public function path_stripping_is_reversable(): void
{
$prefixer = new PathPrefixer('prefix');
$strippedPath = $prefixer->stripPrefix('prefix/some/path.txt');
$this->assertEquals('prefix/some/path.txt', $prefixer->prefixPath($strippedPath));
$prefixedPath = $prefixer->prefixPath('some/path.txt');
$this->assertEquals('some/path.txt', $prefixer->stripPrefix($prefixedPath));
}
/**
* @test
*/
public function prefixing_without_a_prefix(): void
{
$prefixer = new PathPrefixer('');
$path = $prefixer->prefixPath('path/to/prefix.txt');
$this->assertEquals('path/to/prefix.txt', $path);
$path = $prefixer->prefixPath('/path/to/prefix.txt');
$this->assertEquals('path/to/prefix.txt', $path);
}
/**
* @test
*/
public function prefixing_for_a_directory(): void
{
$prefixer = new PathPrefixer('/prefix');
$path = $prefixer->prefixDirectoryPath('something');
$this->assertEquals('/prefix/something/', $path);
$path = $prefixer->prefixDirectoryPath('');
$this->assertEquals('/prefix/', $path);
}
/**
* @test
*/
public function prefixing_for_a_directory_without_a_prefix(): void
{
$prefixer = new PathPrefixer('');
$path = $prefixer->prefixDirectoryPath('something');
$this->assertEquals('something/', $path);
$path = $prefixer->prefixDirectoryPath('');
$this->assertEquals('', $path);
}
/**
* @test
*/
public function stripping_a_directory_prefix(): void
{
$prefixer = new PathPrefixer('/something/');
$path = $prefixer->stripDirectoryPrefix('/something/this/');
$this->assertEquals('this', $path);
$path = $prefixer->stripDirectoryPrefix('/something/and-this\\');
$this->assertEquals('and-this', $path);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ChecksumProvider.php | src/ChecksumProvider.php | <?php
namespace League\Flysystem;
interface ChecksumProvider
{
/**
* @return string MD5 hash of the file contents
*
* @throws UnableToProvideChecksum
* @throws ChecksumAlgoIsNotSupported
*/
public function checksum(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/UnableToProvideChecksum.php | src/UnableToProvideChecksum.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToProvideChecksum extends RuntimeException implements FilesystemException
{
public function __construct(string $reason, string $path, ?Throwable $previous = null)
{
parent::__construct("Unable to get checksum for $path: $reason", 0, $previous);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToSetVisibility.php | src/UnableToSetVisibility.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
use function rtrim;
final class UnableToSetVisibility extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location;
/**
* @var string
*/
private $reason;
public function reason(): string
{
return $this->reason;
}
public static function atLocation(string $filename, string $extraMessage = '', ?Throwable $previous = null): self
{
$message = "Unable to set visibility for file {$filename}. $extraMessage";
$e = new static(rtrim($message), 0, $previous);
$e->reason = $extraMessage;
$e->location = $filename;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_SET_VISIBILITY;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FileAttributes.php | src/FileAttributes.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
class FileAttributes implements StorageAttributes
{
use ProxyArrayAccessToProperties;
private string $type = StorageAttributes::TYPE_FILE;
public function __construct(
private string $path,
private ?int $fileSize = null,
private ?string $visibility = null,
private ?int $lastModified = null,
private ?string $mimeType = null,
private array $extraMetadata = []
) {
$this->path = ltrim($this->path, '/');
}
public function type(): string
{
return $this->type;
}
public function path(): string
{
return $this->path;
}
public function fileSize(): ?int
{
return $this->fileSize;
}
public function visibility(): ?string
{
return $this->visibility;
}
public function lastModified(): ?int
{
return $this->lastModified;
}
public function mimeType(): ?string
{
return $this->mimeType;
}
public function extraMetadata(): array
{
return $this->extraMetadata;
}
public function isFile(): bool
{
return true;
}
public function isDir(): bool
{
return false;
}
public function withPath(string $path): self
{
$clone = clone $this;
$clone->path = $path;
return $clone;
}
public static function fromArray(array $attributes): self
{
return new FileAttributes(
$attributes[StorageAttributes::ATTRIBUTE_PATH],
$attributes[StorageAttributes::ATTRIBUTE_FILE_SIZE] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_VISIBILITY] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_LAST_MODIFIED] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_MIME_TYPE] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_EXTRA_METADATA] ?? []
);
}
public function jsonSerialize(): array
{
return [
StorageAttributes::ATTRIBUTE_TYPE => self::TYPE_FILE,
StorageAttributes::ATTRIBUTE_PATH => $this->path,
StorageAttributes::ATTRIBUTE_FILE_SIZE => $this->fileSize,
StorageAttributes::ATTRIBUTE_VISIBILITY => $this->visibility,
StorageAttributes::ATTRIBUTE_LAST_MODIFIED => $this->lastModified,
StorageAttributes::ATTRIBUTE_MIME_TYPE => $this->mimeType,
StorageAttributes::ATTRIBUTE_EXTRA_METADATA => $this->extraMetadata,
];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToCheckDirectoryExistence.php | src/UnableToCheckDirectoryExistence.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
class UnableToCheckDirectoryExistence extends UnableToCheckExistence
{
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_DIRECTORY_EXISTS;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Config.php | src/Config.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use function array_diff_key;
use function array_flip;
use function array_merge;
class Config
{
public const OPTION_COPY_IDENTICAL_PATH = 'copy_destination_same_as_source';
public const OPTION_MOVE_IDENTICAL_PATH = 'move_destination_same_as_source';
public const OPTION_VISIBILITY = 'visibility';
public const OPTION_DIRECTORY_VISIBILITY = 'directory_visibility';
public const OPTION_RETAIN_VISIBILITY = 'retain_visibility';
public function __construct(private array $options = [])
{
}
/**
* @param mixed $default
*
* @return mixed
*/
public function get(string $property, $default = null)
{
return $this->options[$property] ?? $default;
}
public function extend(array $options): Config
{
return new Config(array_merge($this->options, $options));
}
public function withDefaults(array $defaults): Config
{
return new Config($this->options + $defaults);
}
public function toArray(): array
{
return $this->options;
}
public function withSetting(string $property, mixed $setting): Config
{
return $this->extend([$property => $setting]);
}
public function withoutSettings(string ...$settings): Config
{
return new Config(array_diff_key($this->options, array_flip($settings)));
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToReadFile.php | src/UnableToReadFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToReadFile extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location = '';
/**
* @var string
*/
private $reason = '';
public static function fromLocation(string $location, string $reason = '', ?Throwable $previous = null): UnableToReadFile
{
$e = new static(rtrim("Unable to read file from location: {$location}. {$reason}"), 0, $previous);
$e->location = $location;
$e->reason = $reason;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_READ;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToWriteFile.php | src/UnableToWriteFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToWriteFile extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location = '';
/**
* @var string
*/
private $reason;
public static function atLocation(string $location, string $reason = '', ?Throwable $previous = null): UnableToWriteFile
{
$e = new static(rtrim("Unable to write file at location: {$location}. {$reason}"), 0, $previous);
$e->location = $location;
$e->reason = $reason;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_WRITE;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemAdapter.php | src/FilesystemAdapter.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
interface FilesystemAdapter
{
/**
* @throws FilesystemException
* @throws UnableToCheckExistence
*/
public function fileExists(string $path): bool;
/**
* @throws FilesystemException
* @throws UnableToCheckExistence
*/
public function directoryExists(string $path): bool;
/**
* @throws UnableToWriteFile
* @throws FilesystemException
*/
public function write(string $path, string $contents, Config $config): void;
/**
* @param resource $contents
*
* @throws UnableToWriteFile
* @throws FilesystemException
*/
public function writeStream(string $path, $contents, Config $config): void;
/**
* @throws UnableToReadFile
* @throws FilesystemException
*/
public function read(string $path): string;
/**
* @return resource
*
* @throws UnableToReadFile
* @throws FilesystemException
*/
public function readStream(string $path);
/**
* @throws UnableToDeleteFile
* @throws FilesystemException
*/
public function delete(string $path): void;
/**
* @throws UnableToDeleteDirectory
* @throws FilesystemException
*/
public function deleteDirectory(string $path): void;
/**
* @throws UnableToCreateDirectory
* @throws FilesystemException
*/
public function createDirectory(string $path, Config $config): void;
/**
* @throws InvalidVisibilityProvided
* @throws FilesystemException
*/
public function setVisibility(string $path, string $visibility): void;
/**
* @throws UnableToRetrieveMetadata
* @throws FilesystemException
*/
public function visibility(string $path): FileAttributes;
/**
* @throws UnableToRetrieveMetadata
* @throws FilesystemException
*/
public function mimeType(string $path): FileAttributes;
/**
* @throws UnableToRetrieveMetadata
* @throws FilesystemException
*/
public function lastModified(string $path): FileAttributes;
/**
* @throws UnableToRetrieveMetadata
* @throws FilesystemException
*/
public function fileSize(string $path): FileAttributes;
/**
* @return iterable<StorageAttributes>
*
* @throws FilesystemException
*/
public function listContents(string $path, bool $deep): iterable;
/**
* @throws UnableToMoveFile
* @throws FilesystemException
*/
public function move(string $source, string $destination, Config $config): void;
/**
* @throws UnableToCopyFile
* @throws FilesystemException
*/
public function copy(string $source, string $destination, Config $config): void;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ResolveIdenticalPathConflict.php | src/ResolveIdenticalPathConflict.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
class ResolveIdenticalPathConflict
{
public const IGNORE = 'ignore';
public const FAIL = 'fail';
public const TRY = 'try';
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToCreateDirectory.php | src/UnableToCreateDirectory.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToCreateDirectory extends RuntimeException implements FilesystemOperationFailed
{
private string $location;
private string $reason = '';
public static function atLocation(string $dirname, string $errorMessage = '', ?Throwable $previous = null): UnableToCreateDirectory
{
$message = "Unable to create a directory at {$dirname}. {$errorMessage}";
$e = new static(rtrim($message), 0, $previous);
$e->location = $dirname;
$e->reason = $errorMessage;
return $e;
}
public static function dueToFailure(string $dirname, Throwable $previous): UnableToCreateDirectory
{
$reason = $previous instanceof UnableToCreateDirectory ? $previous->reason() : '';
$message = "Unable to create a directory at $dirname. $reason";
$e = new static(rtrim($message), 0, $previous);
$e->location = $dirname;
$e->reason = $reason ?: $message;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_CREATE_DIRECTORY;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathTraversalDetected.php | src/PathTraversalDetected.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
class PathTraversalDetected extends RuntimeException implements FilesystemException
{
private string $path;
public function path(): string
{
return $this->path;
}
public static function forPath(string $path): PathTraversalDetected
{
$e = new PathTraversalDetected("Path traversal detected: {$path}");
$e->path = $path;
return $e;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/DirectoryListingTest.php | src/DirectoryListingTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use Generator;
use PHPUnit\Framework\TestCase;
use function iterator_to_array;
/**
* @group core
*/
class DirectoryListingTest extends TestCase
{
/**
* @test
*/
public function mapping_a_listing(): void
{
$numbers = $this->generateIntegers(1, 10);
$listing = new DirectoryListing($numbers);
$mappedListing = $listing->map(function (int $i) {
return $i * 2;
});
$mappedNumbers = $mappedListing->toArray();
$expectedNumbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
$this->assertEquals($expectedNumbers, $mappedNumbers);
}
/**
* @test
*/
public function mapping_a_listing_twice(): void
{
$numbers = $this->generateIntegers(1, 10);
$listing = new DirectoryListing($numbers);
$mappedListing = $listing->map(function (int $i) {
return $i * 2;
});
$mappedListing = $mappedListing->map(function (int $i) {
return $i / 2;
});
$mappedNumbers = $mappedListing->toArray();
$expectedNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$this->assertEquals($expectedNumbers, $mappedNumbers);
}
/**
* @test
*/
public function filter_a_listing(): void
{
$numbers = $this->generateIntegers(1, 20);
$listing = new DirectoryListing($numbers);
$fileredListing = $listing->filter(function (int $i) {
return $i % 2 === 0;
});
$mappedNumbers = $fileredListing->toArray();
$expectedNumbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
$this->assertEquals($expectedNumbers, $mappedNumbers);
}
/**
* @test
*/
public function filter_a_listing_twice(): void
{
$numbers = $this->generateIntegers(1, 20);
$listing = new DirectoryListing($numbers);
$filteredListing = $listing->filter(function (int $i) {
return $i % 2 === 0;
});
$filteredListing = $filteredListing->filter(function (int $i) {
return $i > 10;
});
$mappedNumbers = $filteredListing->toArray();
$expectedNumbers = [12, 14, 16, 18, 20];
$this->assertEquals($expectedNumbers, $mappedNumbers);
}
/**
* @test
*/
public function sorting_a_directory_listing(): void
{
$expected = ['a/a/a.txt', 'b/c/a.txt', 'c/b/a.txt', 'c/c/a.txt'];
$listing = new DirectoryListing([
new FileAttributes('b/c/a.txt'),
new FileAttributes('c/c/a.txt'),
new FileAttributes('c/b/a.txt'),
new FileAttributes('a/a/a.txt'),
]);
$actual = $listing->sortByPath()
->map(function ($i) {
return $i->path();
})
->toArray();
self::assertEquals($expected, $actual);
}
/**
* @test
*
* @description this ensures that the output of a sorted listing is iterable
*
* @see https://github.com/thephpleague/flysystem/issues/1342
*/
public function iterating_over_storted_output(): void
{
$listing = new DirectoryListing([
new FileAttributes('b/c/a.txt'),
new FileAttributes('c/c/a.txt'),
new FileAttributes('c/b/a.txt'),
new FileAttributes('a/a/a.txt'),
]);
self::expectNotToPerformAssertions();
iterator_to_array($listing->sortByPath());
}
/**
* @return Generator<int>
*/
private function generateIntegers(int $min, int $max): Generator
{
for ($i = $min; $i <= $max; $i++) {
yield $i;
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ExceptionInformationTest.php | src/ExceptionInformationTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use PHPUnit\Framework\TestCase;
/**
* @group core
*/
class ExceptionInformationTest extends TestCase
{
/**
* @test
*/
public function copy_exception_information(): void
{
$exception = UnableToCopyFile::fromLocationTo('from', 'to');
$this->assertEquals('from', $exception->source());
$this->assertEquals('to', $exception->destination());
$this->assertEquals(FilesystemOperationFailed::OPERATION_COPY, $exception->operation());
}
/**
* @test
*/
public function create_directory_exception_information(): void
{
$exception = UnableToCreateDirectory::atLocation('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_CREATE_DIRECTORY, $exception->operation());
}
/**
* @test
*/
public function delete_directory_exception_information(): void
{
$exception = UnableToDeleteDirectory::atLocation('from', 'some message');
$this->assertEquals('some message', $exception->reason());
$this->assertEquals('from', $exception->location());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_DELETE_DIRECTORY, $exception->operation());
}
/**
* @test
*/
public function delete_file_exception_information(): void
{
$exception = UnableToDeleteFile::atLocation('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertEquals('some message', $exception->reason());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_DELETE, $exception->operation());
}
/**
* @test
*/
public function unable_to_check_for_file_existence(): void
{
$exception = UnableToCheckFileExistence::forLocation('location');
$this->assertEquals(FilesystemOperationFailed::OPERATION_FILE_EXISTS, $exception->operation());
}
/**
* @test
*/
public function unable_to_check_for_existence(): void
{
$exception = UnableToCheckExistence::forLocation('location');
$this->assertEquals(FilesystemOperationFailed::OPERATION_EXISTENCE_CHECK, $exception->operation());
}
/**
* @test
*/
public function unable_to_check_for_directory_existence(): void
{
$exception = UnableToCheckDirectoryExistence::forLocation('location');
$this->assertEquals(FilesystemOperationFailed::OPERATION_DIRECTORY_EXISTS, $exception->operation());
}
/**
* @test
*/
public function move_file_exception_information(): void
{
$exception = UnableToMoveFile::fromLocationTo('from', 'to');
$this->assertEquals('from', $exception->source());
$this->assertEquals('to', $exception->destination());
$this->assertEquals(FilesystemOperationFailed::OPERATION_MOVE, $exception->operation());
}
/**
* @test
*/
public function read_file_exception_information(): void
{
$exception = UnableToReadFile::fromLocation('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertEquals('some message', $exception->reason());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_READ, $exception->operation());
}
/**
* @test
*/
public function retrieve_visibility_exception_information(): void
{
$exception = UnableToRetrieveMetadata::visibility('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertEquals(FileAttributes::ATTRIBUTE_VISIBILITY, $exception->metadataType());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_RETRIEVE_METADATA, $exception->operation());
}
/**
* @test
*/
public function set_visibility_exception_information(): void
{
$exception = UnableToSetVisibility::atLocation('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertEquals('some message', $exception->reason());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_SET_VISIBILITY, $exception->operation());
}
/**
* @test
*/
public function write_file_exception_information(): void
{
$exception = UnableToWriteFile::atLocation('from', 'some message');
$this->assertEquals('from', $exception->location());
$this->assertEquals('some message', $exception->reason());
$this->assertStringContainsString('some message', $exception->getMessage());
$this->assertEquals(FilesystemOperationFailed::OPERATION_WRITE, $exception->operation());
}
/**
* @test
*/
public function unreadable_file_exception_information(): void
{
$exception = UnreadableFileEncountered::atLocation('the-location');
$this->assertEquals('the-location', $exception->location());
$this->assertStringContainsString('the-location', $exception->getMessage());
}
/**
* @test
*/
public function symbolic_link_exception_information(): void
{
$exception = SymbolicLinkEncountered::atLocation('the-location');
$this->assertEquals('the-location', $exception->location());
$this->assertStringContainsString('the-location', $exception->getMessage());
}
/**
* @test
*/
public function path_traversal_exception_information(): void
{
$exception = PathTraversalDetected::forPath('../path.txt');
$this->assertEquals('../path.txt', $exception->path());
$this->assertStringContainsString('../path.txt', $exception->getMessage());
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToDeleteFile.php | src/UnableToDeleteFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToDeleteFile extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location = '';
/**
* @var string
*/
private $reason;
public static function atLocation(string $location, string $reason = '', ?Throwable $previous = null): UnableToDeleteFile
{
$e = new static(rtrim("Unable to delete file located at: {$location}. {$reason}"), 0, $previous);
$e->location = $location;
$e->reason = $reason;
return $e;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_DELETE;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnreadableFileEncountered.php | src/UnreadableFileEncountered.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
final class UnreadableFileEncountered extends RuntimeException implements FilesystemException
{
/**
* @var string
*/
private $location;
public function location(): string
{
return $this->location;
}
public static function atLocation(string $location): UnreadableFileEncountered
{
$e = new static("Unreadable file encountered at location {$location}.");
$e->location = $location;
return $e;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToCheckExistence.php | src/UnableToCheckExistence.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
class UnableToCheckExistence extends RuntimeException implements FilesystemOperationFailed
{
final public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
public static function forLocation(string $path, ?Throwable $exception = null): static
{
return new static("Unable to check existence for: {$path}", 0, $exception);
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_EXISTENCE_CHECK;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ConfigTest.php | src/ConfigTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase
{
/**
* @test
*/
public function a_config_object_exposes_passed_options(): void
{
$config = new Config(['option' => 'value']);
$this->assertEquals('value', $config->get('option'));
}
/**
* @test
*/
public function a_config_object_returns_a_default_value(): void
{
$config = new Config();
$this->assertNull($config->get('option'));
$this->assertEquals('default', $config->get('option', 'default'));
}
/**
* @test
*/
public function extending_a_config_with_options(): void
{
$config = new Config(['option' => 'value', 'first' => 1]);
$extended = $config->extend(['option' => 'overwritten', 'second' => 2]);
$this->assertEquals('overwritten', $extended->get('option'));
$this->assertEquals(1, $extended->get('first'));
$this->assertEquals(2, $extended->get('second'));
}
/**
* @test
*/
public function extending_with_defaults(): void
{
$config = new Config(['option' => 'set']);
$withDefaults = $config->withDefaults(['option' => 'default', 'other' => 'default']);
$this->assertEquals('set', $withDefaults->get('option'));
$this->assertEquals('default', $withDefaults->get('other'));
}
/**
* @test
*/
public function extending_without_settings(): void
{
// arrange
$config = new Config(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]);
// act
$withoutSetting = $config->withoutSettings('b', 'd');
// assert
$this->assertEquals(['a' => 1, 'c' => 3], $withoutSetting->toArray());
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PathNormalizer.php | src/PathNormalizer.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
interface PathNormalizer
{
public function normalizePath(string $path): string;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemTest.php | src/FilesystemTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use DateTimeImmutable;
use DateTimeInterface;
use Generator;
use GuzzleHttp\Psr7\StreamWrapper;
use GuzzleHttp\Psr7\Utils;
use IteratorAggregate;
use League\Flysystem\InMemory\InMemoryFilesystemAdapter;
use League\Flysystem\Local\LocalFilesystemAdapter;
use League\Flysystem\UrlGeneration\PublicUrlGenerator;
use League\Flysystem\UrlGeneration\TemporaryUrlGenerator;
use LogicException;
use PHPUnit\Framework\TestCase;
use function iterator_to_array;
/**
* @group core
*/
class FilesystemTest extends TestCase
{
const ROOT = __DIR__ . '/../test_files/test-root';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @before
*/
public function setupFilesystem(): void
{
$adapter = new LocalFilesystemAdapter(self::ROOT);
$filesystem = new Filesystem($adapter);
$this->filesystem = $filesystem;
}
/**
* @after
*/
public function removeFiles(): void
{
delete_directory(static::ROOT);
}
/**
* @test
*/
public function writing_and_reading_files(): void
{
$this->filesystem->write('path.txt', 'contents');
$contents = $this->filesystem->read('path.txt');
$this->assertEquals('contents', $contents);
}
/**
* @test
*
* @dataProvider invalidStreamInput
*
* @param mixed $input
*/
public function trying_to_write_with_an_invalid_stream_arguments($input): void
{
$this->expectException(InvalidStreamProvided::class);
$this->filesystem->writeStream('path.txt', $input);
}
public static function invalidStreamInput(): Generator
{
$handle = tmpfile();
fclose($handle);
yield "resource that is not open" => [$handle];
yield "something that is not a resource" => [false];
}
/**
* @test
*/
public function writing_and_reading_a_stream(): void
{
$writeStream = stream_with_contents('contents');
$this->filesystem->writeStream('path.txt', $writeStream);
$readStream = $this->filesystem->readStream('path.txt');
fclose($writeStream);
$this->assertIsResource($readStream);
$this->assertEquals('contents', stream_get_contents($readStream));
fclose($readStream);
}
/**
* @test
*/
public function writing_using_a_stream_wrapper(): void
{
$contents = 'contents of the file';
$stream = Utils::streamFor($contents);
$resource = StreamWrapper::getResource($stream);
$this->filesystem->writeStream('from-stream-wrapper.txt', $resource);
fclose($resource);
$this->assertEquals($contents, $this->filesystem->read('from-stream-wrapper.txt'));
}
/**
* @test
*/
public function checking_if_files_exist(): void
{
$this->filesystem->write('path.txt', 'contents');
$pathDotTxtExists = $this->filesystem->fileExists('path.txt');
$otherFileExists = $this->filesystem->fileExists('other.txt');
$this->assertTrue($pathDotTxtExists);
$this->assertFalse($otherFileExists);
}
/**
* @test
*/
public function checking_if_directories_exist(): void
{
$this->filesystem->createDirectory('existing-directory');
$existingDirectory = $this->filesystem->directoryExists('existing-directory');
$notExistingDirectory = $this->filesystem->directoryExists('not-existing-directory');
$this->assertTrue($existingDirectory);
$this->assertFalse($notExistingDirectory);
}
/**
* @test
*/
public function deleting_a_file(): void
{
$this->filesystem->write('path.txt', 'content');
$this->filesystem->delete('path.txt');
$this->assertFalse($this->filesystem->fileExists('path.txt'));
}
/**
* @test
*/
public function creating_a_directory(): void
{
$this->filesystem->createDirectory('here');
$directoryAttrs = $this->filesystem->listContents('')->toArray()[0];
$this->assertInstanceOf(DirectoryAttributes::class, $directoryAttrs);
$this->assertEquals('here', $directoryAttrs->path());
}
/**
* @test
*/
public function deleting_a_directory(): void
{
$this->filesystem->write('dirname/a.txt', 'contents');
$this->filesystem->write('dirname/b.txt', 'contents');
$this->filesystem->write('dirname/c.txt', 'contents');
$this->filesystem->deleteDirectory('dir');
$this->assertTrue($this->filesystem->fileExists('dirname/a.txt'));
$this->filesystem->deleteDirectory('dirname');
$this->assertFalse($this->filesystem->fileExists('dirname/a.txt'));
$this->assertFalse($this->filesystem->fileExists('dirname/b.txt'));
$this->assertFalse($this->filesystem->fileExists('dirname/c.txt'));
}
/**
* @test
*/
public function listing_directory_contents(): void
{
$this->filesystem->write('dirname/a.txt', 'contents');
$this->filesystem->write('dirname/b.txt', 'contents');
$this->filesystem->write('dirname/c.txt', 'contents');
$listing = $this->filesystem->listContents('', false);
$this->assertInstanceOf(DirectoryListing::class, $listing);
$this->assertInstanceOf(IteratorAggregate::class, $listing);
$attributeListing = iterator_to_array($listing);
$this->assertContainsOnlyInstancesOf(StorageAttributes::class, $attributeListing);
$this->assertCount(1, $attributeListing);
}
/**
* @test
*/
public function listing_directory_contents_recursive(): void
{
$this->filesystem->write('dirname/a.txt', 'contents');
$this->filesystem->write('dirname/b.txt', 'contents');
$this->filesystem->write('dirname/c.txt', 'contents');
$listing = $this->filesystem->listContents('', true);
$attributeListing = $listing->toArray();
$this->assertContainsOnlyInstancesOf(StorageAttributes::class, $attributeListing);
$this->assertCount(4, $attributeListing);
}
/**
* @test
*/
public function copying_files(): void
{
$this->filesystem->write('path.txt', 'contents');
$this->filesystem->copy('path.txt', 'new-path.txt');
$this->assertTrue($this->filesystem->fileExists('path.txt'));
$this->assertTrue($this->filesystem->fileExists('new-path.txt'));
}
/**
* @test
*/
public function moving_files(): void
{
$this->filesystem->write('path.txt', 'contents');
$this->filesystem->move('path.txt', 'new-path.txt');
$this->assertFalse($this->filesystem->fileExists('path.txt'));
$this->assertTrue($this->filesystem->fileExists('new-path.txt'));
}
/**
* @test
*/
public function fetching_last_modified(): void
{
$this->filesystem->write('path.txt', 'contents');
$lastModified = $this->filesystem->lastModified('path.txt');
$this->assertIsInt($lastModified);
$this->assertTrue($lastModified > time() - 30);
$this->assertTrue($lastModified < time() + 30);
}
/**
* @test
*/
public function fetching_mime_type(): void
{
$this->filesystem->write('path.txt', 'contents');
$mimeType = $this->filesystem->mimeType('path.txt');
$this->assertEquals('text/plain', $mimeType);
}
/**
* @test
*/
public function fetching_file_size(): void
{
$this->filesystem->write('path.txt', 'contents');
$fileSize = $this->filesystem->fileSize('path.txt');
$this->assertEquals(8, $fileSize);
}
/**
* @test
*/
public function ensuring_streams_are_rewound_when_writing(): void
{
$writeStream = stream_with_contents('contents');
fseek($writeStream, 4);
$this->filesystem->writeStream('path.txt', $writeStream);
$contents = $this->filesystem->read('path.txt');
$this->assertEquals('contents', $contents);
}
/**
* @test
*/
public function setting_visibility(): void
{
$this->filesystem->write('path.txt', 'contents');
$this->filesystem->setVisibility('path.txt', Visibility::PUBLIC);
$publicVisibility = $this->filesystem->visibility('path.txt');
$this->filesystem->setVisibility('path.txt', Visibility::PRIVATE);
$privateVisibility = $this->filesystem->visibility('path.txt');
$this->assertEquals(Visibility::PUBLIC, $publicVisibility);
$this->assertEquals(Visibility::PRIVATE, $privateVisibility);
}
/**
* @test
*
* @dataProvider scenariosCausingPathTraversal
*/
public function protecting_against_path_traversals(callable $scenario): void
{
$this->expectException(PathTraversalDetected::class);
$scenario($this->filesystem);
}
public static function scenariosCausingPathTraversal(): Generator
{
yield [function (FilesystemOperator $filesystem) {
$filesystem->delete('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->deleteDirectory('../path');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->createDirectory('../path');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->read('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->readStream('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->write('../path.txt', 'contents');
}];
yield [function (FilesystemOperator $filesystem) {
$stream = stream_with_contents('contents');
try {
$filesystem->writeStream('../path.txt', $stream);
} finally {
fclose($stream);
}
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->listContents('../path');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->fileExists('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->mimeType('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->fileSize('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->lastModified('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->visibility('../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->setVisibility('../path.txt', Visibility::PUBLIC);
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->copy('../path.txt', 'path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->copy('path.txt', '../path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->move('../path.txt', 'path.txt');
}];
yield [function (FilesystemOperator $filesystem) {
$filesystem->move('path.txt', '../path.txt');
}];
}
/**
* @test
*/
public function listing_exceptions_are_uniformely_represented(): void
{
$filesystem = new Filesystem(
new class() extends InMemoryFilesystemAdapter {
public function listContents(string $path, bool $deep): iterable
{
yield from parent::listContents($path, $deep);
throw new LogicException('Oh no.');
}
}
);
$items = $filesystem->listContents('', true);
$this->expectException(UnableToListContents::class);
iterator_to_array($items); // force the yields
}
/**
* @test
*/
public function failing_to_create_a_public_url(): void
{
$filesystem = new Filesystem(
new class() extends InMemoryFilesystemAdapter implements PublicUrlGenerator {
public function publicUrl(string $path, Config $config): string
{
throw new UnableToGeneratePublicUrl('No reason', $path);
}
}
);
$this->expectException(UnableToGeneratePublicUrl::class);
$filesystem->publicUrl('path.txt');
}
/**
* @test
*/
public function not_configuring_a_public_url(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter());
$this->expectException(UnableToGeneratePublicUrl::class);
$filesystem->publicUrl('path.txt');
}
/**
* @test
*/
public function creating_a_public_url(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
['public_url' => 'https://example.org/public/'],
);
$url = $filesystem->publicUrl('path.txt');
self::assertEquals('https://example.org/public/path.txt', $url);
}
/**
* @test
*/
public function public_url_array_uses_multi_prefixer(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
['public_url' => ['https://cdn1', 'https://cdn2']],
);
$url1 = $filesystem->publicUrl('first-path1.txt');
$url2 = $filesystem->publicUrl('path2.txt');
$url3 = $filesystem->publicUrl('first-path1.txt'); // deterministic
$url4 = $filesystem->publicUrl('/some/path-here.txt');
$url5 = $filesystem->publicUrl('some/path-here.txt'); // deterministic even with leading "/"
self::assertEquals('https://cdn1/first-path1.txt', $url1);
self::assertEquals('https://cdn2/path2.txt', $url2);
self::assertEquals('https://cdn1/first-path1.txt', $url3);
self::assertEquals('https://cdn2/some/path-here.txt', $url4);
self::assertEquals('https://cdn2/some/path-here.txt', $url5);
}
/**
* @test
*/
public function custom_public_url_generator(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
[],
publicUrlGenerator: new class() implements PublicUrlGenerator {
public function publicUrl(string $path, Config $config): string
{
return 'custom/' . $path;
}
},
);
self::assertSame('custom/file.txt', $filesystem->publicUrl('file.txt'));
}
/**
* @test
*/
public function copying_from_and_to_the_same_location_fails(): void
{
$this->expectExceptionObject(UnableToCopyFile::sourceAndDestinationAreTheSame('from.txt', 'from.txt'));
$config = [Config::OPTION_COPY_IDENTICAL_PATH => ResolveIdenticalPathConflict::FAIL];
$this->filesystem->copy('from.txt', 'from.txt', $config);
}
/**
* @test
*/
public function moving_from_and_to_the_same_location_fails(): void
{
$this->expectExceptionObject(UnableToMoveFile::fromLocationTo('from.txt', 'from.txt'));
$config = [Config::OPTION_MOVE_IDENTICAL_PATH => ResolveIdenticalPathConflict::FAIL];
$this->filesystem->move('from.txt', 'from.txt', $config);
}
/**
* @test
*/
public function get_checksum_for_adapter_that_supports(): void
{
$this->filesystem->write('path.txt', 'foobar');
$this->assertSame('3858f62230ac3c915f300c664312c63f', $this->filesystem->checksum('path.txt'));
}
/**
* @test
*/
public function get_checksum_for_adapter_that_does_not_support(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter());
$filesystem->write('path.txt', 'foobar');
$this->assertSame('3858f62230ac3c915f300c664312c63f', $filesystem->checksum('path.txt'));
}
/**
* @test
*/
public function get_checksum_for_adapter_that_does_not_support_specific_algo(): void
{
$adapter = new class() extends InMemoryFilesystemAdapter implements ChecksumProvider {
public function checksum(string $path, Config $config): string
{
throw new ChecksumAlgoIsNotSupported();
}
};
$filesystem = new Filesystem($adapter);
$filesystem->write('path.txt', 'foobar');
$this->assertSame('3858f62230ac3c915f300c664312c63f', $filesystem->checksum('path.txt'));
}
/**
* @test
*/
public function get_sha256_checksum_for_adapter_that_does_not_support(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter(), ['checksum_algo' => 'sha256']);
$filesystem->write('path.txt', 'foobar');
$this->assertSame('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', $filesystem->checksum('path.txt'));
}
/**
* @test
*/
public function get_sha256_checksum_for_adapter_that_does_not_support_while_crc32c_is_the_default(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter(), ['checksum_algo' => 'crc32c']);
$filesystem->write('path.txt', 'foobar');
$checksum = $filesystem->checksum('path.txt', ['checksum_algo' => 'sha256']);
$this->assertSame('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', $checksum);
}
/**
* @test
*/
public function unable_to_get_checksum_for_for_file_that_does_not_exist(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter());
$this->expectException(UnableToProvideChecksum::class);
$filesystem->checksum('path.txt');
}
/**
* @test
*/
public function generating_temporary_urls(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
temporaryUrlGenerator: new class() implements TemporaryUrlGenerator {
public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string
{
return 'https://flysystem.thephpleague.com/' . $path . '?exporesAt=' . $expiresAt->format('U');
}
}
);
$now = \time();
$temporaryUrl = $filesystem->temporaryUrl('some/file.txt', new DateTimeImmutable('@' . $now));
$expectedUrl = 'https://flysystem.thephpleague.com/some/file.txt?exporesAt=' . $now;
self::assertEquals($expectedUrl, $temporaryUrl);
}
/**
* @test
*/
public function not_being_able_to_generate_temporary_urls(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter());
$this->expectException(UnableToGenerateTemporaryUrl::class);
$filesystem->temporaryUrl('some/file.txt', new DateTimeImmutable());
}
/**
* @test
*/
public function ignoring_same_paths_for_move_and_copy(): void
{
$this->expectNotToPerformAssertions();
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
[
Config::OPTION_COPY_IDENTICAL_PATH => ResolveIdenticalPathConflict::IGNORE,
Config::OPTION_MOVE_IDENTICAL_PATH => ResolveIdenticalPathConflict::IGNORE,
]
);
$filesystem->move('from.txt', 'from.txt');
$filesystem->copy('from.txt', 'from.txt');
}
/**
* @test
*/
public function failing_same_paths_for_move(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
[
Config::OPTION_MOVE_IDENTICAL_PATH => ResolveIdenticalPathConflict::FAIL,
]
);
$this->expectExceptionObject(UnableToMoveFile::fromLocationTo('from.txt', 'from.txt'));
$filesystem->move('from.txt', 'from.txt');
}
/**
* @test
*/
public function failing_same_paths_for_copy(): void
{
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
[
Config::OPTION_COPY_IDENTICAL_PATH => ResolveIdenticalPathConflict::FAIL,
]
);
$this->expectExceptionObject(UnableToCopyFile::fromLocationTo('from.txt', 'from.txt'));
$filesystem->copy('from.txt', 'from.txt');
}
/**
* @test
*/
public function unable_to_get_checksum_directory(): void
{
$filesystem = new Filesystem(new InMemoryFilesystemAdapter());
$filesystem->createDirectory('foo');
$this->expectException(UnableToProvideChecksum::class);
$filesystem->checksum('foo');
}
/**
* @test
*
* @dataProvider fileMoveOrCopyScenarios
*/
public function moving_a_file_with_visibility_scenario(
array $mainConfig,
array $moveConfig,
?string $writeVisibility,
string $expectedVisibility
): void {
// arrange
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
$mainConfig
);
$writeConfig = $writeVisibility ? ['visibility' => $writeVisibility] : [];
$filesystem->write('from.txt', 'contents', $writeConfig);
// act
$filesystem->move('from.txt', 'to.txt', $moveConfig);
// assert
$this->assertEquals($expectedVisibility, $filesystem->visibility('to.txt'));
}
/**
* @test
*
* @dataProvider fileMoveOrCopyScenarios
*/
public function copying_a_file_with_visibility_scenario(
array $mainConfig,
array $copyConfig,
?string $writeVisibility,
string $expectedVisibility
): void {
// arrange
$filesystem = new Filesystem(
new InMemoryFilesystemAdapter(),
$mainConfig
);
$writeConfig = $writeVisibility ? ['visibility' => $writeVisibility] : [];
$filesystem->write('from.txt', 'contents', $writeConfig);
// act
$filesystem->copy('from.txt', 'to.txt', $copyConfig);
// assert
$this->assertEquals($expectedVisibility, $filesystem->visibility('to.txt'));
}
public static function fileMoveOrCopyScenarios(): iterable
{
yield 'retain visibility, write default, default private' => [
['retain_visibility' => true, 'visibility' => 'private'],
[],
null,
'private'
];
yield 'retain visibility, write default, default public' => [
['retain_visibility' => true, 'visibility' => 'public'],
[],
null,
'public'
];
yield 'retain visibility, write public, default private' => [
['retain_visibility' => true, 'visibility' => 'private'],
[],
'public',
'public'
];
yield 'retain visibility, write private, default public' => [
['retain_visibility' => true, 'visibility' => 'public'],
[],
'private',
'private'
];
yield 'retain visibility, write default, default private, execute public' => [
['retain_visibility' => true, 'visibility' => 'private'],
['visibility' => 'public'],
null,
'public'
];
yield 'retain visibility, write default, default public, execute private' => [
['retain_visibility' => true, 'visibility' => 'public'],
['visibility' => 'private'],
null,
'private'
];
yield 'retain visibility, write public, default private, execute private' => [
['retain_visibility' => true, 'visibility' => 'private'],
['visibility' => 'private'],
'public',
'private'
];
yield 'retain visibility, write private, default public, execute public' => [
['retain_visibility' => true, 'visibility' => 'public'],
['visibility' => 'public'],
'private',
'public'
];
yield 'do not retain visibility, write default, default private' => [
['retain_visibility' => false, 'visibility' => 'private'],
[],
null,
'private'
];
yield 'do not retain visibility, write default, default public' => [
['retain_visibility' => false, 'visibility' => 'public'],
[],
null,
'public'
];
yield 'do not retain visibility, write public, default private' => [
['retain_visibility' => false, 'visibility' => 'private'],
[],
'public',
'private'
];
yield 'do not retain visibility, write private, default public' => [
['retain_visibility' => false, 'visibility' => 'public'],
[],
'private',
'public'
];
yield 'do not retain visibility, write default, default private, execute public' => [
['retain_visibility' => false, 'visibility' => 'private'],
['visibility' => 'public'],
null,
'public'
];
yield 'do not retain visibility, write default, default public, execute private' => [
['retain_visibility' => false, 'visibility' => 'public'],
['visibility' => 'private'],
null,
'private'
];
yield 'do not retain visibility, write public, default private, execute public' => [
['retain_visibility' => false, 'visibility' => 'private'],
['visibility' => 'public'],
'public',
'public'
];
yield 'do not retain visibility, write private, default public, execute private' => [
['retain_visibility' => false, 'visibility' => 'public'],
['visibility' => 'private'],
'private',
'private'
];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/MountManager.php | src/MountManager.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use DateTimeInterface;
use Throwable;
use function compact;
use function method_exists;
use function sprintf;
class MountManager implements FilesystemOperator
{
/**
* @var array<string, FilesystemOperator>
*/
private $filesystems = [];
/**
* @var Config
*/
private $config;
/**
* MountManager constructor.
*
* @param array<string,FilesystemOperator> $filesystems
*/
public function __construct(array $filesystems = [], array $config = [])
{
$this->mountFilesystems($filesystems);
$this->config = new Config($config);
}
/**
* It is not recommended to mount filesystems after creation because interacting
* with the Mount Manager becomes unpredictable. Use this as an escape hatch.
*/
public function dangerouslyMountFilesystems(string $key, FilesystemOperator $filesystem): void
{
$this->mountFilesystem($key, $filesystem);
}
/**
* @param array<string,FilesystemOperator> $filesystems
*/
public function extend(array $filesystems, array $config = []): MountManager
{
$clone = clone $this;
$clone->config = $this->config->extend($config);
$clone->mountFilesystems($filesystems);
return $clone;
}
public function fileExists(string $location): bool
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->fileExists($path);
} catch (Throwable $exception) {
throw UnableToCheckFileExistence::forLocation($location, $exception);
}
}
public function has(string $location): bool
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->fileExists($path) || $filesystem->directoryExists($path);
} catch (Throwable $exception) {
throw UnableToCheckExistence::forLocation($location, $exception);
}
}
public function directoryExists(string $location): bool
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->directoryExists($path);
} catch (Throwable $exception) {
throw UnableToCheckDirectoryExistence::forLocation($location, $exception);
}
}
public function read(string $location): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->read($path);
} catch (UnableToReadFile $exception) {
throw UnableToReadFile::fromLocation($location, $exception->reason(), $exception);
}
}
public function readStream(string $location)
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->readStream($path);
} catch (UnableToReadFile $exception) {
throw UnableToReadFile::fromLocation($location, $exception->reason(), $exception);
}
}
public function listContents(string $location, bool $deep = self::LIST_SHALLOW): DirectoryListing
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path, $mountIdentifier] = $this->determineFilesystemAndPath($location);
return
$filesystem
->listContents($path, $deep)
->map(
function (StorageAttributes $attributes) use ($mountIdentifier) {
return $attributes->withPath(sprintf('%s://%s', $mountIdentifier, $attributes->path()));
}
);
}
public function lastModified(string $location): int
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->lastModified($path);
} catch (UnableToRetrieveMetadata $exception) {
throw UnableToRetrieveMetadata::lastModified($location, $exception->reason(), $exception);
}
}
public function fileSize(string $location): int
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->fileSize($path);
} catch (UnableToRetrieveMetadata $exception) {
throw UnableToRetrieveMetadata::fileSize($location, $exception->reason(), $exception);
}
}
public function mimeType(string $location): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
return $filesystem->mimeType($path);
} catch (UnableToRetrieveMetadata $exception) {
throw UnableToRetrieveMetadata::mimeType($location, $exception->reason(), $exception);
}
}
public function visibility(string $path): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $location] = $this->determineFilesystemAndPath($path);
try {
return $filesystem->visibility($location);
} catch (UnableToRetrieveMetadata $exception) {
throw UnableToRetrieveMetadata::visibility($path, $exception->reason(), $exception);
}
}
public function write(string $location, string $contents, array $config = []): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
$filesystem->write($path, $contents, $this->config->extend($config)->toArray());
} catch (UnableToWriteFile $exception) {
throw UnableToWriteFile::atLocation($location, $exception->reason(), $exception);
}
}
public function writeStream(string $location, $contents, array $config = []): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
$filesystem->writeStream($path, $contents, $this->config->extend($config)->toArray());
}
public function setVisibility(string $path, string $visibility): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($path);
$filesystem->setVisibility($path, $visibility);
}
public function delete(string $location): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
$filesystem->delete($path);
} catch (UnableToDeleteFile $exception) {
throw UnableToDeleteFile::atLocation($location, $exception->reason(), $exception);
}
}
public function deleteDirectory(string $location): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
$filesystem->deleteDirectory($path);
} catch (UnableToDeleteDirectory $exception) {
throw UnableToDeleteDirectory::atLocation($location, $exception->reason(), $exception);
}
}
public function createDirectory(string $location, array $config = []): void
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($location);
try {
$filesystem->createDirectory($path, $this->config->extend($config)->toArray());
} catch (UnableToCreateDirectory $exception) {
throw UnableToCreateDirectory::dueToFailure($location, $exception);
}
}
public function move(string $source, string $destination, array $config = []): void
{
/** @var FilesystemOperator $sourceFilesystem */
/* @var FilesystemOperator $destinationFilesystem */
[$sourceFilesystem, $sourcePath] = $this->determineFilesystemAndPath($source);
[$destinationFilesystem, $destinationPath] = $this->determineFilesystemAndPath($destination);
$sourceFilesystem === $destinationFilesystem ? $this->moveInTheSameFilesystem(
$sourceFilesystem,
$sourcePath,
$destinationPath,
$source,
$destination,
$config,
) : $this->moveAcrossFilesystems($source, $destination, $config);
}
public function copy(string $source, string $destination, array $config = []): void
{
/** @var FilesystemOperator $sourceFilesystem */
/* @var FilesystemOperator $destinationFilesystem */
[$sourceFilesystem, $sourcePath] = $this->determineFilesystemAndPath($source);
[$destinationFilesystem, $destinationPath] = $this->determineFilesystemAndPath($destination);
$sourceFilesystem === $destinationFilesystem ? $this->copyInSameFilesystem(
$sourceFilesystem,
$sourcePath,
$destinationPath,
$source,
$destination,
$config,
) : $this->copyAcrossFilesystem(
$sourceFilesystem,
$sourcePath,
$destinationFilesystem,
$destinationPath,
$source,
$destination,
$config,
);
}
public function publicUrl(string $path, array $config = []): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($path);
if ( ! method_exists($filesystem, 'publicUrl')) {
throw new UnableToGeneratePublicUrl(sprintf('%s does not support generating public urls.', $filesystem::class), $path);
}
return $filesystem->publicUrl($path, $config);
}
public function temporaryUrl(string $path, DateTimeInterface $expiresAt, array $config = []): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($path);
if ( ! method_exists($filesystem, 'temporaryUrl')) {
throw new UnableToGenerateTemporaryUrl(sprintf('%s does not support generating public urls.', $filesystem::class), $path);
}
return $filesystem->temporaryUrl($path, $expiresAt, $this->config->extend($config)->toArray());
}
public function checksum(string $path, array $config = []): string
{
/** @var FilesystemOperator $filesystem */
[$filesystem, $path] = $this->determineFilesystemAndPath($path);
if ( ! method_exists($filesystem, 'checksum')) {
throw new UnableToProvideChecksum(sprintf('%s does not support providing checksums.', $filesystem::class), $path);
}
return $filesystem->checksum($path, $this->config->extend($config)->toArray());
}
private function mountFilesystems(array $filesystems): void
{
foreach ($filesystems as $key => $filesystem) {
$this->guardAgainstInvalidMount($key, $filesystem);
/* @var string $key */
/* @var FilesystemOperator $filesystem */
$this->mountFilesystem($key, $filesystem);
}
}
private function guardAgainstInvalidMount(mixed $key, mixed $filesystem): void
{
if ( ! is_string($key)) {
throw UnableToMountFilesystem::becauseTheKeyIsNotValid($key);
}
if ( ! $filesystem instanceof FilesystemOperator) {
throw UnableToMountFilesystem::becauseTheFilesystemWasNotValid($filesystem);
}
}
private function mountFilesystem(string $key, FilesystemOperator $filesystem): void
{
$this->filesystems[$key] = $filesystem;
}
/**
* @param string $path
*
* @return array{0:FilesystemOperator, 1:string, 2:string}
*/
private function determineFilesystemAndPath(string $path): array
{
if (strpos($path, '://') < 1) {
throw UnableToResolveFilesystemMount::becauseTheSeparatorIsMissing($path);
}
/** @var string $mountIdentifier */
/** @var string $mountPath */
[$mountIdentifier, $mountPath] = explode('://', $path, 2);
if ( ! array_key_exists($mountIdentifier, $this->filesystems)) {
throw UnableToResolveFilesystemMount::becauseTheMountWasNotRegistered($mountIdentifier);
}
return [$this->filesystems[$mountIdentifier], $mountPath, $mountIdentifier];
}
private function copyInSameFilesystem(
FilesystemOperator $sourceFilesystem,
string $sourcePath,
string $destinationPath,
string $source,
string $destination,
array $config,
): void {
try {
$sourceFilesystem->copy($sourcePath, $destinationPath, $this->config->extend($config)->toArray());
} catch (UnableToCopyFile $exception) {
throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
}
}
private function copyAcrossFilesystem(
FilesystemOperator $sourceFilesystem,
string $sourcePath,
FilesystemOperator $destinationFilesystem,
string $destinationPath,
string $source,
string $destination,
array $config,
): void {
$config = $this->config->extend($config);
$retainVisibility = (bool) $config->get(Config::OPTION_RETAIN_VISIBILITY, true);
$visibility = $config->get(Config::OPTION_VISIBILITY);
try {
if ($visibility == null && $retainVisibility) {
$visibility = $sourceFilesystem->visibility($sourcePath);
$config = $config->extend(compact('visibility'));
}
$stream = $sourceFilesystem->readStream($sourcePath);
$destinationFilesystem->writeStream($destinationPath, $stream, $config->toArray());
} catch (UnableToRetrieveMetadata | UnableToReadFile | UnableToWriteFile $exception) {
throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
}
}
private function moveInTheSameFilesystem(
FilesystemOperator $sourceFilesystem,
string $sourcePath,
string $destinationPath,
string $source,
string $destination,
array $config,
): void {
try {
$sourceFilesystem->move($sourcePath, $destinationPath, $this->config->extend($config)->toArray());
} catch (UnableToMoveFile $exception) {
throw UnableToMoveFile::fromLocationTo($source, $destination, $exception);
}
}
private function moveAcrossFilesystems(string $source, string $destination, array $config = []): void
{
try {
$this->copy($source, $destination, $config);
$this->delete($source);
} catch (UnableToCopyFile | UnableToDeleteFile $exception) {
throw UnableToMoveFile::fromLocationTo($source, $destination, $exception);
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemOperator.php | src/FilesystemOperator.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
interface FilesystemOperator extends FilesystemReader, FilesystemWriter
{
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/CalculateChecksumFromStream.php | src/CalculateChecksumFromStream.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use function hash_final;
use function hash_init;
use function hash_update_stream;
trait CalculateChecksumFromStream
{
private function calculateChecksumFromStream(string $path, Config $config): string
{
try {
$stream = $this->readStream($path);
$algo = (string) $config->get('checksum_algo', 'md5');
$context = hash_init($algo);
hash_update_stream($context, $stream);
return hash_final($context);
} catch (FilesystemException $exception) {
throw new UnableToProvideChecksum($exception->getMessage(), $path, $exception);
}
}
/**
* @return resource
*/
abstract public function readStream(string $path);
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Visibility.php | src/Visibility.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
final class Visibility
{
public const PUBLIC = 'public';
public const PRIVATE = 'private';
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PortableVisibilityGuard.php | src/PortableVisibilityGuard.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
final class PortableVisibilityGuard
{
public static function guardAgainstInvalidInput(string $visibility): void
{
if ($visibility !== Visibility::PUBLIC && $visibility !== Visibility::PRIVATE) {
$className = Visibility::class;
throw InvalidVisibilityProvided::withVisibility(
$visibility,
"either {$className}::PUBLIC or {$className}::PRIVATE"
);
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FileAttributesTest.php | src/FileAttributesTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use Generator;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use function time;
/**
* @group core
*/
class FileAttributesTest extends TestCase
{
/**
* @test
*/
public function exposing_some_values(): void
{
$attrs = new FileAttributes('path.txt');
$this->assertFalse($attrs->isDir());
$this->assertTrue($attrs->isFile());
$this->assertEquals('path.txt', $attrs->path());
$this->assertEquals(StorageAttributes::TYPE_FILE, $attrs->type());
$this->assertNull($attrs->visibility());
$this->assertNull($attrs->fileSize());
$this->assertNull($attrs->mimeType());
$this->assertNull($attrs->lastModified());
}
/**
* @test
*/
public function exposing_all_values(): void
{
$attrs = new FileAttributes('path.txt', 1234, Visibility::PRIVATE, $now = time(), 'plain/text', ['key' => 'value']);
$this->assertEquals('path.txt', $attrs->path());
$this->assertEquals(StorageAttributes::TYPE_FILE, $attrs->type());
$this->assertEquals(Visibility::PRIVATE, $attrs->visibility());
$this->assertEquals(1234, $attrs->fileSize());
$this->assertEquals($now, $attrs->lastModified());
$this->assertEquals('plain/text', $attrs->mimeType());
$this->assertEquals(['key' => 'value'], $attrs->extraMetadata());
}
/**
* @test
*/
public function implements_array_access(): void
{
$attrs = new FileAttributes('path.txt', 1234, Visibility::PRIVATE, $now = time(), 'plain/text', ['key' => 'value']);
$this->assertEquals('path.txt', $attrs['path']);
$this->assertTrue(isset($attrs['path']));
$this->assertEquals(StorageAttributes::TYPE_FILE, $attrs['type']);
$this->assertEquals(Visibility::PRIVATE, $attrs['visibility']);
$this->assertEquals(1234, $attrs['file_size']);
$this->assertEquals($now, $attrs['last_modified']);
$this->assertEquals('plain/text', $attrs['mimeType']);
$this->assertEquals(['key' => 'value'], $attrs['extra_metadata']);
}
/**
* @test
*/
public function properties_can_not_be_set(): void
{
$this->expectException(RuntimeException::class);
$attrs = new FileAttributes('path.txt');
$attrs['visibility'] = Visibility::PUBLIC;
}
/**
* @test
*/
public function properties_can_not_be_unset(): void
{
$this->expectException(RuntimeException::class);
$attrs = new FileAttributes('path.txt');
unset($attrs['visibility']);
}
/**
* @dataProvider data_provider_for_json_transformation
*
* @test
*/
public function json_transformations(FileAttributes $attributes): void
{
$payload = $attributes->jsonSerialize();
$newAttributes = FileAttributes::fromArray($payload);
$this->assertEquals($attributes, $newAttributes);
}
public static function data_provider_for_json_transformation(): Generator
{
yield [new FileAttributes('path.txt', 1234, Visibility::PRIVATE, $now = time(), 'plain/text', ['key' => 'value'])];
yield [new FileAttributes('another.txt')];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemException.php | src/FilesystemException.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use Throwable;
interface FilesystemException extends Throwable
{
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnableToRetrieveMetadata.php | src/UnableToRetrieveMetadata.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
use RuntimeException;
use Throwable;
final class UnableToRetrieveMetadata extends RuntimeException implements FilesystemOperationFailed
{
/**
* @var string
*/
private $location;
/**
* @var string
*/
private $metadataType;
/**
* @var string
*/
private $reason;
public static function lastModified(string $location, string $reason = '', ?Throwable $previous = null): self
{
return static::create($location, FileAttributes::ATTRIBUTE_LAST_MODIFIED, $reason, $previous);
}
public static function visibility(string $location, string $reason = '', ?Throwable $previous = null): self
{
return static::create($location, FileAttributes::ATTRIBUTE_VISIBILITY, $reason, $previous);
}
public static function fileSize(string $location, string $reason = '', ?Throwable $previous = null): self
{
return static::create($location, FileAttributes::ATTRIBUTE_FILE_SIZE, $reason, $previous);
}
public static function mimeType(string $location, string $reason = '', ?Throwable $previous = null): self
{
return static::create($location, FileAttributes::ATTRIBUTE_MIME_TYPE, $reason, $previous);
}
public static function create(string $location, string $type, string $reason = '', ?Throwable $previous = null): self
{
$e = new static("Unable to retrieve the $type for file at location: $location. {$reason}", 0, $previous);
$e->reason = $reason;
$e->location = $location;
$e->metadataType = $type;
return $e;
}
public function reason(): string
{
return $this->reason;
}
public function location(): string
{
return $this->location;
}
public function metadataType(): string
{
return $this->metadataType;
}
public function operation(): string
{
return FilesystemOperationFailed::OPERATION_RETRIEVE_METADATA;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/FilesystemWriter.php | src/FilesystemWriter.php | <?php
declare(strict_types=1);
namespace League\Flysystem;
interface FilesystemWriter
{
/**
* @throws UnableToWriteFile
* @throws FilesystemException
*/
public function write(string $location, string $contents, array $config = []): void;
/**
* @param mixed $contents
*
* @throws UnableToWriteFile
* @throws FilesystemException
*/
public function writeStream(string $location, $contents, array $config = []): void;
/**
* @throws UnableToSetVisibility
* @throws FilesystemException
*/
public function setVisibility(string $path, string $visibility): void;
/**
* @throws UnableToDeleteFile
* @throws FilesystemException
*/
public function delete(string $location): void;
/**
* @throws UnableToDeleteDirectory
* @throws FilesystemException
*/
public function deleteDirectory(string $location): void;
/**
* @throws UnableToCreateDirectory
* @throws FilesystemException
*/
public function createDirectory(string $location, array $config = []): void;
/**
* @throws UnableToMoveFile
* @throws FilesystemException
*/
public function move(string $source, string $destination, array $config = []): void;
/**
* @throws UnableToCopyFile
* @throws FilesystemException
*/
public function copy(string $source, string $destination, array $config = []): void;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ReadOnly/ReadOnlyFilesystemAdapter.php | src/ReadOnly/ReadOnlyFilesystemAdapter.php | <?php
namespace League\Flysystem\ReadOnly;
use DateTimeInterface;
use League\Flysystem\CalculateChecksumFromStream;
use League\Flysystem\ChecksumProvider;
use League\Flysystem\Config;
use League\Flysystem\DecoratedAdapter;
use League\Flysystem\FilesystemAdapter;
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\UnableToSetVisibility;
use League\Flysystem\UnableToWriteFile;
use League\Flysystem\UrlGeneration\PublicUrlGenerator;
use League\Flysystem\UrlGeneration\TemporaryUrlGenerator;
class ReadOnlyFilesystemAdapter extends DecoratedAdapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator
{
use CalculateChecksumFromStream;
public function write(string $path, string $contents, Config $config): void
{
throw UnableToWriteFile::atLocation($path, 'This is a readonly adapter.');
}
public function writeStream(string $path, $contents, Config $config): void
{
throw UnableToWriteFile::atLocation($path, 'This is a readonly adapter.');
}
public function delete(string $path): void
{
throw UnableToDeleteFile::atLocation($path, 'This is a readonly adapter.');
}
public function deleteDirectory(string $path): void
{
throw UnableToDeleteDirectory::atLocation($path, 'This is a readonly adapter.');
}
public function createDirectory(string $path, Config $config): void
{
throw UnableToCreateDirectory::atLocation($path, 'This is a readonly adapter.');
}
public function setVisibility(string $path, string $visibility): void
{
throw UnableToSetVisibility::atLocation($path, 'This is a readonly adapter.');
}
public function move(string $source, string $destination, Config $config): void
{
throw new UnableToMoveFile("Unable to move file from $source to $destination as this is a readonly adapter.");
}
public function copy(string $source, string $destination, Config $config): void
{
throw new UnableToCopyFile("Unable to copy file from $source to $destination as this is a readonly adapter.");
}
public function publicUrl(string $path, Config $config): string
{
if ( ! $this->adapter instanceof PublicUrlGenerator) {
throw UnableToGeneratePublicUrl::noGeneratorConfigured($path);
}
return $this->adapter->publicUrl($path, $config);
}
public function checksum(string $path, Config $config): string
{
if ($this->adapter instanceof ChecksumProvider) {
return $this->adapter->checksum($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($path, $expiresAt, $config);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/ReadOnly/ReadOnlyFilesystemAdapterTest.php | src/ReadOnly/ReadOnlyFilesystemAdapterTest.php | <?php
namespace League\Flysystem\ReadOnly;
use League\Flysystem\Config;
use League\Flysystem\FileAttributes;
use League\Flysystem\InMemory\InMemoryFilesystemAdapter;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToCreateDirectory;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToGeneratePublicUrl;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\UnableToWriteFile;
use League\Flysystem\UrlGeneration\PublicUrlGenerator;
use PHPUnit\Framework\TestCase;
use function ltrim;
class ReadOnlyFilesystemAdapterTest extends TestCase
{
/**
* @test
*/
public function can_perform_read_operations(): void
{
$adapter = $this->realAdapter();
$adapter->write('foo/bar.txt', 'content', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->assertTrue($adapter->fileExists('foo/bar.txt'));
$this->assertTrue($adapter->directoryExists('foo'));
$this->assertSame('content', $adapter->read('foo/bar.txt'));
$this->assertSame('content', \stream_get_contents($adapter->readStream('foo/bar.txt')));
$this->assertInstanceOf(FileAttributes::class, $adapter->visibility('foo/bar.txt'));
$this->assertInstanceOf(FileAttributes::class, $adapter->mimeType('foo/bar.txt'));
$this->assertInstanceOf(FileAttributes::class, $adapter->lastModified('foo/bar.txt'));
$this->assertInstanceOf(FileAttributes::class, $adapter->fileSize('foo/bar.txt'));
$this->assertCount(1, iterator_to_array($adapter->listContents('foo', true)));
}
/**
* @test
*/
public function cannot_write_stream(): void
{
$adapter = new ReadOnlyFilesystemAdapter($this->realAdapter());
$this->expectException(UnableToWriteFile::class);
// @phpstan-ignore-next-line
$adapter->writeStream('foo', 'content', new Config());
}
/**
* @test
*/
public function cannot_write(): void
{
$adapter = new ReadOnlyFilesystemAdapter($this->realAdapter());
$this->expectException(UnableToWriteFile::class);
$adapter->write('foo', 'content', new Config());
}
/**
* @test
*/
public function cannot_delete_file(): void
{
$adapter = $this->realAdapter();
$adapter->write('foo', 'content', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->expectException(UnableToDeleteFile::class);
$adapter->delete('foo');
}
/**
* @test
*/
public function cannot_delete_directory(): void
{
$adapter = $this->realAdapter();
$adapter->createDirectory('foo', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->expectException(UnableToDeleteDirectory::class);
$adapter->deleteDirectory('foo');
}
/**
* @test
*/
public function cannot_create_directory(): void
{
$adapter = new ReadOnlyFilesystemAdapter($this->realAdapter());
$this->expectException(UnableToCreateDirectory::class);
$adapter->createDirectory('foo', new Config());
}
/**
* @test
*/
public function cannot_set_visibility(): void
{
$adapter = $this->realAdapter();
$adapter->write('foo', 'content', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->expectException(UnableToSetVisibility::class);
$adapter->setVisibility('foo', 'private');
}
/**
* @test
*/
public function cannot_move(): void
{
$adapter = $this->realAdapter();
$adapter->write('foo', 'content', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->expectException(UnableToMoveFile::class);
$adapter->move('foo', 'bar', new Config());
}
/**
* @test
*/
public function cannot_copy(): void
{
$adapter = $this->realAdapter();
$adapter->write('foo', 'content', new Config());
$adapter = new ReadOnlyFilesystemAdapter($adapter);
$this->expectException(UnableToCopyFile::class);
$adapter->copy('foo', 'bar', new Config());
}
/**
* @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, '/');
}
};
$readOnlyAdapter = new ReadOnlyFilesystemAdapter($adapter);
$url = $readOnlyAdapter->publicUrl('/path.txt', new Config());
self::assertEquals('memory://path.txt', $url);
}
/**
* @test
*/
public function failing_to_generate_a_public_url(): void
{
$adapter = new ReadOnlyFilesystemAdapter(new InMemoryFilesystemAdapter());
$this->expectException(UnableToGeneratePublicUrl::class);
$adapter->publicUrl('/path.txt', new Config());
}
private function realAdapter(): InMemoryFilesystemAdapter
{
return new InMemoryFilesystemAdapter();
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InMemory/InMemoryFilesystemAdapter.php | src/InMemory/InMemoryFilesystemAdapter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\InMemory;
use League\Flysystem\Config;
use League\Flysystem\DirectoryAttributes;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\Visibility;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use League\MimeTypeDetection\MimeTypeDetector;
use function array_keys;
use function rtrim;
class InMemoryFilesystemAdapter implements FilesystemAdapter
{
public const DUMMY_FILE_FOR_FORCED_LISTING_IN_FLYSYSTEM_TEST = '______DUMMY_FILE_FOR_FORCED_LISTING_IN_FLYSYSTEM_TEST';
/**
* @var InMemoryFile[]
*/
private array $files = [];
private MimeTypeDetector $mimeTypeDetector;
public function __construct(
private string $defaultVisibility = Visibility::PUBLIC,
?MimeTypeDetector $mimeTypeDetector = null
) {
$this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector();
}
public function fileExists(string $path): bool
{
return array_key_exists($this->preparePath($path), $this->files);
}
public function write(string $path, string $contents, Config $config): void
{
$path = $this->preparePath($path);
$file = $this->files[$path] = $this->files[$path] ?? new InMemoryFile();
$file->updateContents($contents, $config->get('timestamp'));
$visibility = $config->get(Config::OPTION_VISIBILITY, $this->defaultVisibility);
$file->setVisibility($visibility);
}
public function writeStream(string $path, $contents, Config $config): void
{
$this->write($path, (string) stream_get_contents($contents), $config);
}
public function read(string $path): string
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToReadFile::fromLocation($path, 'file does not exist');
}
return $this->files[$path]->read();
}
public function readStream(string $path)
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToReadFile::fromLocation($path, 'file does not exist');
}
return $this->files[$path]->readStream();
}
public function delete(string $path): void
{
unset($this->files[$this->preparePath($path)]);
}
public function deleteDirectory(string $path): void
{
$path = $this->preparePath($path);
$path = rtrim($path, '/') . '/';
foreach (array_keys($this->files) as $filePath) {
if (str_starts_with($filePath, $path)) {
unset($this->files[$filePath]);
}
}
}
public function createDirectory(string $path, Config $config): void
{
$filePath = rtrim($path, '/') . '/' . self::DUMMY_FILE_FOR_FORCED_LISTING_IN_FLYSYSTEM_TEST;
$this->write($filePath, '', $config);
}
public function directoryExists(string $path): bool
{
$path = $this->preparePath($path);
$path = rtrim($path, '/') . '/';
foreach (array_keys($this->files) as $filePath) {
if (str_starts_with($filePath, $path)) {
return true;
}
}
return false;
}
public function setVisibility(string $path, string $visibility): void
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToSetVisibility::atLocation($path, 'file does not exist');
}
$this->files[$path]->setVisibility($visibility);
}
public function visibility(string $path): FileAttributes
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToRetrieveMetadata::visibility($path, 'file does not exist');
}
return new FileAttributes($path, null, $this->files[$path]->visibility());
}
public function mimeType(string $path): FileAttributes
{
$preparedPath = $this->preparePath($path);
if (array_key_exists($preparedPath, $this->files) === false) {
throw UnableToRetrieveMetadata::mimeType($path, 'file does not exist');
}
$mimeType = $this->mimeTypeDetector->detectMimeType($path, $this->files[$preparedPath]->read());
if ($mimeType === null) {
throw UnableToRetrieveMetadata::mimeType($path);
}
return new FileAttributes($preparedPath, null, null, null, $mimeType);
}
public function lastModified(string $path): FileAttributes
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToRetrieveMetadata::lastModified($path, 'file does not exist');
}
return new FileAttributes($path, null, null, $this->files[$path]->lastModified());
}
public function fileSize(string $path): FileAttributes
{
$path = $this->preparePath($path);
if (array_key_exists($path, $this->files) === false) {
throw UnableToRetrieveMetadata::fileSize($path, 'file does not exist');
}
return new FileAttributes($path, $this->files[$path]->fileSize());
}
public function listContents(string $path, bool $deep): iterable
{
$prefix = rtrim($this->preparePath($path), '/') . '/';
$prefixLength = strlen($prefix);
$listedDirectories = [];
foreach ($this->files as $filePath => $file) {
if (str_starts_with($filePath, $prefix)) {
$subPath = substr($filePath, $prefixLength);
$dirname = dirname($subPath);
if ($dirname !== '.') {
$parts = explode('/', $dirname);
$dirPath = '';
foreach ($parts as $index => $part) {
if ($deep === false && $index >= 1) {
break;
}
$dirPath .= $part . '/';
if ( ! in_array($dirPath, $listedDirectories, true)) {
$listedDirectories[] = $dirPath;
yield new DirectoryAttributes(trim($prefix . $dirPath, '/'));
}
}
}
$dummyFilename = self::DUMMY_FILE_FOR_FORCED_LISTING_IN_FLYSYSTEM_TEST;
if (str_ends_with($filePath, $dummyFilename)) {
continue;
}
if ($deep === true || ! str_contains($subPath, '/')) {
yield new FileAttributes(ltrim($filePath, '/'), $file->fileSize(), $file->visibility(), $file->lastModified(), $file->mimeType());
}
}
}
}
public function move(string $source, string $destination, Config $config): void
{
$sourcePath = $this->preparePath($source);
$destinationPath = $this->preparePath($destination);
if ( ! $this->fileExists($source)) {
throw UnableToMoveFile::fromLocationTo($source, $destination);
}
if ($sourcePath !== $destinationPath) {
$this->files[$destinationPath] = $this->files[$sourcePath];
unset($this->files[$sourcePath]);
}
if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
$this->setVisibility($destination, $visibility);
}
}
public function copy(string $source, string $destination, Config $config): void
{
$source = $this->preparePath($source);
$destination = $this->preparePath($destination);
if ( ! $this->fileExists($source)) {
throw UnableToCopyFile::fromLocationTo($source, $destination);
}
$lastModified = $config->get('timestamp', time());
$this->files[$destination] = $this->files[$source]->withLastModified($lastModified);
if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
$this->setVisibility($destination, $visibility);
}
}
private function preparePath(string $path): string
{
return '/' . ltrim($path, '/');
}
public function deleteEverything(): void
{
$this->files = [];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InMemory/StaticInMemoryAdapterRegistry.php | src/InMemory/StaticInMemoryAdapterRegistry.php | <?php
namespace League\Flysystem\InMemory;
class StaticInMemoryAdapterRegistry
{
/** @var array<string, InMemoryFilesystemAdapter> */
private static array $filesystems = [];
public static function get(string $name = 'default'): InMemoryFilesystemAdapter
{
return static::$filesystems[$name] ??= new InMemoryFilesystemAdapter();
}
public static function deleteAllFilesystems(): void
{
self::$filesystems = [];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InMemory/InMemoryFile.php | src/InMemory/InMemoryFile.php | <?php
declare(strict_types=1);
namespace League\Flysystem\InMemory;
use const FILEINFO_MIME_TYPE;
use finfo;
/**
* @internal
*/
class InMemoryFile
{
private string $contents = '';
private int $lastModified = 0;
private ?string $visibility = null;
public function updateContents(string $contents, ?int $timestamp): void
{
$this->contents = $contents;
$this->lastModified = $timestamp ?? time();
}
public function lastModified(): int
{
return $this->lastModified;
}
public function withLastModified(int $lastModified): self
{
$clone = clone $this;
$clone->lastModified = $lastModified;
return $clone;
}
public function read(): string
{
return $this->contents;
}
/**
* @return resource
*/
public function readStream()
{
/** @var resource $stream */
$stream = fopen('php://temp', 'w+b');
fwrite($stream, $this->contents);
rewind($stream);
return $stream;
}
public function fileSize(): int
{
return strlen($this->contents);
}
public function mimeType(): string
{
return (string) (new finfo(FILEINFO_MIME_TYPE))->buffer($this->contents);
}
public function setVisibility(string $visibility): void
{
$this->visibility = $visibility;
}
public function visibility(): ?string
{
return $this->visibility;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InMemory/InMemoryFilesystemAdapterTest.php | src/InMemory/InMemoryFilesystemAdapterTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\InMemory;
use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase;
use League\Flysystem\Config;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\Visibility;
use League\MimeTypeDetection\EmptyExtensionToMimeTypeMap;
use League\MimeTypeDetection\ExtensionMimeTypeDetector;
/**
* @group in-memory
*/
class InMemoryFilesystemAdapterTest extends FilesystemAdapterTestCase
{
const PATH = 'path.txt';
/**
* @before
*/
public function resetFunctionMocks(): void
{
reset_function_mocks();
/** @var InMemoryFilesystemAdapter $filesystemAdapter */
$filesystemAdapter = $this->adapter();
$filesystemAdapter->deleteEverything();
}
/**
* @test
*/
public function getting_mimetype_on_a_non_existing_file(): void
{
$this->expectException(UnableToRetrieveMetadata::class);
$this->adapter()->mimeType('path.txt');
}
/**
* @test
*/
public function getting_last_modified_on_a_non_existing_file(): void
{
$this->expectException(UnableToRetrieveMetadata::class);
$this->adapter()->lastModified('path.txt');
}
/**
* @test
*/
public function getting_file_size_on_a_non_existing_file(): void
{
$this->expectException(UnableToRetrieveMetadata::class);
$this->adapter()->fileSize('path.txt');
}
/**
* @test
*/
public function deleting_a_file(): void
{
$this->adapter()->write('path.txt', 'contents', new Config());
$this->assertTrue($this->adapter()->fileExists('path.txt'));
$this->adapter()->delete('path.txt');
$this->assertFalse($this->adapter()->fileExists('path.txt'));
}
/**
* @test
*/
public function deleting_a_directory(): void
{
$adapter = $this->adapter();
$adapter->write('a/path.txt', 'contents', new Config());
$adapter->write('a/b/path.txt', 'contents', new Config());
$adapter->write('a/b/c/path.txt', 'contents', new Config());
$this->assertTrue($adapter->fileExists('a/b/path.txt'));
$this->assertTrue($adapter->fileExists('a/b/c/path.txt'));
$adapter->deleteDirectory('a/b');
$this->assertTrue($adapter->fileExists('a/path.txt'));
$this->assertFalse($adapter->fileExists('a/b/path.txt'));
$this->assertFalse($adapter->fileExists('a/b/c/path.txt'));
}
/**
* @test
*/
public function creating_a_directory_does_nothing(): void
{
$this->adapter()->createDirectory('something', new Config());
$this->assertTrue(true);
}
/**
* @test
*/
public function writing_with_a_stream_and_reading_a_file(): void
{
$handle = stream_with_contents('contents');
$this->adapter()->writeStream(self::PATH, $handle, new Config());
$contents = $this->adapter()->read(self::PATH);
$this->assertEquals('contents', $contents);
}
/**
* @test
*/
public function reading_a_stream(): void
{
$this->adapter()->write(self::PATH, 'contents', new Config());
$contents = $this->adapter()->readStream(self::PATH);
$this->assertEquals('contents', stream_get_contents($contents));
fclose($contents);
}
/**
* @test
*/
public function reading_a_non_existing_file(): void
{
$this->expectException(UnableToReadFile::class);
$this->adapter()->read('path.txt');
}
/**
* @test
*/
public function stream_reading_a_non_existing_file(): void
{
$this->expectException(UnableToReadFile::class);
$this->adapter()->readStream('path.txt');
}
/**
* @test
*/
public function listing_all_files(): void
{
$adapter = $this->adapter();
$adapter->write('path.txt', 'contents', new Config());
$adapter->write('a/path.txt', 'contents', new Config());
$adapter->write('a/b/path.txt', 'contents', new Config());
/** @var StorageAttributes[] $listing */
$listing = iterator_to_array($adapter->listContents('/', true));
$this->assertCount(5, $listing);
$expected = [
'path.txt' => StorageAttributes::TYPE_FILE,
'a/path.txt' => StorageAttributes::TYPE_FILE,
'a/b/path.txt' => StorageAttributes::TYPE_FILE,
'a' => StorageAttributes::TYPE_DIRECTORY,
'a/b' => StorageAttributes::TYPE_DIRECTORY,
];
foreach ($listing as $item) {
$this->assertArrayHasKey($item->path(), $expected);
$this->assertEquals($item->type(), $expected[$item->path()]);
}
}
/**
* @test
*/
public function listing_non_recursive(): void
{
$adapter = $this->adapter();
$adapter->write('path.txt', 'contents', new Config());
$adapter->write('a/path.txt', 'contents', new Config());
$adapter->write('a/b/path.txt', 'contents', new Config());
$listing = iterator_to_array($adapter->listContents('/', false));
$this->assertCount(2, $listing);
}
/**
* @test
*/
public function moving_a_file_successfully(): void
{
$adapter = $this->adapter();
$adapter->write('path.txt', 'contents', new Config());
$adapter->move('path.txt', 'new-path.txt', new Config());
$this->assertFalse($adapter->fileExists('path.txt'));
$this->assertTrue($adapter->fileExists('new-path.txt'));
}
/**
* @test
*/
public function trying_to_move_a_non_existing_file(): void
{
$this->expectException(UnableToMoveFile::class);
$this->adapter()->move('path.txt', 'new-path.txt', new Config());
}
/**
* @test
*/
public function copying_a_file_successfully(): void
{
$adapter = $this->adapter();
$adapter->write('path.txt', 'contents', new Config());
$adapter->copy('path.txt', 'new-path.txt', new Config());
$this->assertTrue($adapter->fileExists('path.txt'));
$this->assertTrue($adapter->fileExists('new-path.txt'));
}
/**
* @test
*/
public function trying_to_copy_a_non_existing_file(): void
{
$this->expectException(UnableToCopyFile::class);
$this->adapter()->copy('path.txt', 'new-path.txt', new Config());
}
/**
* @test
*/
public function not_listing_directory_placeholders(): void
{
$adapter = $this->adapter();
$adapter->createDirectory('directory', new Config());
$contents = iterator_to_array($adapter->listContents('', true));
$this->assertCount(1, $contents);
}
/**
* @test
*/
public function checking_for_metadata(): void
{
mock_function('time', 1234);
$adapter = $this->adapter();
$adapter->write(
self::PATH,
(string) file_get_contents(__DIR__ . '/../AdapterTestUtilities/test_files/flysystem.svg'),
new Config()
);
$this->assertTrue($adapter->fileExists(self::PATH));
$this->assertEquals(754, $adapter->fileSize(self::PATH)->fileSize());
$this->assertEquals(1234, $adapter->lastModified(self::PATH)->lastModified());
$this->assertStringStartsWith('image/svg+xml', $adapter->mimeType(self::PATH)->mimeType());
}
/**
* @test
*/
public function fetching_unknown_mime_type_of_a_file(): void
{
$this->useAdapter(new InMemoryFilesystemAdapter(Visibility::PUBLIC, new ExtensionMimeTypeDetector(new EmptyExtensionToMimeTypeMap())));
parent::fetching_unknown_mime_type_of_a_file();
}
/**
* @test
*/
public function using_custom_timestamp(): void
{
$adapter = $this->adapter();
$now = 100;
$adapter->write('file.txt', 'contents', new Config(['timestamp' => $now]));
$this->assertEquals($now, $adapter->lastModified('file.txt')->lastModified());
$earlier = 50;
$adapter->copy('file.txt', 'new_file.txt', new Config(['timestamp' => $earlier]));
$this->assertEquals($earlier, $adapter->lastModified('new_file.txt')->lastModified());
}
protected static function createFilesystemAdapter(): FilesystemAdapter
{
return new InMemoryFilesystemAdapter();
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/InMemory/StaticInMemoryAdapterRegistryTest.php | src/InMemory/StaticInMemoryAdapterRegistryTest.php | <?php
namespace League\Flysystem\InMemory;
use League\Flysystem\Config;
use League\Flysystem\FilesystemAdapter;
class StaticInMemoryAdapterRegistryTest extends InMemoryFilesystemAdapterTest
{
/**
* @test
*/
public function using_different_name_to_segment_adapters(): void
{
$first = StaticInMemoryAdapterRegistry::get();
$second = StaticInMemoryAdapterRegistry::get('second');
$first->write('foo.txt', 'foo', new Config());
$second->write('bar.txt', 'bar', new Config());
$this->assertTrue($first->fileExists('foo.txt'));
$this->assertFalse($first->fileExists('bar.txt'));
$this->assertTrue($second->fileExists('bar.txt'));
$this->assertFalse($second->fileExists('foo.txt'));
}
/**
* @test
*/
public function files_persist_between_instances(): void
{
$first = StaticInMemoryAdapterRegistry::get();
$second = StaticInMemoryAdapterRegistry::get('second');
$first->write('foo.txt', 'foo', new Config());
$second->write('bar.txt', 'bar', new Config());
$this->assertTrue($first->fileExists('foo.txt'));
$this->assertTrue($second->fileExists('bar.txt'));
$first = StaticInMemoryAdapterRegistry::get();
$second = StaticInMemoryAdapterRegistry::get('second');
$this->assertTrue($first->fileExists('foo.txt'));
$this->assertTrue($second->fileExists('bar.txt'));
}
protected function tearDown(): void
{
StaticInMemoryAdapterRegistry::deleteAllFilesystems();
}
protected static function createFilesystemAdapter(): FilesystemAdapter
{
return StaticInMemoryAdapterRegistry::get();
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/StubStorageClient.php | src/GoogleCloudStorage/StubStorageClient.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use Google\Cloud\Storage\StorageClient;
use function in_array;
class StubStorageClient extends StorageClient
{
private ?StubRiggedBucket $riggedBucket = null;
public function __construct(array $config = [])
{
parent::__construct($config);
}
/**
* @var string|null
*/
protected $projectId;
public function bucket($name, $userProject = false, array $options = [])
{
$knownBuckets = ['flysystem', 'no-acl-bucket-for-ci'];
$isKnownBucket = in_array($name, $knownBuckets);
if ($isKnownBucket && ! $this->riggedBucket) {
$this->riggedBucket = new StubRiggedBucket($this->connection, $name, [
'requesterProjectId' => $this->projectId,
]);
}
return $isKnownBucket ? $this->riggedBucket : parent::bucket($name, $userProject);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/GoogleCloudStorageAdapterTest.php | src/GoogleCloudStorage/GoogleCloudStorageAdapterTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase;
use League\Flysystem\Config;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\PathPrefixer;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToWriteFile;
use function getenv;
/**
* @group gcs
*/
class GoogleCloudStorageAdapterTest extends FilesystemAdapterTestCase
{
/**
* @var string
*/
private static $adapterPrefix = 'ci';
private static StubRiggedBucket $bucket;
private static PathPrefixer $prefixer;
public static function setUpBeforeClass(): void
{
static::$adapterPrefix = 'frank-ci'; // . bin2hex(random_bytes(10));
static::$prefixer = new PathPrefixer(static::$adapterPrefix);
}
protected static function bucketName(): string|array|false
{
return 'flysystem';
}
protected static function visibilityHandler(): VisibilityHandler
{
return new PortableVisibilityHandler();
}
public function prefixPath(string $path): string
{
return static::$prefixer->prefixPath($path);
}
public function prefixDirectoryPath(string $path): string
{
return static::$prefixer->prefixDirectoryPath($path);
}
protected static function createFilesystemAdapter(): FilesystemAdapter
{
if ( ! file_exists(__DIR__ . '/../../google-cloud-service-account.json')) {
self::markTestSkipped("No google service account found in project root.");
}
$clientOptions = [
'projectId' => getenv('GOOGLE_CLOUD_PROJECT'),
'keyFilePath' => __DIR__ . '/../../google-cloud-service-account.json',
];
$storageClient = new StubStorageClient($clientOptions);
/** @var StubRiggedBucket $bucket */
$bucket = $storageClient->bucket(self::bucketName());
static::$bucket = $bucket;
return new GoogleCloudStorageAdapter(
$bucket,
static::$adapterPrefix,
visibilityHandler: self::visibilityHandler(),
);
}
/**
* @test
*/
public function writing_with_specific_metadata(): void
{
$adapter = $this->adapter();
$adapter->write('some/path.txt', 'contents', new Config(['metadata' => ['contentType' => 'text/plain+special']]));
$mimeType = $adapter->mimeType('some/path.txt')->mimeType();
$this->assertEquals('text/plain+special', $mimeType);
}
/**
* @test
*/
public function guessing_the_mime_type_when_writing(): void
{
$adapter = $this->adapter();
$adapter->write('some/config.txt', '<?xml version="1.0" encoding="UTF-8"?><test/>', new Config());
$mimeType = $adapter->mimeType('some/config.txt')->mimeType();
$this->assertEquals('text/xml', $mimeType);
}
/**
* @test
*/
public function fetching_visibility_of_non_existing_file(): void
{
$this->markTestSkipped("
Not relevant for this adapter since it's a missing ACL,
which turns into a 404 which is the expected outcome
of a private visibility. ¯\_(ツ)_/¯
");
}
/**
* @test
*/
public function fetching_unknown_mime_type_of_a_file(): void
{
$this->markTestSkipped("This adapter always returns a mime-type.");
}
/**
* @test
*/
public function listing_a_toplevel_directory(): void
{
$this->clearStorage();
parent::listing_a_toplevel_directory();
}
/**
* @test
*/
public function failing_to_write_a_file(): void
{
$adapter = $this->adapter();
static::$bucket->failForUpload($this->prefixPath('something.txt'));
$this->expectException(UnableToWriteFile::class);
$adapter->write('something.txt', 'contents', new Config());
}
/**
* @test
*/
public function failing_to_delete_a_file(): void
{
$adapter = $this->adapter();
static::$bucket->failForObject($this->prefixPath('filename.txt'));
$this->expectException(UnableToDeleteFile::class);
$adapter->delete('filename.txt');
}
/**
* @test
*/
public function failing_to_delete_a_directory(): void
{
$adapter = $this->adapter();
$this->givenWeHaveAnExistingFile('dir/filename.txt');
static::$bucket->failForObject($this->prefixPath('dir/filename.txt'));
$this->expectException(UnableToDeleteDirectory::class);
$adapter->deleteDirectory('dir');
}
/**
* @test
*/
public function failing_to_retrieve_visibility(): void
{
$adapter = $this->adapter();
static::$bucket->failForObject($this->prefixPath('filename.txt'));
$this->expectException(UnableToRetrieveMetadata::class);
$adapter->visibility('filename.txt');
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/GoogleCloudStorageAdapterWithoutAclTest.php | src/GoogleCloudStorage/GoogleCloudStorageAdapterWithoutAclTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
class GoogleCloudStorageAdapterWithoutAclTest extends GoogleCloudStorageAdapterTest
{
protected static function visibilityHandler(): VisibilityHandler
{
return new UniformBucketLevelAccessVisibility();
}
protected static function bucketName(): string|array|false
{
return 'no-acl-bucket-for-ci';
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/GoogleCloudStorageAdapter.php | src/GoogleCloudStorage/GoogleCloudStorageAdapter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use DateTimeInterface;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Storage\Bucket;
use Google\Cloud\Storage\StorageObject;
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\StorageAttributes;
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\Flysystem\Visibility;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use League\MimeTypeDetection\MimeTypeDetector;
use LogicException;
use Throwable;
use function array_key_exists;
use function base64_decode;
use function bin2hex;
use function count;
use function rtrim;
use function sprintf;
use function strlen;
class GoogleCloudStorageAdapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator
{
private PathPrefixer $prefixer;
private VisibilityHandler $visibilityHandler;
private MimeTypeDetector $mimeTypeDetector;
private static array $algoToInfoMap = [
'md5' => 'md5Hash',
'crc32c' => 'crc32c',
'etag' => 'etag',
];
public function __construct(
private Bucket $bucket,
string $prefix = '',
?VisibilityHandler $visibilityHandler = null,
private string $defaultVisibility = Visibility::PRIVATE,
?MimeTypeDetector $mimeTypeDetector = null,
private bool $streamReads = false,
) {
$this->prefixer = new PathPrefixer($prefix);
$this->visibilityHandler = $visibilityHandler ?? new PortableVisibilityHandler();
$this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector();
}
public function publicUrl(string $path, Config $config): string
{
$location = $this->prefixer->prefixPath($path);
return 'https://storage.googleapis.com/' . $this->bucket->name() . '/' . ltrim($location, '/');
}
public function fileExists(string $path): bool
{
$prefixedPath = $this->prefixer->prefixPath($path);
try {
return $this->bucket->object($prefixedPath)->exists();
} catch (Throwable $exception) {
throw UnableToCheckFileExistence::forLocation($path, $exception);
}
}
public function directoryExists(string $path): bool
{
$prefixedPath = $this->prefixer->prefixPath($path);
$options = [
'delimiter' => '/',
'includeTrailingDelimiter' => true,
];
if (strlen($prefixedPath) > 0) {
$options = ['prefix' => rtrim($prefixedPath, '/') . '/'];
}
try {
$objects = $this->bucket->objects($options);
} catch (Throwable $exception) {
throw UnableToCheckDirectoryExistence::forLocation($path, $exception);
}
if (count($objects->prefixes()) > 0) {
return true;
}
/** @var StorageObject $object */
foreach ($objects as $object) {
return true;
}
return false;
}
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 resource|string $contents
*/
private function upload(string $path, $contents, Config $config): void
{
$prefixedPath = $this->prefixer->prefixPath($path);
$options = ['name' => $prefixedPath];
$visibility = $config->get(Config::OPTION_VISIBILITY, $this->defaultVisibility);
$predefinedAcl = $this->visibilityHandler->visibilityToPredefinedAcl($visibility);
if ($predefinedAcl !== PortableVisibilityHandler::NO_PREDEFINED_VISIBILITY) {
$options['predefinedAcl'] = $predefinedAcl;
}
$metadata = $config->get('metadata', []);
$shouldDetermineMimetype = $contents !== '' && ! array_key_exists('contentType', $metadata);
if ($shouldDetermineMimetype && $mimeType = $this->mimeTypeDetector->detectMimeType($path, $contents)) {
$metadata['contentType'] = $mimeType;
}
$options['metadata'] = $metadata;
try {
$this->bucket->upload($contents, $options);
} catch (Throwable $exception) {
throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception);
}
}
public function read(string $path): string
{
$prefixedPath = $this->prefixer->prefixPath($path);
try {
return $this->bucket->object($prefixedPath)->downloadAsString();
} catch (Throwable $exception) {
throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception);
}
}
public function readStream(string $path)
{
$prefixedPath = $this->prefixer->prefixPath($path);
$options = [];
if ($this->streamReads) {
$options['restOptions']['stream'] = true;
}
try {
$stream = $this->bucket->object($prefixedPath)->downloadAsStream($options)->detach();
} catch (Throwable $exception) {
throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception);
}
// @codeCoverageIgnoreStart
if ( ! is_resource($stream)) {
throw UnableToReadFile::fromLocation($path, 'Downloaded object does not contain a file resource.');
}
// @codeCoverageIgnoreEnd
return $stream;
}
public function delete(string $path): void
{
try {
$prefixedPath = $this->prefixer->prefixPath($path);
$this->bucket->object($prefixedPath)->delete();
} catch (NotFoundException $thisIsOk) {
// this is ok
} catch (Throwable $exception) {
throw UnableToDeleteFile::atLocation($path, $exception->getMessage(), $exception);
}
}
public function deleteDirectory(string $path): void
{
try {
/** @var StorageAttributes[] $listing */
$listing = $this->listContents($path, true);
foreach ($listing as $attributes) {
$this->delete($attributes->path());
}
if ($path !== '') {
$this->delete(rtrim($path, '/') . '/');
}
} catch (Throwable $exception) {
throw UnableToDeleteDirectory::atLocation($path, $exception->getMessage(), $exception);
}
}
public function createDirectory(string $path, Config $config): void
{
$prefixedPath = $this->prefixer->prefixDirectoryPath($path);
if ($prefixedPath !== '') {
$this->bucket->upload('', ['name' => $prefixedPath]);
}
}
public function setVisibility(string $path, string $visibility): void
{
try {
$prefixedPath = $this->prefixer->prefixPath($path);
$object = $this->bucket->object($prefixedPath);
$this->visibilityHandler->setVisibility($object, $visibility);
} catch (Throwable $previous) {
throw UnableToSetVisibility::atLocation($path, $previous->getMessage(), $previous);
}
}
public function visibility(string $path): FileAttributes
{
try {
$prefixedPath = $this->prefixer->prefixPath($path);
$object = $this->bucket->object($prefixedPath);
$visibility = $this->visibilityHandler->determineVisibility($object);
return new FileAttributes($path, null, $visibility);
} catch (Throwable $exception) {
throw UnableToRetrieveMetadata::visibility($path, $exception->getMessage(), $exception);
}
}
public function mimeType(string $path): FileAttributes
{
return $this->fileAttributes($path, 'mimeType');
}
public function lastModified(string $path): FileAttributes
{
return $this->fileAttributes($path, 'lastModified');
}
public function fileSize(string $path): FileAttributes
{
return $this->fileAttributes($path, 'fileSize');
}
private function fileAttributes(string $path, string $type): FileAttributes
{
$exception = null;
$prefixedPath = $this->prefixer->prefixPath($path);
try {
$object = $this->bucket->object($prefixedPath);
$fileAttributes = $this->storageObjectToStorageAttributes($object);
} catch (Throwable $exception) {
// passthrough
}
if ( ! isset($fileAttributes) || ! $fileAttributes instanceof FileAttributes || $fileAttributes[$type] === null) {
throw UnableToRetrieveMetadata::{$type}($path, isset($exception) ? $exception->getMessage() : '', $exception);
}
return $fileAttributes;
}
public function storageObjectToStorageAttributes(StorageObject $object): StorageAttributes
{
$path = $this->prefixer->stripPrefix($object->name());
$info = $object->info();
$lastModified = strtotime($info['updated']);
if (substr($path, -1, 1) === '/') {
return new DirectoryAttributes(rtrim($path, '/'), null, $lastModified);
}
$fileSize = intval($info['size']);
$mimeType = $info['contentType'] ?? null;
return new FileAttributes($path, $fileSize, null, $lastModified, $mimeType, $info);
}
public function listContents(string $path, bool $deep): iterable
{
$prefixedPath = $this->prefixer->prefixPath($path);
$prefixes = $options = [];
if ($prefixedPath !== '') {
$options = ['prefix' => sprintf('%s/', rtrim($prefixedPath, '/'))];
}
if ($deep === false) {
$options['delimiter'] = '/';
$options['includeTrailingDelimiter'] = true;
}
$objects = $this->bucket->objects($options);
/** @var StorageObject $object */
foreach ($objects as $object) {
$prefixes[$this->prefixer->stripDirectoryPrefix($object->name())] = true;
yield $this->storageObjectToStorageAttributes($object);
}
foreach ($objects->prefixes() as $prefix) {
$prefix = $this->prefixer->stripDirectoryPrefix($prefix);
if (array_key_exists($prefix, $prefixes)) {
continue;
}
$prefixes[$prefix] = true;
yield new DirectoryAttributes($prefix);
}
}
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 copy(string $source, string $destination, Config $config): void
{
try {
$visibility = $config->get(Config::OPTION_VISIBILITY);
if ($visibility === null && $config->get(Config::OPTION_RETAIN_VISIBILITY, true)) {
$visibility = $this->visibility($source)->visibility();
}
$prefixedSource = $this->prefixer->prefixPath($source);
$options = ['name' => $this->prefixer->prefixPath($destination)];
$predefinedAcl = $this->visibilityHandler->visibilityToPredefinedAcl(
$visibility ?: PortableVisibilityHandler::NO_PREDEFINED_VISIBILITY
);
if ($predefinedAcl !== PortableVisibilityHandler::NO_PREDEFINED_VISIBILITY) {
$options['predefinedAcl'] = $predefinedAcl;
}
$this->bucket->object($prefixedSource)->copy($this->bucket, $options);
} catch (Throwable $previous) {
throw UnableToCopyFile::fromLocationTo($source, $destination, $previous);
}
}
public function checksum(string $path, Config $config): string
{
$algo = $config->get('checksum_algo', 'md5');
$header = static::$algoToInfoMap[$algo] ?? null;
if ($header === null) {
throw new ChecksumAlgoIsNotSupported();
}
$prefixedPath = $this->prefixer->prefixPath($path);
try {
$checksum = $this->bucket->object($prefixedPath)->info()[$header]
?? throw new LogicException("Header not present: $header");
} catch (Throwable $exception) {
throw new UnableToProvideChecksum($exception->getMessage(), $path);
}
return bin2hex(base64_decode($checksum));
}
public function temporaryUrl(string $path, DateTimeInterface $expiresAt, Config $config): string
{
$location = $this->prefixer->prefixPath($path);
try {
return $this->bucket->object($location)->signedUrl($expiresAt, $config->get('gcp_signing_options', []));
} 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/GoogleCloudStorage/StubRiggedBucket.php | src/GoogleCloudStorage/StubRiggedBucket.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use Google\Cloud\Storage\Bucket;
use LogicException;
use Throwable;
class StubRiggedBucket extends Bucket
{
private array $triggers = [];
public function failForObject(string $name, ?Throwable $throwable = null): void
{
$this->setupTrigger('object', $name, $throwable);
}
public function failForUpload(string $name, ?Throwable $throwable = null): void
{
$this->setupTrigger('upload', $name, $throwable);
}
public function object($name, array $options = [])
{
$this->pushTrigger('object', $name);
return parent::object($name, $options);
}
public function upload($data, array $options = [])
{
$this->pushTrigger('upload', $options['name'] ?? 'unknown-object-name');
return parent::upload($data, $options);
}
private function setupTrigger(string $method, string $name, ?Throwable $throwable): void
{
$this->triggers[$method][$name] = $throwable ?? new LogicException('unknown error');
}
private function pushTrigger(string $method, string $name): void
{
$trigger = $this->triggers[$method][$name] ?? null;
if ($trigger instanceof Throwable) {
unset($this->triggers[$method][$name]);
throw $trigger;
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/VisibilityHandler.php | src/GoogleCloudStorage/VisibilityHandler.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use Google\Cloud\Storage\StorageObject;
interface VisibilityHandler
{
public function setVisibility(StorageObject $object, string $visibility): void;
public function determineVisibility(StorageObject $object): string;
public function visibilityToPredefinedAcl(string $visibility): string;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/PortableVisibilityHandler.php | src/GoogleCloudStorage/PortableVisibilityHandler.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Storage\Acl;
use Google\Cloud\Storage\StorageObject;
use League\Flysystem\Visibility;
class PortableVisibilityHandler implements VisibilityHandler
{
public const NO_PREDEFINED_VISIBILITY = 'noPredefinedVisibility';
public const ACL_PUBLIC_READ = 'publicRead';
public const ACL_AUTHENTICATED_READ = 'authenticatedRead';
public const ACL_PRIVATE = 'private';
public const ACL_PROJECT_PRIVATE = 'projectPrivate';
public function __construct(
private string $entity = 'allUsers',
private string $predefinedPublicAcl = self::ACL_PUBLIC_READ,
private string $predefinedPrivateAcl = self::ACL_PROJECT_PRIVATE
) {
}
public function setVisibility(StorageObject $object, string $visibility): void
{
if ($visibility === Visibility::PRIVATE) {
$object->acl()->delete($this->entity);
} elseif ($visibility === Visibility::PUBLIC) {
$object->acl()->update($this->entity, Acl::ROLE_READER);
}
}
public function determineVisibility(StorageObject $object): string
{
try {
$acl = $object->acl()->get(['entity' => 'allUsers']);
} catch (NotFoundException $exception) {
return Visibility::PRIVATE;
}
return $acl['role'] === Acl::ROLE_READER
? Visibility::PUBLIC
: Visibility::PRIVATE;
}
public function visibilityToPredefinedAcl(string $visibility): string
{
switch ($visibility) {
case Visibility::PUBLIC:
return $this->predefinedPublicAcl;
case self::NO_PREDEFINED_VISIBILITY:
return self::NO_PREDEFINED_VISIBILITY;
default:
return $this->predefinedPrivateAcl;
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/GoogleCloudStorage/UniformBucketLevelAccessVisibility.php | src/GoogleCloudStorage/UniformBucketLevelAccessVisibility.php | <?php
declare(strict_types=1);
namespace League\Flysystem\GoogleCloudStorage;
use Google\Cloud\Storage\StorageObject;
class UniformBucketLevelAccessVisibility implements VisibilityHandler
{
public const NO_PREDEFINED_VISIBILITY = 'noPredefinedVisibility';
public function setVisibility(StorageObject $object, string $visibility): void
{
// noop
}
public function determineVisibility(StorageObject $object): string
{
return self::NO_PREDEFINED_VISIBILITY;
}
public function visibilityToPredefinedAcl(string $visibility): string
{
return self::NO_PREDEFINED_VISIBILITY;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnixVisibility/PortableVisibilityConverterTest.php | src/UnixVisibility/PortableVisibilityConverterTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\UnixVisibility;
use League\Flysystem\InvalidVisibilityProvided;
use League\Flysystem\Visibility;
use PHPUnit\Framework\TestCase;
/**
* @group unix-visibility
*/
class PortableVisibilityConverterTest extends TestCase
{
/**
* @test
*/
public function determining_visibility_for_a_file(): void
{
$interpreter = new PortableVisibilityConverter();
$this->assertEquals(0644, $interpreter->forFile(Visibility::PUBLIC));
$this->assertEquals(0600, $interpreter->forFile(Visibility::PRIVATE));
}
/**
* @test
*/
public function determining_an_incorrect_visibility_for_a_file(): void
{
$this->expectException(InvalidVisibilityProvided::class);
$interpreter = new PortableVisibilityConverter();
$interpreter->forFile('incorrect');
}
/**
* @test
*/
public function determining_visibility_for_a_directory(): void
{
$interpreter = new PortableVisibilityConverter();
$this->assertEquals(0755, $interpreter->forDirectory(Visibility::PUBLIC));
$this->assertEquals(0700, $interpreter->forDirectory(Visibility::PRIVATE));
}
/**
* @test
*/
public function determining_an_incorrect_visibility_for_a_directory(): void
{
$this->expectException(InvalidVisibilityProvided::class);
$interpreter = new PortableVisibilityConverter();
$interpreter->forDirectory('incorrect');
}
/**
* @test
*/
public function inversing_for_a_file(): void
{
$interpreter = new PortableVisibilityConverter();
$this->assertEquals(Visibility::PUBLIC, $interpreter->inverseForFile(0644));
$this->assertEquals(Visibility::PRIVATE, $interpreter->inverseForFile(0600));
$this->assertEquals(Visibility::PUBLIC, $interpreter->inverseForFile(0404));
}
/**
* @test
*/
public function inversing_for_a_directory(): void
{
$interpreter = new PortableVisibilityConverter();
$this->assertEquals(Visibility::PUBLIC, $interpreter->inverseForDirectory(0755));
$this->assertEquals(Visibility::PRIVATE, $interpreter->inverseForDirectory(0700));
$this->assertEquals(Visibility::PUBLIC, $interpreter->inverseForDirectory(0404));
}
/**
* @test
*/
public function determining_default_for_directories(): void
{
$interpreter = new PortableVisibilityConverter();
$this->assertEquals(0700, $interpreter->defaultForDirectories());
$interpreter = new PortableVisibilityConverter(0644, 0600, 0755, 0700, Visibility::PUBLIC);
$this->assertEquals(0755, $interpreter->defaultForDirectories());
}
/**
* @test
*/
public function creating_from_array(): void
{
$interpreter = PortableVisibilityConverter::fromArray([
'file' => [
'public' => 0640,
'private' => 0604,
],
'dir' => [
'public' => 0740,
'private' => 7604,
],
]);
$this->assertEquals(0640, $interpreter->forFile(Visibility::PUBLIC));
$this->assertEquals(0604, $interpreter->forFile(Visibility::PRIVATE));
$this->assertEquals(0740, $interpreter->forDirectory(Visibility::PUBLIC));
$this->assertEquals(7604, $interpreter->forDirectory(Visibility::PRIVATE));
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnixVisibility/VisibilityConverter.php | src/UnixVisibility/VisibilityConverter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\UnixVisibility;
interface VisibilityConverter
{
public function forFile(string $visibility): int;
public function forDirectory(string $visibility): int;
public function inverseForFile(int $visibility): string;
public function inverseForDirectory(int $visibility): string;
public function defaultForDirectories(): int;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/UnixVisibility/PortableVisibilityConverter.php | src/UnixVisibility/PortableVisibilityConverter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\UnixVisibility;
use League\Flysystem\PortableVisibilityGuard;
use League\Flysystem\Visibility;
class PortableVisibilityConverter implements VisibilityConverter
{
public function __construct(
private int $filePublic = 0644,
private int $filePrivate = 0600,
private int $directoryPublic = 0755,
private int $directoryPrivate = 0700,
private string $defaultForDirectories = Visibility::PRIVATE
) {
}
public function forFile(string $visibility): int
{
PortableVisibilityGuard::guardAgainstInvalidInput($visibility);
return $visibility === Visibility::PUBLIC
? $this->filePublic
: $this->filePrivate;
}
public function forDirectory(string $visibility): int
{
PortableVisibilityGuard::guardAgainstInvalidInput($visibility);
return $visibility === Visibility::PUBLIC
? $this->directoryPublic
: $this->directoryPrivate;
}
public function inverseForFile(int $visibility): string
{
if ($visibility === $this->filePublic) {
return Visibility::PUBLIC;
} elseif ($visibility === $this->filePrivate) {
return Visibility::PRIVATE;
}
return Visibility::PUBLIC; // default
}
public function inverseForDirectory(int $visibility): string
{
if ($visibility === $this->directoryPublic) {
return Visibility::PUBLIC;
} elseif ($visibility === $this->directoryPrivate) {
return Visibility::PRIVATE;
}
return Visibility::PUBLIC; // default
}
public function defaultForDirectories(): int
{
return $this->defaultForDirectories === Visibility::PUBLIC ? $this->directoryPublic : $this->directoryPrivate;
}
/**
* @param array<mixed> $permissionMap
*/
public static function fromArray(array $permissionMap, string $defaultForDirectories = Visibility::PRIVATE): PortableVisibilityConverter
{
return new PortableVisibilityConverter(
$permissionMap['file']['public'] ?? 0644,
$permissionMap['file']['private'] ?? 0600,
$permissionMap['dir']['public'] ?? 0755,
$permissionMap['dir']['private'] ?? 0700,
$defaultForDirectories
);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AsyncAwsS3/AsyncAwsS3Adapter.php | src/AsyncAwsS3/AsyncAwsS3Adapter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\AsyncAwsS3;
use AsyncAws\Core\Exception\Http\ClientException;
use AsyncAws\Core\Stream\ResultStream;
use AsyncAws\S3\Input\GetObjectRequest;
use AsyncAws\S3\Result\HeadObjectOutput;
use AsyncAws\S3\S3Client;
use AsyncAws\S3\ValueObject\AwsObject;
use AsyncAws\S3\ValueObject\CommonPrefix;
use AsyncAws\S3\ValueObject\ObjectIdentifier;
use AsyncAws\SimpleS3\SimpleS3Client;
use DateTimeImmutable;
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\PathPrefixer;
use League\Flysystem\StorageAttributes;
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\UnableToListContents;
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 Throwable;
use function trim;
class AsyncAwsS3Adapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumProvider, TemporaryUrlGenerator
{
/**
* @var string[]
*/
public const AVAILABLE_OPTIONS = [
'ACL',
'CacheControl',
'ContentDisposition',
'ContentEncoding',
'ContentLength',
'ContentType',
'ContentMD5',
'Expires',
'GrantFullControl',
'GrantRead',
'GrantReadACP',
'GrantWriteACP',
'Metadata',
'MetadataDirective',
'RequestPayer',
'SSECustomerAlgorithm',
'SSECustomerKey',
'SSECustomerKeyMD5',
'SSEKMSKeyId',
'ServerSideEncryption',
'StorageClass',
'Tagging',
'WebsiteRedirectLocation',
'ChecksumAlgorithm',
'CopySourceSSECustomerAlgorithm',
'CopySourceSSECustomerKey',
'CopySourceSSECustomerKeyMD5',
];
/**
* @var string[]
*/
protected const EXTRA_METADATA_FIELDS = [
'Metadata',
'StorageClass',
'ETag',
'VersionId',
];
private PathPrefixer $prefixer;
private VisibilityConverter $visibility;
private MimeTypeDetector $mimeTypeDetector;
/**
* @var array|string[]
*/
private array $forwardedOptions;
/**
* @var array|string[]
*/
private array $metadataFields;
/**
* @param S3Client|SimpleS3Client $client Uploading of files larger than 5GB is only supported with SimpleS3Client
*/
public function __construct(
private S3Client $client,
private string $bucket,
string $prefix = '',
?VisibilityConverter $visibility = null,
?MimeTypeDetector $mimeTypeDetector = null,
array $forwardedOptions = self::AVAILABLE_OPTIONS,
array $metadataFields = self::EXTRA_METADATA_FIELDS,
) {
$this->prefixer = new PathPrefixer($prefix);
$this->visibility = $visibility ?? new PortableVisibilityConverter();
$this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector();
$this->forwardedOptions = $forwardedOptions;
$this->metadataFields = $metadataFields;
}
public function fileExists(string $path): bool
{
try {
return $this->client->objectExists(
[
'Bucket' => $this->bucket,
'Key' => $this->prefixer->prefixPath($path),
]
)->isSuccess();
} catch (ClientException $e) {
throw UnableToCheckFileExistence::forLocation($path, $e);
}
}
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);
}
public function read(string $path): string
{
$body = $this->readObject($path);
return $body->getContentAsString();
}
public function readStream(string $path)
{
$body = $this->readObject($path);
return $body->getContentAsResource();
}
public function delete(string $path): void
{
$arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];
try {
$this->client->deleteObject($arguments);
} catch (Throwable $exception) {
throw UnableToDeleteFile::atLocation($path, '', $exception);
}
}
public function deleteDirectory(string $path): void
{
$prefix = $this->prefixer->prefixDirectoryPath($path);
$prefix = ltrim($prefix, '/');
$objects = [];
$params = ['Bucket' => $this->bucket, 'Prefix' => $prefix];
try {
$result = $this->client->listObjectsV2($params);
/** @var AwsObject $item */
foreach ($result->getContents() as $item) {
$key = $item->getKey();
if (null !== $key) {
$objects[] = $this->createObjectIdentifierForXmlRequest($key);
}
}
if (empty($objects)) {
return;
}
foreach (array_chunk($objects, 1000) as $chunk) {
$this->client->deleteObjects([
'Bucket' => $this->bucket,
'Delete' => ['Objects' => $chunk],
]);
}
} catch (\Throwable $e) {
throw UnableToDeleteDirectory::atLocation($path, $e->getMessage(), $e);
}
}
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]);
try {
$this->upload(rtrim($path, '/') . '/', '', $config);
} catch (Throwable $e) {
throw UnableToCreateDirectory::dueToFailure($path, $e);
}
}
public function setVisibility(string $path, string $visibility): void
{
$arguments = [
'Bucket' => $this->bucket,
'Key' => $this->prefixer->prefixPath($path),
'ACL' => $this->visibility->visibilityToAcl($visibility),
];
try {
$this->client->putObjectAcl($arguments);
} catch (Throwable $exception) {
throw UnableToSetVisibility::atLocation($path, $exception->getMessage(), $exception);
}
}
public function visibility(string $path): FileAttributes
{
$arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];
try {
$result = $this->client->getObjectAcl($arguments);
$grants = $result->getGrants();
} catch (Throwable $exception) {
throw UnableToRetrieveMetadata::visibility($path, $exception->getMessage(), $exception);
}
$visibility = $this->visibility->aclToVisibility($grants);
return new FileAttributes($path, null, $visibility);
}
public function mimeType(string $path): FileAttributes
{
$attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_MIME_TYPE);
if (null === $attributes->mimeType()) {
throw UnableToRetrieveMetadata::mimeType($path);
}
return $attributes;
}
public function lastModified(string $path): FileAttributes
{
$attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_LAST_MODIFIED);
if (null === $attributes->lastModified()) {
throw UnableToRetrieveMetadata::lastModified($path);
}
return $attributes;
}
public function fileSize(string $path): FileAttributes
{
$attributes = $this->fetchFileMetadata($path, FileAttributes::ATTRIBUTE_FILE_SIZE);
if (null === $attributes->fileSize()) {
throw UnableToRetrieveMetadata::fileSize($path);
}
return $attributes;
}
public function directoryExists(string $path): bool
{
try {
$prefix = $this->prefixer->prefixDirectoryPath($path);
$options = ['Bucket' => $this->bucket, 'Prefix' => $prefix, 'MaxKeys' => 1, 'Delimiter' => '/'];
return $this->client->listObjectsV2($options)->getKeyCount() > 0;
} catch (Throwable $exception) {
throw UnableToCheckDirectoryExistence::forLocation($path, $exception);
}
}
public function listContents(string $path, bool $deep): iterable
{
$path = trim($path, '/');
$prefix = trim($this->prefixer->prefixPath($path), '/');
$prefix = $prefix === '' ? '' : $prefix . '/';
$options = ['Bucket' => $this->bucket, 'Prefix' => $prefix];
if (false === $deep) {
$options['Delimiter'] = '/';
}
try {
$listing = $this->retrievePaginatedListing($options);
foreach ($listing as $item) {
$item = $this->mapS3ObjectMetadata($item);
if ($item->path() === $path) {
continue;
}
yield $item;
}
} catch (\Throwable $e) {
throw UnableToListContents::atLocation($path, $deep, $e);
}
}
public function move(string $source, string $destination, Config $config): void
{
if ($source === $destination) {
return;
}
try {
$this->copy($source, $destination, $config);
$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;
}
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);
}
$arguments = [
'ACL' => $this->visibility->visibilityToAcl($visibility ?: 'private'),
'Bucket' => $this->bucket,
'Key' => $this->prefixer->prefixPath($destination),
'CopySource' => rawurlencode($this->bucket . '/' . $this->prefixer->prefixPath($source)),
];
try {
$this->client->copyObject($arguments);
} catch (Throwable $exception) {
throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
}
}
/**
* @param string|resource $body
*/
private function upload(string $path, $body, Config $config): void
{
$key = $this->prefixer->prefixPath($path);
$acl = $this->determineAcl($config);
$options = $this->createOptionsFromConfig($config);
$shouldDetermineMimetype = '' !== $body && ! \array_key_exists('ContentType', $options);
if ($shouldDetermineMimetype && $mimeType = $this->mimeTypeDetector->detectMimeType($key, $body)) {
$options['ContentType'] = $mimeType;
}
try {
if ($this->client instanceof SimpleS3Client) {
// Supports upload of files larger than 5GB
$this->client->upload($this->bucket, $key, $body, array_merge($options, ['ACL' => $acl]));
} else {
$this->client->putObject(array_merge($options, [
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => $body,
'ACL' => $acl,
]));
}
} 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
{
$options = [];
foreach ($this->forwardedOptions as $option) {
$value = $config->get($option, '__NOT_SET__');
if ('__NOT_SET__' !== $value) {
$options[$option] = $value;
}
}
return $options;
}
private function fetchFileMetadata(string $path, string $type): FileAttributes
{
$arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];
try {
$result = $this->client->headObject($arguments);
$result->resolve();
} catch (Throwable $exception) {
throw UnableToRetrieveMetadata::create($path, $type, $exception->getMessage(), $exception);
}
$attributes = $this->mapS3ObjectMetadata($result, $path);
if ( ! $attributes instanceof FileAttributes) {
throw UnableToRetrieveMetadata::create($path, $type, 'Unable to retrieve file attributes, directory attributes received.');
}
return $attributes;
}
/**
* @param HeadObjectOutput|AwsObject|CommonPrefix $item
*/
private function mapS3ObjectMetadata($item, ?string $path = null): StorageAttributes
{
if (null === $path) {
if ($item instanceof AwsObject) {
$path = $this->prefixer->stripPrefix($item->getKey() ?? '');
} elseif ($item instanceof CommonPrefix) {
$path = $this->prefixer->stripPrefix($item->getPrefix() ?? '');
} else {
throw new \RuntimeException(sprintf('Argument 2 of "%s" cannot be null when $item is not instance of "%s" or %s', __METHOD__, AwsObject::class, CommonPrefix::class));
}
}
if ('/' === substr($path, -1)) {
return new DirectoryAttributes(rtrim($path, '/'));
}
$mimeType = null;
$fileSize = null;
$lastModified = null;
$dateTime = null;
$metadata = [];
if ($item instanceof AwsObject) {
$dateTime = $item->getLastModified();
$fileSize = $item->getSize();
} elseif ($item instanceof CommonPrefix) {
// No data available
} elseif ($item instanceof HeadObjectOutput) {
$mimeType = $item->getContentType();
$fileSize = $item->getContentLength();
$dateTime = $item->getLastModified();
$metadata = $this->extractExtraMetadata($item);
} else {
throw new \RuntimeException(sprintf('Object of class "%s" is not supported in %s()', \get_class($item), __METHOD__));
}
if ($dateTime instanceof \DateTimeInterface) {
$lastModified = $dateTime->getTimestamp();
}
return new FileAttributes($path, $fileSize !== null ? (int) $fileSize : null, null, $lastModified, $mimeType, $metadata);
}
/**
* @param HeadObjectOutput $metadata
*/
private function extractExtraMetadata($metadata): array
{
$extracted = [];
foreach ($this->metadataFields as $field) {
$method = 'get' . $field;
if ( ! method_exists($metadata, $method)) {
continue;
}
$value = $metadata->$method();
if (null !== $value) {
$extracted[$field] = $value;
}
}
return $extracted;
}
private function retrievePaginatedListing(array $options): Generator
{
$result = $this->client->listObjectsV2($options);
foreach ($result as $item) {
yield $item;
}
}
private function readObject(string $path): ResultStream
{
$options = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];
try {
return $this->client->getObject($options)->getBody();
} catch (Throwable $exception) {
throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception);
}
}
private function createObjectIdentifierForXmlRequest(string $key): ObjectIdentifier
{
$escapedKey = htmlentities($key, ENT_XML1 | ENT_QUOTES, 'UTF-8');
if ($escapedKey === '') {
throw new \RuntimeException(sprintf('Cannot escape key "%s" for XML request, htmlentities() returned an empty string.', $key));
}
return new ObjectIdentifier(['Key' => $escapedKey]);
}
public function publicUrl(string $path, Config $config): string
{
if ( ! $this->client instanceof SimpleS3Client) {
throw UnableToGeneratePublicUrl::noGeneratorConfigured($path, 'Client needs to be instance of SimpleS3Client');
}
try {
return $this->client->getUrl($this->bucket, $this->prefixer->prefixPath($path));
} 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 {
$request = new GetObjectRequest([
'Bucket' => $this->bucket,
'Key' => $this->prefixer->prefixPath($path),
] + $config->get('get_object_options', []));
return $this->client->presign($request, DateTimeImmutable::createFromInterface($expiresAt));
} 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/AsyncAwsS3/AsyncAwsS3AdapterTest.php | src/AsyncAwsS3/AsyncAwsS3AdapterTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\AsyncAwsS3;
use AsyncAws\Core\Exception\Http\ClientException;
use AsyncAws\Core\Exception\Http\NetworkException;
use AsyncAws\Core\Test\Http\SimpleMockedResponse;
use AsyncAws\Core\Test\ResultMockFactory;
use AsyncAws\S3\Result\HeadObjectOutput;
use AsyncAws\S3\Result\ListObjectsV2Output;
use AsyncAws\S3\Result\PutObjectOutput;
use AsyncAws\S3\S3Client;
use AsyncAws\S3\ValueObject\AwsObject;
use AsyncAws\SimpleS3\SimpleS3Client;
use Exception;
use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use League\Flysystem\ChecksumAlgoIsNotSupported;
use League\Flysystem\Config;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToCheckFileExistence;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToListContents;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToWriteFile;
use League\Flysystem\Visibility;
use function getenv;
use function iterator_to_array;
/**
* @group aws
*/
class AsyncAwsS3AdapterTest extends FilesystemAdapterTestCase
{
/**
* @var bool
*/
private $shouldCleanUp = false;
/**
* @var string
*/
private static $adapterPrefix = 'test-prefix';
/**
* @var S3Client|null
*/
private static $s3Client;
/**
* @var S3ClientStub
*/
private static $stubS3Client;
private static function awsConfig(): array
{
$key = getenv('FLYSYSTEM_AWS_S3_KEY');
$secret = getenv('FLYSYSTEM_AWS_S3_SECRET');
$region = getenv('FLYSYSTEM_AWS_S3_REGION') ?: 'eu-central-1';
if ( ! $key || ! $secret) {
self::markTestSkipped('No AWS credentials present for testing.');
}
return [
'accessKeyId' => $key,
'accessKeySecret' => $secret,
'region' => $region,
];
}
protected function setUp(): void
{
parent::setUp();
$this->retryOnException(NetworkException::class);
}
public static function setUpBeforeClass(): void
{
static::$adapterPrefix = '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());
}
}
}
private static function s3Client(): S3Client
{
if (static::$s3Client instanceof S3Client) {
return static::$s3Client;
}
$bucket = getenv('FLYSYSTEM_AWS_S3_BUCKET');
if ( ! $bucket) {
self::markTestSkipped('No AWS credentials present for testing.');
}
static::$s3Client = new SimpleS3Client(self::awsConfig());
return static::$s3Client;
}
/**
* @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
*
* @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 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 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->throwExceptionWhenExecutingCommand('CopyObject');
$this->expectException(UnableToMoveFile::class);
$adapter->move('source.txt', 'destination.txt', 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 delete_directory_replaces_special_characters_by_xml_entity_codes(): void
{
$this->runScenario(function () {
$directory = 'to-delete';
$object = sprintf('/%s/\'\"&<>.txt', $directory);
$adapter = $this->adapter();
$adapter->write(
$object,
'',
new Config()
);
$adapter->deleteDirectory($directory);
$this->assertFalse($adapter->fileExists($object));
$this->assertFalse($adapter->directoryExists($directory));
});
}
/**
* @test
*/
public function delete_directory_throws_exception_if_object_key_can_not_be_escaped_correctly(): void
{
$listObjectsMock = $this->getMockBuilder(ListObjectsV2Output::class)
->disableOriginalConstructor()
->onlyMethods(['getContents'])
->getMock();
$listObjectsMock->expects(self::once())
->method('getContents')
->willReturn([new AwsObject(['Key' => "\x8F.txt"])]);
$s3Client = $this->getMockBuilder(S3Client::class)
->disableOriginalConstructor()
->onlyMethods(['ListObjectsV2'])
->getMock();
$s3Client->expects(self::once())
->method('ListObjectsV2')
->willReturn($listObjectsMock);
$filesystem = new AsyncAwsS3Adapter($s3Client, 'my-bucket');
$this->expectException(UnableToDeleteDirectory::class);
$this->expectExceptionMessageMatches('/htmlentities\(\) returned an empty string/');
$filesystem->deleteDirectory('directory/containing/objects/with/un-escapable/key');
}
/**
* @test
*/
public function fetching_unknown_mime_type_of_a_file(): void
{
$this->adapter();
$result = ResultMockFactory::create(HeadObjectOutput::class, []);
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 = ResultMockFactory::create(HeadObjectOutput::class, []);
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();
$exception = new ClientException(new SimpleMockedResponse());
static::$stubS3Client->throwExceptionWhenExecutingCommand('ObjectExists', $exception);
$this->expectException(UnableToCheckFileExistence::class);
$adapter->fileExists('something-that-does-exist.txt');
}
/**
* @test
*/
public function configuring_http_streaming_via_options(): void
{
$adapter = $this->useAdapter($this->createFilesystemAdapter());
$this->givenWeHaveAnExistingFile('path.txt');
$resource = $adapter->readStream('path.txt');
$metadata = stream_get_meta_data($resource);
fclose($resource);
$this->assertTrue($metadata['seekable']);
}
/**
* @test
*/
public function write_with_s3_client(): void
{
$file = 'foo/bar.txt';
$prefix = 'all-files';
$bucket = 'foobar';
$contents = 'contents';
$s3Client = $this->getMockBuilder(S3Client::class)
->disableOriginalConstructor()
->onlyMethods(['putObject'])
->getMock();
$s3Client->expects(self::once())
->method('putObject')
->with(self::callback(function (array $input) use ($file, $prefix, $bucket, $contents) {
if ($input['Key'] !== $prefix . '/' . $file) {
return false;
}
if ($contents !== $input['Body']) {
return false;
}
if ($input['Bucket'] !== $bucket) {
return false;
}
return true;
}))->willReturn(ResultMockFactory::create(PutObjectOutput::class));
$filesystem = new AsyncAwsS3Adapter($s3Client, $bucket, $prefix);
$filesystem->write($file, $contents, new Config());
}
/**
* @test
*/
public function write_with_simple_s3_client(): void
{
$file = 'foo/bar.txt';
$prefix = 'all-files';
$bucket = 'foobar';
$contents = 'contents';
$s3Client = $this->getMockBuilder(SimpleS3Client::class)
->disableOriginalConstructor()
->onlyMethods(['upload', 'putObject'])
->getMock();
$s3Client->expects(self::never())->method('putObject');
$s3Client->expects(self::once())
->method('upload')
->with($bucket, $prefix . '/' . $file, $contents);
$filesystem = new AsyncAwsS3Adapter($s3Client, $bucket, $prefix);
$filesystem->write($file, $contents, new Config());
}
/**
* @test
*/
public function failing_to_write_a_file(): void
{
$adapter = $this->adapter();
static::$stubS3Client->throwExceptionWhenExecutingCommand('PutObject');
$this->expectException(UnableToWriteFile::class);
$adapter->write('foo/bar.txt', 'contents', new Config());
}
/**
* @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 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'));
});
}
/**
* @test
*/
public function copying_a_file_with_non_ascii_characters(): void
{
$this->runScenario(function () {
$adapter = $this->adapter();
$adapter->write(
'ıÇöü🤔.txt',
'contents to be copied',
new Config()
);
$adapter->copy('ıÇöü🤔.txt', 'ıÇöü🤔_copy.txt', new Config());
$this->assertTrue($adapter->fileExists('ıÇöü🤔.txt'));
$this->assertTrue($adapter->fileExists('ıÇöü🤔_copy.txt'));
$this->assertEquals('contents to be copied', $adapter->read('ıÇöü🤔_copy.txt'));
});
}
/**
* @test
*/
public function top_level_directory_excluded_from_listing(): void
{
$this->runScenario(function () {
$adapter = $this->adapter();
$adapter->write('directory/file.txt', '', new Config());
$adapter->createDirectory('empty', new Config());
$adapter->createDirectory('nested/nested', new Config());
$listing1 = iterator_to_array($adapter->listContents('directory', true));
$listing2 = iterator_to_array($adapter->listContents('empty', true));
$listing3 = iterator_to_array($adapter->listContents('nested', true));
self::assertCount(1, $listing1);
self::assertCount(0, $listing2);
self::assertCount(1, $listing3);
});
}
/**
* @test
*/
public function failing_to_list_contents(): void
{
$adapter = $this->adapter();
static::$stubS3Client->throwExceptionWhenExecutingCommand('ListObjectsV2');
$this->expectException(UnableToListContents::class);
iterator_to_array($adapter->listContents('/path', false));
}
protected static function createFilesystemAdapter(): FilesystemAdapter
{
static::$stubS3Client = new S3ClientStub(static::s3Client(), self::awsConfig());
/** @var string $bucket */
$bucket = getenv('FLYSYSTEM_AWS_S3_BUCKET');
$prefix = getenv('FLYSYSTEM_AWS_S3_PREFIX') ?: static::$adapterPrefix;
return new AsyncAwsS3Adapter(static::$stubS3Client, $bucket, $prefix, null, null);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/AsyncAwsS3/VisibilityConverter.php | src/AsyncAwsS3/VisibilityConverter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\AsyncAwsS3;
use AsyncAws\S3\ValueObject\Grant;
interface VisibilityConverter
{
public function visibilityToAcl(string $visibility): string;
/**
* @param Grant[] $grants
*/
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/AsyncAwsS3/PortableVisibilityConverter.php | src/AsyncAwsS3/PortableVisibilityConverter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\AsyncAwsS3;
use AsyncAws\S3\ValueObject\Grant;
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';
/**
* @var string
*/
private $defaultForDirectories;
public function __construct(string $defaultForDirectories = Visibility::PUBLIC)
{
$this->defaultForDirectories = $defaultForDirectories;
}
public function visibilityToAcl(string $visibility): string
{
if (Visibility::PUBLIC === $visibility) {
return self::PUBLIC_ACL;
}
return self::PRIVATE_ACL;
}
/**
* @param Grant[] $grants
*/
public function aclToVisibility(array $grants): string
{
foreach ($grants as $grant) {
if (null === $grantee = $grant->getGrantee()) {
continue;
}
$granteeUri = $grantee->getURI();
$permission = $grant->getPermission();
if (self::PUBLIC_GRANTEE_URI === $granteeUri && self::PUBLIC_GRANTS_PERMISSION === $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/AsyncAwsS3/S3ClientStub.php | src/AsyncAwsS3/S3ClientStub.php | <?php
declare(strict_types=1);
namespace League\Flysystem\AsyncAwsS3;
use AsyncAws\Core\Exception\Exception;
use AsyncAws\Core\Exception\Http\NetworkException;
use AsyncAws\Core\Result;
use AsyncAws\S3\Input\CopyObjectRequest;
use AsyncAws\S3\Input\DeleteObjectRequest;
use AsyncAws\S3\Input\DeleteObjectsRequest;
use AsyncAws\S3\Input\GetObjectAclRequest;
use AsyncAws\S3\Input\GetObjectRequest;
use AsyncAws\S3\Input\HeadObjectRequest;
use AsyncAws\S3\Input\ListObjectsV2Request;
use AsyncAws\S3\Input\PutObjectAclRequest;
use AsyncAws\S3\Input\PutObjectRequest;
use AsyncAws\S3\Result\CopyObjectOutput;
use AsyncAws\S3\Result\DeleteObjectOutput;
use AsyncAws\S3\Result\DeleteObjectsOutput;
use AsyncAws\S3\Result\GetObjectAclOutput;
use AsyncAws\S3\Result\GetObjectOutput;
use AsyncAws\S3\Result\HeadObjectOutput;
use AsyncAws\S3\Result\ListObjectsV2Output;
use AsyncAws\S3\Result\ObjectExistsWaiter;
use AsyncAws\S3\Result\PutObjectAclOutput;
use AsyncAws\S3\Result\PutObjectOutput;
use AsyncAws\S3\S3Client;
use AsyncAws\SimpleS3\SimpleS3Client;
use DateTimeImmutable;
use Symfony\Component\HttpClient\MockHttpClient;
/**
* @codeCoverageIgnore
*/
class S3ClientStub extends SimpleS3Client
{
/**
* @var S3Client
*/
private $actualClient;
/**
* @var Exception[]
*/
private $stagedExceptions = [];
/**
* @var Result[]
*/
private $stagedResult = [];
public function __construct(SimpleS3Client $client, $configuration = [])
{
$this->actualClient = $client;
parent::__construct($configuration, null, new MockHttpClient());
}
public function throwExceptionWhenExecutingCommand(string $commandName, ?Exception $exception = null): void
{
$this->stagedExceptions[$commandName] = $exception ?? new NetworkException();
}
public function stageResultForCommand(string $commandName, Result $result): void
{
$this->stagedResult[$commandName] = $result;
}
private function getStagedResult(string $name): ?Result
{
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 $result;
}
return null;
}
/**
* @param array|CopyObjectRequest $input
*/
public function copyObject($input): CopyObjectOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('CopyObject') ?? $this->actualClient->copyObject($input);
}
/**
* @param array|DeleteObjectRequest $input
*/
public function deleteObject($input): DeleteObjectOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('DeleteObject') ?? $this->actualClient->deleteObject($input);
}
/**
* @param array|HeadObjectRequest $input
*/
public function headObject($input): HeadObjectOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('HeadObject') ?? $this->actualClient->headObject($input);
}
/**
* @param array|HeadObjectRequest $input
*/
public function objectExists($input): ObjectExistsWaiter
{
// @phpstan-ignore-next-line
return $this->getStagedResult('ObjectExists') ?? $this->actualClient->objectExists($input);
}
/**
* @param array|ListObjectsV2Request $input
*/
public function listObjectsV2($input): ListObjectsV2Output
{
// @phpstan-ignore-next-line
return $this->getStagedResult('ListObjectsV2') ?? $this->actualClient->listObjectsV2($input);
}
/**
* @param array|DeleteObjectsRequest $input
*/
public function deleteObjects($input): DeleteObjectsOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('DeleteObjects') ?? $this->actualClient->deleteObjects($input);
}
/**
* @param array|GetObjectAclRequest $input
*/
public function getObjectAcl($input): GetObjectAclOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('GetObjectAcl') ?? $this->actualClient->getObjectAcl($input);
}
/**
* @param array|PutObjectAclRequest $input
*/
public function putObjectAcl($input): PutObjectAclOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('PutObjectAcl') ?? $this->actualClient->putObjectAcl($input);
}
/**
* @param array|PutObjectRequest $input
*/
public function putObject($input): PutObjectOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('PutObject') ?? $this->actualClient->putObject($input);
}
/**
* @param array|GetObjectRequest $input
*/
public function getObject($input): GetObjectOutput
{
// @phpstan-ignore-next-line
return $this->getStagedResult('GetObject') ?? $this->actualClient->getObject($input);
}
public function getUrl(string $bucket, string $key): string
{
return $this->actualClient->getUrl($bucket, $key);
}
public function getPresignedUrl(string $bucket, string $key, ?DateTimeImmutable $expires = null, ?string $versionId = null): string
{
return $this->actualClient->getPresignedUrl($bucket, $key, $expires);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/UnableToEstablishAuthenticityOfHost.php | src/PhpseclibV2/UnableToEstablishAuthenticityOfHost.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use League\Flysystem\FilesystemException;
use RuntimeException;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\UnableToEstablishAuthenticityOfHost" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\UnableToEstablishAuthenticityOfHost" instead.
*/
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/PhpseclibV2/SftpStub.php | src/PhpseclibV2/SftpStub.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @internal This is only used for testing purposes.
*
* @deprecated The "League\Flysystem\PhpseclibV2\SftpStub" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\SftpStub" instead.
*/
class SftpStub extends SFTP
{
/**
* @var array<string,bool>
*/
private $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 reset(): void
{
$this->tripWires = [];
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/UnableToConnectToSftpHost.php | src/PhpseclibV2/UnableToConnectToSftpHost.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use League\Flysystem\FilesystemException;
use RuntimeException;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\UnableToConnectToSftpHost" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\UnableToConnectToSftpHost" instead.
*/
class UnableToConnectToSftpHost extends RuntimeException implements FilesystemException
{
public static function atHostname(string $host): UnableToConnectToSftpHost
{
return new UnableToConnectToSftpHost("Unable to connect to host: $host");
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/SftpAdapter.php | src/PhpseclibV2/SftpAdapter.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
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 phpseclib\Net\SFTP;
use Throwable;
use function rtrim;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\SftpAdapter" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\SftpAdapter" instead.
*/
class SftpAdapter implements FilesystemAdapter
{
/**
* @var ConnectionProvider
*/
private $connectionProvider;
/**
* @var VisibilityConverter
*/
private $visibilityConverter;
/**
* @var PathPrefixer
*/
private $prefixer;
/**
* @var MimeTypeDetector
*/
private $mimeTypeDetector;
public function __construct(
ConnectionProvider $connectionProvider,
string $root,
?VisibilityConverter $visibilityConverter = null,
?MimeTypeDetector $mimeTypeDetector = null,
private bool $detectMimeTypeUsingPath = false,
) {
$this->connectionProvider = $connectionProvider;
$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 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 ($listing === false) {
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['permissions'] & 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 ( ! $connection->rename($sourceLocation, $destinationLocation)) {
throw UnableToMoveFile::fromLocationTo($source, $destination);
}
}
public function copy(string $source, string $destination, Config $config): void
{
try {
$readStream = $this->readStream($source);
$visibility = $this->visibility($source)->visibility();
$this->writeStream($destination, $readStream, new Config(compact(Config::OPTION_VISIBILITY)));
} catch (Throwable $exception) {
if (isset($readStream) && is_resource($readStream)) {
@fclose($readStream);
}
throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/ConnectionProvider.php | src/PhpseclibV2/ConnectionProvider.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\ConnectionProvider" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\ConnectionProvider" instead.
*/
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/PhpseclibV2/SftpConnectionProviderTest.php | src/PhpseclibV2/SftpConnectionProviderTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
use PHPUnit\Framework\TestCase;
use function class_exists;
/**
* @group sftp
* @group sftp-connection
* @group legacy
*/
class SftpConnectionProviderTest extends TestCase
{
protected function setUp(): void
{
if ( ! class_exists('phpseclib\Net\SFTP')) {
self::markTestSkipped("PHPSecLib V2 is not installed");
}
parent::setUp();
}
/**
* @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 = $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);
$provider->provideConnection();
}
/**
* @test
*/
public function authenticating_with_an_ssh_agent(): void
{
$provider = SftpConnectionProvider::fromArray(
[
'host' => 'localhost',
'username' => 'bar',
'useAgent' => true,
'port' => 2222,
]
);
$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 = $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());
$provider->provideConnection();
}
/**
* @test
*/
public function verifying_a_fingerprint(): void
{
$key = file_get_contents(__DIR__ . '/../../test_files/sftp/ssh_host_rsa_key.pub');
$fingerPrint = $this->computeFingerPrint($key);
$provider = SftpConnectionProvider::fromArray(
[
'host' => 'localhost',
'username' => 'foo',
'password' => 'pass',
'port' => 2222,
'hostFingerprint' => $fingerPrint,
]
);
$anotherConnection = $provider->provideConnection();
$this->assertInstanceOf(SFTP::class, $anotherConnection);
}
/**
* @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',
]
);
$provider->provideConnection();
}
/**
* @test
*/
public function providing_an_invalid_password(): void
{
$this->expectException(UnableToAuthenticate::class);
$provider = SftpConnectionProvider::fromArray(
[
'host' => 'localhost',
'username' => 'foo',
'password' => 'lol',
'port' => 2222,
]
);
$provider->provideConnection();
}
private function computeFingerPrint(string $publicKey): string
{
$content = explode(' ', $publicKey, 3);
return implode(':', str_split(md5(base64_decode($content[1])), 2));
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/UnableToLoadPrivateKey.php | src/PhpseclibV2/UnableToLoadPrivateKey.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use League\Flysystem\FilesystemException;
use RuntimeException;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\UnableToLoadPrivateKey" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\UnableToLoadPrivateKey" instead.
*/
class UnableToLoadPrivateKey extends RuntimeException implements FilesystemException
{
public function __construct(string $message = "Unable to load private key.")
{
parent::__construct($message);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/SftpConnectionProvider.php | src/PhpseclibV2/SftpConnectionProvider.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Crypt\RSA;
use phpseclib\Net\SFTP;
use phpseclib\System\SSH\Agent;
use Throwable;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\SftpConnectionProvider" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\SftpConnectionProvider" instead.
*/
class SftpConnectionProvider implements ConnectionProvider
{
/**
* @var string
*/
private $host;
/**
* @var string
*/
private $username;
/**
* @var string|null
*/
private $password;
/**
* @var bool
*/
private $useAgent;
/**
* @var int
*/
private $port;
/**
* @var int
*/
private $timeout;
/**
* @var SFTP|null
*/
private $connection;
/**
* @var ConnectivityChecker
*/
private $connectivityChecker;
/**
* @var string|null
*/
private $hostFingerprint;
/**
* @var string|null
*/
private $privateKey;
/**
* @var string|null
*/
private $passphrase;
/**
* @var int
*/
private $maxTries;
public function __construct(
string $host,
string $username,
?string $password = null,
?string $privateKey = null,
?string $passphrase = null,
int $port = 22,
bool $useAgent = false,
int $timeout = 10,
int $maxTries = 4,
?string $hostFingerprint = null,
?ConnectivityChecker $connectivityChecker = null,
private bool $disableStatCache = true,
) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->privateKey = $privateKey;
$this->passphrase = $passphrase;
$this->useAgent = $useAgent;
$this->port = $port;
$this->timeout = $timeout;
$this->hostFingerprint = $hostFingerprint;
$this->connectivityChecker = $connectivityChecker ?? new SimpleConnectivityChecker();
$this->maxTries = $maxTries;
}
public function provideConnection(): SFTP
{
$tries = 0;
start:
$connection = $this->connection instanceof SFTP
? $this->connection
: $this->setupConnection();
if ( ! $this->connectivityChecker->isConnected($connection)) {
$connection->disconnect();
$this->connection = null;
if ($tries < $this->maxTries) {
$tries++;
goto start;
}
throw UnableToConnectToSftpHost::atHostname($this->host);
}
return $this->connection = $connection;
}
private function setupConnection(): SFTP
{
$connection = new SFTP($this->host, $this->port, $this->timeout);
$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);
return implode(':', str_split(md5(base64_decode($content[1])), 2));
}
private function authenticate(SFTP $connection): void
{
if ($this->privateKey !== null) {
$this->authenticateWithPrivateKey($connection);
} elseif ($this->useAgent) {
$this->authenticateWithAgent($connection);
} elseif ( ! $connection->login($this->username, $this->password)) {
throw UnableToAuthenticate::withPassword();
}
}
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
);
}
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();
}
private function loadPrivateKey(): RSA
{
if ("---" !== substr($this->privateKey, 0, 3) && is_file($this->privateKey)) {
$this->privateKey = file_get_contents($this->privateKey);
}
$key = new RSA();
if ($this->passphrase !== null) {
$key->setPassword($this->passphrase);
}
if ( ! $key->loadKey($this->privateKey)) {
throw new UnableToLoadPrivateKey();
}
return $key;
}
private function authenticateWithAgent(SFTP $connection): void
{
$agent = new Agent();
if ( ! $connection->login($this->username, $agent)) {
throw UnableToAuthenticate::withSshAgent();
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/FixatedConnectivityChecker.php | src/PhpseclibV2/FixatedConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\FixatedConnectivityChecker" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\FixatedConnectivityChecker" instead.
*/
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/PhpseclibV2/ConnectivityChecker.php | src/PhpseclibV2/ConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\ConnectivityChecker" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\ConnectivityChecker" instead.
*/
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/PhpseclibV2/UnableToAuthenticate.php | src/PhpseclibV2/UnableToAuthenticate.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use League\Flysystem\FilesystemException;
use RuntimeException;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\UnableToAuthenticate" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\UnableToAuthenticate" instead.
*/
class UnableToAuthenticate extends RuntimeException implements FilesystemException
{
public static function withPassword(): UnableToAuthenticate
{
return new UnableToAuthenticate('Unable to authenticate using a password.');
}
public static function withPrivateKey(): UnableToAuthenticate
{
return new UnableToAuthenticate('Unable to authenticate using a private key.');
}
public static function withSshAgent(): UnableToAuthenticate
{
return new UnableToAuthenticate('Unable to authenticate using an SSH agent.');
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/StubSftpConnectionProvider.php | src/PhpseclibV2/StubSftpConnectionProvider.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\StubSftpConnectionProvider" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\StubSftpConnectionProvider" instead.
*/
class StubSftpConnectionProvider implements ConnectionProvider
{
/**
* @var string
*/
private $host;
/**
* @var string
*/
private $username;
/**
* @var string|null
*/
private $password;
/**
* @var int
*/
private $port;
/**
* @var SftpStub
*/
private $connection;
public function __construct(
string $host,
string $username,
?string $password = null,
int $port = 22
) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->port = $port;
}
public function provideConnection(): SFTP
{
if ( ! $this->connection instanceof SFTP) {
$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/PhpseclibV2/SftpAdapterTest.php | src/PhpseclibV2/SftpAdapterTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
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 function class_exists;
/**
* @group sftp
* @group legacy
*/
class SftpAdapterTest extends FilesystemAdapterTestCase
{
/**
* @var ConnectionProvider
*/
private static $connectionProvider;
/**
* @var SftpStub
*/
private $connection;
public static function setUpBeforeClass(): void
{
if ( ! class_exists('phpseclib\Net\SFTP')) {
self::markTestSkipped("PHPSecLib V2 is not installed");
}
}
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->reset();
}
/**
* @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));
}
private static function connectionProvider(): ConnectionProvider
{
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();
$adapter = new SftpAdapter($provider, '/invalid');
return $adapter;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/PhpseclibV2/SimpleConnectivityChecker.php | src/PhpseclibV2/SimpleConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
/**
* @deprecated The "League\Flysystem\PhpseclibV2\SimpleConnectivityChecker" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\SimpleConnectivityChecker" instead.
*/
class SimpleConnectivityChecker implements ConnectivityChecker
{
public function isConnected(SFTP $connection): bool
{
return $connection->isConnected();
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToEnableUtf8Mode.php | src/Ftp/UnableToEnableUtf8Mode.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use RuntimeException;
final class UnableToEnableUtf8Mode 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/RawListFtpConnectivityCheckerTest.php | src/Ftp/RawListFtpConnectivityCheckerTest.php | <?php
namespace League\Flysystem\Ftp;
use League\Flysystem\AdapterTestUtilities\RetryOnTestException;
use PHPUnit\Framework\TestCase;
/**
* @group ftp
*/
class RawListFtpConnectivityCheckerTest extends TestCase
{
use RetryOnTestException;
/**
* @test
*/
public function detecting_if_a_connection_is_connected(): void
{
$this->retryOnException(UnableToConnectToFtpHost::class);
$this->runScenario(function () {
$options = FtpConnectionOptions::fromArray([
'host' => 'localhost',
'port' => 2121,
'root' => '/home/foo/upload/',
'username' => 'foo',
'password' => 'pass',
]);
$provider = new FtpConnectionProvider();
$connection = $provider->createConnection($options);
$connectedChecker = new RawListFtpConnectivityChecker();
$this->assertTrue($connectedChecker->isConnected($connection));
@ftp_close($connection);
$this->assertFalse($connectedChecker->isConnected($connection));
});
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/StubConnectionProvider.php | src/Ftp/StubConnectionProvider.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
class StubConnectionProvider implements ConnectionProvider
{
public mixed $connection;
public function __construct(private ConnectionProvider $provider)
{
}
public function createConnection(FtpConnectionOptions $options)
{
return $this->connection = $this->provider->createConnection($options);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToResolveConnectionRoot.php | src/Ftp/UnableToResolveConnectionRoot.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use RuntimeException;
use Throwable;
final class UnableToResolveConnectionRoot extends RuntimeException implements FtpConnectionException
{
private function __construct(string $message, ?Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
public static function itDoesNotExist(string $root, string $reason = ''): UnableToResolveConnectionRoot
{
return new UnableToResolveConnectionRoot(
'Unable to resolve connection root. It does not seem to exist: ' . $root . "\nreason: $reason"
);
}
public static function couldNotGetCurrentDirectory(string $message = ''): UnableToResolveConnectionRoot
{
return new UnableToResolveConnectionRoot(
'Unable to resolve connection root. Could not resolve the current directory. ' . $message
);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToConnectToFtpHost.php | src/Ftp/UnableToConnectToFtpHost.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use RuntimeException;
final class UnableToConnectToFtpHost extends RuntimeException implements FtpConnectionException
{
public static function forHost(string $host, int $port, bool $ssl, string $reason = ''): UnableToConnectToFtpHost
{
$usingSsl = $ssl ? ', using ssl' : '';
return new UnableToConnectToFtpHost("Unable to connect to host $host at port $port$usingSsl. $reason");
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/NoopCommandConnectivityCheckerTest.php | src/Ftp/NoopCommandConnectivityCheckerTest.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use League\Flysystem\AdapterTestUtilities\RetryOnTestException;
use PHPUnit\Framework\TestCase;
/**
* @group ftp
*/
class NoopCommandConnectivityCheckerTest extends TestCase
{
use RetryOnTestException;
protected function setUp(): void
{
$this->retryOnException(UnableToConnectToFtpHost::class);
}
/**
* @test
*/
public function detecting_a_good_connection(): void
{
$options = FtpConnectionOptions::fromArray([
'host' => 'localhost',
'port' => 2121,
'root' => '/home/foo/upload',
'username' => 'foo',
'password' => 'pass',
]);
$connection = (new FtpConnectionProvider())->createConnection($options);
$connected = (new NoopCommandConnectivityChecker())->isConnected($connection);
$this->assertTrue($connected);
}
/**
* @test
*/
public function detecting_a_closed_connection(): void
{
$options = FtpConnectionOptions::fromArray([
'host' => 'localhost',
'port' => 2121,
'root' => '/home/foo/upload',
'username' => 'foo',
'password' => 'pass',
]);
$this->runScenario(function () use ($options) {
$connection = (new FtpConnectionProvider())->createConnection($options);
ftp_close($connection);
$connected = (new NoopCommandConnectivityChecker())->isConnected($connection);
$this->assertFalse($connected);
});
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/ConnectionProvider.php | src/Ftp/ConnectionProvider.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
interface ConnectionProvider
{
/**
* @return resource
*/
public function createConnection(FtpConnectionOptions $options);
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/NoopCommandConnectivityChecker.php | src/Ftp/NoopCommandConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use TypeError;
use ValueError;
class NoopCommandConnectivityChecker implements ConnectivityChecker
{
public function isConnected($connection): bool
{
// @codeCoverageIgnoreStart
try {
$response = @ftp_raw($connection, 'NOOP');
} catch (TypeError | ValueError $typeError) {
return false;
}
// @codeCoverageIgnoreEnd
$responseCode = $response ? (int) preg_replace('/\D/', '', implode('', $response)) : false;
return $responseCode === 200;
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToSetFtpOption.php | src/Ftp/UnableToSetFtpOption.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use RuntimeException;
class UnableToSetFtpOption extends RuntimeException implements FtpConnectionException
{
public static function whileSettingOption(string $option): UnableToSetFtpOption
{
return new UnableToSetFtpOption("Unable to set FTP option $option.");
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/RawListFtpConnectivityChecker.php | src/Ftp/RawListFtpConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use ValueError;
class RawListFtpConnectivityChecker implements ConnectivityChecker
{
/**
* @inheritDoc
*/
public function isConnected($connection): bool
{
try {
return $connection !== false && @ftp_rawlist($connection, './') !== false;
} catch (ValueError $errror) {
return false;
}
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/InvalidListResponseReceived.php | src/Ftp/InvalidListResponseReceived.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use League\Flysystem\FilesystemException;
use RuntimeException;
class InvalidListResponseReceived extends RuntimeException implements FilesystemException
{
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/ConnectivityCheckerThatCanFail.php | src/Ftp/ConnectivityCheckerThatCanFail.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
class ConnectivityCheckerThatCanFail implements ConnectivityChecker
{
private bool $failNextCall = false;
public function __construct(private ConnectivityChecker $connectivityChecker)
{
}
public function failNextCall(): void
{
$this->failNextCall = true;
}
/**
* @inheritDoc
*/
public function isConnected($connection): bool
{
if ($this->failNextCall) {
$this->failNextCall = false;
return false;
}
return $this->connectivityChecker->isConnected($connection);
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/ConnectivityChecker.php | src/Ftp/ConnectivityChecker.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
interface ConnectivityChecker
{
/**
* @param resource $connection
*/
public function isConnected($connection): bool;
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
thephpleague/flysystem | https://github.com/thephpleague/flysystem/blob/5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277/src/Ftp/UnableToAuthenticate.php | src/Ftp/UnableToAuthenticate.php | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use RuntimeException;
final class UnableToAuthenticate extends RuntimeException implements FtpConnectionException
{
public function __construct()
{
parent::__construct("Unable to login/authenticate with FTP");
}
}
| php | MIT | 5966a8ba23e62bdb518dd9e0e665c2dbd4b5b277 | 2026-01-04T15:02:49.867552Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.