Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Setup
description: "Setup PHP and composer and install dependencies"

inputs:
php-version:
default: "8.3"
coverage:
default: xdebug
composer-flags:
default: ""

runs:
using: "composite"
steps:
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ inputs.php-version }}
coverage: ${{ inputs.coverage }}

- name: Get composer cache directory
id: composer-cache
shell: bash
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

- name: Cache dependencies
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-

- name: Install dependencies
shell: bash
run: composer update --prefer-dist --no-interaction ${{ inputs.composer-flags }}
62 changes: 62 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
phpcs:
runs-on: ubuntu-24.04
name: PHPCS
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup
uses: ./.github/actions/setup
with:
coverage: none

- name: Run PHPCS
run: vendor/bin/phpcs

phpstan:
runs-on: ubuntu-24.04
name: PHPStan
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup
uses: ./.github/actions/setup
with:
coverage: none

- name: Install optional dependency doctrine/dbal
run: composer require doctrine/dbal

- name: Run PHPStan
run: vendor/bin/phpstan analyse

test:
runs-on: ubuntu-24.04
strategy:
max-parallel: 3
matrix:
php-version: [ 8.2, 8.3 ]
composer-flags: [ "", "--prefer-lowest" ]
name: Test on PHP ${{ matrix.php-version }} ${{ matrix.composer-flags }}
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup
uses: ./.github/actions/setup
with:
php-version: ${{ matrix.php-version }}
composer-flags: ${{ matrix.composer-flags }}

- name: Run tests (Unit and Feature)
run: vendor/bin/phpunit --coverage-text
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
clover.xml
html/
vendor/*
composer.lock
.phpunit.result.cache
28 changes: 28 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BSD 3-Clause License

Copyright (c) 2022, Joshua Thijssen

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
Auto-generated README for icore-php-typearray
# Typed Array

Simple wrapper around property-accessor to fetch elements in a typed way. This package is created because I was fiddling around with a lot of json-arrays
that were not typed and phpstan had a big issue with that.

So, instead of having `mixed[] $myarray`, we can use `TypeArray`, and fetch elements with:

```
$arr = new TypeArray(['foo' => 'string', 'bar' => 4 ]);

$arr->getString('[foo]'); // always returns a string
$arr->getString('[notexists]', 'defaultval'); // Returns default val when not found

$arr->getInt('[bar]'); // returns int(4)
$arr->getInt('[foo]'); // Returns InvalidTypeException as this element is a string, not an int

```

See symfony propertyaccess component for the path syntax used.
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "minvws/icore-php-typearray",
"description": "Typed Array",
"type": "library",
"require": {
"php": ">=8.0.2",
"symfony/property-access": "^6.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"squizlabs/php_codesniffer": "^3.6",
"phpstan/phpstan": "^1.0"
},
"suggest": {
"doctrine/dbal": "For using type_array directly with Doctrine"
},
"license": "BSD-3-Clause",
"autoload": {
"psr-4": {
"MinVWS\\TypeArray\\": "src/"
}
},
"authors": [
{
"name": "Joshua Thijssen",
"email": "jthijssen@noxlogic.nl"
}
],
"scripts": {
"test": [
"vendor/bin/phpcs",
"vendor/bin/phpstan",
"vendor/bin/phpunit"
]
}
}
9 changes: 9 additions & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<ruleset>
<arg name="basepath" value="."/>

<file>./src</file>
<file>./tests</file>

<rule ref="PSR12" />
</ruleset>
6 changes: 6 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
parameters:
paths:
- src
level: 8
inferPrivatePropertyTypeFromConstructor: true
reportUnmatchedIgnoredErrors: false
13 changes: 13 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory>./src</directory>
</include>
</coverage>
<testsuites>
<testsuite name="TypeArray Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
23 changes: 23 additions & 0 deletions phpunit.xml.dist.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals = "false"
backupStaticAttributes = "false"
colors = "true"
convertErrorsToExceptions = "true"
convertNoticesToExceptions = "true"
convertWarningsToExceptions = "true"
processIsolation = "false"
stopOnFailure = "false">

<testsuites>
<testsuite name="TypeArray Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
</phpunit>
99 changes: 99 additions & 0 deletions src/Doctrine/DBAL/Types/TypeArrayType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

namespace MinVWS\TypeArray\Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Exception\InvalidType;
use Doctrine\DBAL\Types\Exception\SerializationFailed;
use Doctrine\DBAL\Types\Exception\ValueNotConvertible;
use Doctrine\DBAL\Types\Type;
use Doctrine\Deprecations\Deprecation;
use JsonException;
use MinVWS\TypeArray\TypeArray;

use function is_resource;
use function json_encode;
use function stream_get_contents;

use const JSON_PRESERVE_ZERO_FRACTION;
use const JSON_THROW_ON_ERROR;

class TypeArrayType extends Type
{
public const TYPE = 'type_array';

/**
* {@inheritdoc}
*/
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
return $platform->getJsonTypeDeclarationSQL($column);
}

/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): false|string|null
{
if ($value === null) {
return null;
}

if (! $value instanceof TypeArray) {
throw InvalidType::new($value, self::TYPE, ['null', TypeArray::class]);
}

try {
return json_encode($value->toArray(), JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION);
} catch (JsonException $e) {
throw SerializationFailed::new($value, self::TYPE, $e->getMessage(), $e);
}
}

/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?TypeArray
{
if ($value === null || $value === '') {
return null;
}

if (is_resource($value)) {
$value = stream_get_contents($value);
}

try {
return TypeArray::fromJson(strval($value));
} catch (JsonException $e) {
throw ValueNotConvertible::new($value, $this->getName(), $e->getMessage(), $e);
}
}

/**
* {@inheritdoc}
*/
public function getName(): string
{
return self::TYPE;
}

/**
* {@inheritdoc}
*
* @deprecated
*/
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
Deprecation::triggerIfCalledFromOutside(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/5509',
'%s is deprecated.',
__METHOD__,
);

return true;
}
}
13 changes: 13 additions & 0 deletions src/Exception/IncorrectDataTypeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace MinVWS\TypeArray\Exception;

class IncorrectDataTypeException extends \Exception
{
public function __construct(string $want, string $have)
{
parent::__construct(sprintf('Incorrect data type. Want: %s, have: %s', $want, $have));
}
}
13 changes: 13 additions & 0 deletions src/Exception/InvalidIndexException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace MinVWS\TypeArray\Exception;

class InvalidIndexException extends \Exception
{
public function __construct(string $path)
{
parent::__construct(sprintf('Invalid index: "%s"', $path));
}
}
Loading