定制 echoaro/laravel-json-mutator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

echoaro/laravel-json-mutator

最新稳定版本:v0.0.2-alpha

Composer 安装命令:

composer require echoaro/laravel-json-mutator

包简介

A Laravel package for easy JSON metadata management with custom casts

README 文档

README

Packagist Downloads License Tests PHP Version Laravel Framework

A powerful Laravel package for easy JSON metadata management with custom casts, dot notation support, and fluent interface.

Features

  • Easy JSON Management: Simple and intuitive API for managing JSON metadata
  • Dot Notation Support: Access nested data using dot notation (e.g., user.profile.name)
  • Fluent Interface: Chain methods for better readability
  • Type Safety: Full type hints and return type declarations
  • Array Access: Use array syntax for accessing metadata
  • Laravel Integration: Seamless integration with Laravel Eloquent models
  • Laravel 11+ & 12 Support: New Attribute-based cast for better compatibility
  • Comprehensive Testing: Full test coverage with PHPUnit

Quick Links

Installation

You can install the package via Composer:

composer require echoaro/laravel-json-mutator

The package will automatically register itself with Laravel.

Requirements

  • PHP: ^8.2
  • Laravel: ^10.0|^11.0|^12.0

Basic Usage

1. Add the Cast to Your Model

Option 1: Traditional Cast (Laravel 10+)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use JsonMutator\Casts\JsonMutatorCast;

class User extends Model
{
    protected $casts = [
        'metadata' => JsonMutatorCast::class,
    ];
}

Option 2: Attribute Cast (Laravel 11+ Recommended)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use JsonMutator\Casts\JsonMutatorAttributeCast;

class User extends Model
{
    protected function metadata(): Attribute
    {
        return JsonMutatorAttributeCast::make();
    }
}

2. Use the metadata (column name) in Your Code

// Create a new user
$user = new User();

// Using array access syntax
$user->metadata['profile']['name'] = 'John Doe';
$user->metadata['profile']['email'] = 'john@example.com';
$user->metadata['preferences']['theme'] = 'dark';

// Access metadata using array access
echo $user->metadata['profile']['name']; // Output: John Doe
echo $user->metadata['profile']['email']; // Output: john@example.com

// Using magic properties
$user->metadata->user_role = 'admin';
$user->metadata->last_login = '2024-01-15 10:30:00';

echo $user->metadata->user_role; // Output: admin
echo $user->metadata->last_login; // Output: 2024-01-15 10:30:00

// Using direct array assignment
$user->metadata = [
    'profile' => [
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ],
    'preferences' => [
        'theme' => 'dark'
    ]
];

// Save the user
$user->save();

Advanced Usage

Merging Data

// Merge arrays
$user->metadata->merge([
    'settings' => [
        'notifications' => true
    ]
]);

// Merge collections
$collection = collect(['tags' => ['admin', 'moderator']]);
$user->metadata->merge($collection);

// Merge other metadata mutators
$otherMetadata = new MetadataMutator(['role' => 'admin']);
$user->metadata->merge($otherMetadata);

Working with Collections

// Convert to Laravel Collection
$collection = $user->metadata->toCollection();

// Use collection methods
$user->metadata->toCollection()->each(function ($value, $key) {
    echo "$key: $value";
});

Static Methods

use JsonMutator\Mutators\JsonMutatorDTO;

// Create from JSON string
$metadata = JsonMutatorDTO::fromJson('{"key":"value"}');

// Create from array
$metadata = JsonMutatorDTO::fromArray(['key' => 'value']);

// Create from collection
$metadata = JsonMutatorDTO::fromCollection(collect(['key' => 'value']));

Fluent Interface

$user->metadata
    ->set('profile.name', 'John Doe')
    ->set('profile.email', 'john@example.com')
    ->set('preferences.theme', 'dark')
    ->set('preferences.language', 'en')
    ->forget('old_setting')
    ->merge(['new_setting' => 'value']);

Database Migration

Create a migration to add a metadata column:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->json('metadata')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('metadata');
        });
    }
};

Available Methods

JsonMutator Methods

Method Description
get($key, $default = null) Get a value using dot notation
set($key, $value) Set a value using dot notation
has($key) Check if a key exists
forget($key) Remove a key
merge($data) Merge data into data
replace($data) Replace all data
clear() Clear all data
isEmpty() Check if data is empty
isNotEmpty() Check if data is not empty
toArray() Get as array
toCollection() Get as Laravel Collection
toJson($options = 0) Get as JSON string
count() Get number of items

Static Methods

Method Description
fromJson($json) Create from JSON string
fromArray($array) Create from array
fromCollection($collection) Create from collection

Configuration

Publish the configuration file:

php artisan vendor:publish --tag=json-mutator-config

This will create config/json-mutator.php with the following options:

return [
    'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
    'defaults' => [
        'empty_value' => '{}',
        'null_value' => null,
    ],
    'validation' => [
        'max_depth' => 10,
        'max_length' => 65535,
    ],
];

Testing

Run the tests:

composer test

Test Coverage

The package includes comprehensive test coverage for all functionality:

  • JsonMutator Tests: All methods and edge cases
  • JsonMutatorCast Tests: Traditional cast functionality
  • JsonMutatorAttributeCast Tests: Laravel 11+ Attribute cast
  • Integration Tests: Full Laravel integration

Continuous Integration

This package uses GitHub Actions for continuous integration:

  • Multiple PHP versions: 8.2, 8.3
  • Latest Laravel version: 12.x
  • Code coverage: Uploaded to Codecov
  • Automatic testing: On every push and pull request

Development

Local Development Setup

  1. Clone the repository:
git clone https://github.com/echoaro/laravel-json-mutator.git
cd laravel-json-mutator
  1. Install dependencies:
composer install
  1. Run tests:
composer test
  1. Run tests with coverage:
composer test -- --coverage-html coverage/

Contributing

Please see CONTRIBUTING.md for details.

License

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

Credits

统计信息

  • 总下载量: 7
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-31