phine/compact

A PHP library for compacting the contents of files.

1.1.0 2014-01-07 00:32 UTC

README

Build Status Coverage Status Latest Stable Version Total Downloads

A PHP library for compacting the contents of files.

Requirement

Installation

Via Composer:

$ composer require "phine/compact=~1.0"

Usage

The Compact library provides a consistent way of compacting files and their contents. The purpose of the library is simply to reduce the size of the contents without affecting how it is used. For example, compacting a JSON file would involve removing any excess whitespace that was used for "pretty printing".

use Phine\Compact\Json;

$compactor = new Json();

echo $compactor->compactFile('example.json');

// which is also the same as

echo $compactor->compactContents(file_get_contents('example.json'));

Assuming we had this in example.json:

{
    "name": 123
}

The contents would then be compacted to:

{"name":123}

Bundled Compactors

The library also includes the following compactor classes:

  • Phine\Compact\Json — For compacting JSON files.
  • Phine\Compact\Php — For compacting PHP files.
  • Phine\Compact\Xml — For compacting XML files.

Creating a Compactor

The library includes an interface that all bundled classes implement. An abstract class is also included, which all bundled compactor classes extend. When you create your own compactor class, you will want to extend the Phine\Compact\AbstractCompact class.

use Phine\Compact\AbstractCompact;

/**
 * Simply trims all lines.
 */
class Trim extends AbstractCompact
{
    /**
     * {@inheritDoc}
     */
    public function compactContents($contents)
    {
        $contents = preg_replace('/^\s+/m', '', $contents);
        $contents = preg_replace('/\s+$/m', '', $contents);

        return $contents;
    }
}

When extending the AbstractCompact class, the compactFile() method will already be implemented for you. It will rely on the compactContents() method to compact the contents after it has been read from the file.

Please considering adding your compactor class to the wiki.

Collections

If you need to manage multiple compactors, the library offers a Collection class. In addition to the class, an interface is provided so that different implementations can be supported.

use Phine\Compact\Collection;
use Phine\Compact\Json;
use Phine\Compact\Php;
use Phine\Compact\Xml;

$collection = new Collection();
$collection->addCompactor(new Json());
$collection->addCompactor(new Php());
$collection->addCompactor(new Xml());

$json = <<<JSON
{
    "key": "value"
}
JSON;

echo $collection->getCompactor('json')->compactContents($json);
// {"key":"value"}

Documentation

You can find the API documentation here.

License

This library is available under the MIT license.