VFS (Virtual File System)

Overview

VFS (Virtual File System)

Virtual File System

Master branch build status Published version PHP ~5.4 MIT Licensed

VFS is a virtual file system for PHP built using the stream wrapper API. Streams are exposed just as typical file:// or http:// streams are to PHP's built-in functions and keywords like fopen and require. This implementation attempts to stay true to the typical streams, including triggering warnings and handling edge cases appropriately.

It can be installed in whichever way you prefer, but I recommend Composer.

{
    "require": {
        "adlawson/vfs": "*"
    }
}

Documentation

After creating and mounting the file system, you have the option of manipulating the virtual file system either via PHP's built-in functions, the VFS interfaces, or interfaces provided by another file system library.

mkdir('vfs://foo/bar/baz'); $laravel = new Illuminate\Filesystem(); $laravel->isDirectory('vfs://foo/bar/baz'); //true // Triggers PHP warnings on error just like typical streams rename('vfs://path/to/nowhere', 'vfs://path/to/somewhere'); // PHP Warning: rename(vfs://path/to/nowhere,vfs://path/to/somewhere): No such file or directory in /srv/index.php on line 1; triggered in /srv/src/Logger/PhpErrorLogger.php on line 32">

use Vfs\FileSystem;
use Vfs\Node\Directory;
use Vfs\Node\File;

// Create and mount the file system
$fs = FileSystem::factory('vfs://');
$fs->mount();

// Add `/foo` and `/foo/bar.txt`
$foo = new Directory(['bar.txt' => new File('Hello, World!')]);
$fs->get('/')->add('foo', $foo);

// Get contents of `/foo/bar.txt`
$fs->get('/foo/bar.txt')->getContent(); // Hello, World!
file_get_contents('vfs://foo/bar.txt'); // Hello, World!

