PHP code example of james-harper / data-contracts

1. Go to this page and download the library: Download james-harper/data-contracts 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/ */

    

james-harper / data-contracts example snippets


use DataContracts\DataContract;

class User extends DataContract
{
  protected $schema = 'path/to/file.json';
  protected static $id = 'guid';
}

use DataContracts\DataContract;

class User extends DataContract
{
  protected $schema = 'path/to/file.json';
}

use DataContracts\User as UserContract;

UserContract::describe();
// ['first_name', 'last_name', 'email', 'role']
UserContract::all();
// ['first_name', 'last_name', 'email', 'role']
UserContract::validationRules();
// ['first_name' => ['

UserContract::validationRulesOptional();
// ['account_id' => ['numeric']...]
UserContract::rulesExcept('numeric');
UserContract::rulesExcept(['numeric', 'min'])

$user = new User([
    'id' => 1,
    'name' => 'James',
    'email' => '[email protected]',
    'extraField' => 123,
]);
UserContract::fromEloquent($user);
// ['id' => 'James', 'name' => 'James', 'email' => '[email protected]']

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource {
    public function toArray()
    {
        return UserContract::fromResource($this);
    }
}

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource {
    public function toArray()
    {
        $user = UserContract::fromResource($this);
        $user['name'] = strtoupper($this->name);
        return $user;
    }
}
shell
php cli delete:contract Todo
php cli delete:contract User
shell
php cli validate:schema {name}

date-fullyear   = 4DIGIT
date-month      = 2DIGIT  ; 01-12
date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
                            ; month/year
time-hour       = 2DIGIT  ; 00-23
time-minute     = 2DIGIT  ; 00-59
time-second     = 2DIGIT  ; 00-58, 00-59, 00-60 based on leap second
                            ; rules
time-secfrac    = "." 1*DIGIT
time-numoffset  = ("+" / "-") time-hour ":" time-minute
time-offset     = "Z" / time-numoffset

partial-time    = time-hour ":" time-minute ":" time-second
                    [time-secfrac]
full-date       = date-fullyear "-" date-month "-" date-mday
full-time       = partial-time time-offset

date-time       = full-date "T" full-time