PHPackages                             bocharsky-bw/file-naming-resolver - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bocharsky-bw/file-naming-resolver

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

bocharsky-bw/file-naming-resolver
=================================

A lightweight library which helps to resolve a file/directory naming of uploaded files using various naming strategies.

v0.3.2(9y ago)1104.9k3MITPHPPHP &gt;=5.3

Since Dec 13Pushed 9y ago4 watchersCompare

[ Source](https://github.com/bocharsky-bw/FileNamingResolver)[ Packagist](https://packagist.org/packages/bocharsky-bw/file-naming-resolver)[ Docs](https://github.com/bocharsky-bw/FileNamingResolver)[ RSS](/packages/bocharsky-bw-file-naming-resolver/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (1)Versions (7)Used By (0)

FileNamingResolver
==================

[](#filenamingresolver)

A lightweight library which helps to resolve a file/directory naming of uploaded files using various naming strategies.

> This library solves only naming things and do *nothing* with any files or directories directly. If you are looking for some filesystem abstraction layer - looks closer to [Gaufrette](https://github.com/KnpLabs/Gaufrette), [symfony/filesystem](https://github.com/symfony/filesystem) or [Flysystem](https://github.com/thephpleague/flysystem)libraries.

[![Travis Status](https://camo.githubusercontent.com/aa590f7123b6dbebe9c51f6ada5d2a4695ec595306c2d4599360efbc0e5702cb/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f626f63686172736b792d62772f46696c654e616d696e675265736f6c7665722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/bocharsky-bw/FileNamingResolver)[![HHVM Status](https://camo.githubusercontent.com/be41eb4fb5ef3945d4f22fb3050f78cc52fcc70fcf6a93c99abce6052bb19f81/68747470733a2f2f696d672e736869656c64732e696f2f6868766d2f626f63686172736b792d62772f66696c652d6e616d696e672d7265736f6c7665722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](http://hhvm.h4cc.de/package/bocharsky-bw/file-naming-resolver)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/1f5ec74949c487d6c4b6448e0208477413ccf2579d41212950e0fc06f7d37ba5/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f626f63686172736b792d62772f46696c654e616d696e675265736f6c7665722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/bocharsky-bw/FileNamingResolver/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/b42a8f76698f29041fa7752fe5b2a84f9536f7412350b2f8771186f5ff514a29/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f626f63686172736b792d62772f46696c654e616d696e675265736f6c7665722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/bocharsky-bw/FileNamingResolver/?branch=master)[![Software License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](https://github.com/bocharsky-bw/FileNamingResolver/blob/master/LICENSE)[![Latest Version](https://camo.githubusercontent.com/c1319250cc4d2237a065814891a3d4f8772fb5c37312091fd5ba0b254bbde19c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f626f63686172736b792d62772f66696c652d6e616d696e672d7265736f6c7665722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/bocharsky-bw/file-naming-resolver)

[![SensioLabsInsight](https://camo.githubusercontent.com/2f36344c8ae3aae9a52dfba94fe22655a8543b4c0cd4a385bd732ba1a49bef8a/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f35613463666130662d323262312d346437362d616462332d3337333031376632316565382f6269672e706e67)](https://insight.sensiolabs.com/projects/5a4cfa0f-22b1-4d76-adb3-373017f21ee8)

Contents
--------

[](#contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [FileInfo](#fileinfo)
- [Strategy list](#strategy-list)
    - [AggregateNamingStrategy](#aggregatenamingstrategy)
    - [CallbackNamingStrategy](#callbacknamingstrategy)
    - [ContentHashNamingStrategy](#contenthashnamingstrategy)
    - [DatetimeNamingStrategy](#datetimenamingstrategy)
    - [HashNamingStrategy](#hashnamingstrategy)
- [Example](#example)
- [Contribution](#contribution)

Requirements
------------

[](#requirements)

This library is standalone without any dependencies. To use it in your project ensure you correspond to the next requirements:

- PHP `5.3` or higher

Installation
------------

[](#installation)

The preferred way to install this package is to use [Composer](https://getcomposer.org/):

```
$ composer require bocharsky-bw/file-naming-resolver
```

If you don't use `Composer` - register this package in your autoloader manually following [PSR-4](http://www.php-fig.org/psr/psr-4/) autoloader standard or simply download this library and `require` the necessary files directly in your scripts:

```
require_once __DIR__ . '/path/to/library/src/FileNamingResolver.php';
// and other files you intend to use...
```

Usage
-----

[](#usage)

First of all, before using file naming resolver, you should determine which naming strategy to use. You can use different strategies out-of-the-box or easily create your own one by implementing the `NamingStrategyInterface` interface or extends the `AbstractNamingStrategy` class which already implemented it for you.

```
// don't forget to use namespaces
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\HashNamingStrategy;

// First of all, upload new file or use any uploaded file on the your server

// Create source FileInfo object from FQFN of uploaded file
$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

// Create at least one naming strategy object
$hashStrategy = new HashNamingStrategy();

// Create file naming resolver and pass naming strategy to it
$namingResolver = new FileNamingResolver($hashStrategy);

// Resolve new name using specified naming strategy
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/4e/d3/a51a07c8e89ff8f228075b7fc76b.jpg

// Use rename() / move_uploaded_file() built-in functions, Gaufrette or any other filesystem
// abstraction library to move uploaded file to the directory according to suggested pathname.
```

> **NOTE:** In all examples hereinafter the `__DIR__` equals to `/var/www/html/web`.

FileInfo
--------

[](#fileinfo)

The `FileNamingResolver\FileInfo` class extends `\SplFileInfo` object. For more info check the [SplFileInfo](http://php.net/manual/en/class.splfileinfo.php). Below shown list of frequently used getters of this class:

```
$fileInfo = new FileInfo('/var/www/html/web/uploads/products/image.jpg');

echo $fileInfo->toString();     // '/var/www/html/web/uploads/products/image.jpg'
echo $fileInfo->getPathname();  // '/var/www/html/web/uploads/products/image.jpg'
echo $fileInfo->getPath();      // '/var/www/html/web/uploads/products'
echo $fileInfo->getFilename();  // 'image.jpg'
echo $fileInfo->getBasename();  // 'image'
echo $fileInfo->getExtension(); // 'jpg'
echo $fileInfo->getPathRelativeTo('/var/www/html/web');     // 'uploads/products'
echo $fileInfo->getPathnameRelativeTo('/var/www/html/web'); // 'uploads/products/image.jpg'
```

Strategy list
-------------

[](#strategy-list)

### AggregateNamingStrategy

[](#aggregatenamingstrategy)

This naming strategy allows to use as many naming strategies as you need at once. Its aggregate results. Each new result pathname based on the previous one.

```
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\AggregateNamingStrategy;
use FileNamingResolver\NamingStrategy\DatetimeNamingStrategy;
use FileNamingResolver\NamingStrategy\HashNamingStrategy;

$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

$datetimeStrategy = new DatetimeNamingStrategy();
$hashStrategy = new HashNamingStrategy();
// Create an aggregate naming strategy object
$strategies = [
    $datetimeStrategy,
    $hashStrategy,
    // and so on as many as you need...
];
$aggregateStrategy = new AggregateNamingStrategy($strategies);

$namingResolver = new FileNamingResolver($aggregateStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/2015/12/9c/98/87cbf44f53c9f6fa08f44ce705c8.jpg
```

To reverse applying order of strategies pass `true` as second parameter to the constructor of `AggregateNamingStrategy` class:

```
$aggregateStrategy = new AggregateNamingStrategy($strategies, AggregateNamingStrategy::MODE_REVERSE);

$namingResolver = new FileNamingResolver($aggregateStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/a0/cb/2015/12/11-23-35-039900.jpg
```

### CallbackNamingStrategy

[](#callbacknamingstrategy)

This naming strategy allows create a custom naming logic using custom callbacks.

```
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\CallbackNamingStrategy;

$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

// Create a custom callback naming strategy object
$callbackStrategy = new CallbackNamingStrategy(function (FileInfo $srcFileInfo) {
    $dstFileInfo = $srcFileInfo
        // Add 'products' suffix to the path
        ->changePath($srcFileInfo->getPath().FileInfo::SEPARATOR_DIRECTORY.'products')
        // Generate custom basename of the file without extension
        ->changeBasename(time().'-'.uniqid()) // comment this line to keep original basename
        // or do whatever custom naming logic you want here...
    ;

    return $dstFileInfo;
});

$namingResolver = new FileNamingResolver($callbackStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/products/1450004778-566d512a32d2c.jpg
```

### ContentHashNamingStrategy

[](#contenthashnamingstrategy)

The naming behavior of hash naming strategy looks like [Twig](https://github.com/twigphp/Twig) naming of cached files.

```
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\ContentHashNamingStrategy;

$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

// Create a hash naming strategy object
$contentHashStrategy = new ContentHashNamingStrategy(
    // Hashing algorithm, by default: 'md5'
    ContentHashNamingStrategy::ALGORITHM_SHA1, // 'sha1'
    // Count of parts for explode, by default: 2
    3,
    // Length of each exploded part, by default: 2
    3,
    // Keep full filename for easy searching
    true
);

$namingResolver = new FileNamingResolver($contentHashStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/4ed/3a5/1a0/4ed3a51a07c8e89ff8f228075b7fc76b.jpg
```

> **NOTE:** Be sure that source file *really* exist before using `ContentHashNamingStrategy`otherwise an `InvalidArgumentException` will be thrown. You probably need to use a `isFile()`method on `FileInfo` object to be sure that file exists. It's necessary because this naming strategy try to hash a *real* file content.

### DatetimeNamingStrategy

[](#datetimenamingstrategy)

The naming behavior of datetime naming strategy looks like [WordPress](https://github.com/wordpress/wordpress) naming of uploaded media files.

```
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\DatetimeNamingStrategy;

$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

// Create a datetime naming strategy object
$datetimeStrategy = new DatetimeNamingStrategy(
    // DateTime format for directories, by default: 'Y/m'
    DateTimeNamingStrategy::FORMAT_DIR_YEAR_MONTH_DAY,         // 'Y/m/d'
    // DateTime format for files, by default: 'H-i-s-u'
    DateTimeNamingStrategy::FORMAT_FILE_TIMESTAMP_MICROSECONDS // 'U-u'
);

$namingResolver = new FileNamingResolver($datetimeStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/2015/12/13/1450004392-907500.jpg
```

### HashNamingStrategy

[](#hashnamingstrategy)

The naming behavior of hash naming strategy looks like [Twig](https://github.com/twigphp/Twig) naming of cached files.

```
use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\HashNamingStrategy;

$srcFileInfo = new FileInfo(__DIR__.'/uploads/image.jpg');

// Create a hash naming strategy object
$hashStrategy = new HashNamingStrategy(
    // Hashing algorithm, by default: 'md5'
    HashNamingStrategy::ALGORITHM_SHA1, // 'sha1'
    // Count of parts for explode, by default: 2
    3,
    // Length of each exploded part, by default: 2
    3,
    // Keep full filename for easy searching
    true
);

$namingResolver = new FileNamingResolver($hashStrategy);
$dstFileInfo = $namingResolver->resolve($srcFileInfo);
echo $dstFileInfo->toString(); // /var/www/html/web/uploads/4ed/3a5/1a0/4ed3a51a07c8e89ff8f228075b7fc76b.jpg
```

Example
-------

[](#example)

There is a full working example how to upload files with a simple HTML form and built-in PHP functions using FileNamingResolver library.

```
