Added Laravel project

This commit is contained in:
2017-09-17 00:35:10 +02:00
parent a3c19304d5
commit ecf605b8f5
6246 changed files with 682270 additions and 2 deletions

19
Laravel/vendor/league/flysystem/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2013-2017 Frank de Jonge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,60 @@
{
"name": "league/flysystem",
"description": "Filesystem abstraction: Many filesystems, one API.",
"keywords": [
"filesystem", "filesystems", "files", "storage", "dropbox", "aws",
"abstraction", "s3", "ftp", "sftp", "remote", "webdav",
"file systems", "cloud", "cloud files", "rackspace", "copy.com"
],
"license": "MIT",
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frenky.net"
}
],
"require": {
"php": ">=5.5.9"
},
"require-dev": {
"ext-fileinfo": "*",
"phpunit/phpunit": "~4.8",
"mockery/mockery": "~0.9",
"phpspec/phpspec": "^2.2"
},
"autoload": {
"psr-4": {
"League\\Flysystem\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"League\\Flysystem\\Stub\\": "stub/"
}
},
"suggest": {
"ext-fileinfo": "Required for MimeType",
"league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem",
"league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files",
"league/flysystem-azure": "Allows you to use Windows Azure Blob storage",
"league/flysystem-webdav": "Allows you to use WebDAV storage",
"league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2",
"league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3",
"spatie/flysystem-dropbox": "Allows you to use Dropbox storage",
"srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications",
"league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching",
"league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib",
"league/flysystem-ziparchive": "Allows you to use ZipArchive adapter"
},
"conflict": {
"league/flysystem-sftp": "<1.0.6"
},
"config": {
"bin-dir": "bin"
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
}
}

View File

@@ -0,0 +1 @@
_site

View File

@@ -0,0 +1 @@
flysystem.thephpleague.com

View File

@@ -0,0 +1,8 @@
# Path to project specific favicon.ico, leave blank to use default
favicon:
# Path to project specific apple-touch-icon-precomposed.png, leave blank to use default
apple_touch:
# Path to project logo
logo:

View File

@@ -0,0 +1,30 @@
Getting Started:
Introduction: '/'
Installation: '/installation/'
Integrations: '/integrations/'
Core concepts: '/core-concepts/'
The API: '/api/'
Mount Manager: '/mount-manager/'
Caching: '/caching/'
Recipes: '/recipes/'
Plugins: '/plugins/'
Upgrade to 1.0.0: '/upgrade-to-1.0.0/'
Creating an adapter: '/creating-an-adapter/'
Performance: '/performance/'
Adapters:
Local: '/adapter/local/'
Azure: '/adapter/azure/'
AWS S3 V2: '/adapter/aws-s3-v2/'
AWS S3 V3: '/adapter/aws-s3-v3/'
Copy.com: '/adapter/copy/'
Dropbox: '/adapter/dropbox/'
FTP: '/adapter/ftp/'
GridFS: '/adapter/gridfs/'
Memory: '/adapter/memory/'
Null / Test: '/adapter/null-test/'
Rackspace: '/adapter/rackspace/'
ReplicateAdapter: '/adapter/replicate/'
SFTP: '/adapter/sftp/'
WebDAV: '/adapter/webdav/'
PHPCR: '/adapter/phpcr/'
ZipArchive: '/adapter/zip-archive/'

View File

@@ -0,0 +1,4 @@
title: "Flysystem"
tagline: "Multiple Filesystems, One API"
description: "Filesystem abstraction package allowing you to use the same API for both local, remote and cloud filesystems."
google_analytics_tracking_id: "UA-46050814-3"

View File

@@ -0,0 +1,100 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% if page.url == '/' %}
<title>{{ site.data.project.title }} - {{ site.data.project.tagline }}</title>
{% else %}
<title>{{ page.title }} - {{ site.data.project.title }}</title>
{% endif %}
{% if site.data.project.description %}
<meta name="description" content="{{ site.data.project.description }}">
{% endif %}
{% if site.data.images.favicon %}
<link rel="icon" type="image/x-icon" href="{{ site.data.images.favicon }}" />
{% else %}
<link rel="icon" type="image/x-icon" href="//theme.thephpleague.com/img/favicon.ico" />
{% endif %}
{% if site.data.images.apple_touch %}
<link rel="apple-touch-icon-precomposed" href="{{ site.data.images.apple_touch }}">
{% else %}
<link rel="apple-touch-icon-precomposed" href="//theme.thephpleague.com/img/apple-touch-icon-precomposed.png">
{% endif %}
<link rel="stylesheet" href="//theme.thephpleague.com/css/all.css">
<base href="//flysystem.thephpleague.com{{ page.permalink }}">
</head>
<body>
<section class="all_packages">
<a href="//thephpleague.com/">
<img src="//theme.thephpleague.com/img/loep_logo.png" width="195" height="200" alt="The League of Extraordinary Packages">
</a>
<h2>Our Packages:</h2>
<ul>
<!-- Loaded via JavaScript -->
</ul>
</section>
<header>
<a class="logo" href="/">
{% if site.data.images.logo %}
<span class="icon">
<img src="{{ site.data.images.logo }}" width="50" height="40" alt="{{ site.data.project.title }} - {{ site.data.project.tagline }}">
</span>
{% endif %}
<span class="name">{{ site.data.project.title }}</span>
<span class="tagline">{{ site.data.project.tagline }}</span>
</a>
<a href="//thephpleague.com/" class="league">
Presented by The League of Extraordinary Packages
</a>
</header>
<input type="checkbox" id="menu">
<label for="menu" onclick>
<div class="closed">&#9776; Menu</div>
<div class="open">&#9776; Hide Menu</div>
</label>
<main>
<menu>
{% for section in site.data.menu %}
<h2>{{ section[0] }}</h2>
<ul>
{% for link in section[1] %}
<li {% if page.url == link[1] %}class="selected"{% endif %}>
<a href="{{ link[1] }}">{{ link[0] }}</a>
</li>
{% endfor %}
</ul>
{% endfor %}
</menu>
<article>
{{ content }}
</article>
</main>
<footer>
<span>&copy; Copyright <a href="//thephpleague.com">The League of Extraordinary Packages</a>.</span>
<span>Site design by <a href="//reinink.ca">Jonathan Reinink</a>.</span>
</footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//theme.thephpleague.com/js/scripts.js"></script>
<script src="//theme.thephpleague.com/js/prism.js"></script>
{% if site.data.project.google_analytics_tracking_id %}
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','{{ site.data.project.google_analytics_tracking_id }}');ga('send','pageview');
</script>
{% endif %}
</body>
</html>

View File

