Skip to content

Commit

Permalink
Merge pull request #5 from waadmawlood/2.x
Browse files Browse the repository at this point in the history
migrate to new version 2.x more food of methods
  • Loading branch information
waadmawlood authored Jan 29, 2025
2 parents 8508eb4 + 3e2aedb commit 5e37f82
Show file tree
Hide file tree
Showing 16 changed files with 1,274 additions and 313 deletions.
135 changes: 66 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@

Laravel Model Metadata is a package designed to manage metadata with JSON support for multiple data types. It allows you to easily attach, manage, and query metadata on your Laravel models using the `HasManyMetadata` or `HasOneMetadata` traits.

## ✨ Requirements
# 📚 Documentation

- PHP 8.1 or higher
- Laravel 10.0 or higher
For detailed documentation, including usage examples and best practices, please refer to the [Documentation](https://waad-mawlood.gitbook.io/model-metadata).

# ✨ Requirements

- PHP 8.0 or higher
- Laravel framework 9.30.1 or higher
- JSON extension enabled

## 💼 Installation
# 💼 Installation

1. Install the package using Composer:
```bash
Expand All @@ -27,46 +31,78 @@ Laravel Model Metadata is a package designed to manage metadata with JSON suppor
php artisan migrate
```

## 🎈 Usage
# 🎈 Usage

### 🔥 HasManyMetadata Trait
## 🔥 HasOneMetadata Trait

This trait allows a model to have multiple metadata records. Add the trait to your model:
Add the HasOneMetadata trait to your model to enable a single metadata record:

```php
use Waad\Metadata\Traits\HasManyMetadata;
use Waad\Metadata\Traits\HasOneMetadata;

class Post extends Model
class Company extends Model
{
use HasManyMetadata;
use HasOneMetadata; // <--- Add this trait to your model
}
```

Available methods:
#### Some methods:

#### Creating Metadata
```php
// Create metadata with array
$post->createMetadata(['key' => 'value', 'another_key' => 'another_value']);
// Create metadata with array (only works if no metadata exists)
$company->createMetadata(['key' => 'value', 'another_key' => 'another_value']);

// Create metadata with collection
$post->createMetadata(collect(['key' => 'value']));
$company->createMetadata(collect(['key' => 'value']));

// Update existing metadata
$company->updateMetadata(['new_key' => 'new_value']);

// Delete the metadata
$company->deleteMetadata();

// Get metadata as array
$metadata = $company->getMetadata();

// Get metadata as collection
$metadataCollection = $company->getMetadataCollection();
```

#### Updating Metadata
-------------

## 🔥 HasManyMetadata Trait

Add the HasManyMetadata trait to your model to enable multiple metadata records:

```php
// Update metadata by ID
$post->updateMetadata('metadata_id', ['new_key' => 'new_value']);
use Waad\Metadata\Traits\HasManyMetadata;

class Post extends Model
{
use HasManyMetadata; // <--- Add this trait to your model

// Enabled Append id with content metadata (default)
public $metadataNameIdEnabled = true;

// Custom Append key of id with metadata (default)
public $metadataNameId = 'id';
}
```
see [Configuration Append Id](https://waad-mawlood.gitbook.io/model-metadata/basics/markdown-1/use-in-model) for more details

#### Some methods:

#### Deleting Metadata
```php
// Create metadata with array or collection
$post->createMetadata(['key1' => 'value1', 'key2' => 'value2']);
$post->createMetadata(collect(['key1' => 'value1', 'key2' => 'value2']));

// Update metadata by ID
$post->updateMetadata('{metadata_id}', ['new_key' => 'new_value']);

// Delete metadata by ID
$post->deleteMetadata('metadata_id');
```
$post->deleteMetadata('{metadata_id}');

#### Retrieving Metadata
```php
// Get all metadata objects
$metadata = $post->metadata;
// or
Expand All @@ -85,62 +121,23 @@ $metadataCollection = $post->getMetadataCollection();
$searchResults = $post->searchMetadata('search_term');
```

### 🔥 HasOneMetadata Trait

This trait allows a model to have a single metadata record. Add the trait to your model:

```php
use Waad\Metadata\Traits\HasOneMetadata;

class Company extends Model
{
use HasOneMetadata;
}
```

Available methods:

#### Creating Metadata
```php
// Create metadata with array (only works if no metadata exists)
$company->createMetadata(['key' => 'value', 'another_key' => 'another_value']);

// Create metadata with collection
$company->createMetadata(collect(['key' => 'value']));
```

#### Updating Metadata
```php
// Update existing metadata
$company->updateMetadata(['new_key' => 'new_value']);
```
-------------

#### Deleting Metadata
```php
// Delete the metadata
$company->deleteMetadata();
```
# 🧪 Testing

#### Retrieving Metadata
```php
// Get metadata as array
$metadata = $company->getMetadata();
To run the tests for development, use the following command:

// Get metadata as collection
$metadataCollection = $company->getMetadataCollection();
```bash
composer test
```

Both traits use JSON casting for the metadata column, allowing you to store complex data structures. The metadata is stored in a polymorphic relationship, making it flexible and reusable across different models.


## 👨‍💻 Contributors
# 👨‍💻 Contributors

- **Waad Mawlood**
- Email: [email protected]
- Role: Developer



## 📝 License
# 📝 License

This package is open-sourced software licensed under the [MIT license](LICENSE).
10 changes: 6 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
}
],
"require": {
"php": "^8.1",
"php": "^8.0",
"ext-json": "*",
"laravel/framework": "^10.0|^11.0"
"laravel/framework": "^9.30.1|^10.0|^11.0"
},
"require-dev": {
"orchestra/testbench": "^8.0|^9.0",
"laravel/pint": "^1.0",
"orchestra/testbench": "^7.0|^8.0|^9.0",
"pestphp/pest-plugin-laravel": "^2.4"
},
"autoload": {
Expand Down Expand Up @@ -44,7 +45,8 @@
},
"scripts": {
"test": "vendor/bin/pest",
"test:coverage": "vendor/bin/pest --coverage"
"test:coverage": "vendor/bin/pest --coverage",
"lint": "vendor/bin/pint"
},
"keywords": [
"laravel",
Expand Down
2 changes: 1 addition & 1 deletion migrations/1_create_model_meta_data_table.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ public function down(): void
{
Schema::dropIfExists('model_metadata');
}
};
};
47 changes: 47 additions & 0 deletions src/Helpers/Helper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Waad\Metadata\Helpers;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

class Helper
{
public function isNullOrStringEmptyOrWhitespaceOrEmptyArray(mixed $value): bool
{
if (is_null($value)) {
return true;
}

if (is_string($value) && trim($value) === '') {
return true;
}

if ($value instanceof Collection) {
$value = $value->toArray();
}

return is_array($value) && empty($value);
}

public function pipMetadataToClearKeyNameId(array|Collection $metadata, string $keyNameId = 'id'): array
{
$metadata = $metadata instanceof Collection ? $metadata->toArray() : $metadata;
$firstItem = Arr::first($metadata);

// Check if metadata is nested (array of arrays)
if (filled($firstItem) && is_array($firstItem)) {
return array_map(fn ($item) => Arr::except($item, $keyNameId), $metadata);
}

return Arr::except($metadata, $keyNameId);
}

public function isNestedMetadata(array|Collection $metadata): bool
{
$metadata = $metadata instanceof Collection ? $metadata->toArray() : $metadata;
$firstItem = Arr::first($metadata);

return filled($firstItem) && is_array($firstItem);
}
}
16 changes: 14 additions & 2 deletions src/Models/Metadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
class Metadata extends Model
{
use HasUlids;

protected $table = 'model_metadata';

protected $guarded = [];
Expand All @@ -34,4 +34,16 @@ protected function asDateTime($value)

return $value;
}
}

protected function asJson($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}

public function mergeIdToMetadata(string $keyNameId = 'id'): self
{
$this->metadata = array_merge([$keyNameId => $this->id], $this->metadata ?? []);

return $this;
}
}
8 changes: 4 additions & 4 deletions src/Providers/MetadataServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@
namespace Waad\Metadata\Providers;

use Illuminate\Support\ServiceProvider;
use Waad\Metadata\Helpers\Helper;

class MetadataServiceProvider extends ServiceProvider
{
public function register()
{
//
$this->app->singleton(Helper::class);
}

public function boot()
{
if (!$this->app->runningInConsole()) {
if (! $this->app->runningInConsole()) {
return;
}

$this->publishes([
__DIR__ . '/../../migrations/1_create_model_meta_data_table.php' =>
database_path('migrations/'. date('Y_m_d_His', time()) .'_create_model_meta_data_table.php'),
__DIR__.'/../../migrations/1_create_model_meta_data_table.php' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_model_meta_data_table.php'),
], 'metadata-migrations');
}
}
Loading

0 comments on commit 5e37f82

Please sign in to comment.