// Add `/foo/bar` and `/foo/bar/baz.php`
mkdir('vfs://foo/bar');
file_put_contents('vfs://foo/bar.php', ');

// Require `/foo/bar.php`
require 'vfs://foo/baz.php';

// Works with any other file system library too
$symfony = new Symfony\Component\Filesystem\Filesystem();
$symfony->mkdir('vfs://foo/bar/baz');
$laravel = new Illuminate\Filesystem();
$laravel->isDirectory('vfs://foo/bar/baz'); //true

// Triggers PHP warnings on error just like typical streams
rename('vfs://path/to/nowhere', 'vfs://path/to/somewhere');
// PHP Warning: rename(vfs://path/to/nowhere,vfs://path/to/somewhere): No such file or directory in /srv/index.php on line 1; triggered in /srv/src/Logger/PhpErrorLogger.php on line 32

Example use cases

If you need to ask what you'd use a virtual file system for, you probably don't need one, but just in case, I've compiled a small list of examples:

  • Testing file system libraries without writing to disc
  • Runtime evaluation without eval (via write and require)
  • ...we need some more!

Todo

Current tasks are listed on the github issues page, but some are listed here for reference:

  • Symlinks
  • File locks
  • Permissions/ACL

Contributing

Contributions are accepted via Pull Request, but passing unit tests must be included before it will be considered for merge.

$ curl -O https://raw.githubusercontent.com/adlawson/vagrantfiles/master/php/Vagrantfile
$ vagrant up
$ vagrant ssh
...

$ cd /srv
$ composer install
$ vendor/bin/phpunit

License

The content of this library is released under the MIT License by Andrew Lawson.
You can find a copy of this license in LICENSE or at http://opensource.org/licenses/mit.

Comments
  • Create directory recursively

    Create directory recursively

    • Removes call to non-existent method ‘checkBit’
    • Uses $recursive option passed as 2nd argument to determine if recursion should occur
    • Removes unused argument from DirectoryHandle::buildNodesRecursive
    opened by cspray 6
  • Can VFS be used as sandbox FS for a shell like app?

    Can VFS be used as sandbox FS for a shell like app?

    Is it possible to use this as file system for JSON-RPC where client is command line app in a browser? Or this FS vanish when the script end. Is it possilbe to save reference to VFS in a $_SESSION?

    opened by jcubic 5
  • `is_readable` returns false

    `is_readable` returns false

    Trying basic code from example, but is_readable() returns false, while file_get_contents() returns contents without problems. I assume this is because it's stream and looks like is_readable() returns false for streams.

    Any idea/workaround for this?

    question 
    opened by azamat-sharapov 4
  • PHP function is_dir() does not work with vfs.php

    PHP function is_dir() does not work with vfs.php

    Seems like is_dir() does not work with a virtual directory. My guess is something is not completely correct with the value of $directory->getMode(), but I'm not sure.

    Test case to reproduce the issue

    <?php
    
    namespace Vfs;
    
    use Vfs\Node\Directory;
    use Vfs\Node\File;
    
    class PHPFileFunctionsTest extends \PHPUnit_Framework_TestCase
    {
        const SCHEME = 'foobar://';
    
        /**
         * @var FileSystem
         */
        private $fs;
    
        public function setUp()
        {
            $fs = FileSystem::factory( self::SCHEME );
    
            $someDir = new Directory( array( 'file' => new File( 'foobar' ) ) );
    
            $fs->get( '/' )->add( 'some_dir', $someDir );
    
            $this->fs = $fs;
        }
    
        public function tearDown()
        {
            $this->fs->unmount();
    
            unset( $this->fs );
        }
    
        public function testFileGetContentsWorks()
        {
            $path = self::SCHEME . 'some_dir/file';
    
            $this->assertEquals( 'foobar', file_get_contents( $path ) );
        }
    
        public function testIsDirWorks()
        {
            $path = self::SCHEME . 'some_dir';
    
            $this->assertTrue( is_dir( $path ) );
        }
    }
    
    

    Output from running PHPUnit:

    There was 1 failure:
    
    1) Vfs\PHPFileFunctionsTest::testIsDirWorks
    Failed asserting that false is true.
    
    /home/vagrant/src/github/vfs.php/test/unit/PHPFileFunctionsTest.php:46
    
    FAILURES!
    Tests: 163, Assertions: 379, Failures: 1.
    
    opened by stubbetje 3
  • Symlinks

    Symlinks

    While symlink() isn't supported by PHP Stream Wrappers to create symlinks, you can still interact with symlinks that already exist.

    <?php
    use Vfs\FileSystemBuilder;
    use Vfs\Node\FileLink;
    
    $fs = (new FileSystemBuilder())->setTree(['foo' => ['bar' => 'baz']])->build();
    $fs->get('/')->add(new FileLink('my_symlink', $fs->get('/foo/bar')));
    
    is_link('vfs://my_symlink'); // => true
    

    They're actually implemented as hard links rather than symbolic links, meaning that if the target file is moved or renamed the link still works. It was easier to implement this way.

    enhancement 
    opened by adlawson 0
  • Add a Gitter chat badge to README.md

    Add a Gitter chat badge to README.md

    opened by gitter-badger 0
  • Remove extra $original docblock

    Remove extra $original docblock

    This triggers the symfony debug class loader with the following:

      1x: The "Vfs\Stream\AbstractHandle::rename()" method will require a new "string $origin" argument in the next major version of its interface "Vfs\Stream\HandleInterface", not defining it is deprecated.
    
    opened by Sam152 0
  • Match docblock to defined param name.

    Match docblock to defined param name.

    The mismatch triggers symfonys debug class loader with:

      1x: The "Vfs\Node\Factory\NodeFactory::buildFileLink()" method will require a new "FileInterface $file" argument in the next major version of its interface "Vfs\Node\Factory\NodeFactoryInterface", not defining it is deprecated.
    
    opened by Sam152 0
  • Add changelog

    Add changelog

    Changes at this stage are sometimes quite large. Good thing is that not many people use this library so I can get away with it for now but I should really add a useful changelog.

    task 
    opened by adlawson 0
  • Handle open mode (and modifier) not always considered

    Handle open mode (and modifier) not always considered

    Some of the time, especially when opening a file/directory handle, the open mode is taken into account (w vs w+ vs xt etc). The mode and modifier both need to be taken into account when reading/writing/deleting handles.

    bug enhancement 
    opened by adlawson 0
Owner
Andrew Lawson
Engineer @monzo
Andrew Lawson
🐋 This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

?? This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

Anton Kliek 1 Jan 26, 2022
Uma loja virtual de teclados feita nas aulas de PW-II na ETEC com PHP e bootstrap

