" /> " /> "/>

Make your PHP arrays sweet'n'safe

Related tags

Miscellaneous mess
Overview

Mess

Build Status Psalm coverage PHP from Packagist Latest Stable Version GitHub commits Software License

We face a few problems in our PHP projects

  • Illogical type casting (PHP's native implementation is way too "smart")
  • Pointless casts like array => float are allowed
  • Boilerplate code to work with arrays (check if isset(), throw an exception, cast the type, etc.)

Consider an example:

$userId = $queryParams['userId'] ?? null;
if ($userId === null) {
    throw ...
}
$userId = (int)$userId;

Way too verbose. Any ideas?

$userId = (new Mess($queryParams))['userId']->getAsInt();

You can mess with API responses/configs/whatever:

$mess = new Mess($response);
$book = new Book(
    $mess['title']->getString(),
    $mess['isBestseller']->getBool(),
    $mess['stats']['rating']->getInt(),
    $mess['tags']->getListOfString()
);

Generics support (Psalm compatible)

  • getListOfString()
  • getListOfInt()
  • getArrayOfStringToString()
  • getArrayOfStringToBool()
  • etc.

Installation

$ composer require zakirullin/mess

Dealing with mess

findInt(); // null $config['param']->getInt(); // UnexpectedTypeException $config['param']->getAsInt(); // 1 $config['param']->findInt(); // UnexpectedTypeException $config['param']->findAsInt(); // 1 ">
$queryParams = new Mess(['isDeleted' => 'true']);
$queryParams['isDeleted']->getBool(); // UnexpectedTypeException
$queryParams['isDeleted']->getAsBool(); // true

$value = new Mess('25');
$value->getInt(); // UnexpectedTypeException
$value->getAsInt(); // 25
$value->getString(); // '25'

$value = new Mess('25a');
$value->getInt(); // UnexpectedTypeException
$value->getAsInt(); // UncastableValueException

$config = new Mess(['param' => '1']);
$config['a']['b']->getInt(); // MissingKeyException: "MissingKeyException: a.b"
$config['a']['b']->findInt(); // null
$config['param']->getInt(); // UnexpectedTypeException 
$config['param']->getAsInt(); // 1
$config['param']->findInt(); // UnexpectedTypeException
$config['param']->findAsInt(); // 1

As you might notice, type casting is performed while using (find|get)As* methods. Having trouble grasping get*()/find*()? Check out brilliant Ocramius's slides.

Type casting with Mess is rather predictable

'\d+' => int // OK
'buzz12' => int // UncastableValueException
bool => int // UncastableValueException
array => int // UncastableValueException
object => int // UncastableValueException
resource => int // UncastableValueException

Fairly simple, isn't it? Let us fail fast!

Why one needs THAT naive type casting?

Let's imagine a library that is configured this way:

$config = [
    'retries' => 5, // int
    'delay' => 20, // int
]

// Initialization 
$retries = $config['retries'] ?? null;
if ($retries === null) {
    throw new MissingConfigKeyException(...);
}
...
$retries = (int)$retries;
$delay = (int)$delay;

Client-side code:

$config => [
    'retries' => [5, 10, 30], // (int)array => 1
    'delay' => true, // (int)bool => 1
]

No matter if that's a misuse, or a result of major update: The system will continue to work. And that's the worst thing about it. It will continue to work, though, not in a way it was supposed to work. PHP is trying to do its best to let it work at least somehow.

The library comes in handy in a variety of scenarios 🚀

  • Deserialized data
  • Request body/query
  • API response
  • Config
  • etc.
Comments
  • Little fixes to make it compatible with 8.1

    Little fixes to make it compatible with 8.1

    • add #[\ReturnTypeWillChange] for MessInterface::getOffset
    • update psalm to handle ReturnTypeWillChange
    • fix isArrayOfStringToMixed function - get rid of unused var & dockblock
    opened by the-toster 2
  • psalm-pure ckeck fails

    psalm-pure ckeck fails

    New psalm version not allow @psalm-pure annotation on methods that referenced to $this (a lot of Mess.php methods). Looks like @psalm-mutation-free should be used instead.

    opened by the-toster 1
  • MessInterface should have psalm annotations

    MessInterface should have psalm annotations

    Thank you for this lib. It's very useful with psalm.

    When I use something like (new Mess($options))['key']->getArrayOfStringToString() psalm infer it type as array<array-key, mixed>, because Mess::getOffset() returns MessInterface, where getArrayOfStringToString are not annotated.

    So I suggest annotate it too.

    If you think this is ok, I will crete PR.

    opened by the-toster 1
  • Add generics (getMapOfStringTo(Int|Bool|String)

    Add generics (getMapOfStringTo(Int|Bool|String)

    public function getMapOfStringToInt(): array;
    public function getMapOfStringToBool(): array;
    public function getMapOfStringToString(): array
    
    public function getAsMapOfStringToInt(): array;
    public function getAsMapOfStringToBool(): array;
    public function getAsMapOfStringToString(): array
    

    etc.

    opened by zakirullin 1
  • Fix annotations according to more precise psalm checks

    Fix annotations according to more precise psalm checks

    Two groups of annotations fixed

    • for getters - pure replaced with mutation-free,
    • for conversion functions - add pure-callable annotations related to #12
    opened by the-toster 0
  • Adding support for nullable/optional fields?

    Adding support for nullable/optional fields?

    First of all; I love the package, it replaced a number of helper methods that I had written in my own codebase to solve similar problems when working with data from external APIs etc.

    One problem I'm having with it, however, is that some of the APIs I'm working with return "" (empty strings) for fields that have no data. I can't ->getAsInt() these fields, since "" can't be cast to an integer. Would it be possible to add support for something like this:

    >>> $field = "";
    >>> $mess = new Mess($field);
    >>> $mess->getAsNullableInt();
    => null
    

    I'll leave the naming to you, of course, but ->getAsNullableInt() or ->getAsIntOrNull() seem reasonable to me.

    opened by BrekiTomasson 9
Releases(0.8.2)
Owner
Artem Zakirullin
Artem Zakirullin
🏆 Learn You PHP! - An introduction to PHP's core features: i/o, http, arrays, exceptions and so on.

Learn You PHP! The very first PHP School workshop. A revolutionary new way to learn PHP Bring your imagination to life in an open learning eco-system

PHP School 311 Dec 30, 2022
PHP functions that help you validate structure of complex nested PHP arrays.

PHP functions that help you validate structure of complex nested PHP arrays.

cd rubin 7 May 22, 2022
This package was created to provide simple way to manipulate arrays in PHP

PHP Collections This package was created to provide simple way to manipulate arrays in PHP. The package was inspired by the Laravel Collections.

Wojciech Mleczek 13 Jul 26, 2021
Dobren Dragojević 6 Jun 11, 2023
Simple libary for functional programing paradigm with arrays.

rodrigodornelles/php-array-lib simple libary for functional programing paradigm with arrays Features Test driven development style (TDD) PHP version c

null 10 Nov 28, 2022
Safely break down arrays or objects, and put them back together in new shapes.

traverse/reshape traverse() and reshape() are companion functions that safely break down arrays or objects and put them back together in new shapes. t

Alley Interactive 2 Aug 4, 2022
PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

?? Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Zeeshan Ahmad 20 Dec 8, 2018
Run your WP site on github pages, php innovation award winner https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html

Gitpress Run wordpress directly on github pages Gitpress won the innovation award for may 2021 Read more about this https://naveen17797.github.io/gitp

naveen 13 Nov 18, 2022
A PHP Library To Make Your Work Work Easier/Faster

This Is A Php Library To Make Your Work Easier/Faster,

functionality 2 Dec 30, 2022
❄️ Magento 2 Snowflake module allow you to add snow and even more on your site and make winter fun.

❄️ Magento 2 Snowflake module allow you to add snow and even more on your site and make winter fun.

OpenGento 6 Apr 30, 2022
The best announcer for PocketMine-MP 4.0 servers, make messages for your users very easily

BroadcastACM The best announcer for PocketMine-MP 4.0 servers, make messages for your users very easily. Make the best announcements for your server w

fernanACM 3 May 30, 2022
A trait to make building your own custom Laravel Model Searches a lot easier.

BrekiTomasson\LaravelModelFinder A simple trait that makes building your own custom Laravel Model Searches a lot easier and safer. It ensures that you

Breki Tomasson 3 Nov 27, 2022
Sslurp is a simple library which aims to make properly dealing with SSL in PHP suck less.

Sslurp v1.0 by Evan Coury Introduction Dealing with SSL properly in PHP is a pain in the ass and completely insecure by default. Sslurp aims to make i

Evan Coury 65 Oct 14, 2022
AI PHP is a wrapper for rubix ml to make AI very approachable

AI PHP Rubix Wrap A wrapper for Rubix ML to make it very approachable Example: $report = RubixService::train($data, 'column_with_label'); Where co

null 15 Nov 5, 2022
A PHP package to make the Chronopost API easier to use.

Chronopost API A PHP package to make the Chronopost API easier to use. Table of Contents Requirements Installation Usage Testing Requirements PHP 7.3,

HOUIS Mathis 9 Oct 27, 2022
meterN is a lightweight set of PHP/JS files that make a " Home energy metering & monitoring " solution.

meterN - Home energy monitor - (PHP/JS Energy Metering & Monitoring) What can meterN do for you ? meterN is a lightweight set of PHP/JS files that mak

Jean-Marc Louviaux 4 Nov 30, 2022
This library uses GD and EXIF (optional) PHP extensions so make sure you have them installed.

simple and fast image processing class that can downscale, compress and convert images using php-gd native functions

Leon 8 Jul 15, 2022
Make WhatsApp ChatBot and use WhatsApp API to send the WhatsApp messages in php .

Ultramsg.com WhatsApp Bot using WhatsApp API and ultramsg Demo WhatsApp API ChatBot using Ultramsg API with php. Chatbot tasks: The output of the comm

Ultramsg 33 Nov 19, 2022