GithubHelp home page GithubHelp logo

plasm's Introduction

Plasm

GitHub license Build Status codecov Code Climate

Filter, cast, and validate incoming data from forms, APIs, CLI, etc.

Schema and Changeset for PHP are inspired by Ecto.Changeset from Elixir's Ecto library.

In Development!

Planned for V1.0:

  • Default messages str replacements
  • Finish default validators
  • One or two provided Framework/ORM integrations
  • Figure how to implement DB constraints from Integrations (unique, etc.)

Install

Use composer.

composer require plasm/plasm:dev-master@dev

Usage

1) Define a Schema:

In the schema we specify all the fields we care about and specify what type we want them to be cast to.

Options:

  • type: required. the type the field should be cast to
  • default: Will default to this value if not present in changeset $attrs
  • virtual: This will be a future to mark fields as not for storing
<?php

use Plasm\Schema;

class UserSchema extends Schema
{
    public function definition()
    {
        return [
            'name' => ['type' => 'string'],
            'email' => ['type' => 'string'],
            'is_admin' => ['type' => 'boolean', 'default' => false],
            'age' => ['type' => 'integer'],
            'money' => ['type' => 'float'],
            'password' => ['type' => 'string', 'virtual' => true],
            'password_confirmation' => ['type' => 'string', 'virtual' => true],
            'password_hash' => ['type' => 'string'],
            'nothing' => ['type' => 'string', 'default' => null]
        ];
    }
}

2) Define a Changeset:

You can define multiple changesets in the same class. You can create completely different ones or build on top of others.

For example, below we'll have a createChangeset for creating a user that just builds off our generic changeset and making some of the fields required.

<?php

use Plasm\Changeset;

class UserChangeset extends Changeset
{
    /**
     * Changeset for a User.
     */
    public function changeset($attrs)
    {
        return $this
            ->cast(['name', 'email', 'is_admin', 'age', 'money', 'password', 'nothing'])
            ->validateFormat('email', '/.+@.+\..+/')
            ->validateLength('password', ['min' => 8])
            ->validateConfirmation('password')
            ->validateNumber('age', ['greater_than' => 12], 'You need to be at least 13');
    }

    /**
     * Changeset for creating a User.
     */
    public function createChangeset($attrs)
    {
        return $this
            ->changeset($attrs)
            ->validateRequired(['name', 'email', 'age', 'password'])
            ->validateChange(
                'password',
                $this->validatePassStrength(),
                'Your password is too weak'
            );
    }

    /**
     * A custom validator for checking password strength.
     */
    private function validatePassStrength()
    {
        return function($password) {
            $zxcvbn = new \ZxcvbnPhp\Zxcvbn();
            $strength = $zxcvbn->passwordStrength($password);

            return $strength['score'] >= 3;
        };
    }
}

3) Use them somewhere:

Just for example's sake, the example below looks a lot like a typical Laravel controller's store method.

We'll pass all the request data into the createChangeset changeset and not worry since our cast method will filter out the fields we specify, cast them to their specified types, and validate them.

If we used the EloquentChangesets trait we could call the createModel method after checking if the changeset is valid. If it wasn't valid we can return to the view with the changeset and display the changeset errors to the user.

function store($request)
{
    $changeset = UserChangeset::using(UserSchema::class)
        ->createChangeset($request->all());

    if (! $changeset->valid()) {
        return back()->with('changeset', $changeset);
    }

    $user = $changeset->createModel();

    return redirect()->route('users/index')
        ->with('success', "User {$user->email} added");
}

License

MIT

Credits

plasm's People

Contributors

ryanwinchester avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

krlv omphemetse

plasm's Issues

Finish implementing Validations

Implement validations and test:

  • acceptance (valid & invalid)
  • cast (valid & invalid)
  • change (valid & invalid)
  • confirmation (valid & invalid)
  • count:is (valid & invalid)
  • count:min (valid & invalid)
  • count:max (valid & invalid)
  • exclusion (valid & invalid)
  • format (valid & invalid)
  • inclusion (valid & invalid)
  • length:is (valid & invalid)
  • length:min (valid & invalid)
  • length:max (valid & invalid)
  • number:less_than (valid & invalid)
  • number:greater_than (valid & invalid)
  • number:less_than_or_equal_to (valid & invalid)
  • number:greater_than_or_equal_to (valid & invalid)
  • number:equal_to (valid & invalid)
  • required (valid & invalid)
  • subset (valid & invalid)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.