etec-tectok-teclados Uma loja virtual de teclados feita nas aulas de PW-II na ETEC com PHP e bootstrap Translations: ???? English tectok.herokuapp.com

Luis Felipe Santos do Nascimento 5 May 3, 2022
COP4331 Class Project 1 - "ConnectUs" virtual contact manager/Rolodex

ConnectUs COP4331 Class Project 1 - "ConnectUs" virtual contact manager/Rolodex Team Members Orion (Project Manager) Eric (Database) Rafael (API/Backe

Orion 3 Dec 9, 2022
A virtual machine for executing programs written in Hack.

HHVM HHVM page | HHVM documentation | Hacklang page | General group | Dev group | Twitter HHVM is an open-source virtual machine designed for executin

Meta 17.5k Dec 30, 2022
File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.

Sebastian Tschan 31.1k Dec 30, 2022
Smart File System - Use SmartFileInfo with useful methods that you need everyday

Smart File System - Use SmartFileInfo with useful methods that you need everyday

null 78 Dec 22, 2022
Get the system resources in PHP, as memory, number of CPU'S, Temperature of CPU or GPU, Operating System, Hard Disk usage, .... Works in Windows & Linux

system-resources. A class to get the hardware resources We can get CPU load, CPU/GPU temperature, free/used memory & Hard disk. Written in PHP It is a

Rafael Martin Soto 10 Oct 15, 2022
Tier3 POS SYSTEM - FBR Integrated POS System

FBR-POS-INTEGRATION-SERVICES Tier3 POS SYSTEM - FBR Integrated POS System Minimum System Requirements : PHP version 7.2+ (openssl, curl, gd, intl and

Tier3 Pakistan 2 Feb 28, 2022
Admidio is a free open source user management system for websites of organizations and groups. The system has a flexible role model so that it’s possible to reflect the structure and permissions of your organization.

Admidio Admidio is a free open source user management system for websites of organizations and groups. The system has a flexible role model so that it

Admidio 212 Dec 30, 2022
Optimizes class loading performance by generating a single PHP file containing all of the autoloaded files.

Class Preloader for PHP This tool is used to generate a single PHP script containing all of the classes required for a specific use case. Using a sing

Class Preloader 356 Nov 26, 2022
⚙️ A WordPress plugin to set WordPress options from a .env file.

dotenv A WordPress plugin to set WordPress options from a .env file. Any WPENV_ prefixed variables in the .env will be used to override the WordPress

Brad Parbs 13 Oct 6, 2022
CrateKeyShopGUI Pocketmine-MP plugin which can be set in Config.yml file

CrateKeyShopGUI CrateKeyShopGUI Pocketmine-MP plugin which can be set in Config.yml file Depend FormAPI EconomyAPI PiggyCrate InvCrashFix Download Dow

null 4 Jan 7, 2022
🔨 Prefixes all PHP namespaces in a file/directory to isolate the code bundled in PHARs.

PHP-Scoper PHP-Scoper is a tool which essentially moves any body of code, including all dependencies such as vendor directories, to a new and distinct

Humbug 590 Jan 2, 2023
Rules to detect game engines and other technologies based on Steam depot file lists

SteamDB File Detection Rule Sets This is a set of scripts that are used by SteamDB to make educated guesses about the engine(s) & technology used to b

Steam Database 103 Dec 14, 2022
This shell script and PHP file create a browseable HTML site from the Zig standard library source.

Browseable Zig standard library This shell script and PHP file create a browseable HTML site from the Zig standard library source. The idea is to inve

Dave Gauer 3 Mar 20, 2022
Write to Laravel Config files and maintain file integrity

Laravel Config Writer Write to Laravel Config files and maintain file integrity. This library is an extension of the Config component used by Laravel.

Sam Geo 158 Dec 30, 2022
Control all text in multiple file bad words filter with worps

About Worps | PHP! Control all text in multiple file bad words filter with worps If you try online Click What to do use for worps Create new object Wo

null 1 Dec 30, 2021
A PHP library for creating EDI 837 claim equivalent to paper-claim 1500. EDI X12 ANSI 837 File 5010 Version

EDI X12 ANSI 5010 PHP Library for creating EDI X12 ANSI 837 File 5010 Version A Simple PHP function for creating an EDI X12 ANSI 837 file version 0050

WalksWithMe 7 Jan 3, 2023