GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - inspirum/arrayable-php: PHP Arrayable interface with to-array method.

BranchesTags
Open more actions menu

Latest commit

 

History

57 Commits
57 Commits

Folders and files

NameName
Last commit message
Last commit date
.github/workflows
.github/workflows
 
 
core
core
 
 
src
src
 
 
tests
tests
 
 
.editorconfig
.editorconfig
 
 
.gitattributes
.gitattributes
 
 
.gitignore
.gitignore
 
 
.scrutinizer.yml
.scrutinizer.yml
 
 
CHANGELOG.md
CHANGELOG.md
 
 
LICENSE.md
LICENSE.md
 
 
README.md
README.md
 
 
composer.json
composer.json
 
 
phpcs.xml
phpcs.xml
 
 
phpstan.neon
phpstan.neon
 
 
phpunit.xml.dist
phpunit.xml.dist
 
 

Repository files navigation

Arrayable

Latest Stable Version Build Status Coverage Status Quality Score PHPStan Total Downloads Software License

Motivation

Unfortunately PHP does not have a nice way how to typecast objects to array.

There is the __toString() magic method for \Stringable interface (since PHP 8.0) and the jsonSerialize() method for \JsonSerializable interface (since PHP 5.4), but __toArray() method is not (and will not) be supported – there are just several rejected draft RFC (object_cast_to_types, to array, ...) that suggests some kind of object to scalar type casting.

But so far (at least) there is no way to implement some (not even magic) method to be called when cast to array.

Ideally, something like this would work:

class Person
{
    public function __construct(
        public string $name,
        protected string $username,
        private string $password,
    ) {}
 
    public function __toArray(): array
    {
        return [
            'name' => $this->name,
            'email' => $this->username,
        ];
    }
}

$person = new Person('John Doe', '[email protected]', 'secret_pwd');

$personArray = (array) $person; // casting triggers __toArray()

/**
var_dump($personArray);
[
  'name' => 'John Doe'
  'email' => '[email protected]'
]
*/

but actually it cast to array like this:

/**
var_dump($personArray);
[
  'name' => 'John Doe'
  '*username' => '[email protected]'
  'Person@password' => 'secret_pwd'
]
*/

Usage example

All the code snippets shown here are modified for clarity, so they may not be executable.

This package implements simple \Arrayable (or \Inspirum\Arrayable\Arrayable) interface.

/** @implements \Arrayable<string, string> */
class Person implements \Arrayable
{
    public function __construct(
        public string $name,
        protected string $username,
        protected string $password,
    ) {}
 
    /** @return array<string, string> */
    public function __toArray(): array
    {
        return [
            'name' => $this->name,
            'email' => $this->username,
        ];
    }
}

$person = new Person('John Doe', '[email protected]', 'secret_pwd');

There is \is_arrayable() function (or \Inspirum\Arrayable\Convertor::isArrayable() method) to check if given data are able to type cast itself to array.

var_dump(\is_arrayable([1, 2, 3])); // bool(true)
var_dump(\is_arrayable(new \ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(\is_arrayable(new \ArrayObject([4, 5, 6]))); // bool(true)
var_dump(\is_arrayable((function () { yield 1; })())); // bool(true)
var_dump(\is_arrayable(new \stdClass())); // bool(true)
var_dump(\is_arrayable($person)); // bool(true)
var_dump(\is_arrayable(1)); // bool(false)
var_dump(\is_arrayable(new class {})); // bool(false)

Then there is \to_array() function (or \Inspirum\Arrayable\Convertor::toArray() method) to recursively cast data to array.

$data = \to_array(new \ArrayIterator([1, $person, (object) ['a' => true]]));

/**
var_dump($data);
[
  0 => 1
  1 => [ 
    'name' => 'John Doe'
    'email' => '[email protected]'
  ]
  2 => [
   'a' => true
  ]
*/

Optional $limit parameter sets how many levels are converted, deeper data are returned unchanged.

$data = \to_array([1, new \ArrayIterator([2, new \ArrayIterator([3])])], limit: 2);

/**
var_dump($data);
[
  0 => 1
  1 => [
    0 => 2
    1 => ArrayIterator([3])
  ]
]
*/

Optional $depth parameter (default 512) sets the maximum nesting depth, like in json_encode. Deeper data (including self-referencing objects) throw \RuntimeException.

\to_array([1, [2, [3]]], depth: 2); // throws RuntimeException: Maximum depth of 2 exceeded

There are also helper abstract classes for common use for DAO (BaseModel) and collection (BaseCollection, BaseListCollection) objects.

Implement __toArray(), call toArray(). Their toArray(), jsonSerialize() and __toString() are final and always return the __toArray() data.

System requirements

  • PHP 8.1+
  • ext-json

Installation

Run composer require command

$ composer require inspirum/arrayable

Testing

To run unit tests, run:

$ composer test:test

To show coverage, run:

$ composer test:coverage

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

  • Tomáš Novotný
  • All Contributors

License

The MIT License (MIT). Please see License File for more information.

About

PHP Arrayable interface with to-array method.

Topics

arrayarrayablephpto-arraytoarraytoarray-interface

Resources

Readme
MIT license

Code of conduct

Code of conduct

Contributing

Contributing
Activity
Custom properties

Stars

3 stars

Watchers

0 watching

Forks

1 fork
Report repository

Releases

Used by

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.