PHPackages                             jimmyoak/utilities - 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. jimmyoak/utilities

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

jimmyoak/utilities
==================

3.3.0(9y ago)8111.3k↓46.7%23MITPHPPHP &gt;=5.5.0

Since May 12Pushed 9y ago2 watchersCompare

[ Source](https://github.com/jimmyoak/utilities)[ Packagist](https://packagist.org/packages/jimmyoak/utilities)[ RSS](/packages/jimmyoak-utilities/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (49)Used By (3)

JimmyOak Utilities
==================

[](#jimmyoak-utilities)

[![Build Status](https://camo.githubusercontent.com/a1b09ebcd02edd77de35b8272df22ae6bd5d40298f005de1d3af862ffdfcf4d7/68747470733a2f2f7472617669732d63692e6f72672f6a696d6d796f616b2f7574696c69746965732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jimmyoak/utilities)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/2e122ce12e1861c627457903f26f1f2cef61b2fe2ba7473ad0c5a98b866f850b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a696d6d796f616b2f7574696c69746965732f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jimmyoak/utilities/?branch=master)[![Coverage Status](https://camo.githubusercontent.com/4ea348edac02bd2769201a318516ca6444d202b58d4315ac16dab851812a0027/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6a696d6d796f616b2f7574696c69746965732f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/jimmyoak/utilities?branch=master)

- [Installation](#installation)
- [Features](#features)
- [Examples](#examples)
    - [Collections](#collections)
        - [Collection](#collection)
        - [TypedCollection](#typedcollection)
        - [Set](#set)
        - [TypedSet](#typedset)
    - [Event Publisher](#eventpublisher)
    - [DataType](#datatype)
        - [Enum](#enum)
        - [SimpleValueObject](#simplevalueobject)
    - [ArrayUtils](#arrayutils)
        - [Flatten](#flatten)
        - [ToXmlString and ToXml](#toxmlstring-and-toxml)
    - [ObjectUtils](#objectutils)
        - [ToArray](#toarray)
        - [ToXmlString and ToXml](#toxmlstring-and-toxml)
    - [StringUtils](#stringutils)
        - [BeginsWith](#beginswith)
        - [EndsWith](#endswith)
        - [RemoveAccents](#removeaccents)
        - [RemoveExtraSpaces](#removeextraspaces)
        - [IsUrl and IsEmail](#isurl-and-isemail)
    - [FileUtils](#fileutils)
        - [ExtensionIs](#extensionis)
        - [MakePath](#makepath)
        - [GetExtension](#getextension)
        - [GetNameWithoutExtension](#getnamewithoutextension)
        - [ScanDir](#scandir)
- [Quality](#quality)
- [Contribute](#contribute)
- [Authors](#authors)
- [License](#license)

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

[](#installation)

Use [Composer](https://getcomposer.org) to install the package:

```
$ composer require jimmyoak/utilities
```

For PHP 5.3 compatibility use \*.\*.\*b versions (yep, I marked them as beta versions):

```
$ composer require jimmyoak/utilities:2.5.1b
```

Features
--------

[](#features)

- Collection and Set utilities (Typed/Untyped collections and sets)
- Enum base class
- SimpleValueObject base class
- Event publisher
- Array utilities
- File utilities
- String utilities

Examples
--------

[](#examples)

### Collections

[](#collections)

#### Collection

[](#collection)

```
$collection = new \JimmyOak\Collection\Collection();
$collection[] = 'Foo';
$collection[] = 'Bar';

foreach ($collection as $value) {
    echo $value . ' ';
}

//prints: Foo Bar
```

#### TypedCollection

[](#typedcollection)

```
$collection = new \JimmyOak\Collection\TypedCollection(\DateTime::class);
$collection[] = new \DateTime();
$collection[] = new \DateInterval('P1D'); //Throws \JimmyOak\Exception\Collection\NotValidObjectTypeException
```

#### Set

[](#set)

You can fill the collection with object, scalars...

```
$collection = new \JimmyOak\Collection\Set();
$collection[] = 'Foo';
$collection[] = 'Foo';
$collection[] = 'Bar';

foreach ($collection as $value) {
    echo $value . ' ';
}

//prints: Foo Bar
```

#### TypedSet

[](#typedset)

You can fill the collection with object, scalars...

```
$collection = new \JimmyOak\Collection\TypedSet(\DateTime::class);
$aDateTime = new \DateTime('1992-10-07');
$collection[] = $aDateTime;
$collection[] = $aDateTime;
try {
    $collection[] = new \DateInterval('P1D'); //throws \JimmyOak\Exception\Collection\NotValidObjectTypeException
} catch (\JimmyOak\Exception\Collection\NotValidObjectTypeException $e) {
    //Do nothing ^^'
}

foreach ($collection as $value) {
    echo $value->format('Y-m-d') . ' ';
}

//prints: 1992-10-07
```

Of course you can hipervitaminate these classes:

```
class DateTimeCollection extends \JimmyOak\Collection\TypedSet
{
    public function __construct() {
        $this->setObjectType(\DateTime::class);
    }

    public function asStrings()
    {
        $dates = [];
        foreach ($this as $value) {
            $dates[] = $value->format('Y-m-d');
        }

        return $dates;
    }
}

$dateTimeCollection = new \DateTimeCollection();
$aDateTime = new \DateTime('1992-10-07');
$dateTimeCollection[] = $aDateTime;
$dateTimeCollection[] = $aDateTime;
$dateTimeCollection[] = new \DateTime('1992-09-08');

foreach ($dateTimeCollection->asStrings() as $dateTimeString) {
    echo $dateTimeString . ' - ';
}

// prints: 1992-10-07 - 1992-09-08 -
```

### EventPublisher

[](#eventpublisher)

```
class MessageEvent extends Event
{
    private $message;

    public function __construct($message)
    {
        parent::__construct();
        $this->message = $message;
    }

    public function getMessage()
    {
        return $this->message;
    }
}

class MessageSubscriber extends EventSubscriber
{
    public function isSubscribedTo(Event $event)
    {
        return $event instanceof MessageEvent;
    }

    public function handle(Event $event)
    {
        printf(
            '[%s]: %s %s',
            $event->getOccurredOn()->format('Y-m-d H:i:s'),
            $event->getMessage(),
            PHP_EOL
        );
    }
}

SingleEventPublisher::instance()
    ->subscribe(new MessageSubscriber())
    ->publish(new MessageEvent('Hi!'))
    ->publish(new MessageEvent('Bye!'));
```

### DataType

[](#datatype)

#### Enum

[](#enum)

```
class FuelType extends \JimmyOak\DataType\Enum
{
    const GASOLINE = 'gasoline';
    const DIESEL = 'diesel';
    const KEROSENE = 'kerosene';
}

echo 'Available fuels: ' . PHP_EOL;
foreach (FuelType::getConstList() as $constName => $value) {
    echo $constName . ' => ' . $value . PHP_EOL;
}

echo PHP_EOL;
//prints:
// Available fuels:
// GASOLINE => gasoline
// DIESEL => diesel
// KEROSENE => kerosene

$gasoline = new FuelType(FuelType::GASOLINE);
echo $gasoline->value() . PHP_EOL; //prints: 'gasoline'
echo (string) $gasoline . PHP_EOL; //prints: 'gasoline'

$nonExistentFuelType = new FuelType('grass'); //throws \InvalidArgumentException
```

### SimpleValueObject

[](#simplevalueobject)

```
class Amount extends \JimmyOak\DataType\SimpleValueObject
{
    public function add(Amount $amount) {
        return $this->mutate($this->value() + $amount->value());
    }
}

$amount = new \Amount(500);
echo (string) $amount . PHP_EOL; //prints: 500
echo $amount->value() . PHP_EOL; //prints: 500

$anotherAmount = new \Amount(700);
echo ($amount->equals($anotherAmount) ? 'EQUAL' : 'NOT EQUAL') . PHP_EOL; //prints: NOT EQUAL

$newAmount = $amount->add(new Amount(200));
echo $amount->value() . PHP_EOL; //prints: 500
echo $newAmount->value() . PHP_EOL; //prints: 700

echo ($anotherAmount->equals($newAmount) ? 'EQUAL' : 'NOT EQUAL') . PHP_EOL; //prints: EQUAL
```

Utility
-------

[](#utility)

### ArrayUtils

[](#arrayutils)

#### Flatten

[](#flatten)

```
$array = [
    'FOO',
    [ 'BAR' ],
    'CHILDREN' => [
        'FOO2' => 'FOOBAR',
        'BAR2' => 'FOOBAR2',
        [
            'FOO2' => 'FOOBAR3'
        ]
    ]
];

$notPreservedKeys = \JimmyOak\Utility\ArrayUtils::instance()->flatten($array, \JimmyOak\Utility\ArrayUtils::NO_PRESERVE_KEYS);
// Overrides existing keys (overrides keys 0 and FOO2 existing in children)
$preservedKeys = \JimmyOak\Utility\ArrayUtils::instance()->flatten($array, \JimmyOak\Utility\ArrayUtils::PRESERVE_KEYS);
// Overrides only ASSOCIATIVE KEYS
$preservedAssociativeKeys = \JimmyOak\Utility\ArrayUtils::instance()->flatten($array, \JimmyOak\Utility\ArrayUtils::PRESERVE_ASSOCIATIVE_KEYS);

var_export($notPreservedKeys);
echo PHP_EOL . PHP_EOL;
var_export($preservedKeys);
echo PHP_EOL . PHP_EOL;
var_export($preservedAssociativeKeys);

// prints:
// array (
//   0 => 'FOO',
//   1 => 'BAR',
//   2 => 'FOOBAR',
//   3 => 'FOOBAR2',
//   4 => 'FOOBAR3',
// )
//
// array (
//   0 => 'BAR',
//   'FOO2' => 'FOOBAR3',
//   'BAR2' => 'FOOBAR2',
// )
//
// array (
//   0 => 'FOO',
//   1 => 'BAR',
//   'FOO2' => 'FOOBAR3',
//   'BAR2' => 'FOOBAR2',
// )
```

#### ToXmlString and ToXml

[](#toxmlstring-and-toxml)

```
$array = [
    'details' => [
        'media' => [
            'image' => [
                'anImage.png',
                'anotherImage.png',
            ],
            'video' => 'aVideo.mp4',
            'audio' => [],
        ]
    ]
];

$xml = \JimmyOak\Utility\ArrayUtils::instance()->toXmlString($array);
echo $xml . PHP_EOL . PHP_EOL;

// prints: anImage.pnganotherImage.pngaVideo.mp4

// Converts array into SimpleXmlElement
$xml = \JimmyOak\Utility\ArrayUtils::instance()->toXml($array);
var_dump($xml);

// prints:
// class SimpleXMLElement#3 (1) {
//     public $media =>
//     class SimpleXMLElement#4 (3) {
//         public $image =>
//         array(2) {
//             [0] =>
//             string(11) "anImage.png"
//             [1] =>
//             string(16) "anotherImage.png"
//         }
//         public $video =>
//         string(10) "aVideo.mp4"
//         public $audio =>
//         class SimpleXMLElement#5 (0) {
//         }
//     }
// }
```

### ObjectUtils

[](#objectutils)

#### ToArray

[](#toarray)

```
class Foo
{
    public $public = 'public';
    protected $protected = 'protected';
    private $private = 'private';
    private $anObject;

    /**
     * Foo constructor.
     *
     * @param $anObject
     */
    public function __construct($anObject)
    {
        $this->anObject = $anObject;
    }
}

class Bar
{
    private $value = 'value';
}

$foo = new Foo(new Bar());

//Shallow
$arrayed = \JimmyOak\Utility\ObjectUtils::instance()->toArray($foo, \JimmyOak\Utility\ObjectUtils::SHALLOW);
var_export($arrayed);
// prints:
//array (
//    'public' => 'public',
//)

echo PHP_EOL . PHP_EOL;

//Deep
$arrayed = \JimmyOak\Utility\ObjectUtils::instance()->toArray($foo, \JimmyOak\Utility\ObjectUtils::DEEP);
var_export($arrayed);
// prints:
//array (
//    'public' => 'public',
//    'protected' => 'protected',
//    'private' => 'private',
//    'anObject' =>
//        array (
//            'value' => 'value',
//        ),
//)
```

#### ToXmlString and ToXml

[](#toxmlstring-and-toxml-1)

Note: ToXml would do the same but returns a SimpleXml object

```
class Foo
{
    public $public = 'public';
    protected $protected = 'protected';
    private $private = 'private';
    private $anObject;

    /**
     * Foo constructor.
     *
     * @param $anObject
     */
    public function __construct($anObject)
    {
        $this->anObject = $anObject;
    }
}

class Bar
{
    private $value = 'value';
}

$foo = new Foo(new Bar());

$xml = \JimmyOak\Utility\ObjectUtils::instance()->toXmlString($foo, \JimmyOak\Utility\ObjectUtils::SHALLOW);
echo $xml . PHP_EOL;
// prints: public

$xml = \JimmyOak\Utility\ObjectUtils::instance()->toXmlString($foo, \JimmyOak\Utility\ObjectUtils::DEEP);
echo $xml . PHP_EOL;
// prints: publicprotectedprivatevalue
```

### StringUtils

[](#stringutils)

#### BeginsWith

[](#beginswith)

```
echo (\JimmyOak\Utility\StringUtils::instance()->beginsWith('Foo', 'fo') ? 'true' : 'false') . PHP_EOL;
//prints: false
echo (\JimmyOak\Utility\StringUtils::instance()->beginsWith('Foo', 'fo', \JimmyOak\Utility\StringUtils::CASE_INSENSITIVE) ? 'true' : 'false') . PHP_EOL;
//returns: true

echo (\JimmyOak\Utility\StringUtils::instance()->beginsWith('Fóo', 'Fo') ? 'true' : 'false') . PHP_EOL;
//prints: false
echo (\JimmyOak\Utility\StringUtils::instance()->beginsWith('Fóo', 'Fo', \JimmyOak\Utility\StringUtils::ACCENT_INSENSITIVE) ? 'true' : 'false') . PHP_EOL;
//returns: true

echo (\JimmyOak\Utility\StringUtils::instance()->beginsWith(
        'Fóo',
        'fo',
        \JimmyOak\Utility\StringUtils::ACCENT_INSENSITIVE | \JimmyOak\Utility\StringUtils::CASE_INSENSITIVE
    ) ? 'true' : 'false') . PHP_EOL;
//returns: true
```

#### EndsWith

[](#endswith)

Same behaviour as beginsWith but with ending needle.

#### RemoveAccents

[](#removeaccents)

```
echo \JimmyOak\Utility\StringUtils::instance()->removeAccents('Fóôñ');
// prints: Foon
```

#### RemoveExtraSpaces

[](#removeextraspaces)

```
echo \JimmyOak\Utility\StringUtils::instance()->removeExtraSpaces('  Foo    Bar     ');
// prints: Foo Bar
```

#### IsUrl and IsEmail

[](#isurl-and-isemail)

```
echo (\JimmyOak\Utility\StringUtils::instance()->isUrl('http://github.com/jimmyoak') ? 'true' : 'false') . PHP_EOL;
// prints: true

echo (\JimmyOak\Utility\StringUtils::instance()->isUrl('github.com/jimmyoak') ? 'true' : 'false') . PHP_EOL;
// prints: false

echo (\JimmyOak\Utility\StringUtils::instance()->isEmail('adrian.robles.maiz@gmail.com') ? 'true' : 'false') . PHP_EOL;
// prints: true

echo (\JimmyOak\Utility\StringUtils::instance()->isEmail('adrian.robles.maiz') ? 'true' : 'false') . PHP_EOL;
// prints: false
```

### FileUtils

[](#fileutils)

#### ExtensionIs

[](#extensionis)

```
echo (\JimmyOak\Utility\FileUtils::instance()->extensionIs('foo.php', 'php') ? 'true' : 'false') . PHP_EOL;
// prints: true

echo (\JimmyOak\Utility\FileUtils::instance()->extensionIs('foo.php', 'bar') ? 'true' : 'false') . PHP_EOL;
// prints: false
```

#### MakePath

[](#makepath)

```
echo \JimmyOak\Utility\FileUtils::instance()->makePath('/some', 'awesome/', 'and/incredible', 'nice.file');
// prints: /some/awesome/and/incredible/nice.file
```

#### GetExtension

[](#getextension)

```
echo \JimmyOak\Utility\FileUtils::instance()->getExtension('file.php');
// prints: php
```

#### GetNameWithoutExtension

[](#getnamewithoutextension)

```
echo \JimmyOak\Utility\FileUtils::instance()->getExtension('file.php');
// prints: file
```

#### ScanDir

[](#scandir)

See FileUtilsTest better :P

---

Quality
-------

[](#quality)

To run the PHPUnit tests at the command line, go to the tests directory and issue `phpunit`.

This library attempts to comply with [PSR-2](http://www.php-fig.org/psr/psr-2/) and [PSR-4](http://www.php-fig.org/psr/psr-4/).

If you notice compliance oversights, please send a patch via pull request.

Contribute
----------

[](#contribute)

Contributions to the package are always welcome!

- Report any bugs or issues you find on the [issue tracker](https://github.com/jimmyoak/utilities/issues/new).
- You can grab the source code at the package's [Git repository](https://github.com/jimmyoak/utilities).

Authors
-------

[](#authors)

- \[Adrián Robles Maiz (a.k.a Jimmy K. Oak)\] ()

License
-------

[](#license)

The code base is licensed under the MIT license.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 90.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~13 days

Recently: every ~7 days

Total

47

Last Release

3400d ago

Major Versions

1.7.3 → 2.0.02015-06-26

2.5.1b → 3.0.02016-12-26

PHP version history (3 changes)1.0.2PHP &gt;=5.4.0

1.7.2PHP &gt;=5.5.0

2.5.1bPHP &gt;=5.3.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/78fab774f12b9fcbee507458659c59fe18b691dd5033a0f0528f9f7e14f38eef?d=identicon)[jimmyoak](/maintainers/jimmyoak)

---

Top Contributors

[![jimmyoak](https://avatars.githubusercontent.com/u/7147129?v=4)](https://github.com/jimmyoak "jimmyoak (20 commits)")[![nilportugues](https://avatars.githubusercontent.com/u/550948?v=4)](https://github.com/nilportugues "nilportugues (1 commits)")[![patxi1980](https://avatars.githubusercontent.com/u/1370286?v=4)](https://github.com/patxi1980 "patxi1980 (1 commits)")

---

Tags

collectiondatatypeenumphpsimplevalueobjectvalueobjectcollectionjimmyjimmyoakutilities

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jimmyoak-utilities/health.svg)

```
[![Health](https://phpackages.com/badges/jimmyoak-utilities/health.svg)](https://phpackages.com/packages/jimmyoak-utilities)
```

###  Alternatives

[pragmarx/ia-collection

Laravel Illuminate Agnostic Collection

473.4M2](/packages/pragmarx-ia-collection)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
