Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sweikenb committed Jul 14, 2024
0 parents commit 6ec8b9a
Show file tree
Hide file tree
Showing 31 changed files with 1,556 additions and 0 deletions.
75 changes: 75 additions & 0 deletions .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
name: PHP Composer

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

permissions:
contents: read
pages: write
id-token: write

concurrency:
group: "pages"
cancel-in-progress: false

jobs:
build:
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
php-version:
- "8.2"
- "8.3"
dependency-versions:
- "lowest"
- "highest"

steps:
- name: Checkout source
uses: actions/checkout@v4

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: xdebug

- name: Install composer dependencies
uses: ramsey/composer-install@v2
with:
dependency-versions: ${{ matrix.dependency-versions }}

- name: Run test-suite
run: composer run-script phpunit

- name: Setup Pages
if: github.ref == 'refs/heads/main'
id: pages
uses: actions/configure-pages@v3

- name: Upload artifact
if: github.ref == 'refs/heads/main'
uses: actions/upload-pages-artifact@v2
with:
path: ./coverage/html

deploy:
runs-on: ubuntu-latest

if: github.ref == 'refs/heads/main'

environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

needs: build

steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/*.cache
/coverage
/composer.lock
10 changes: 10 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

$finder = (new PhpCsFixer\Finder())
->in(__DIR__);

return (new PhpCsFixer\Config())
->setRules([
'@Symfony' => true,
])
->setFinder($finder);
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2024 Simon Schröer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
191 changes: 191 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# sweikenb/dirty

Library for checking if an object or array has changes (is dirty) since the last check.

License: MIT

## Installation

```bash
composer require sweikenb/dirty
```

If you plan to use this library in a **Symfony** project, consider checking out the corresponding
[DirtyBundle](https://github.com/sweikenb/dirty-bundle) instead.

## Usage

**How does it work?**

In order to check if the test-subject has untracked changes, the given object or array will be normalized, flattened and
stored using a configurable storage adapter.

The next time the check is executed the current data will be compared to the data of the previous check.
Which of the subjects fields will be tracked or ignored can be [configured](#configuration) (see below).

**Usage:**

As the result of the check, you will receive a detailed list of fields that changed and the corresponding previous and
current value:

```php
$categoryId = 'category:123';
$categoryData = [
'title' => 'My Category',
'tags' => ['Foo', 'Bar', 'Baz'],
'createdAt' => '2024-07-10 15:31:00'
];

$service = new \Sweikenb\Library\Dirty\Service\DirtyCheckService();

$result = $service->execute($categoryId, $categoryData);

if ($result->isDirty) {
foreach ($result->diffs as $fieldPath => $diff) {
echo sprintf("Field '%s' is dirty! '%s' -> '%s'\n", $fieldPath, $diff->previously, $diff->currently);
}
}
```

### Configuration

In some cases you might have data-structures that contain volatile values (e.g. dynamic timestamps) that will always
trigger a false-positiv for the dirty-check:

#### Ignore fields

If you want to **ignore** certain fields, you can specify which fields should be ignored during the check. If the
configured fields contain complex data _(object or array)_ the affected field and all of it subsequent data will be
**ignored** _(the field acts like a **wildcard**)_:

```php
$userId = 'user:123';
$userData = [
'username' => 'some-user'
'security' => [
'password' => '...',
'passwordSalt' => '...',
'pgp-key' => '...'
]
'meta' => [
'source' => 'sso'
'createdAt' => '2024-07-10 15:41:10'
]
];

$config = new \Sweikenb\Library\Dirty\Model\ConfigModel(ignoreFieldPath: [
'security', // will ignore the whole "security" subset
'meta.createdAt' // will only ignore the "createdAt" field under "meta"
]);

$service = new \Sweikenb\Library\Dirty\Service\DirtyCheckService();

$result = $service->execute($userId, $userData, $config);

if ($result->isDirty) {
foreach ($result->diffs as $fieldPath => $diff) {
echo sprintf("Field '%s' is dirty! '%s' -> '%s'\n", $fieldPath, $diff->previously, $diff->currently);
}
}
```

#### Check only certain fields

You can also explicitly allow fields that should be checked, any other fields will be ignored. If the
configured fields contain complex data _(object or array)_ the affected field and all of it subsequent data will be
**checked** _(the field acts like a **wildcard**)_:

```php
$userId = 'user:123';
$userData = [
'username' => 'some-user'
'security' => [
'password' => '...',
'passwordSalt' => '...',
'pgp-key' => '...',
]
'meta' => [
'source' => 'sso'
'createdAt' => '2024-07-10 15:41:10'
]
];

$config = new \Sweikenb\Library\Dirty\Model\ConfigModel([
'username', // check the "username" field
'meta', // check the "meta" field with all containing sub-fields
]);

$service = new \Sweikenb\Library\Dirty\Service\DirtyCheckService();

$result = $service->execute($userId, $userData, $config);

if ($result->isDirty) {
foreach ($result->diffs as $fieldPath => $diff) {
echo sprintf("Field '%s' is dirty! '%s' -> '%s'\n", $fieldPath, $diff->previously, $diff->currently);
}
}
```

#### Combine check and ignore fields

Please note that the "ignore"-configuration will be applied after the "allow"-configuration, that means you can combine
them to enable certain structures and then explicitly remove a single field or subset from it:

```php
$userId = 'user:123';
$userData = [
'username' => 'some-user'
'security' => [
'password' => '...',
'passwordSalt' => '...',
'pgp-key' => '...',
]
'meta' => [
'source' => 'sso'
'createdAt' => '2024-07-10 15:41:10'
]
];

$config = new \Sweikenb\Library\Dirty\Model\ConfigModel(
[
'username', // check the "username" field
'meta', // check the "meta" field with all containing sub-fields
],
[
'meta.createdAt', // ignore the "createdAt" sub-field even tough "meta" was explicitly configured to be checked
]
);

$service = new \Sweikenb\Library\Dirty\Service\DirtyCheckService();

$result = $service->execute($userId, $userData, $config);

if ($result->isDirty) {
foreach ($result->diffs as $fieldPath => $diff) {
echo sprintf("Field '%s' is dirty! '%s' -> '%s'\n", $fieldPath, $diff->previously, $diff->currently);
}
}
```

## Storage Adapters

Storage adapters and their primary use-cases:

* **Filesystem Adapter** _(default)_
* local **development** or stage environments
* single-server setups
* low amounts of data to check
* this adapter is **NOT RECOMMENDED** to be used with a network storage mount and highly benefits from a fast
underlying storage _(e.g. SSD)_
* files will not be cleaned up automatically, you need to write your own script for that!
* **REDIS Adapter** _(or compatible such as "ValKey")_
* **Symfony** applications via [DirtyBundle](https://github.com/sweikenb/dirty-bundle)
* **production** or stage environments
* multi-server setups
* any data-set size

You can add custom storage adapters if needed by implementing the `Sweikenb\Library\Dirty\Api\StorageAdapterInterface`.

## Configuration and customization

* _TODO_
46 changes: 46 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "sweikenb/dirty",
"description": "Library for checking if an object or array has changes (is dirty) since the last check.",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Simon Schröer",
"email": "[email protected]"
}
],
"require": {
"php": "^8.2",
"ext-json": "*",
"symfony/serializer": "^6.4 | ^7.0",
"symfony/property-access": "^6.4 | ^7.0"
},
"require-dev": {
"ext-xdebug": "*",
"phpunit/phpunit": "^11.2",
"symplify/easy-coding-standard": "^12.3",
"friendsofphp/php-cs-fixer": "^3.59"
},
"suggest": {
"ext-redis": "*",
"snc/redis-bundle": "*"
},
"autoload": {
"psr-4": {
"Sweikenb\\Library\\Dirty\\": "src/"
},
"exclude-from-classmap": [
"examples/",
"tests/"
]
},
"autoload-dev": {
"psr-4": {
"Sweikenb\\Library\\Dirty\\Tests\\": "tests/"
}
},
"scripts": {
"phpcs-fixer": "./vendor/bin/php-cs-fixer fix src --rules=@Symfony",
"phpunit": "XDEBUG_MODE=coverage php ./vendor/bin/phpunit -c phpunit.dist.xml"
}
}
26 changes: 26 additions & 0 deletions examples/000_value_diffs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

use Sweikenb\Library\Dirty\Service\DirtyCheckService;

require __DIR__.'/../vendor/autoload.php';

$dirtyCheck = new DirtyCheckService();

/*
* Execute this example multiple times to see the library in action
*/

$id = 'my_identifier';

$foo = [
'some' => 'foo',
'Bar' => 'baz',
'foo' => microtime(true),
];

$result = $dirtyCheck->execute($id, $foo);
if ($result->isDirty) {
foreach ($result->diffs as $fieldPath => $valueDiff) {
echo sprintf("Field '%s' is dirty! '%s' -> '%s'\n", $fieldPath, $valueDiff->previously, $valueDiff->currently);
}
}
Loading

0 comments on commit 6ec8b9a

Please sign in to comment.