@@ -0,0 +1,55 @@
---
layout: default
permalink: /adapter/aws-s3-v2/
title: Aws S3 Adapter V2
---
# Aws S3 Adapter - SDK V2
## Installation
~~~ bash
composer require league/flysystem-aws-s3-v2
~~~
## Usage
~~~ php
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v2\AwsS3Adapter;
use League\Flysystem\Filesystem;
$client = S3Client::factory([
'key' => '[your key]',
'secret' => '[your secret]',
'region' => '[aws-region]',
]);
$adapter = new AwsS3Adapter($client, 'bucket-name', 'optional/path/prefix');
$filesystem = new Filesystem($adapter);
~~~
To enable [reduced redunancy storage](http://aws.amazon.com/s3/details/#RRS) set up your adapter like so:
~~~ php
$adapter = new AwsS3Adapter($client, 'bucket-name', 'optional/path/prefix', [
'StorageClass' => 'REDUCED_REDUNDANCY',
]);
~~~
### Compatible storage protocols
If you're using a storage service which implements the S3 protocols, you can set the `base_url` configuration option when constructing the client.
~~~ php
$client = S3Client::factory([
'base_url' => 'http://some.other.endpoint',
// ... other settings
]);
~~~
Known compliant storage providers are:
* [Google Cloud Storage](https://cloud.google.com/storage/docs/migrating#migration-simple)
* Know more? Please submit a PR!

View File

@@ -0,0 +1,32 @@
---
layout: default
permalink: /adapter/aws-s3-v3/
title: Aws S3 Adapter V3
---
# Aws S3 Adapter - SDK V3
## Installation
~~~ bash
composer require league/flysystem-aws-s3-v3
~~~
## Usage
~~~ php
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
$client = S3Client::factory([
'credentials' => [
'key' => 'your-key',
'secret' => 'your-secret',
],
'region' => 'your-region',
'version' => 'latest|version',
]);
$adapter = new AwsS3Adapter($client, 'your-bucket-name', 'optional/path/prefix');
~~~

View File

@@ -0,0 +1,31 @@
---
layout: default
permalink: /adapter/azure/
title: Azure Blob Storage
---
# Azure Blob Storage
## Installation
~~~ bash
composer require league/flysystem-azure
~~~
## Usage
~~~ php
use WindowsAzure\Common\ServicesBuilder;
use League\Flysystem\Filesystem;
use League\Flysystem\Azure\AzureAdapter;
$endpoint = sprintf(
'DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s',
'account-name',
'api-key'
);
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($endpoint);
$filesystem = new Filesystem(new AzureAdapter($blobRestProxy, 'my-container'));
~~~

View File

@@ -0,0 +1,24 @@
---
layout: default
permalink: /adapter/copy/
title: Copy.com Adapter
---
# Copy.com Adapter
## Installation
~~~ bash
composer require league/flysystem-copy
~~~
## Usage
~~~ php
use Barracuda\Copy\API;
use League\Flysystem\Filesystem;
use League\Flysystem\Copy\CopyAdapter;
$client = new API($consumerKey, $consumerSecret, $accessToken, $tokenSecret);
$filesystem = new Filesystem(new CopyAdapter($client, 'optional/path/prefix'));
~~~

View File

@@ -0,0 +1,29 @@
---
layout: default
permalink: /adapter/dropbox/
title: Dropbox Adapter
---
# Dropbox Adapter
## Installation
~~~ bash
composer require spatie/flysystem-dropbox
~~~
## Usage
A token can be generated in the [App Console](https://www.dropbox.com/developers/apps) for any Dropbox API app. You'll find more info at [the Dropbox Developer Blog](https://blogs.dropbox.com/developers/2014/05/generate-an-access-token-for-your-own-account/).
~~~ php
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client;
use Spatie\FlysystemDropbox\DropboxAdapter;
$client = new Client($authorizationToken);
$adapter = new DropboxAdapter($client);
$filesystem = new Filesystem($adapter);
~~~

View File

@@ -0,0 +1,31 @@
---
layout: default
permalink: /adapter/ftp/
title: FTP Adapter
---
# FTP Adapter
## Installation
Comes with the main Flysystem package.
## Usage
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Ftp as Adapter;
$filesystem = new Filesystem(new Adapter([
'host' => 'ftp.example.com',
'username' => 'username',
'password' => 'password',
/** optional config settings */
'port' => 21,
'root' => '/path/to/root',
'passive' => true,
'ssl' => true,
'timeout' => 30,
]));
~~~

View File

@@ -0,0 +1,26 @@
---
layout: default
permalink: /adapter/gridfs/
title: GridFS Adapter
---
# GridFS Adapter
## Installation
~~~ bash
composer require league/flysystem-gridfs
~~~
## Usage
~~~ php
use League\Flysystem\GridFS\GridFSAdapter;
use League\Flysystem\Filesystem;
$mongoClient = new MongoClient();
$gridFs = $mongoClient->selectDB('db_name')->getGridFS();
$adapter = new GridFSAdapter($gridFs);
$filesystem = new Filesystem($adapter);
~~~

View File

@@ -0,0 +1,62 @@
---
layout: default
permalink: /adapter/local/
title: Local Adapter
---
# Local Adapter
## Installation
Comes with the main Flysystem package.
## Usage
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;
$adapter = new Local(__DIR__.'/path/to/root');
$filesystem = new Filesystem($adapter);
~~~
## Locks
By default this adapter uses a lock during writes
and updates. This behaviour can be altered using the
second constructor argument.
~~~ php
$adapter = new Local(__DIR__.'/path/to/too', 0);
~~~
## Links [added in 1.0.8]
The Local adapter doesn't support links, this violates
the root path constraint which is enforced throughout
Flysystem. By default, when links are encountered an
exception is thrown. This behaviour can be altered
using the third constructor argument.
~~~ php
// Skip links
$adapter = new Local(__DIR__.'/path/to/too', LOCK_EX, Local::SKIP_LINKS);
// Throw exceptions (default)
$adapter = new Local(__DIR__.'/path/to/too', LOCK_EX, Local::DISALLOW_LINKS);
~~~
## File and directory permission settings [added in 1.0.14]
~~~ php
$adapter = new Local(__DIR__.'/path/to/too', LOCK_EX, Local::DISALLOW_LINKS, [
'file' => [
'public' => 0744,
'private' => 0700,
],
'dir' => [
'public' => 0755,
'private' => 0700,
]
]);
~~~

View File

@@ -0,0 +1,24 @@
---
layout: default
permalink: /adapter/memory/
title: Memory Adapter
---
# Memory Adapter
This adapter keeps the filesystem completely in memory. This is useful when you need a filesystem, but don't want it persisted.
## Installation
~~~ bash
composer require league/flysystem-memory
~~~
## Usage
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Memory\MemoryAdapter;
$filesystem = new Filesystem(new MemoryAdapter());
~~~

View File

@@ -0,0 +1,20 @@
---
layout: default
permalink: /adapter/null-test/
title: Null Adapter
---
# Null Adapter
## Installation
Comes with the main Flysystem package.
## Usage
Acts like `/dev/null`
~~~ php
$adapter = new League\Flysystem\Adapter\NullAdapter;
$filesystem = new League\Flysystem\Filesystem($adapter);
~~~

View File

@@ -0,0 +1,48 @@
---
layout: default
permalink: /adapter/phpcr/
title: PHPCR Adapter
---
# PHPCR Adapter
This adapter works with any [PHPCR](http://phpcr.github.io) implementation.
Choose the one that fits your needs and add it to your project, or composer
will complain that you miss `phpcr/phpcr-implementation`. See
[this article](http://symfony.com/doc/master/cmf/cookbook/database/choosing_phpcr_implementation.html)
for more on choosing your implementation.
## Installation
Assuming you go with jackalope-doctrine-dbal, do:
~~~bash
composer require jackalope/jackalope-doctrine-dbal league/flysystem-phpcr
~~~
## Usage
Bootstrap your PHPCR implementation. If you chose jackalope-doctrine-dbal with sqlite,
this will look like this for example:
~~~php
use League\Flysystem\Filesystem;
use League\Flysystem\Phpcr\PhpcrAdapter;
use Jackalope\RepositoryFactoryDoctrineDBAL;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\DriverManager;
$connection = DriverManager::getConnection([
'driver' => 'pdo_sqlite',
'path' => '/path/to/sqlite.db',
]);
$factory = new RepositoryFactoryDoctrineDBAL();
$repository = $factory->getRepository([
'jackalope.doctrine_dbal_connection' => $connection,
]);
$session = $repository->login(new SimpleCredentials('', ''));
// this part looks the same regardless of your phpcr implementation.
$root = '/flysystem_tests';
$filesystem = new Filesystem(new PhpcrAdapter($session, $root));
~~~

View File

@@ -0,0 +1,32 @@
---
layout: default
permalink: /adapter/rackspace/
title: Rackspace Adapter
---
# Rackspace Adapter
## Installation
~~~ bash
composer require league/flysystem-rackspace
~~~
## Usage
~~~ php
use OpenCloud\OpenStack;
use OpenCloud\Rackspace;
use League\Flysystem\Filesystem;
use League\Flysystem\Rackspace\RackspaceAdapter;
$client = new OpenStack(Rackspace::UK_IDENTITY_ENDPOINT, [
'username' => ':username',
'password' => ':password',
]);
$store = $client->objectStoreService('cloudFiles', 'LON');
$container = $store->getContainer('flysystem');
$filesystem = new Filesystem(new RackspaceAdapter($container, 'optional/path/prefix'));
~~~

View File

@@ -0,0 +1,23 @@
---
layout: default
permalink: /adapter/replicate/
title: Replicate Adapter
---
# Replicate Adapter
## Installation
~~~ bash
composer require league/flysystem-replicate-adapter
~~~
## Usage
The `ReplicateAdapter` facilitates smooth transitions between adapters, allowing an application to stay functional and migrate its files from one adapter to another. The adapter takes two other adapters, a source and a replica. Every change is delegated to both adapters, while all the read operations are passed onto the source only.
~~~ php
$source = new League\Flysystem\AwsS3V3\AwsS3Adapter(...);
$replica = new League\Flysystem\Adapter\Local(...);
$adapter = new League\Flysystem\Replicate\ReplicateAdapter($source, $replica);
~~~

View File

@@ -0,0 +1,30 @@
---
layout: default
permalink: /adapter/sftp/
title: SFTP Adapter
---
# SFTP Adapter
## Installation
~~~ bash
composer require league/flysystem-sftp
~~~
## Usage
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
$filesystem = new Filesystem(new SftpAdapter([
'host' => 'example.com',
'port' => 21,
'username' => 'username',
'password' => 'password',
'privateKey' => 'path/to/or/contents/of/privatekey',
'root' => '/path/to/root',
'timeout' => 10,
]));
~~~

View File

@@ -0,0 +1,21 @@
---
layout: default
permalink: /adapter/webdav/
title: WebDAV Adapter
---
# WebDAV Adapter
## Installation
~~~ bash
composer require league/flysystem-webdav
~~~
## Usage
~~~ php
$client = new Sabre\DAV\Client($settings);
$adapter = new League\Flysystem\WebDAV\WebDAVAdapter($client, 'optional/path/prefix');
$flysystem = new League\Flysystem\Filesystem($adapter);
~~~

View File

@@ -0,0 +1,30 @@
---
layout: default
permalink: /adapter/zip-archive/
title: ZipArchive Adapter
---
# ZipArchive Adapter
## Installation
~~~ bash
composer require league/flysystem-ziparchive
~~~
## Usage
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
$filesystem = new Filesystem(new ZipArchiveAdapter(__DIR__.'/path/to/archive.zip'));
~~~
### Force Save
When creating a new zip file it will only be saved at the end of the PHP request because the ZipArchive library relies on an internal `__destruct` method to be called. You can force the saving of the zip file before the end of the request by calling the `close` method on the archive through the adapter.
~~~ php
$filesystem->getAdapter()->getArchive()->close();
~~~

View File

@@ -0,0 +1,231 @@
---
layout: default
permalink: /api/
title: API
---
# API
## General Usage
__Write Files__
~~~ php
$filesystem->write('path/to/file.txt', 'contents');
~~~
__Update Files__
~~~ php
$filesystem->update('path/to/file.txt', 'new contents');
~~~
__Write or Update Files__
~~~ php
$filesystem->put('path/to/file.txt', 'contents');
~~~
__Read Files__
~~~ php
$contents = $filesystem->read('path/to/file.txt');
~~~
__Check if a file exists__
~~~ php
$exists = $filesystem->has('path/to/file.txt');
~~~
__NOTE__: This only has consistent behaviour for files, not directories. Directories
are less important in Flysystem, they're created implicitly and often ignored because
not every adapter (filesystem type) supports directories.
__Delete Files__
~~~ php
$filesystem->delete('path/to/file.txt');
~~~
__Read and Delete__
~~~ php
$contents = $filesystem->readAndDelete('path/to/file.txt');
~~~
__Rename Files__
~~~ php
$filesystem->rename('filename.txt', 'newname.txt');
~~~
__Copy Files__
~~~ php
$filesystem->copy('filename.txt', 'duplicate.txt');
~~~
__Get Mimetypes__
~~~ php
$mimetype = $filesystem->getMimetype('path/to/file.txt');
~~~
__Get Timestamps__
~~~ php
$timestamp = $filesystem->getTimestamp('path/to/file.txt');
~~~
__Get File Sizes__
~~~ php
$size = $filesystem->getSize('path/to/file.txt');
~~~
__Create Directories__
~~~ php
$filesystem->createDir('path/to/nested/directory');
~~~
Directories are also made implicitly when writing to a deeper path
~~~ php
$filesystem->write('path/to/file.txt', 'contents');
~~~
__Delete Directories__
~~~ php
$filesystem->deleteDir('path/to/directory');
~~~
The above method will delete directories recursively
__NOTE__: All paths used by Flysystem API are relative to the adapter root directory.
__Manage Visibility__
Visibility is the abstraction of file permissions across multiple platforms. Visibility can be either public or private.
~~~ php
use League\Flysystem\AdapterInterface;
$filesystem->write('db.backup', $backup, [
'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);
// or simply
$filesystem->write('db.backup', $backup, ['visibility' => 'private']);
~~~
You can also change and check visibility of existing files
~~~ php
if ($filesystem->getVisibility('secret.txt') === 'private') {
$filesystem->setVisibility('secret.txt', 'public');
}
~~~
## Global visibility setting
You can set the visibility as a default, which prevents you from setting it all over the place.
~~~ php
$filesystem = new League\Flysystem\Filesystem($adapter, [
'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);
~~~
__List Contents__
~~~ php
$contents = $filemanager->listContents();
~~~
The result of a contents listing is a collection of arrays containing all the metadata the file manager knows at that time. By default you'll receive path info and file type. Additional info could be supplied by default depending on the adapter used.
Example:
~~~ php
foreach ($contents as $object) {
echo $object['basename'].' is located at'.$object['path'].' and is a '.$object['type'];
}
~~~
By default Flysystem lists the top directory non-recursively. You can supply a directory name and recursive boolean to get more precise results
~~~ php
$contents = $filesystem->listContents('some/dir', true);
~~~
__List paths__
~~~ php
$filesystem->addPlugin(new ListPaths());
$paths = $filesystem->listPaths();
foreach ($paths as $path) {
echo $path;
}
~~~
__List with ensured presence of specific metadata__
~~~ php
$listing = $filesystem->listWith(['mimetype', 'size', 'timestamp'], 'optional/path/to/dir', true);
foreach ($listing as $object) {
echo $object['path'].' has mimetype: '.$object['mimetype'];
}
~~~
__Get file into with explicit metadata__
~~~ php
$info = $filesystem->getWithMetadata('path/to/file.txt', ['timestamp', 'mimetype']);
echo $info['mimetype'];
echo $info['timestamp'];
~~~
__NOTE__: This requires the `League\Flysystem\Plugin\GetWithMetadata` plugin.
## Using streams for reads and writes
<p class="message-notice">
Some SDK's close streams after consuming them, therefore, before calling fclose on the resource, check if it's still valid using <code>is_resource</code>.
</p>
~~~ php
$stream = fopen('/path/to/database.backup', 'r+');
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);
// Using write you can also directly set the visibility
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream, [
'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);
if (is_resource($stream)) {
fclose($stream);
}
// Or update a file with stream contents
$filesystem->updateStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);
// Retrieve a read-stream
$stream = $filesystem->readStream('something/is/here.ext');
$contents = stream_get_contents($stream);
fclose($stream);
// Create or overwrite using a stream.
$putStream = tmpfile();
fwrite($putStream, $contents);
rewind($putStream);
$filesystem->putStream('somewhere/here.txt', $putStream);
if (is_resource($putStream)) {
fclose($putStream);
}
~~~

View File

@@ -0,0 +1,126 @@
---
layout: default
permalink: /caching/
title: Caching
---
# Caching
File system I/O is slow, so Flysystem uses cached file system meta-data to boost performance. When your application needs to scale you can also choose to use a (shared) persistent caching solution for this.
Or enable a per request caching (recommended).
## Installing the adapter cache decorator
~~~bash
composer require league/flysystem-cached-adapter
~~~
This package supplies an Adapter decorator which acts as a caching proxy.
The CachedAdapter (the decorator) caches anything but the file contents. This keeps the cache small enough to be beneficial and covers all the file system inspection operations.
## Memory Caching
The easiest way to boost the performance of Flysystem is to add Memory caching.
This type of caching will cache everything in the lifetime of the current process (cli-job or http-request).
Setting it up is easy:
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local as Adapter;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Memory as CacheStore;
// Create the adapter
$localAdapter = new Local('/path/to/root');
// Create the cache store
$cacheStore = new CacheStore();
// Decorate the adapter
$adapter = new CachedAdapter($localAdapter, $cacheStore);
// And use that to create the file system
$filesystem = new Filesystem($adapter);
~~~
You can now use the file system as you would have before, but caching will be done for you on the fly.
## Persistent Caching
The following examples demonstrate how you can setup persistent meta-data caching:
## Predis Caching Setup
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local as Adapter;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Predis as Cache;
$adapter = new CachedAdapter(new Adapter(__DIR__.'/path/to/root'), new Cache);
$filesystem = new Filesystem($adapter);
// Or supply a client
$client = new Predis\Client;
$adapter = new CachedAdapter(new Adapter(__DIR__.'/path/to/root'), new Cache($client));
$filesystem = new Filesystem($adapter);
~~~
## Memcached Caching Setup
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local as Adapter;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Memcached as Cache;
$memcached = new Memcached;
$memcached->addServer('localhost', 11211);
$adapter = new CachedAdapter(
new Adapter(__DIR__.'/path/to/root'),
new Cache($memcached, 'storageKey', 300)
);
$filesystem = new Filesystem($adapter);
// Storage Key and expire time are optional
~~~
## Adapter Caching Setup
~~~ php
use Dropbox\Client;
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Dropbox;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Adapter;
$client = new Client('token', 'app');
$dropbox = new Dropbox($client, 'prefix');
$local = new Local('path');
$cache = new Adapter($local, 'file', 300);
$adapter = new CachedAdapter($dropbox, $cache);
$filesystem = new Filesystem($adapter);
~~~
## Stash Caching Setup
~~~ php
use Stash\Pool;
use League\Flysystem\Adapter\Local as Adapter;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Stash as Cache;
$pool = new Pool();
// you can optionally pass a driver (recommended, default: in-memory driver)
$cache = new Cache($pool, 'storageKey', 300);
// Storage Key and expire time are optional
$adapter = new CachedAdapter(new Adapter(__DIR__.'/path/to/root'), $cache);
$filesystem = new Filesystem($adapter);
~~~
For list of drivers and configuration options check their [documentation](http://www.stashphp.com/Drivers.html).

View File

@@ -0,0 +1,55 @@
---
layout: default
permalink: /core-concepts/
title: Core Concepts
---
# Core Concepts
In order to better understand how and why Flysystem works
the way it does, several concepts require some explanation.
## Overview
* [Adapters](#adapters)
* [Relative Paths](#relative-paths)
* [Files first](#files-first)
## Adapters
The main entry point for the file system API is the
FilesystemInterface. When working with file systems, this is
the class you'll want to be talking to.
Flysystem works the way it does because of its use of the
adapter pattern. The inconsistencies of the different file
systems are eliminated in these adapters.
While adapters have a public interface (publicly accessible
methods), they should be considered __internal__.
## Relative Paths
Portability is a very important concept within Flysystem. In order
to roll out this aspect to the fullest, all paths in Flysystem are
relative. File system root paths, whether remote or local, are viewed
as endpoints. Because of this, file systems are movable independently.
This allows parts of the application file handling to move to other
storage types, while the majority is in a centralized location.
Like the storage type, root paths are an implementation detail. When
root paths are defined as configuration, the stability of your code
improves.
## Files First
Flysystem has a files first approach. Storage systems like AWS S3
are linear file systems, this means the path to a file is used as an
identifier, rather than a representation of all the directories it's
nested in.
This means directories are second class citizens. Because of this,
directories will be automatically created on file systems that require
them when writing files. Not only does this make handling writes a lot
easier, it also ensures a consistent behaviors across all file system
types.

View File

@@ -0,0 +1,59 @@
---
layout: default
permalink: /creating-an-adapter/
title: Creating an adapter
---
# Creating an adapter
If you want to address a file system, and there's no
adapter available, you'll need to create your own.
## What is an adapter
An adapter can be seen as a plug - it bridges the gap
between initially incompatible API's. The job of the adapter
is to translate requests into calls the file system
understands and re-format responses to comply with
the interface of the generic file system.
An adapter should __NEVER__ be used directly. It should
__ONLY__ be used to create a `League\Flysystem\FilesystemInterface`
implementation instance.
## The main interface to implement
An adapter is required to be an implementation of
`League\Flysystem\AdapterInterface`. This interface
dictates all the methods that need to be implemented.
The interface of an adapter is similar to the
`League\Flysystem\FilesystemInterface`, the method
names are the same, but the response is often different.
Responses from adapters are often arrays containing the
requested value. This is done because many calls to
file systems return more values than initially requested
by the client. In order to be able to optimize file system
handling, all metadata is returned. For instance, when a
`listContents` call not only returns the paths, but also
timestamps or other related metadata, this information is
not lost. This information is returned through metadata, allowing
caching decorators to pick it up, and store for further use.
### Response values
key | description | type
----------- | ------------------------ | -----------
type | `file` or `dir` | `string`
path | path to the file or dir | `string`
contents | file contents | `string`
stream | file contents | `resource`
visibility | `public` or `private` | `string`
timestamp | modified time | `integer`
## Sharing the wealth
Have you created an adapter? Be sure to let us know!
Either create an issue on the GitHub repository, or
send a PR adding a link to the README. Contributions
are always very welcome.

View File

@@ -0,0 +1,40 @@
---
layout: default
permalink: /
title: Introduction
---
# Introduction
<span style="float: left; margin: 0 10px 0 0;">
[![SensioLabsInsight](//insight.sensiolabs.com/projects/9820f1af-2fd0-4ab6-b42a-03e0c821e0af/big.png)](//insight.sensiolabs.com/projects/9820f1af-2fd0-4ab6-b42a-03e0c821e0af)
</span>
[![Author](//img.shields.io/badge/author-@frankdejonge-blue.svg?style=flat-square)](//twitter.com/frankdejonge)
[![Source Code](//img.shields.io/badge/source-thephpleague/flysystem-blue.svg?style=flat-square)](//github.com/thephpleague/flysystem)
[![Latest Version](//img.shields.io/github/tag/thephpleague/flysystem.svg?style=flat-square)](//github.com/thephpleague/flysystem/releases)
[![Software License](//img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](//github.com/thephpleague/flysystem/blob/master/LICENSE)
[![Build Status](//img.shields.io/travis/thephpleague/flysystem/master.svg?style=flat-square)](//travis-ci.org/thephpleague/flysystem)
[![Coverage Status](//img.shields.io/scrutinizer/coverage/g/thephpleague/flysystem.svg?style=flat-square)](//scrutinizer-ci.com/g/thephpleague/flysystem/code-structure)
[![Quality Score](//img.shields.io/scrutinizer/g/thephpleague/flysystem.svg?style=flat-square)](//scrutinizer-ci.com/g/thephpleague/flysystem)
[![Total Downloads](//img.shields.io/packagist/dt/league/flysystem.svg?style=flat-square)](//packagist.org/packages/league/flysystem)
![php 5.5+](//img.shields.io/badge/php-min%205.5-red.svg?style=flat-square)
Flysystem is a filesystem abstraction which allows you to easily swap out a local filesystem for a remote one. Technical debt is reduced as is the chance of vendor lock-in.
## Goals
* Have a generic API for handling common tasks across multiple file storage engines.
* Have consistent output which you can rely on.
* Integrate well with other packages/frameworks.
* Be cacheable.
* Emulate directories in systems that support none, like AwsS3.
* Support third party plugins.
* Make it easy to test your filesystem interactions.
* Support streams for big file handling
## Questions?
Flysystem was created by Frank de Jonge, follow him on Twitter for updates: [@frankdejonge](//twitter.com/frankdejonge).
Please submit issues on [Github](//github.com/thephpleague/flysystem).

View File

@@ -0,0 +1,32 @@
---
layout: default
permalink: /installation/
title: Installation
---
# Installation
Through Composer, obviously:
~~~ bash
composer require league/flysystem
~~~
You can also use Flysystem without using Composer by registering an autoloader function:
~~~ php
spl_autoload_register(function($class) {
$prefix = 'League\\Flysystem\\';
if ( ! substr($class, 0, 17) === $prefix) {
return;
}
$class = substr($class, strlen($prefix));
$location = __DIR__ . 'path/to/flysystem/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($location)) {
require_once($location);
}
});
~~~

View File

@@ -0,0 +1,21 @@
---
layout: default
permalink: /integrations/
title: Integrations
---
# Integrations
Want to get started quickly? Check out some of these bridging packages:
* [Laravel integration](https://github.com/GrahamCampbell/Laravel-Flysystem)
* [Symfony integration](https://github.com/1up-lab/OneupFlysystemBundle)
* [Zend Framework integration](https://github.com/bushbaby/BsbFlysystem)
* [CakePHP integration](https://github.com/WyriHaximus/FlyPie)
* [Silex integration](https://github.com/WyriHaximus/SliFly)
* [Yii 2 integration](https://github.com/creocoder/yii2-flysystem)
* [Backup manager](https://github.com/heybigname/backup-manager)
### Other integrations
Laravel 5 will ship with Flysystem as the underlying engine for local and remote file handling.

View File

@@ -0,0 +1,80 @@
---
layout: default
permalink: /mount-manager/
title: Mount Manager
---
# Mount Manager
Flysystem comes with an wrapper class to easily work with multiple file system instances
from a single object. The `League\Flysystem\MountManager` is an easy to use container allowing
you to simplify more complex cross file system interactions.
Setting up a Mount Manager is easy:
~~~ php
$ftp = new League\Flysystem\Filesystem($ftpAdapter);
$s3 = new League\Flysystem\Filesystem($s3Adapter);
$local = new League\Flysystem\Filesystem($localAdapter);
// Add them in the constructor
$manager = new League\Flysystem\MountManager([
'ftp' => $ftp,
's3' => $s3,
]);
// Or mount them later
$manager->mountFilesystem('local', $local);
~~~
Now we do all the file operations we'd normally do on a `Flysystem\Filesystem` instance.
~~~ php
// Read from FTP
$contents = $manager->read('ftp://some/file.txt');
// And write to local
$manager->write('local://put/it/here.txt', $contents);
~~~
This makes it easy to code up simple sync strategies.
~~~ php
$contents = $manager->listContents('local://uploads', true);
foreach ($contents as $entry) {
$update = false;
if ( ! $manager->has('storage://'.$entry['path'])) {
$update = true;
} elseif ($manager->getTimestamp('local://'.$entry['path']) > $manager->getTimestamp('storage://'.$entry['path'])) {
$update = true;
}
if ($update) {
$manager->put('storage://'.$entry['path'], $manager->read('local://'.$entry['path']));
}
}
~~~
## Specialized calls
### Copy
The copy method provided by the Mount Manager takes the origin of the file into account.
When it detects the source and destination are located on a different file systems it'll
use a streamed upload instead, transparently.
~~~ php
$mountManager->copy('local://some/file.ext', 'backup://storage/location.ext');
~~~
### Move
The `move` call is the multi-file system counterpart to `rename`. Where rename must be used on
the same file system, the `move` call provides the same conceptual behavior, but then on two
different file systems.
~~~ php
$mountManager->move('local://some/upload.jpeg', 'cdn://users/1/profile-picture.jpeg');
~~~

View File

@@ -0,0 +1,26 @@
---
layout: default
permalink: /performance/
title: API
---
# Performance
Flysystem aims to be as reliable as possible. In some cases this means doing extra
checks to make sure the outcome will be as expected. For some adapter this means Flysystem
will make extra calls to assert whether or not a file exists. This improves the reliability
but also impacts performance. You can opt out of this behaviour.
~~~ php
new League\Flysystem\Config;
new League\Flysystem\Filesystem;
$local = Filesystem($localAdapter, new Config([
'disable_asserts' => true,
]));
~~~
This will disable the asserts which happen before the following calls: write, writeStream, update,
updateStream, copy (2x), and delete.
This functionality is available since `1.0.26`.

View File

@@ -0,0 +1,46 @@
---
layout: default
permalink: /plugins/
title: Plugins
---
# Plugins
Need a feature which is not included in Flysystem's bag of tricks? Write a plugin!
~~~ php
use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;
class MaximusAwesomeness implements PluginInterface
{
protected $filesystem;
public function setFilesystem(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
}
public function getMethod()
{
return 'getDown';
}
public function handle($path = null)
{
$contents = $this->filesystem->read($path);
return sha1($contents);
}
}
~~~
Now we're ready to use the plugin
~~~ php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter;
$filesystem = new Filesystem(new Adapter\Local(__DIR__.'/path/to/files/'));
$filesystem->addPlugin(new MaximusAwesomeness);
$sha1 = $filesystem->getDown('path/to/file');
~~~

View File

@@ -0,0 +1,99 @@
---
layout: default
permalink: /recipes/
title: Recipes
---
# Recipes
Flysystem Recipes describe common tasks and/or describe prefered ways to deal with
a problem. Please consider contributing a recipe. Contributions are very welcome!
## Handling uploads
### Plain PHP Upload
~~~ php
$stream = fopen($_FILES[$uploadname]['tmp_name'], 'r+');
$filesystem->writeStream('uploads/'.$_FILES[$uploadname]['name'], $stream);
fclose($stream);
~~~
### Symfony Upload
~~~ php
/** @var Symfony\Component\HttpFoundation\Request $request */
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $request->files->get($uploadname);
if ($file->isValid()) {
$stream = fopen($file->getRealPath(), 'r+');
$filesystem->writeStream('uploads/'.$file->getClientOriginalName(), $stream);
fclose($stream);
}
~~~
### Laravel 5 - DI
~~~ php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class UploadController extends Controller {
/**
* Upload a file.
*
* @param Request $request
* @return Response
*/
public function store(Request $request, FilesystemInterface $filesystem)
{
$file = $request->file('upload');
$stream = fopen($file->getRealPath(), 'r+');
$filesystem->writeStream('uploads/'.$file->getClientOriginalName(), $stream);
fclose($stream);
}
}
~~~
### Laravel 4/5 - Static-Access Proxy
~~~ php
$file = Request::file($uploadname);
if ($file->isValid()) {
$stream = fopen($file->getRealPath(), 'r+');
$filesystem->writeStream('uploads/'.$file->getClientOriginalName(), $stream);
fclose($stream);
}
~~~
### Yii 2 Upload
~~~ php
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\web\UploadedFile;
class FileController extends Controller
{
public function actionUpload()
{
$file = UploadedFile::getInstanceByName($uploadname);
if ($file->error === UPLOAD_ERR_OK) {
$stream = fopen($file->tempName, 'r+');
$filesystem->writeStream('uploads/'.$file->name, $stream);
fclose($stream);
}
}
}
~~~

View File

@@ -0,0 +1,66 @@
---
layout: default
permalink: /upgrade-to-1.0.0/
title: Upgrade to 1.0.0
---
# Upgrade to 1.0.0
While version 1.0.0 is largely backwards compatible from earlier versions in every
day usage, some parts require a different boostrapping.
## Relocated Adapters
In order to have better dependency management, and to remove some of the
version contstraints, some of the adapters have been moved out of the main
repository. These adapters are:
* [AwsS3: AWS SDK V2 Adapter](/adapter/aws-s3-v2/)
* [AwsS3V3: AWS SDK V3 Adapter](/adapter/aws-s3-v3/)
* [Dropbox](/adapter/dropbox/)
* [Rackspace](/adapter/rackspace/)
* [GridFS](/adapter/gridfs/)
* [Sftp](/adapter/sftp/)
* [WebDAV](/adapter/webdav/)
* [ZipArchive](/adapter/zip-archive/)
## Caching
Caching has been removed from the main Filesystem class and is now implemented
as an adapter decorator.
### Version 0.x
~~~ php
$filesystem = new Filesystem($adapter, $cacheAdapter);
~~~
### Version 1.0.0
Install the required adapter decorator:
~~~ bash
composer require league/flysystem-cached-adapter
~~~
And convert the bootstrapping to:
~~~ php
use League\Flysystem\Adapter\Local;
use League\Flysystem\Cached\CachedAdapter;
$decoratedAdapter = new CachedAdapter($adapter, $cacheAdapter);
$filesystem = new Filesystem($decoratedAdapter);
~~~
## Helper Methods
In order to clean up the Filsystem class, some helper functions have been moved to plugins.
* ListWith
* ListPaths
* ListFiles
* GetWithMetadata
* EmptyDir (new)

View File

@@ -0,0 +1,71 @@
<?php
namespace League\Flysystem\Adapter;
use League\Flysystem\AdapterInterface;
abstract class AbstractAdapter implements AdapterInterface
{
/**
* @var string path prefix
*/
protected $pathPrefix;
/**
* @var string
*/
protected $pathSeparator = '/';
/**
* Set the path prefix.
*
* @param string $prefix
*
* @return void
*/
public function setPathPrefix($prefix)
{
$prefix = (string) $prefix;
if ($prefix === '') {
$this->pathPrefix = null;
return;
}
$this->pathPrefix = rtrim($prefix, '\\/') . $this->pathSeparator;
}
/**
* Get the path prefix.
*
* @return string path prefix
*/
public function getPathPrefix()
{
return $this->pathPrefix;
}
/**
* Prefix a path.
*
* @param string $path
*
* @return string prefixed path
*/
public function applyPathPrefix($path)
{
return $this->getPathPrefix() . ltrim($path, '\\/');
}
/**
* Remove a path prefix.
*
* @param string $path
*
* @return string path without the prefix
*/
public function removePathPrefix($path)
{
return substr($path, strlen($this->getPathPrefix()));
}
}

View File

@@ -0,0 +1,632 @@
<?php
namespace League\Flysystem\Adapter;
use DateTime;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\NotSupportedException;
use League\Flysystem\SafeStorage;
use RuntimeException;
abstract class AbstractFtpAdapter extends AbstractAdapter
{
/**
* @var mixed
*/
protected $connection;
/**
* @var string
*/
protected $host;
/**
* @var int
*/
protected $port = 21;
/**
* @var bool
*/
protected $ssl = false;
/**
* @var int
*/
protected $timeout = 90;
/**
* @var bool
*/
protected $passive = true;
/**
* @var string
*/
protected $separator = '/';
/**
* @var string|null
*/
protected $root;
/**
* @var int
*/
protected $permPublic = 0744;
/**
* @var int
*/
protected $permPrivate = 0700;
/**
* @var array
*/
protected $configurable = [];
/**
* @var string
*/
protected $systemType;
/**
* @var bool
*/
protected $alternativeRecursion = false;
/**
* @var SafeStorage
*/
protected $safeStorage;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config)
{
$this->safeStorage = new SafeStorage();
$this->setConfig($config);
}
/**
* Set the config.
*
* @param array $config
*
* @return $this
*/
public function setConfig(array $config)
{
foreach ($this->configurable as $setting) {
if ( ! isset($config[$setting])) {
continue;
}
$method = 'set' . ucfirst($setting);
if (method_exists($this, $method)) {
$this->$method($config[$setting]);
}
}
return $this;
}
/**
* Returns the host.
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set the host.
*
* @param string $host
*
* @return $this
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Set the public permission value.
*
* @param int $permPublic
*
* @return $this
*/
public function setPermPublic($permPublic)
{
$this->permPublic = $permPublic;
return $this;
}
/**
* Set the private permission value.
*
* @param int $permPrivate
*
* @return $this
*/
public function setPermPrivate($permPrivate)
{
$this->permPrivate = $permPrivate;
return $this;
}
/**
* Returns the ftp port.
*
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* Returns the root folder to work from.
*
* @return string
*/
public function getRoot()
{
return $this->root;
}
/**
* Set the ftp port.
*
* @param int|string $port
*
* @return $this
*/
public function setPort($port)
{
$this->port = (int) $port;
return $this;
}
/**
* Set the root folder to work from.
*
* @param string $root
*
* @return $this
*/
public function setRoot($root)
{
$this->root = rtrim($root, '\\/') . $this->separator;
return $this;
}
/**
* Returns the ftp username.
*
* @return string username
*/
public function getUsername()
{
$username = $this->safeStorage->retrieveSafely('username');
return $username !== null ? $username : 'anonymous';
}
/**
* Set ftp username.
*
* @param string $username
*
* @return $this
*/
public function setUsername($username)
{
$this->safeStorage->storeSafely('username', $username);
return $this;
}
/**
* Returns the password.
*
* @return string password
*/
public function getPassword()
{
return $this->safeStorage->retrieveSafely('password');
}
/**
* Set the ftp password.
*
* @param string $password
*
* @return $this
*/
public function setPassword($password)
{
$this->safeStorage->storeSafely('password', $password);
return $this;
}
/**
* Returns the amount of seconds before the connection will timeout.
*
* @return int
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* Set the amount of seconds before the connection should timeout.
*
* @param int $timeout
*
* @return $this
*/
public function setTimeout($timeout)
{
$this->timeout = (int) $timeout;
return $this;
}
/**
* Return the FTP system type.
*
* @return string
*/
public function getSystemType()
{
return $this->systemType;
}
/**
* Set the FTP system type (windows or unix).
*
* @param string $systemType
*
* @return $this
*/
public function setSystemType($systemType)
{
$this->systemType = strtolower($systemType);
return $this;
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
return $this->listDirectoryContents($directory, $recursive);
}
abstract protected function listDirectoryContents($directory, $recursive = false);
/**
* Normalize a directory listing.
*
* @param array $listing
* @param string $prefix
*
* @return array directory listing
*/
protected function normalizeListing(array $listing, $prefix = '')
{
$base = $prefix;
$result = [];
$listing = $this->removeDotDirectories($listing);
while ($item = array_shift($listing)) {
if (preg_match('#^.*:$#', $item)) {
$base = trim($item, ':');
continue;
}
$result[] = $this->normalizeObject($item, $base);
}
return $this->sortListing($result);
}
/**
* Sort a directory listing.
*
* @param array $result
*
* @return array sorted listing
*/
protected function sortListing(array $result)
{
$compare = function ($one, $two) {
return strnatcmp($one['path'], $two['path']);
};
usort($result, $compare);
return $result;
}
/**
* Normalize a file entry.
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*
* @throws NotSupportedException
*/
protected function normalizeObject($item, $base)
{
$systemType = $this->systemType ?: $this->detectSystemType($item);
if ($systemType === 'unix') {
return $this->normalizeUnixObject($item, $base);
} elseif ($systemType === 'windows') {
return $this->normalizeWindowsObject($item, $base);
}
throw NotSupportedException::forFtpSystemType($systemType);
}
/**
* Normalize a Unix file entry.
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*/
protected function normalizeUnixObject($item, $base)
{
$item = preg_replace('#\s+#', ' ', trim($item), 7);
if (count(explode(' ', $item, 9)) !== 9) {
throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
}
list($permissions, /* $number */, /* $owner */, /* $group */, $size, /* $month */, /* $day */, /* $time*/, $name) = explode(' ', $item, 9);
$type = $this->detectType($permissions);
$path = $base === '' ? $name : $base . $this->separator . $name;
if ($type === 'dir') {
return compact('type', 'path');
}
$permissions = $this->normalizePermissions($permissions);
$visibility = $permissions & 0044 ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE;
$size = (int) $size;
return compact('type', 'path', 'visibility', 'size');
}
/**
* Normalize a Windows/DOS file entry.
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*/
protected function normalizeWindowsObject($item, $base)
{
$item = preg_replace('#\s+#', ' ', trim($item), 3);
if (count(explode(' ', $item, 4)) !== 4) {
throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
}
list($date, $time, $size, $name) = explode(' ', $item, 4);
$path = $base === '' ? $name : $base . $this->separator . $name;
// Check for the correct date/time format
$format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
$dt = DateTime::createFromFormat($format, $date . $time);
$timestamp = $dt ? $dt->getTimestamp() : (int) strtotime("$date $time");
if ($size === '<DIR>') {
$type = 'dir';
return compact('type', 'path', 'timestamp');
}
$type = 'file';
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
$size = (int) $size;
return compact('type', 'path', 'visibility', 'size', 'timestamp');
}
/**
* Get the system type from a listing item.
*
* @param string $item
*
* @return string the system type
*/
protected function detectSystemType($item)
{
return preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item) ? 'windows' : 'unix';
}
/**
* Get the file type from the permissions.
*
* @param string $permissions
*
* @return string file type
*/
protected function detectType($permissions)
{
return substr($permissions, 0, 1) === 'd' ? 'dir' : 'file';
}
/**
* Normalize a permissions string.
*
* @param string $permissions
*
* @return int
*/
protected function normalizePermissions($permissions)
{
// remove the type identifier
$permissions = substr($permissions, 1);
// map the string rights to the numeric counterparts
$map = ['-' => '0', 'r' => '4', 'w' => '2', 'x' => '1'];
$permissions = strtr($permissions, $map);
// split up the permission groups
$parts = str_split($permissions, 3);
// convert the groups
$mapper = function ($part) {
return array_sum(str_split($part));
};
// converts to decimal number
return octdec(implode('', array_map($mapper, $parts)));
}
/**
* Filter out dot-directories.
*
* @param array $list
*
* @return array
*/
public function removeDotDirectories(array $list)
{
$filter = function ($line) {
if ( $line !== '' && ! preg_match('#.* \.(\.)?$|^total#', $line)) {
return true;
}
return false;
};
return array_filter($list, $filter);
}
/**
* @inheritdoc
*/
public function has($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
return $this->getMetadata($path);
}
/**
* Ensure a directory exists.
*
* @param string $dirname
*/
public function ensureDirectory($dirname)
{
$dirname = (string) $dirname;
if ($dirname !== '' && ! $this->has($dirname)) {
$this->createDir($dirname, new Config());
}
}
/**
* @return mixed
*/
public function getConnection()
{
$tries = 0;
while ( ! $this->isConnected() && $tries < 3) {
$tries++;
$this->disconnect();
$this->connect();
}
return $this->connection;
}
/**
* Get the public permission value.
*
* @return int
*/
public function getPermPublic()
{
return $this->permPublic;
}
/**
* Get the private permission value.
*
* @return int
*/
public function getPermPrivate()
{
return $this->permPrivate;
}
/**
* Disconnect on destruction.
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Establish a connection.
*/
abstract public function connect();
/**
* Close the connection.
*/
abstract public function disconnect();
/**
* Check if a connection is active.
*
* @return bool
*/
abstract public function isConnected();
}

View File

@@ -0,0 +1,10 @@
<?php
namespace League\Flysystem\Adapter;
/**
* Adapters that implement this interface let the Filesystem know that it files can be overwritten using the write
* functions and don't need the update function to be called. This can help improve performance when asserts are disabled.
*/
interface CanOverwriteFiles {}

View File

@@ -0,0 +1,569 @@
<?php
namespace League\Flysystem\Adapter;
use ErrorException;
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\Util;
use League\Flysystem\Util\MimeType;
use RuntimeException;
class Ftp extends AbstractFtpAdapter
{
use StreamedCopyTrait;
/**
* @var int
*/
protected $transferMode = FTP_BINARY;
/**
* @var null|bool
*/
protected $ignorePassiveAddress = null;
/**
* @var bool
*/
protected $recurseManually = false;
/**
* @var bool
*/
protected $utf8 = false;
/**
* @var array
*/
protected $configurable = [
'host',
'port',
'username',
'password',
'ssl',
'timeout',
'root',
'permPrivate',
'permPublic',
'passive',
'transferMode',
'systemType',
'ignorePassiveAddress',
'recurseManually',
'utf8',
];
/**
* @var bool
*/
protected $isPureFtpd;
/**
* Set the transfer mode.
*
* @param int $mode
*
* @return $this
*/
public function setTransferMode($mode)
{
$this->transferMode = $mode;
return $this;
}
/**
* Set if Ssl is enabled.
*
* @param bool $ssl
*
* @return $this
*/
public function setSsl($ssl)
{
$this->ssl = (bool) $ssl;
return $this;
}
/**
* Set if passive mode should be used.
*
* @param bool $passive
*/
public function setPassive($passive = true)
{
$this->passive = $passive;
}
/**
* @param bool $ignorePassiveAddress
*/
public function setIgnorePassiveAddress($ignorePassiveAddress)
{
$this->ignorePassiveAddress = $ignorePassiveAddress;
}
/**
* @param bool $recurseManually
*/
public function setRecurseManually($recurseManually)
{
$this->recurseManually = $recurseManually;
}
/**
* @param bool $utf8
*/
public function setUtf8($utf8)
{
$this->utf8 = (bool) $utf8;
}
/**
* Connect to the FTP server.
*/
public function connect()
{
if ($this->ssl) {
$this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
} else {
$this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
}
if ( ! $this->connection) {
throw new RuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort());
}
$this->login();
$this->setUtf8Mode();
$this->setConnectionPassiveMode();
$this->setConnectionRoot();
$this->isPureFtpd = $this->isPureFtpdServer();
}
/**
* Set the connection to UTF-8 mode.
*/
protected function setUtf8Mode()
{
if ($this->utf8) {
$response = ftp_raw($this->connection, "OPTS UTF8 ON");
if (substr($response[0], 0, 3) !== '200') {
throw new RuntimeException(
'Could not set UTF-8 mode for connection: ' . $this->getHost() . '::' . $this->getPort()
);
}
}
}
/**
* Set the connections to passive mode.
*
* @throws RuntimeException
*/
protected function setConnectionPassiveMode()
{
if (is_bool($this->ignorePassiveAddress) && defined('FTP_USEPASVADDRESS')) {
ftp_set_option($this->connection, FTP_USEPASVADDRESS, ! $this->ignorePassiveAddress);
}
if ( ! ftp_pasv($this->connection, $this->passive)) {
throw new RuntimeException(
'Could not set passive mode for connection: ' . $this->getHost() . '::' . $this->getPort()
);
}
}
/**
* Set the connection root.
*/
protected function setConnectionRoot()
{
$root = $this->getRoot();
$connection = $this->connection;
if (isset($root) && ! ftp_chdir($connection, $root)) {
throw new RuntimeException('Root is invalid or does not exist: ' . $this->getRoot());
}
// Store absolute path for further reference.
// This is needed when creating directories and
// initial root was a relative path, else the root
// would be relative to the chdir'd path.
$this->root = ftp_pwd($connection);
}
/**
* Login.
*
* @throws RuntimeException
*/
protected function login()
{
set_error_handler(function () {});
$isLoggedIn = ftp_login(
$this->connection,
$this->getUsername(),
$this->getPassword()
);
restore_error_handler();
if ( ! $isLoggedIn) {
$this->disconnect();
throw new RuntimeException(
'Could not login with connection: ' . $this->getHost() . '::' . $this->getPort(
) . ', username: ' . $this->getUsername()
);
}
}
/**
* Disconnect from the FTP server.
*/
public function disconnect()
{
if (is_resource($this->connection)) {
ftp_close($this->connection);
}
$this->connection = null;
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$stream = fopen('php://temp', 'w+b');
fwrite($stream, $contents);
rewind($stream);
$result = $this->writeStream($path, $stream, $config);
fclose($stream);
if ($result === false) {
return false;
}
$result['contents'] = $contents;
$result['mimetype'] = Util::guessMimeType($path, $contents);
return $result;
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, Config $config)
{
$this->ensureDirectory(Util::dirname($path));
if ( ! ftp_fput($this->getConnection(), $path, $resource, $this->transferMode)) {
return false;
}
if ($visibility = $config->get('visibility')) {
$this->setVisibility($path, $visibility);
}
$type = 'file';
return compact('type', 'path', 'visibility');
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
return $this->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, Config $config)
{
return $this->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
return ftp_rename($this->getConnection(), $path, $newpath);
}
/**
* @inheritdoc
*/
public function delete($path)
{
return ftp_delete($this->getConnection(), $path);
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$connection = $this->getConnection();
$contents = array_reverse($this->listDirectoryContents($dirname));
foreach ($contents as $object) {
if ($object['type'] === 'file') {
if ( ! ftp_delete($connection, $object['path'])) {
return false;
}
} elseif ( ! ftp_rmdir($connection, $object['path'])) {
return false;
}
}
return ftp_rmdir($connection, $dirname);
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
$connection = $this->getConnection();
$directories = explode('/', $dirname);
foreach ($directories as $directory) {
if (false === $this->createActualDirectory($directory, $connection)) {
$this->setConnectionRoot();
return false;
}
ftp_chdir($connection, $directory);
}
$this->setConnectionRoot();
return ['type' => 'dir', 'path' => $dirname];
}
/**
* Create a directory.
*
* @param string $directory
* @param resource $connection
*
* @return bool
*/
protected function createActualDirectory($directory, $connection)
{
// List the current directory
$listing = ftp_nlist($connection, '.') ?: [];
foreach ($listing as $key => $item) {
if (preg_match('~^\./.*~', $item)) {
$listing[$key] = substr($item, 2);
}
}
if (in_array($directory, $listing, true)) {
return true;
}
return (boolean) ftp_mkdir($connection, $directory);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
$connection = $this->getConnection();
if ($path === '') {
return ['type' => 'dir', 'path' => ''];
}
if (@ftp_chdir($connection, $path) === true) {
$this->setConnectionRoot();
return ['type' => 'dir', 'path' => $path];
}
$listing = $this->ftpRawlist('-A', str_replace('*', '\\*', $path));
if (empty($listing) || in_array('total 0', $listing, true)) {
return false;
}
if (preg_match('/.* not found/', $listing[0])) {
return false;
}
if (preg_match('/^total [0-9]*$/', $listing[0])) {
array_shift($listing);
}
return $this->normalizeObject($listing[0], '');
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
if ( ! $metadata = $this->getMetadata($path)) {
return false;
}
$metadata['mimetype'] = MimeType::detectByFilename($path);
return $metadata;
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
$timestamp = ftp_mdtm($this->getConnection(), $path);
return ($timestamp !== -1) ? ['path' => $path, 'timestamp' => $timestamp] : false;
}
/**
* @inheritdoc
*/
public function read($path)
{
if ( ! $object = $this->readStream($path)) {
return false;
}
$object['contents'] = stream_get_contents($object['stream']);
fclose($object['stream']);
unset($object['stream']);
return $object;
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$stream = fopen('php://temp', 'w+b');
$result = ftp_fget($this->getConnection(), $stream, $path, $this->transferMode);
rewind($stream);
if ( ! $result) {
fclose($stream);
return false;
}
return ['type' => 'file', 'path' => $path, 'stream' => $stream];
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$mode = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? $this->getPermPublic() : $this->getPermPrivate();
if ( ! ftp_chmod($this->getConnection(), $mode, $path)) {
return false;
}
return compact('path', 'visibility');
}
/**
* @inheritdoc
*
* @param string $directory
*/
protected function listDirectoryContents($directory, $recursive = true)
{
$directory = str_replace('*', '\\*', $directory);
if ($recursive && $this->recurseManually) {
return $this->listDirectoryContentsRecursive($directory);
}
$options = $recursive ? '-alnR' : '-aln';
$listing = $this->ftpRawlist($options, $directory);
return $listing ? $this->normalizeListing($listing, $directory) : [];
}
/**
* @inheritdoc
*
* @param string $directory
*/
protected function listDirectoryContentsRecursive($directory)
{
$listing = $this->normalizeListing($this->ftpRawlist('-aln', $directory) ?: []);
$output = [];
foreach ($listing as $directory) {
$output[] = $directory;
if ($directory['type'] !== 'dir') continue;
$output = array_merge($output, $this->listDirectoryContentsRecursive($directory['path']));
}
return $output;
}
/**
* Check if the connection is open.
*
* @return bool
* @throws ErrorException
*/
public function isConnected()
{
try {
return is_resource($this->connection) && ftp_rawlist($this->connection, '/') !== false;
} catch (ErrorException $e) {
if (strpos($e->getMessage(), 'ftp_rawlist') === false) {
throw $e;
}
return false;
}
}
/**
* @return null|string
*/
protected function isPureFtpdServer()
{
$response = ftp_raw($this->connection, 'HELP');
return stripos(implode(' ', $response), 'Pure-FTPd') !== false;
}
/**
* The ftp_rawlist function with optional escaping.
*
* @param string $options
* @param string $path
*
* @return array
*/
protected function ftpRawlist($options, $path)
{
$connection = $this->getConnection();
if ($this->isPureFtpd) {
$path = str_replace(' ', '\ ', $path);
}
return ftp_rawlist($connection, $options . ' ' . $path);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace League\Flysystem\Adapter;
class Ftpd extends Ftp
{
/**
* @inheritdoc
*/
public function getMetadata($path)
{
if ($path === '') {
return ['type' => 'dir', 'path' => ''];
}
if (! ($object = ftp_raw($this->getConnection(), 'STAT ' . $path)) || count($object) < 3) {
return false;
}
if (substr($object[1], 0, 5) === "ftpd:") {
return false;
}
return $this->normalizeObject($object[1], '');
}
/**
* @inheritdoc
*/
protected function listDirectoryContents($directory, $recursive = true)
{
$listing = ftp_rawlist($this->getConnection(), $directory, $recursive);
if ($listing === false || ( ! empty($listing) && substr($listing[0], 0, 5) === "ftpd:")) {
return [];
}
return $this->normalizeListing($listing, $directory);
}
}

View File

@@ -0,0 +1,510 @@
<?php
namespace League\Flysystem\Adapter;
use DirectoryIterator;
use FilesystemIterator;
use finfo as Finfo;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\Exception;
use League\Flysystem\NotSupportedException;
use League\Flysystem\UnreadableFileException;
use League\Flysystem\Util;
use LogicException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
class Local extends AbstractAdapter
{
/**
* @var int
*/
const SKIP_LINKS = 0001;
/**
* @var int
*/
const DISALLOW_LINKS = 0002;
/**
* @var array
*/
protected static $permissions = [
'file' => [
'public' => 0644,
'private' => 0600,
],
'dir' => [
'public' => 0755,
'private' => 0700,
]
];
/**
* @var string
*/
protected $pathSeparator = DIRECTORY_SEPARATOR;
/**
* @var array
*/
protected $permissionMap;
/**
* @var int
*/
protected $writeFlags;
/**
* @var int
*/
private $linkHandling;
/**
* Constructor.
*
* @param string $root
* @param int $writeFlags
* @param int $linkHandling
* @param array $permissions
*
* @throws LogicException
*/
public function __construct($root, $writeFlags = LOCK_EX, $linkHandling = self::DISALLOW_LINKS, array $permissions = [])
{
$root = is_link($root) ? realpath($root) : $root;
$this->permissionMap = array_replace_recursive(static::$permissions, $permissions);
$this->ensureDirectory($root);
if ( ! is_dir($root) || ! is_readable($root)) {
throw new LogicException('The root path ' . $root . ' is not readable.');
}
$this->setPathPrefix($root);
$this->writeFlags = $writeFlags;
$this->linkHandling = $linkHandling;
}
/**
* Ensure the root directory exists.
*
* @param string $root root directory path
*
* @return void
*
* @throws Exception in case the root directory can not be created
*/
protected function ensureDirectory($root)
{
if ( ! is_dir($root)) {
$umask = umask(0);
@mkdir($root, $this->permissionMap['dir']['public'], true);
umask($umask);
if ( ! is_dir($root)) {
throw new Exception(sprintf('Impossible to create the root directory "%s".', $root));
}
}
}
/**
* @inheritdoc
*/
public function has($path)
{
$location = $this->applyPathPrefix($path);
return file_exists($location);
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$location = $this->applyPathPrefix($path);
$this->ensureDirectory(dirname($location));
if (($size = file_put_contents($location, $contents, $this->writeFlags)) === false) {
return false;
}
$type = 'file';
$result = compact('contents', 'type', 'size', 'path');
if ($visibility = $config->get('visibility')) {
$result['visibility'] = $visibility;
$this->setVisibility($path, $visibility);
}
return $result;
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, Config $config)
{
$location = $this->applyPathPrefix($path);
$this->ensureDirectory(dirname($location));
$stream = fopen($location, 'w+b');
if ( ! $stream) {
return false;
}
stream_copy_to_stream($resource, $stream);
if ( ! fclose($stream)) {
return false;
}
if ($visibility = $config->get('visibility')) {
$this->setVisibility($path, $visibility);
}
$type = 'file';
return compact('type', 'path', 'visibility');
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$location = $this->applyPathPrefix($path);
$stream = fopen($location, 'rb');
return ['type' => 'file', 'path' => $path, 'stream' => $stream];
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, Config $config)
{
return $this->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
$location = $this->applyPathPrefix($path);
$mimetype = Util::guessMimeType($path, $contents);
$size = file_put_contents($location, $contents, $this->writeFlags);
if ($size === false) {
return false;
}
$type = 'file';
return compact('type', 'path', 'size', 'contents', 'mimetype');
}
/**
* @inheritdoc
*/
public function read($path)
{
$location = $this->applyPathPrefix($path);
$contents = file_get_contents($location);
if ($contents === false) {
return false;
}
return ['type' => 'file', 'path' => $path, 'contents' => $contents];
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
$location = $this->applyPathPrefix($path);
$destination = $this->applyPathPrefix($newpath);
$parentDirectory = $this->applyPathPrefix(Util::dirname($newpath));
$this->ensureDirectory($parentDirectory);
return rename($location, $destination);
}
/**
* @inheritdoc
*/
public function copy($path, $newpath)
{
$location = $this->applyPathPrefix($path);
$destination = $this->applyPathPrefix($newpath);
$this->ensureDirectory(dirname($destination));
return copy($location, $destination);
}
/**
* @inheritdoc
*/
public function delete($path)
{
$location = $this->applyPathPrefix($path);
return unlink($location);
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
$result = [];
$location = $this->applyPathPrefix($directory);
if ( ! is_dir($location)) {
return [];
}
$iterator = $recursive ? $this->getRecursiveDirectoryIterator($location) : $this->getDirectoryIterator($location);
foreach ($iterator as $file) {
$path = $this->getFilePath($file);
if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) {
continue;
}
$result[] = $this->normalizeFileInfo($file);
}
return array_filter($result);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
$location = $this->applyPathPrefix($path);
$info = new SplFileInfo($location);
return $this->normalizeFileInfo($info);
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
$location = $this->applyPathPrefix($path);
$finfo = new Finfo(FILEINFO_MIME_TYPE);
$mimetype = $finfo->file($location);
if (in_array($mimetype, ['application/octet-stream', 'inode/x-empty'])) {
$mimetype = Util\MimeType::detectByFilename($location);
}
return ['path' => $path, 'type' => 'file', 'mimetype' => $mimetype];
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
$location = $this->applyPathPrefix($path);
clearstatcache(false, $location);
$permissions = octdec(substr(sprintf('%o', fileperms($location)), -4));
$visibility = $permissions & 0044 ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE;
return compact('path', 'visibility');
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$location = $this->applyPathPrefix($path);
$type = is_dir($location) ? 'dir' : 'file';
$success = chmod($location, $this->permissionMap[$type][$visibility]);
if ($success === false) {
return false;
}
return compact('path', 'visibility');
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
$location = $this->applyPathPrefix($dirname);
$umask = umask(0);
$visibility = $config->get('visibility', 'public');
if ( ! is_dir($location) && ! mkdir($location, $this->permissionMap['dir'][$visibility], true)) {
$return = false;
} else {
$return = ['path' => $dirname, 'type' => 'dir'];
}
umask($umask);
return $return;
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$location = $this->applyPathPrefix($dirname);
if ( ! is_dir($location)) {
return false;
}
$contents = $this->getRecursiveDirectoryIterator($location, RecursiveIteratorIterator::CHILD_FIRST);
/** @var SplFileInfo $file */
foreach ($contents as $file) {
$this->guardAgainstUnreadableFileInfo($file);
$this->deleteFileInfoObject($file);
}
return rmdir($location);
}
/**
* @param SplFileInfo $file
*/
protected function deleteFileInfoObject(SplFileInfo $file)
{
switch ($file->getType()) {
case 'dir':
rmdir($file->getRealPath());
break;
case 'link':
unlink($file->getPathname());
break;
default:
unlink($file->getRealPath());
}
}
/**
* Normalize the file info.
*
* @param SplFileInfo $file
*
* @return array|void
*
* @throws NotSupportedException
*/
protected function normalizeFileInfo(SplFileInfo $file)
{
if ( ! $file->isLink()) {
return $this->mapFileInfo($file);
}
if ($this->linkHandling & self::DISALLOW_LINKS) {
throw NotSupportedException::forLink($file);
}
}
/**
* Get the normalized path from a SplFileInfo object.
*
* @param SplFileInfo $file
*
* @return string
*/
protected function getFilePath(SplFileInfo $file)
{
$location = $file->getPathname();
$path = $this->removePathPrefix($location);
return trim(str_replace('\\', '/', $path), '/');
}
/**
* @param string $path
* @param int $mode
*
* @return RecursiveIteratorIterator
*/
protected function getRecursiveDirectoryIterator($path, $mode = RecursiveIteratorIterator::SELF_FIRST)
{
return new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
$mode
);
}
/**
* @param string $path
*
* @return DirectoryIterator
*/
protected function getDirectoryIterator($path)
{
$iterator = new DirectoryIterator($path);
return $iterator;
}
/**
* @param SplFileInfo $file
*
* @return array
*/
protected function mapFileInfo(SplFileInfo $file)
{
$normalized = [
'type' => $file->getType(),
'path' => $this->getFilePath($file),
];
$normalized['timestamp'] = $file->getMTime();
if ($normalized['type'] === 'file') {
$normalized['size'] = $file->getSize();
}
return $normalized;
}
/**
* @param SplFileInfo $file
*
* @throws UnreadableFileException
*/
protected function guardAgainstUnreadableFileInfo(SplFileInfo $file)
{
if ( ! $file->isReadable()) {
throw UnreadableFileException::forFileInfo($file);
}
}
}

View File

@@ -0,0 +1,144 @@
<?php
namespace League\Flysystem\Adapter;
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
use League\Flysystem\Adapter\Polyfill\StreamedTrait;
use League\Flysystem\Config;
class NullAdapter extends AbstractAdapter
{
use StreamedTrait;
use StreamedCopyTrait;
/**
* Check whether a file is present.
*
* @param string $path
*
* @return bool
*/
public function has($path)
{
return false;
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$type = 'file';
$result = compact('contents', 'type', 'path');
if ($visibility = $config->get('visibility')) {
$result['visibility'] = $visibility;
}
return $result;
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
return false;
}
/**
* @inheritdoc
*/
public function read($path)
{
return false;
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
return false;
}
/**
* @inheritdoc
*/
public function delete($path)
{
return false;
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
return [];
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
return false;
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
return compact('visibility');
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
return ['path' => $dirname, 'type' => 'dir'];
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
return false;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use LogicException;
trait NotSupportingVisibilityTrait
{
/**
* Get the visibility of a file.
*
* @param string $path
*
* @throws LogicException
*/
public function getVisibility($path)
{
throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path);
}
/**
* Set the visibility for a file.
*
* @param string $path
* @param string $visibility
*
* @throws LogicException
*/
public function setVisibility($path, $visibility)
{
throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path . ', visibility: ' . $visibility);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use League\Flysystem\Config;
trait StreamedCopyTrait
{
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function copy($path, $newpath)
{
$response = $this->readStream($path);
if ($response === false || ! is_resource($response['stream'])) {
return false;
}
$result = $this->writeStream($newpath, $response['stream'], new Config());
if ($result !== false && is_resource($response['stream'])) {
fclose($response['stream']);
}
return $result !== false;
}
// Required abstract method
/**
* @param string $path
* @return resource
*/
abstract public function readStream($path);
/**
* @param string $path
* @param resource $resource
* @param Config $config
* @return resource
*/
abstract public function writeStream($path, $resource, Config $config);
}

View File

@@ -0,0 +1,44 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
/**
* A helper for adapters that only handle strings to provide read streams.
*/
trait StreamedReadingTrait
{
/**
* Reads a file as a stream.
*
* @param string $path
*
* @return array|false
*
* @see League\Flysystem\ReadInterface::readStream()
*/
public function readStream($path)
{
if ( ! $data = $this->read($path)) {
return false;
}
$stream = fopen('php://temp', 'w+b');
fwrite($stream, $data['contents']);
rewind($stream);
$data['stream'] = $stream;
unset($data['contents']);
return $data;
}
/**
* Reads a file.
*
* @param string $path
*
* @return array|false
*
* @see League\Flysystem\ReadInterface::read()
*/
abstract public function read($path);
}

View File

@@ -0,0 +1,9 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
trait StreamedTrait
{
use StreamedReadingTrait;
use StreamedWritingTrait;
}

View File

@@ -0,0 +1,60 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use League\Flysystem\Config;
use League\Flysystem\Util;
trait StreamedWritingTrait
{
/**
* Stream fallback delegator.
*
* @param string $path
* @param resource $resource
* @param Config $config
* @param string $fallback
*
* @return mixed fallback result
*/
protected function stream($path, $resource, Config $config, $fallback)
{
Util::rewindStream($resource);
$contents = stream_get_contents($resource);
$fallbackCall = [$this, $fallback];
return call_user_func($fallbackCall, $path, $contents, $config);
}
/**
* Write using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config
*
* @return mixed false or file metadata
*/
public function writeStream($path, $resource, Config $config)
{
return $this->stream($path, $resource, $config, 'write');
}
/**
* Update a file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object or visibility setting
*
* @return mixed false of file metadata
*/
public function updateStream($path, $resource, Config $config)
{
return $this->stream($path, $resource, $config, 'update');
}
// Required abstract methods
abstract public function write($pash, $contents, Config $config);
abstract public function update($pash, $contents, Config $config);
}

View File

@@ -0,0 +1,8 @@
<?php
namespace League\Flysystem\Adapter;
class SynologyFtp extends Ftpd
{
// This class merely exists because of BC.
}

View File

@@ -0,0 +1,118 @@
<?php
namespace League\Flysystem;
interface AdapterInterface extends ReadInterface
{
/**
* @const VISIBILITY_PUBLIC public visibility
*/
const VISIBILITY_PUBLIC = 'public';
/**
* @const VISIBILITY_PRIVATE private visibility
*/
const VISIBILITY_PRIVATE = 'private';
/**
* Write a new file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function write($path, $contents, Config $config);
/**
* Write a new file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function writeStream($path, $resource, Config $config);
/**
* Update a file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function update($path, $contents, Config $config);
/**
* Update a file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function updateStream($path, $resource, Config $config);
/**
* Rename a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function rename($path, $newpath);
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function copy($path, $newpath);
/**
* Delete a file.
*
* @param string $path
*
* @return bool
*/
public function delete($path);
/**
* Delete a directory.
*
* @param string $dirname
*
* @return bool
*/
public function deleteDir($dirname);
/**
* Create a directory.
*
* @param string $dirname directory name
* @param Config $config
*
* @return array|false
*/
public function createDir($dirname, Config $config);
/**
* Set the visibility for a file.
*
* @param string $path
* @param string $visibility
*
* @return array|false file meta data
*/
public function setVisibility($path, $visibility);
}

View File

@@ -0,0 +1,107 @@
<?php
namespace League\Flysystem;
class Config
{
/**
* @var array
*/
protected $settings = [];
/**
* @var Config
*/
protected $fallback;
/**
* Constructor.
*
* @param array $settings
*/
public function __construct(array $settings = [])
{
$this->settings = $settings;
}
/**
* Get a setting.
*
* @param string $key
* @param mixed $default
*
* @return mixed config setting or default when not found
*/
public function get($key, $default = null)
{
if ( ! array_key_exists($key, $this->settings)) {
return $this->getDefault($key, $default);
}
return $this->settings[$key];
}
/**
* Check if an item exists by key.
*
* @param string $key
*
* @return bool
*/
public function has($key)
{
if (array_key_exists($key, $this->settings)) {
return true;
}
return $this->fallback instanceof Config
? $this->fallback->has($key)
: false;
}
/**
* Try to retrieve a default setting from a config fallback.
*
* @param string $key
* @param mixed $default
*
* @return mixed config setting or default when not found
*/
protected function getDefault($key, $default)
{
if ( ! $this->fallback) {
return $default;
}
return $this->fallback->get($key, $default);
}
/**
* Set a setting.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function set($key, $value)
{
$this->settings[$key] = $value;
return $this;
}
/**
* Set the fallback.
*
* @param Config $fallback
*
* @return $this
*/
public function setFallback(Config $fallback)
{
$this->fallback = $fallback;
return $this;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace League\Flysystem;
/**
* @internal
*/
trait ConfigAwareTrait
{
/**
* @var Config
*/
protected $config;
/**
* Set the config.
*
* @param Config|array|null $config
*/
protected function setConfig($config)
{
$this->config = $config ? Util::ensureConfig($config) : new Config;
}
/**
* Get the Config.
*
* @return Config config object
*/
public function getConfig()
{
return $this->config;
}
/**
* Convert a config array to a Config object with the correct fallback.
*
* @param array $config
*
* @return Config
*/
protected function prepareConfig(array $config)
{
$config = new Config($config);
$config->setFallback($this->getConfig());
return $config;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace League\Flysystem;
class Directory extends Handler
{
/**
* Delete the directory.
*
* @return bool
*/
public function delete()
{
return $this->filesystem->deleteDir($this->path);
}
/**
* List the directory contents.
*
* @param bool $recursive
*
* @return array|bool directory contents or false
*/
public function getContents($recursive = false)
{
return $this->filesystem->listContents($this->path, $recursive);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace League\Flysystem;
class Exception extends \Exception
{
//
}

View File

@@ -0,0 +1,202 @@
<?php
namespace League\Flysystem;
class File extends Handler
{
/**
* Check whether the file exists.
*
* @return bool
*/
public function exists()
{
return $this->filesystem->has($this->path);
}
/**
* Read the file.
*
* @return string file contents
*/
public function read()
{
return $this->filesystem->read($this->path);
}
/**
* Read the file as a stream.
*
* @return resource file stream
*/
public function readStream()
{
return $this->filesystem->readStream($this->path);
}
/**
* Write the new file.
*
* @param string $content
*
* @return bool success boolean
*/
public function write($content)
{
return $this->filesystem->write($this->path, $content);
}
/**
* Write the new file using a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function writeStream($resource)
{
return $this->filesystem->writeStream($this->path, $resource);
}
/**
* Update the file contents.
*
* @param string $content
*
* @return bool success boolean
*/
public function update($content)
{
return $this->filesystem->update($this->path, $content);
}
/**
* Update the file contents with a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function updateStream($resource)
{
return $this->filesystem->updateStream($this->path, $resource);
}
/**
* Create the file or update if exists.
*
* @param string $content
*
* @return bool success boolean
*/
public function put($content)
{
return $this->filesystem->put($this->path, $content);
}
/**
* Create the file or update if exists using a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function putStream($resource)
{
return $this->filesystem->putStream($this->path, $resource);
}
/**
* Rename the file.
*
* @param string $newpath
*
* @return bool success boolean
*/
public function rename($newpath)
{
if ($this->filesystem->rename($this->path, $newpath)) {
$this->path = $newpath;
return true;
}
return false;
}
/**
* Copy the file.
*
* @param string $newpath
*
* @return File|false new file or false
*/
public function copy($newpath)
{
if ($this->filesystem->copy($this->path, $newpath)) {
return new File($this->filesystem, $newpath);
}
return false;
}
/**
* Get the file's timestamp.
*
* @return int unix timestamp
*/
public function getTimestamp()
{
return $this->filesystem->getTimestamp($this->path);
}
/**
* Get the file's mimetype.
*
* @return string mimetime
*/
public function getMimetype()
{
return $this->filesystem->getMimetype($this->path);
}
/**
* Get the file's visibility.
*
* @return string visibility
*/
public function getVisibility()
{
return $this->filesystem->getVisibility($this->path);
}
/**
* Get the file's metadata.
*
* @return array
*/
public function getMetadata()
{
return $this->filesystem->getMetadata($this->path);
}
/**
* Get the file size.
*
* @return int file size
*/
public function getSize()
{
return $this->filesystem->getSize($this->path);
}
/**
* Delete the file.
*
* @return bool success boolean
*/
public function delete()
{
return $this->filesystem->delete($this->path);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace League\Flysystem;
use Exception as BaseException;
class FileExistsException extends Exception
{
/**
* @var string
*/
protected $path;
/**
* Constructor.
*
* @param string $path
* @param int $code
* @param BaseException $previous
*/
public function __construct($path, $code = 0, BaseException $previous = null)
{
$this->path = $path;
parent::__construct('File already exists at path: ' . $this->getPath(), $code, $previous);
}
/**
* Get the path which was found.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace League\Flysystem;
use Exception as BaseException;
class FileNotFoundException extends Exception
{
/**
* @var string
*/
protected $path;
/**
* Constructor.
*
* @param string $path
* @param int $code
* @param \Exception $previous
*/
public function __construct($path, $code = 0, BaseException $previous = null)
{
$this->path = $path;
parent::__construct('File not found at path: ' . $this->getPath(), $code, $previous);
}
/**
* Get the path which was not found.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
}

View File

@@ -0,0 +1,405 @@
<?php
namespace League\Flysystem;
use InvalidArgumentException;
use League\Flysystem\Adapter\CanOverwriteFiles;
use League\Flysystem\Plugin\PluggableTrait;
use League\Flysystem\Util\ContentListingFormatter;
/**
* @method array getWithMetadata(string $path, array $metadata)
* @method bool forceCopy(string $path, string $newpath)
* @method bool forceRename(string $path, string $newpath)
* @method array listFiles(string $path = '', boolean $recursive = false)
* @method array listPaths(string $path = '', boolean $recursive = false)
* @method array listWith(array $keys = [], $directory = '', $recursive = false)
*/
class Filesystem implements FilesystemInterface
{
use PluggableTrait;
use ConfigAwareTrait;
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* Constructor.
*
* @param AdapterInterface $adapter
* @param Config|array $config
*/
public function __construct(AdapterInterface $adapter, $config = null)
{
$this->adapter = $adapter;
$this->setConfig($config);
}
/**
* Get the Adapter.
*
* @return AdapterInterface adapter
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* @inheritdoc
*/
public function has($path)
{
$path = Util::normalizePath($path);
return strlen($path) === 0 ? false : (bool) $this->getAdapter()->has($path);
}
/**
* @inheritdoc
*/
public function write($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$this->assertAbsent($path);
$config = $this->prepareConfig($config);
return (bool) $this->getAdapter()->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$this->assertAbsent($path);
$config = $this->prepareConfig($config);
Util::rewindStream($resource);
return (bool) $this->getAdapter()->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function put($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
if ( ! $this->adapter instanceof CanOverwriteFiles && $this->has($path)) {
return (bool) $this->getAdapter()->update($path, $contents, $config);
}
return (bool) $this->getAdapter()->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function putStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
Util::rewindStream($resource);
if ( ! $this->adapter instanceof CanOverwriteFiles &&$this->has($path)) {
return (bool) $this->getAdapter()->updateStream($path, $resource, $config);
}
return (bool) $this->getAdapter()->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function readAndDelete($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
$contents = $this->read($path);
if ($contents === false) {
return false;
}
$this->delete($path);
return $contents;
}
/**
* @inheritdoc
*/
public function update($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
$this->assertPresent($path);
return (bool) $this->getAdapter()->update($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
$this->assertPresent($path);
Util::rewindStream($resource);
return (bool) $this->getAdapter()->updateStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function read($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if ( ! ($object = $this->getAdapter()->read($path))) {
return false;
}
return $object['contents'];
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if ( ! $object = $this->getAdapter()->readStream($path)) {
return false;
}
return $object['stream'];
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
$path = Util::normalizePath($path);
$newpath = Util::normalizePath($newpath);
$this->assertPresent($path);
$this->assertAbsent($newpath);
return (bool) $this->getAdapter()->rename($path, $newpath);
}
/**
* @inheritdoc
*/
public function copy($path, $newpath)
{
$path = Util::normalizePath($path);
$newpath = Util::normalizePath($newpath);
$this->assertPresent($path);
$this->assertAbsent($newpath);
return $this->getAdapter()->copy($path, $newpath);
}
/**
* @inheritdoc
*/
public function delete($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
return $this->getAdapter()->delete($path);
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$dirname = Util::normalizePath($dirname);
if ($dirname === '') {
throw new RootViolationException('Root directories can not be deleted.');
}
return (bool) $this->getAdapter()->deleteDir($dirname);
}
/**
* @inheritdoc
*/
public function createDir($dirname, array $config = [])
{
$dirname = Util::normalizePath($dirname);
$config = $this->prepareConfig($config);
return (bool) $this->getAdapter()->createDir($dirname, $config);
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
$directory = Util::normalizePath($directory);
$contents = $this->getAdapter()->listContents($directory, $recursive);
return (new ContentListingFormatter($directory, $recursive))->formatListing($contents);
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getMimetype($path)) || ! array_key_exists('mimetype', $object)) {
return false;
}
return $object['mimetype'];
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getTimestamp($path)) || ! array_key_exists('timestamp', $object)) {
return false;
}
return $object['timestamp'];
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getVisibility($path)) || ! array_key_exists('visibility', $object)) {
return false;
}
return $object['visibility'];
}
/**
* @inheritdoc
*/
public function getSize($path)
{
$path = Util::normalizePath($path);
if (( ! $object = $this->getAdapter()->getSize($path)) || ! array_key_exists('size', $object)) {
return false;
}
return (int) $object['size'];
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$path = Util::normalizePath($path);
return (bool) $this->getAdapter()->setVisibility($path, $visibility);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
return $this->getAdapter()->getMetadata($path);
}
/**
* @inheritdoc
*/
public function get($path, Handler $handler = null)
{
$path = Util::normalizePath($path);
if ( ! $handler) {
$metadata = $this->getMetadata($path);
$handler = $metadata['type'] === 'file' ? new File($this, $path) : new Directory($this, $path);
}
$handler->setPath($path);
$handler->setFilesystem($this);
return $handler;
}
/**
* Assert a file is present.
*
* @param string $path path to file
*
* @throws FileNotFoundException
*
* @return void
*/
public function assertPresent($path)
{
if ($this->config->get('disable_asserts', false) === false && ! $this->has($path)) {
throw new FileNotFoundException($path);
}
}
/**
* Assert a file is absent.
*
* @param string $path path to file
*
* @throws FileExistsException
*
* @return void
*/
public function assertAbsent($path)
{
if ($this->config->get('disable_asserts', false) === false && $this->has($path)) {
throw new FileExistsException($path);
}
}
}

View File

@@ -0,0 +1,276 @@
<?php
namespace League\Flysystem;
interface FilesystemInterface
{
/**
* Check whether a file exists.
*
* @param string $path
*
* @return bool
*/
public function has($path);
/**
* Read a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents or false on failure.
*/
public function read($path);
/**
* Retrieves a read-stream for a path.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return resource|false The path resource or false on failure.
*/
public function readStream($path);
/**
* List contents of a directory.
*
* @param string $directory The directory to list.
* @param bool $recursive Whether to list recursively.
*
* @return array A list of file metadata.
*/
public function listContents($directory = '', $recursive = false);
/**
* Get a file's metadata.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return array|false The file metadata or false on failure.
*/
public function getMetadata($path);
/**
* Get a file's size.
*
* @param string $path The path to the file.
*
* @return int|false The file size or false on failure.
*/
public function getSize($path);
/**
* Get a file's mime-type.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file mime-type or false on failure.
*/
public function getMimetype($path);
/**
* Get a file's timestamp.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The timestamp or false on failure.
*/
public function getTimestamp($path);
/**
* Get a file's visibility.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The visibility (public|private) or false on failure.
*/
public function getVisibility($path);
/**
* Write a new file.
*
* @param string $path The path of the new file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function write($path, $contents, array $config = []);
/**
* Write a new file using a stream.
*
* @param string $path The path of the new file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws \InvalidArgumentException If $resource is not a file handle.
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function writeStream($path, $resource, array $config = []);
/**
* Update an existing file.
*
* @param string $path The path of the existing file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function update($path, $contents, array $config = []);
/**
* Update an existing file using a stream.
*
* @param string $path The path of the existing file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws \InvalidArgumentException If $resource is not a file handle.
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function updateStream($path, $resource, array $config = []);
/**
* Rename a file.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileExistsException Thrown if $newpath exists.
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function rename($path, $newpath);
/**
* Copy a file.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileExistsException Thrown if $newpath exists.
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function copy($path, $newpath);
/**
* Delete a file.
*
* @param string $path
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function delete($path);
/**
* Delete a directory.
*
* @param string $dirname
*
* @throws RootViolationException Thrown if $dirname is empty.
*
* @return bool True on success, false on failure.
*/
public function deleteDir($dirname);
/**
* Create a directory.
*
* @param string $dirname The name of the new directory.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function createDir($dirname, array $config = []);
/**
* Set the visibility for a file.
*
* @param string $path The path to the file.
* @param string $visibility One of 'public' or 'private'.
*
* @return bool True on success, false on failure.
*/
public function setVisibility($path, $visibility);
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function put($path, $contents, array $config = []);
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws \InvalidArgumentException Thrown if $resource is not a resource.
*
* @return bool True on success, false on failure.
*/
public function putStream($path, $resource, array $config = []);
/**
* Read and delete a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents, or false on failure.
*/
public function readAndDelete($path);
/**
* Get a file/directory handler.
*
* @param string $path The path to the file.
* @param Handler $handler An optional existing handler to populate.
*
* @return Handler Either a file or directory handler.
*/
public function get($path, Handler $handler = null);
/**
* Register a plugin.
*
* @param PluginInterface $plugin The plugin to register.
*
* @return $this
*/
public function addPlugin(PluginInterface $plugin);
}

View File

@@ -0,0 +1,12 @@
<?php
namespace League\Flysystem;
use LogicException;
/**
* Thrown when the MountManager cannot find a filesystem.
*/
class FilesystemNotFoundException extends LogicException
{
}

View File

@@ -0,0 +1,134 @@
<?php
namespace League\Flysystem;
use BadMethodCallException;
abstract class Handler
{
/**
* @var string
*/
protected $path;
/**
* @var FilesystemInterface
*/
protected $filesystem;
/**
* Constructor.
*
* @param FilesystemInterface $filesystem
* @param string $path
*/
public function __construct(FilesystemInterface $filesystem = null, $path = null)
{
$this->path = $path;
$this->filesystem = $filesystem;
}
/**
* Check whether the entree is a directory.
*
* @return bool
*/
public function isDir()
{
return $this->getType() === 'dir';
}
/**
* Check whether the entree is a file.
*
* @return bool
*/
public function isFile()
{
return $this->getType() === 'file';
}
/**
* Retrieve the entree type (file|dir).
*
* @return string file or dir
*/
public function getType()
{
$metadata = $this->filesystem->getMetadata($this->path);
return $metadata['type'];
}
/**
* Set the Filesystem object.
*
* @param FilesystemInterface $filesystem
*
* @return $this
*/
public function setFilesystem(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
return $this;
}
/**
* Retrieve the Filesystem object.
*
* @return FilesystemInterface
*/
public function getFilesystem()
{
return $this->filesystem;
}
/**
* Set the entree path.
*
* @param string $path
*
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Retrieve the entree path.
*
* @return string path
*/
public function getPath()
{
return $this->path;
}
/**
* Plugins pass-through.
*
* @param string $method
* @param array $arguments
*
* @return mixed
*/
public function __call($method, array $arguments)
{
array_unshift($arguments, $this->path);
$callback = [$this->filesystem, $method];
try {
return call_user_func_array($callback, $arguments);
} catch (BadMethodCallException $e) {
throw new BadMethodCallException(
'Call to undefined method '
. get_called_class()
. '::' . $method
);
}
}
}

View File

@@ -0,0 +1,320 @@
<?php
namespace League\Flysystem;
use InvalidArgumentException;
use League\Flysystem\FilesystemNotFoundException;
use League\Flysystem\Plugin\PluggableTrait;
use League\Flysystem\Plugin\PluginNotFoundException;
/**
* Class MountManager.
*
* Proxies methods to Filesystem (@see __call):
*
* @method AdapterInterface getAdapter($prefix)
* @method Config getConfig($prefix)
* @method bool has($path)
* @method bool write($path, $contents, array $config = [])
* @method bool writeStream($path, $resource, array $config = [])
* @method bool put($path, $contents, $config = [])
* @method bool putStream($path, $contents, $config = [])
* @method string readAndDelete($path)
* @method bool update($path, $contents, $config = [])
* @method bool updateStream($path, $resource, $config = [])
* @method string|false read($path)
* @method resource|false readStream($path)
* @method bool rename($path, $newpath)
* @method bool delete($path)
* @method bool deleteDir($dirname)
* @method bool createDir($dirname, $config = [])
* @method array listFiles($directory = '', $recursive = false)
* @method array listPaths($directory = '', $recursive = false)
* @method array getWithMetadata($path, array $metadata)
* @method string|false getMimetype($path)
* @method string|false getTimestamp($path)
* @method string|false getVisibility($path)
* @method int|false getSize($path);
* @method bool setVisibility($path, $visibility)
* @method array|false getMetadata($path)
* @method Handler get($path, Handler $handler = null)
* @method Filesystem flushCache()
* @method void assertPresent($path)
* @method void assertAbsent($path)
* @method Filesystem addPlugin(PluginInterface $plugin)
*/
class MountManager
{
use PluggableTrait;
/**
* @var FilesystemInterface[]
*/
protected $filesystems = [];
/**
* Constructor.
*
* @param FilesystemInterface[] $filesystems [:prefix => Filesystem,]
*
* @throws InvalidArgumentException
*/
public function __construct(array $filesystems = [])
{
$this->mountFilesystems($filesystems);
}
/**
* Mount filesystems.
*
* @param FilesystemInterface[] $filesystems [:prefix => Filesystem,]
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function mountFilesystems(array $filesystems)
{
foreach ($filesystems as $prefix => $filesystem) {
$this->mountFilesystem($prefix, $filesystem);
}
return $this;
}
/**
* Mount filesystems.
*
* @param string $prefix
* @param FilesystemInterface $filesystem
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function mountFilesystem($prefix, FilesystemInterface $filesystem)
{
if ( ! is_string($prefix)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #1 to be a string.');
}
$this->filesystems[$prefix] = $filesystem;
return $this;
}
/**
* Get the filesystem with the corresponding prefix.
*
* @param string $prefix
*
* @throws FilesystemNotFoundException
*
* @return FilesystemInterface
*/
public function getFilesystem($prefix)
{
if ( ! isset($this->filesystems[$prefix])) {
throw new FilesystemNotFoundException('No filesystem mounted with prefix ' . $prefix);
}
return $this->filesystems[$prefix];
}
/**
* Retrieve the prefix from an arguments array.
*
* @param array $arguments
*
* @throws InvalidArgumentException
*
* @return array [:prefix, :arguments]
*/
public function filterPrefix(array $arguments)
{
if (empty($arguments)) {
throw new InvalidArgumentException('At least one argument needed');
}
$path = array_shift($arguments);
if ( ! is_string($path)) {
throw new InvalidArgumentException('First argument should be a string');
}
list($prefix, $path) = $this->getPrefixAndPath($path);
array_unshift($arguments, $path);
return [$prefix, $arguments];
}
/**
* @param string $directory
* @param bool $recursive
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return array
*/
public function listContents($directory = '', $recursive = false)
{
list($prefix, $directory) = $this->getPrefixAndPath($directory);
$filesystem = $this->getFilesystem($prefix);
$result = $filesystem->listContents($directory, $recursive);
foreach ($result as &$file) {
$file['filesystem'] = $prefix;
}
return $result;
}
/**
* Call forwarder.
*
* @param string $method
* @param array $arguments
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return mixed
*/
public function __call($method, $arguments)
{
list($prefix, $arguments) = $this->filterPrefix($arguments);
return $this->invokePluginOnFilesystem($method, $arguments, $prefix);
}
/**
* @param string $from
* @param string $to
* @param array $config
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return bool
*/
public function copy($from, $to, array $config = [])
{
list($prefixFrom, $from) = $this->getPrefixAndPath($from);
$buffer = $this->getFilesystem($prefixFrom)->readStream($from);
if ($buffer === false) {
return false;
}
list($prefixTo, $to) = $this->getPrefixAndPath($to);
$result = $this->getFilesystem($prefixTo)->writeStream($to, $buffer, $config);
if (is_resource($buffer)) {
fclose($buffer);
}
return $result;
}
/**
* List with plugin adapter.
*
* @param array $keys
* @param string $directory
* @param bool $recursive
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return array
*/
public function listWith(array $keys = [], $directory = '', $recursive = false)
{
list($prefix, $directory) = $this->getPrefixAndPath($directory);
$arguments = [$keys, $directory, $recursive];
return $this->invokePluginOnFilesystem('listWith', $arguments, $prefix);
}
/**
* Move a file.
*
* @param string $from
* @param string $to
* @param array $config
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return bool
*/
public function move($from, $to, array $config = [])
{
list($prefixFrom, $pathFrom) = $this->getPrefixAndPath($from);
list($prefixTo, $pathTo) = $this->getPrefixAndPath($to);
if ($prefixFrom === $prefixTo) {
$filesystem = $this->getFilesystem($prefixFrom);
$renamed = $filesystem->rename($pathFrom, $pathTo);
if ($renamed && isset($config['visibility'])) {
return $filesystem->setVisibility($pathTo, $config['visibility']);
}
return $renamed;
}
$copied = $this->copy($from, $to, $config);
if ($copied) {
return $this->delete($from);
}
return false;
}
/**
* Invoke a plugin on a filesystem mounted on a given prefix.
*
* @param string $method
* @param array $arguments
* @param string $prefix
*
* @throws FilesystemNotFoundException
*
* @return mixed
*/
public function invokePluginOnFilesystem($method, $arguments, $prefix)
{
$filesystem = $this->getFilesystem($prefix);
try {
return $this->invokePlugin($method, $arguments, $filesystem);
} catch (PluginNotFoundException $e) {
// Let it pass, it's ok, don't panic.
}
$callback = [$filesystem, $method];
return call_user_func_array($callback, $arguments);
}
/**
* @param string $path
*
* @throws InvalidArgumentException
*
* @return string[] [:prefix, :path]
*/
protected function getPrefixAndPath($path)
{
if (strpos($path, '://') < 1) {
throw new InvalidArgumentException('No prefix detected in path: ' . $path);
}
return explode('://', $path, 2);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace League\Flysystem;
use RuntimeException;
use SplFileInfo;
class NotSupportedException extends RuntimeException
{
/**
* Create a new exception for a link.
*
* @param SplFileInfo $file
*
* @return static
*/
public static function forLink(SplFileInfo $file)
{
$message = 'Links are not supported, encountered link at ';
return new static($message . $file->getPathname());
}
/**
* Create a new exception for a link.
*
* @param string $systemType
*
* @return static
*/
public static function forFtpSystemType($systemType)
{
$message = "The FTP system type '$systemType' is currently not supported.";
return new static($message);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace League\Flysystem\Plugin;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;
abstract class AbstractPlugin implements PluginInterface
{
/**
* @var FilesystemInterface
*/
protected $filesystem;
/**
* Set the Filesystem object.
*
* @param FilesystemInterface $filesystem
*/
public function setFilesystem(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace League\Flysystem\Plugin;
class EmptyDir extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'emptyDir';
}
/**
* Empty a directory's contents.
*
* @param $dirname
*/
public function handle($dirname)
{
$listing = $this->filesystem->listContents($dirname, false);
foreach ($listing as $item) {
if ($item['type'] === 'dir') {
$this->filesystem->deleteDir($item['path']);
} else {
$this->filesystem->delete($item['path']);
}
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace League\Flysystem\Plugin;
use League\Flysystem\FileNotFoundException;
class ForcedCopy extends AbstractPlugin
{
/**
* @inheritdoc
*/
public function getMethod()
{
return 'forceCopy';
}
/**
* Copies a file, overwriting any existing files.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function handle($path, $newpath)
{
try {
$deleted = $this->filesystem->delete($newpath);
} catch (FileNotFoundException $e) {
// The destination path does not exist. That's ok.
$deleted = true;
}
if ($deleted) {
return $this->filesystem->copy($path, $newpath);
}
return false;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace League\Flysystem\Plugin;
use League\Flysystem\FileNotFoundException;
class ForcedRename extends AbstractPlugin
{
/**
* @inheritdoc
*/
public function getMethod()
{
return 'forceRename';
}
/**
* Renames a file, overwriting the destination if it exists.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function handle($path, $newpath)
{
try {
$deleted = $this->filesystem->delete($newpath);
} catch (FileNotFoundException $e) {
// The destination path does not exist. That's ok.
$deleted = true;
}
if ($deleted) {
return $this->filesystem->rename($path, $newpath);
}
return false;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace League\Flysystem\Plugin;
use InvalidArgumentException;
class GetWithMetadata extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'getWithMetadata';
}
/**
* Get metadata for an object with required metadata.
*
* @param string $path path to file
* @param array $metadata metadata keys
*
* @throws InvalidArgumentException
*
* @return array|false metadata
*/
public function handle($path, array $metadata)
{
$object = $this->filesystem->getMetadata($path);
if ( ! $object) {
return false;
}
$keys = array_diff($metadata, array_keys($object));
foreach ($keys as $key) {
if ( ! method_exists($this->filesystem, $method = 'get' . ucfirst($key))) {
throw new InvalidArgumentException('Could not fetch metadata: ' . $key);
}
$object[$key] = $this->filesystem->{$method}($path);
}
return $object;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace League\Flysystem\Plugin;
class ListFiles extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'listFiles';
}
/**
* List all files in the directory.
*
* @param string $directory
* @param bool $recursive
*
* @return array
*/
public function handle($directory = '', $recursive = false)
{
$contents = $this->filesystem->listContents($directory, $recursive);
$filter = function ($object) {
return $object['type'] === 'file';
};
return array_values(array_filter($contents, $filter));
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace League\Flysystem\Plugin;
class ListPaths extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'listPaths';
}
/**
* List all paths.
*
* @param string $directory
* @param bool $recursive
*
* @return array paths
*/
public function handle($directory = '', $recursive = false)
{
$result = [];
$contents = $this->filesystem->listContents($directory, $recursive);
foreach ($contents as $object) {
$result[] = $object['path'];
}
return $result;
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace League\Flysystem\Plugin;
class ListWith extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'listWith';
}
/**
* List contents with metadata.
*
* @param array $keys
* @param string $directory
* @param bool $recursive
*
* @return array listing with metadata
*/
public function handle(array $keys = [], $directory = '', $recursive = false)
{
$contents = $this->filesystem->listContents($directory, $recursive);
foreach ($contents as $index => $object) {
if ($object['type'] === 'file') {
$missingKeys = array_diff($keys, array_keys($object));
$contents[$index] = array_reduce($missingKeys, [$this, 'getMetadataByName'], $object);
}
}
return $contents;
}
/**
* Get a meta-data value by key name.
*
* @param array $object
* @param $key
*
* @return array
*/
protected function getMetadataByName(array $object, $key)
{
$method = 'get' . ucfirst($key);
if ( ! method_exists($this->filesystem, $method)) {
throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key);
}
$object[$key] = $this->filesystem->{$method}($object['path']);
return $object;
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace League\Flysystem\Plugin;
use BadMethodCallException;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;
use LogicException;
trait PluggableTrait
{
/**
* @var array
*/
protected $plugins = [];
/**
* Register a plugin.
*
* @param PluginInterface $plugin
*
* @throws LogicException
*
* @return $this
*/
public function addPlugin(PluginInterface $plugin)
{
if ( ! method_exists($plugin, 'handle')) {
throw new LogicException(get_class($plugin) . ' does not have a handle method.');
}
$this->plugins[$plugin->getMethod()] = $plugin;
return $this;
}
/**
* Find a specific plugin.
*
* @param string $method
*
* @throws PluginNotFoundException
*
* @return PluginInterface
*/
protected function findPlugin($method)
{
if ( ! isset($this->plugins[$method])) {
throw new PluginNotFoundException('Plugin not found for method: ' . $method);
}
return $this->plugins[$method];
}
/**
* Invoke a plugin by method name.
*
* @param string $method
* @param array $arguments
* @param FilesystemInterface $filesystem
*
* @throws PluginNotFoundException
*
* @return mixed
*/
protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem)
{
$plugin = $this->findPlugin($method);
$plugin->setFilesystem($filesystem);
$callback = [$plugin, 'handle'];
return call_user_func_array($callback, $arguments);
}
/**
* Plugins pass-through.
*
* @param string $method
* @param array $arguments
*
* @throws BadMethodCallException
*
* @return mixed
*/
public function __call($method, array $arguments)
{
try {
return $this->invokePlugin($method, $arguments, $this);
} catch (PluginNotFoundException $e) {
throw new BadMethodCallException(
'Call to undefined method '
. get_class($this)
. '::' . $method
);
}
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace League\Flysystem\Plugin;
use LogicException;
class PluginNotFoundException extends LogicException
{
// This exception doesn't require additional information.
}

View File

@@ -0,0 +1,20 @@
<?php
namespace League\Flysystem;
interface PluginInterface
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod();
/**
* Set the Filesystem object.
*
* @param FilesystemInterface $filesystem
*/
public function setFilesystem(FilesystemInterface $filesystem);
}

View File

@@ -0,0 +1,88 @@
<?php
namespace League\Flysystem;
interface ReadInterface
{
/**
* Check whether a file exists.
*
* @param string $path
*
* @return array|bool|null
*/
public function has($path);
/**
* Read a file.
*
* @param string $path
*
* @return array|false
*/
public function read($path);
/**
* Read a file as a stream.
*
* @param string $path
*
* @return array|false
*/
public function readStream($path);
/**
* List contents of a directory.
*
* @param string $directory
* @param bool $recursive
*
* @return array
*/
public function listContents($directory = '', $recursive = false);
/**
* Get all the meta data of a file or directory.
*
* @param string $path
*
* @return array|false
*/
public function getMetadata($path);
/**
* Get the size of a file.
*
* @param string $path
*
* @return array|false
*/
public function getSize($path);
/**
* Get the mimetype of a file.
*
* @param string $path
*
* @return array|false
*/
public function getMimetype($path);
/**
* Get the timestamp of a file.
*
* @param string $path
*
* @return array|false
*/
public function getTimestamp($path);
/**
* Get the visibility of a file.
*
* @param string $path
*
* @return array|false
*/
public function getVisibility($path);
}

View File

@@ -0,0 +1,10 @@
<?php
namespace League\Flysystem;
use LogicException;
class RootViolationException extends LogicException
{
//
}

View File

@@ -0,0 +1,39 @@
<?php
namespace League\Flysystem;
final class SafeStorage
{
/**
* @var string
*/
private $hash;
/**
* @var array
*/
protected static $safeStorage = [];
public function __construct()
{
$this->hash = spl_object_hash($this);
static::$safeStorage[$this->hash] = [];
}
public function storeSafely($key, $value)
{
static::$safeStorage[$this->hash][$key] = $value;
}
public function retrieveSafely($key)
{
if (array_key_exists($key, static::$safeStorage[$this->hash])) {
return static::$safeStorage[$this->hash][$key];
}
}
public function __destruct()
{
unset(static::$safeStorage[$this->hash]);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace League\Flysystem;
use SplFileInfo;
class UnreadableFileException extends Exception
{
public static function forFileInfo(SplFileInfo $fileInfo)
{
return new static(
sprintf(
'Unreadable file encountered: %s',
$fileInfo->getRealPath()
)
);
}
}

View File

@@ -0,0 +1,310 @@
<?php
namespace League\Flysystem;
use League\Flysystem\Util\MimeType;
use LogicException;
class Util
{
/**
* Get normalized pathinfo.
*
* @param string $path
*
* @return array pathinfo
*/
public static function pathinfo($path)
{
$pathinfo = pathinfo($path) + compact('path');
$pathinfo['dirname'] = array_key_exists('dirname', $pathinfo)
? static::normalizeDirname($pathinfo['dirname']) : '';
return $pathinfo;
}
/**
* Normalize a dirname return value.
*
* @param string $dirname
*
* @return string normalized dirname
*/
public static function normalizeDirname($dirname)
{
return $dirname === '.' ? '' : $dirname;
}
/**
* Get a normalized dirname from a path.
*
* @param string $path
*
* @return string dirname
*/
public static function dirname($path)
{
return static::normalizeDirname(dirname($path));
}
/**
* Map result arrays.
*
* @param array $object
* @param array $map
*
* @return array mapped result
*/
public static function map(array $object, array $map)
{
$result = [];
foreach ($map as $from => $to) {
if ( ! isset($object[$from])) {
continue;
}
$result[$to] = $object[$from];
}
return $result;
}
/**
* Normalize path.
*
* @param string $path
*
* @throws LogicException
*
* @return string
*/
public static function normalizePath($path)
{
return static::normalizeRelativePath($path);
}
/**
* Normalize relative directories in a path.
*
* @param string $path
*
* @throws LogicException
*
* @return string
*/
public static function normalizeRelativePath($path)
{
$path = str_replace('\\', '/', $path);
$path = static::removeFunkyWhiteSpace($path);
$parts = [];
foreach (explode('/', $path) as $part) {
switch ($part) {
case '':
case '.':
break;
case '..':
if (empty($parts)) {
throw new LogicException(
'Path is outside of the defined root, path: [' . $path . ']'
);
}
array_pop($parts);
break;
default:
$parts[] = $part;
break;
}
}
return implode('/', $parts);
}
/**
* Removes unprintable characters and invalid unicode characters.
*
* @param string $path
*
* @return string $path
*/
protected static function removeFunkyWhiteSpace($path) {
// We do this check in a loop, since removing invalid unicode characters
// can lead to new characters being created.
while (preg_match('#\p{C}+|^\./#u', $path)) {
$path = preg_replace('#\p{C}+|^\./#u', '', $path);
}
return $path;
}
/**
* Normalize prefix.
*
* @param string $prefix
* @param string $separator
*
* @return string normalized path
*/
public static function normalizePrefix($prefix, $separator)
{
return rtrim($prefix, $separator) . $separator;
}
/**
* Get content size.
*
* @param string $contents
*
* @return int content size
*/
public static function contentSize($contents)
{
return defined('MB_OVERLOAD_STRING') ? mb_strlen($contents, '8bit') : strlen($contents);
}
/**
* Guess MIME Type based on the path of the file and it's content.
*
* @param string $path
* @param string|resource $content
*
* @return string|null MIME Type or NULL if no extension detected
*/
public static function guessMimeType($path, $content)
{
$mimeType = MimeType::detectByContent($content);
if ( ! (empty($mimeType) || in_array($mimeType, ['application/x-empty', 'text/plain', 'text/x-asm']))) {
return $mimeType;
}
return MimeType::detectByFilename($path);
}
/**
* Emulate directories.
*
* @param array $listing
*
* @return array listing with emulated directories
*/
public static function emulateDirectories(array $listing)
{
$directories = [];
$listedDirectories = [];
foreach ($listing as $object) {
list($directories, $listedDirectories) = static::emulateObjectDirectories(
$object,
$directories,
$listedDirectories
);
}
$directories = array_diff(array_unique($directories), array_unique($listedDirectories));
foreach ($directories as $directory) {
$listing[] = static::pathinfo($directory) + ['type' => 'dir'];
}
return $listing;
}
/**
* Ensure a Config instance.
*
* @param null|array|Config $config
*
* @return Config config instance
*
* @throw LogicException
*/
public static function ensureConfig($config)
{
if ($config === null) {
return new Config();
}
if ($config instanceof Config) {
return $config;
}
if (is_array($config)) {
return new Config($config);
}
throw new LogicException('A config should either be an array or a Flysystem\Config object.');
}
/**
* Rewind a stream.
*
* @param resource $resource
*/
public static function rewindStream($resource)
{
if (ftell($resource) !== 0 && static::isSeekableStream($resource)) {
rewind($resource);
}
}
public static function isSeekableStream($resource)
{
$metadata = stream_get_meta_data($resource);
return $metadata['seekable'];
}
/**
* Get the size of a stream.
*
* @param resource $resource
*
* @return int stream size
*/
public static function getStreamSize($resource)
{
$stat = fstat($resource);
return $stat['size'];
}
/**
* Emulate the directories of a single object.
*
* @param array $object
* @param array $directories
* @param array $listedDirectories
*
* @return array
*/
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories)
{
if ($object['type'] === 'dir') {
$listedDirectories[] = $object['path'];
}
if (empty($object['dirname'])) {
return [$directories, $listedDirectories];
}
$parent = $object['dirname'];
while ( ! empty($parent) && ! in_array($parent, $directories)) {
$directories[] = $parent;
$parent = static::dirname($parent);
}
if (isset($object['type']) && $object['type'] === 'dir') {
$listedDirectories[] = $object['path'];
return [$directories, $listedDirectories];
}
return [$directories, $listedDirectories];
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace League\Flysystem\Util;
use League\Flysystem\Util;
/**
* @internal
*/
class ContentListingFormatter
{
/**
* @var string
*/
private $directory;
/**
* @var bool
*/
private $recursive;
/**
* @param string $directory
* @param bool $recursive
*/
public function __construct($directory, $recursive)
{
$this->directory = $directory;
$this->recursive = $recursive;
}
/**
* Format contents listing.
*
* @param array $listing
*
* @return array
*/
public function formatListing(array $listing)
{
$listing = array_values(
array_map(
[$this, 'addPathInfo'],
array_filter($listing, [$this, 'isEntryOutOfScope'])
)
);
return $this->sortListing($listing);
}
private function addPathInfo(array $entry)
{
return $entry + Util::pathinfo($entry['path']);
}
/**
* Determine if the entry is out of scope.
*
* @param array $entry
*
* @return bool
*/
private function isEntryOutOfScope(array $entry)
{
if (empty($entry['path']) && $entry['path'] !== '0') {
return false;
}
if ($this->recursive) {
return $this->residesInDirectory($entry);
}
return $this->isDirectChild($entry);
}
/**
* Check if the entry resides within the parent directory.
*
* @param $entry
*
* @return bool
*/
private function residesInDirectory(array $entry)
{
if ($this->directory === '') {
return true;
}
return strpos($entry['path'], $this->directory . '/') === 0;
}
/**
* Check if the entry is a direct child of the directory.
*
* @param $entry
*
* @return bool
*/
private function isDirectChild(array $entry)
{
return Util::dirname($entry['path']) === $this->directory;
}
/**
* @param array $listing
*
* @return array
*/
private function sortListing(array $listing)
{
usort(
$listing,
function ($a, $b) {
return strcasecmp($a['path'], $b['path']);
}
);
return $listing;
}
}

View File

@@ -0,0 +1,216 @@
<?php
namespace League\Flysystem\Util;
use Finfo;
use ErrorException;
/**
* @internal
*/
class MimeType
{
/**
* Detects MIME Type based on given content.
*
* @param mixed $content
*
* @return string|null MIME Type or NULL if no mime type detected
*/
public static function detectByContent($content)
{
if ( ! class_exists('Finfo') || ! is_string($content)) {
return;
}
try {
$finfo = new Finfo(FILEINFO_MIME_TYPE);
return $finfo->buffer($content) ?: null;
} catch( ErrorException $e ) {
// This is caused by an array to string conversion error.
}
}
/**
* Detects MIME Type based on file extension.
*
* @param string $extension
*
* @return string|null MIME Type or NULL if no extension detected
*/
public static function detectByFileExtension($extension)
{
static $extensionToMimeTypeMap;
if (! $extensionToMimeTypeMap) {
$extensionToMimeTypeMap = static::getExtensionToMimeTypeMap();
}
if (isset($extensionToMimeTypeMap[$extension])) {
return $extensionToMimeTypeMap[$extension];
}
return 'text/plain';
}
/**
* @param string $filename
*
* @return string
*/
public static function detectByFilename($filename)
{
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return empty($extension) ? 'text/plain' : static::detectByFileExtension($extension);
}
/**
* @return array Map of file extension to MIME Type
*/
public static function getExtensionToMimeTypeMap()
{
return [
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'csv' => 'text/x-comma-separated-values',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'psd' => 'application/x-photoshop',
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/pdf',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => 'application/javascript',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => 'application/x-tar',
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/x-zip',
'rar' => 'application/x-rar',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => 'audio/x-wav',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dot' => 'application/msword',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'word' => 'application/msword',
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => 'application/json',
'pem' => 'application/x-x509-user-cert',
'p10' => 'application/x-pkcs10',
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => 'application/pkcs7-mime',
'p7m' => 'application/pkcs7-mime',
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => 'application/x-x509-ca-cert',
'crl' => 'application/pkix-crl',
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => 'application/pkix-cert',
'3g2' => 'video/3gpp2',
'3gp' => 'video/3gp',
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => 'video/mp4',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => 'video/x-ms-wmv',
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => 'audio/ogg',
'kmz' => 'application/vnd.google-earth.kmz',
'kml' => 'application/vnd.google-earth.kml+xml',
'ics' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => 'application/x-7z-compressed',
'cdr' => 'application/cdr',
'wma' => 'audio/x-ms-wma',
'jar' => 'application/java-archive',
];
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace League\Flysystem\Util;
class StreamHasher
{
/**
* @var string
*/
private $algo;
/**
* StreamHasher constructor.
*
* @param string $algo
*/
public function __construct($algo)
{
$this->algo = $algo;
}
/**
* @param $resource
*
* @return string
*/
public function hash($resource)
{
rewind($resource);
$context = hash_init($this->algo);
hash_update_stream($context, $resource);
fclose($resource);
return hash_final($context);
}
}