PHP code example of plumthedev / json-shape

1. Go to this page and download the library: Download plumthedev/json-shape library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

plumthedev / json-shape example snippets


$user->preferences['notifcations']['email'];  // typo. ships green. pages you at 2am.

$user->preferences->theme;          // string — autocompleted, type-checked
$user->preferences->emailEnabled(); // bool — and that 2am typo? now a PHPStan error
$user->save();                      // encoded back to JSON automatically

// Before — flying blind.
$prefs = $user->preferences;            // array
$prefs['theme'] ?? 'light';             // is "theme" a real key? you guess.
$prefs['notifcations']['email'];        // typo compiles fine. fails for a user.

// After — typed, the same data.
$user->preferences->theme;              // string
$user->preferences->emailEnabled();     // bool
$user->preferences['theme'];            // array access still works when you want it

namespace App\Shapes;

use Plumthedev\JsonShape\JsonShape;

/**
 * @phpstan-type PreferencesData array{
 *     theme: string,
 *     emailEnabled: bool,
 *     locale?: string,
 * }
 *
 * @extends JsonShape<PreferencesData>
 */
class PreferencesShape extends JsonShape
{
    public string $theme {
        get => $this->attributes['theme'];
    }

    public function emailEnabled(): bool
    {
        return $this->fluent->boolean('emailEnabled');
    }

    public function setTheme(string $value): self
    {
        return $this->tap(fn () => $this->attributes['theme'] = $value);
    }
}

use App\Shapes\PreferencesShape;
use Plumthedev\JsonShape\Casts\AsJsonShape;

class User extends Model
{
    public function casts(): array
    {
        return ['preferences' => AsJsonShape::of(PreferencesShape::class)];
    }
}

$user = User::find(1);

$user->preferences->theme;          // string, typed
$user->preferences->emailEnabled(); // bool

$user->preferences->setTheme('dark');
$user->save();