From 602e169489014641a0b4c8af88b2bfcfaca25f33 Mon Sep 17 00:00:00 2001 From: ananevam Date: Thu, 15 Oct 2015 18:04:59 +0500 Subject: [PATCH] initial --- .editorconfig | 15 + .gitignore | 6 + CHANGELOG.md | 20 + CONTRIBUTING.md | 32 ++ LICENSE.md | 21 ++ README.md | 238 ++++++++++++ composer.json | 50 +++ src/FormBuilder.php | 226 +++++++++++ src/ModelFormBuilder.php | 365 ++++++++++++++++++ src/SkeletonClass.php | 26 ++ src/ValidatorTrait.php | 53 +++ src/WaveModel.php | 581 +++++++++++++++++++++++++++++ src/WavelaravelServiceProvider.php | 28 ++ src/helpers.php | 15 + 14 files changed, 1676 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 src/FormBuilder.php create mode 100644 src/ModelFormBuilder.php create mode 100644 src/SkeletonClass.php create mode 100644 src/ValidatorTrait.php create mode 100644 src/WaveModel.php create mode 100644 src/WavelaravelServiceProvider.php create mode 100644 src/helpers.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cd8eb86 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eaae75 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor +/node_modules +Homestead.yaml +Homestead.json +.env +.DS_Store \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..881c4a1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All Notable changes to `:package_name` will be documented in this file + +## NEXT - YYYY-MM-DD + +### Added +- Nothing + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d879fde --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,32 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/:package_name). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. + +- **Create feature branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + + +## Running Tests + +``` bash +$ composer test +``` + + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..9a1d265 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) 2015 :author_name <:author_email> + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..656da4e --- /dev/null +++ b/README.md @@ -0,0 +1,238 @@ +# wavelaravel/wavelaravel + +Features: self model validation, form model binding(including relations), STI pattern. + +## Installation + +`composer.json` + +``` json +"repositories": [ + { + "type": "vcs", + "url": "https://bitbucket.org/Minoru/wavelaravel" + } +] +``` +``` json +"require": { + "wavelaravel/wavelaravel": "dev-master" +} +``` + +And run `composer update` + +## Usage +You must extend your classes from Wavelaravel\Wavelaravel\WaveModel +``` php +use Wavelaravel\Wavelaravel\WaveModel; + +class Post extends WaveModel { +} +``` +## Validation +Declare validation rules in array `$validation_rules`. + +You can create custom validation rules the same way you would for the Laravel Validator. +``` php +class Post extends WaveModel { + protected $fillable = ['name', 'preview', 'body']; + public $validation_rules = [ + 'name'=>'required', + ]; +} +``` + +## Model Hooks +Here's the complete list of available hooks: + +- `before`/`afterCreate()` + +- `before`/`afterSave()` + +- `before`/`afterUpdate()` + +- `before`/`afterDelete()` + + +## Relations +Wavelaravel don't support many to many relation, but you can use default laravel method. + +Relation rules to declare in array `relations_rules` +If you add flag `'validate'=>true` in relation rule, validator will check relation models validation. + + +Sometimes we don't need to save relation model if all its fields are empty. In such case you can add parameter reject_if and declare static check function. + +Example: + +``` php +class Post extends WaveModel { + protected $fillable = ['name', 'preview', 'body','comments', 'images']; + + public $validation_rules = [ + 'name'=>'required', + ]; + public $relations_rules = array( + 'comments' => [ + self::HAS_MANY, 'App\Models\Comment', 'validate'=>true + ], + 'images' => [ + self::MORPH_MANY, + 'App\Models\Image', + 'owner', + 'validate' => true, + 'reject_if' => 'rejectIf', + ], + ); + public static function rejectIf($model){ + if ($model->file_file_name == '' and $model->name == '' and !$model->id){ + return true; + }else{ + return false; + } + } +} +``` + +## Form Model Binding +Example views form +posts/create.blade.php +``` php +@extends('layouts.master') +@section('content') +

Create New Post

+
+ @include('posts/_form') +@endsection +``` +posts/edit.blade.php +``` php +@extends('layouts.master') +@section('content') +

Edit Post

+
+ @include('posts/_form') +@endsection +``` +posts/_form.blade.php +``` php +{!! $f = form_for($post, ['class'=>'form-horizontal']) !!} +@if ($post->hasErrors()) +

+ {!! implode('
', array_dot($post->errors)) !!} +

+@endif +
+ {!! $f->label('name', null, ['class' => 'col-sm-3 control-label']) !!} +
+ {!! $f->text('name', ['class' => 'form-control']) !!} +
+
+
+
+ {!! $f->submit('Save',null, ['class' => 'btn btn-primary form-control']) !!} +
+
+{!! $f->close() !!} +``` +You can use `fields_for` for relation models + +Example: +```php +@foreach ($f->fields_for('comments') as $cf) + {!! $cf() !!} +
+ {!! $cf->label('name', null, ['class' => 'col-sm-3 control-label']) !!} +
+ {!! $cf->text('name', ['class' => 'form-control']) !!} +
+
+@endforeach +``` +Method `{!! $cf() !!}` out model id attribute if it exists. Controller changes for it? Nothing. Only add `comments` in fillable fields +`protected $fillable = ['name', 'preview', 'body','comments'];` + +Since wavelaravel uses self model validation we dont't need to use redirect withErrors, use like ruby on rails method, model field `errors` required errors messages + +Example controller +``` php +class PostController extends Controller { + public function index() { + $posts = Post::all(); + return view('posts.index', compact('posts')); + } + public function create() { + $post = new Post(); + return view('posts.create', compact('post')); + } + public function store(Request $request) { + $post = new Post($request->input('post')); + if ($post->save()){ + return redirect()->route('posts.show',$post); + }else { + return view('posts.create', compact('post')); + } + } + public function show($id) { + $post = Post::findOrFail($id); + return view('posts.show', compact('post')); + } + public function edit($id) { + $post = Post::findOrFail($id); + return view('posts.edit', compact('post')); + } + public function update($id, Request $request) { + $post = Post::findOrFail($id); + if ($post->update($request->input('post'))){ + return redirect()->route('posts.show', $post); + }else{ + return view('posts.edit', compact('post')); + } + + } + public function destroy($id) { + Post::destroy($id); + return redirect()->route('posts.index'); + } +} +``` + +If you use resource for declare routing for model, wavelaravel will guess routing. +``` php +Route::resource('posts', 'PostController'); +``` + +Else you can substitute its route + +Example create: +```php +@section('content') + {!! $f = form_for($model, ['action' => route("admin.news.store"), 'files'=>true, 'class'=>'form-horizontal']) !!} + @include("admin/news/_form") + {!! $f->close() !!} +@endsection +``` + +Example edit: +```php +@section('content') + {!! $f = form_for($model, ['action' => route("admin.news.update", [$model->id]), 'files'=>true, 'class'=>'form-horizontal']) !!} + @include("admin/news/_form") + {!! $f->close() !!} +@endsection +``` + +## STI pattern +Just add field `sti_field` and create migration with string field. + +Example: +```php +class Post extends WaveModel { + public $sti_field = 'class_name'; +} +``` +```php +class SecondPost extends Post { +} +``` \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..164be53 --- /dev/null +++ b/composer.json @@ -0,0 +1,50 @@ +{ + "name": "wavelaravel/wavelaravel", + "description": "Self-Model Validation, Form model binding", + "keywords": [ + "league", + "WaveLaravel" + ], + "homepage": "https://github.com/thephpwavelaravel/wavelaravel", + "license": "MIT", + "authors": [ + { + "name": "Alexander Ananev", + "email": "minoru.null@gmail.com", + "homepage": "https://vk.com/minoru", + "role": "Developer" + } + ], + "require": { + "illuminate/support": "~5.1", + "php" : ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit" : "4.*", + "scrutinizer/ocular": "~1.1" + }, + "autoload": { + "psr-4": { + "Wavelaravel\\Wavelaravel\\": "src" + }, + "files": [ + "src/helpers.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Wavelaravel\\Wavelaravel\\Test\\": "tests" + }, + "files": [ + "src/helpers.php" + ] + }, + "scripts": { + "test": "phpunit" + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + } +} diff --git a/src/FormBuilder.php b/src/FormBuilder.php new file mode 100644 index 0000000..0acb28a --- /dev/null +++ b/src/FormBuilder.php @@ -0,0 +1,226 @@ +'.csrf_field().self::getAppendMethod($method); + } + + /** + * Added hidden method if his is patch/put/delete + * + * @param string $method + * + * @return string + */ + protected static function getAppendMethod($method){ + if (in_array($method, self::$fake_methods)){ + return self::input('hidden', '_method', $method); + }else{ + return ''; + } + } + + /** + * Close the current form. + * + * @return string + */ + public static function close(){ + return ''; + } + + /** + * Create a form label element. + * + * @param string $for + * @param string $value + * @param array $options + * + * @return string + */ + public static function label($for, $value=null, $options=[]){ + if ($value === null or $value === false){ + $value = studly_case($for); + } + $options['for'] = $for; + + return ''.$value.''; + } + + /** + * Create a form input field. + * + * @param string $type + * @param string $name + * @param string $value + * @param array $options + * + * @return string + */ + public static function input($type, $name, $value, $options=[]){ + return ''; + } + + /** + * Create a date input field. + * + * @param string $name + * @param string $value + * @param array $options + * + * @return string + */ + public static function date($name, $value, $options=[]){ + if($value instanceof \DateTime or $value instanceof \Carbon\Carbon) { + $value = $value->format('Y-m-d'); + } + return self::input('date', $name, $value, $options); + } + + /** + * Create a textarea input field. + * + * @param string $name + * @param string $value + * @param array $options + * + * @return string + */ + public static function textarea($name, $value, $options=[]){ + return ''; + } + + /** + * Create a file input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public static function file($name, $options=[]){ + return ''; + } + + /** + * Create a checkbox input field. + * + * @param string $name + * @param bool $checked + * @param array $options + * + * @return string + */ + public static function checkbox($name, $checked=null, $options=[]){ + $hidden = self::input('hidden', $name, 0); + $checkbox = ''; + return $hidden . "\r\n" . $checkbox; + } + + /** + * Create a radio button input field. + * + * @param string $name + * @param mixed $value + * @param bool $checked + * @param array $options + * + * @return string + */ + public static function radio($name, $value, $checked=null, $options=[]){ + return ''; + } + + /** + * Create a select box field. + * + * @param string $name + * @param array $list + * @param string $selected + * @param array $options + * + * @return string + */ + public static function select($name, $list=[], $selected = null, $options=[]){ + $select = ''; + } + + /** + * Create a submit button element. + * + * @param string $value + * @param string $name + * @param array $options + * + * @return string + */ + public static function submit($value=null, $name=null, $options=[]){ + if ($name === null){ + $name = 'commit'; + } + if ($value === null){ + $value = 'Commit'; + } + return self::input('submit', $name, $value, $options); + } + + protected static function getHtmlParamsFromOptions($options=[]){ + $result = []; + foreach ($options as $name=>$value){ + $result[] = "{$name}=\"{$value}\""; + } + return (count($result) > 0 ? ' ':'') . implode(' ', $result); + } +} \ No newline at end of file diff --git a/src/ModelFormBuilder.php b/src/ModelFormBuilder.php new file mode 100644 index 0000000..b6e9aa6 --- /dev/null +++ b/src/ModelFormBuilder.php @@ -0,0 +1,365 @@ +model = $model; + $this->prefix_fields_name = $prefix_fields_name; + $this->open_form_options = $options; + $this->index_field = $index_field; + $this->relation_name = $relation_name; + } + + /** + * Open up a new HTML form. + * + * @param array $options + * + * @return string + */ + public function open($options=[]){ + if (!isset($options['action'])) { + $route_segment = str_plural($this->getModelName()); + $route = $route_segment . ($this->model->id ? '.update' : '.store'); + + if (Route::has($route)) { + $options['action'] = $this->model->id ? route($route, $this->model) : route($route); + } + } + if (!isset($options['method']) and $this->model->id){ + $options['method'] = 'patch'; + } + return FormBuilder::open($options); + } + + public function fields_for($relation_name, $models=null){ + if ($models === null){ + $models = $this->model->$relation_name; + } + + if ($models instanceof Model){ + yield new self($models, [], $this->getModelName()); + }elseif($models instanceof Collection or is_array($models)){ + $i=0; + foreach ($models as $model){ + yield new self($model, [], $this->getModelName(), $i, $relation_name); + $i++; + } + } + } + + public function __invoke() + { + if ($this->model->id) { + return $this->input('hidden', 'id'); + }else{ + return ''; + } + } + + /** + * Close the current form. + * + * @return string + */ + public function close(){ + return FormBuilder::close(); + } + + /** + * Create a form label element. + * + * @param string $for + * @param string $value + * @param array $options + * + * @return string + */ + public function label($for, $text=null, $options=[]){ + if ($text === null or $text === false){ + $trans_path = 'validation.attributes.'.$this->getModelName().'.'.$for; + if (Lang::has($trans_path)){ + $text = trans($trans_path); + } + } + $options = $this->prepareLabelOptions($for, $options); + return FormBuilder::label($this->getInputId($for), $text, $options); + } + + /** + * Create a text input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function text($name, $options=[]){ + return $this->input('text', $name, $options); + } + + /** + * Create a textarea input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function textarea($name, $options=[]){ + $value = $this->getInputValue($name); + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::textarea($this->getInputName($name), $value, $options); + } + + /** + * Create a hidden input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function hidden($name, $options=[]){ + return $this->input('hidden', $name, $options); + } + + /** + * Create a password input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function password($name, $options=[]){ + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::input('password', $this->getInputName($name), '', $options); + } + + /** + * Create a form input field. + * + * @param string $type + * @param string $name + * @param array $options + * + * @return string + */ + public function input($type, $name, $options=[]){ + $value = $this->getInputValue($name, $options); + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::input($type, $this->getInputName($name), $value, $options); + } + + /** + * Create an e-mail input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function email($name, $options=[]){ + return $this->input('email', $name, $options); + } + + /** + * Create a file input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function file($name, $options=[]){ + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::file($this->getInputName($name), $options); + } + + /** + * Create a checkbox input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function checkbox($name, $options=[]){ + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::checkbox($this->getInputName($name), ($this->getInputValue($name) ? true : false), $options); + } + + /** + * Create a radio button input field. + * + * @param string $name + * @param mixed $value + * @param array $options + * + * @return string + */ + public function radio($name, $value, $options=[]){ + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::radio($this->getInputName($name), $value, $value == $this->getInputValue($name), $options); + } + + /** + * Create a select box field. + * + * @param string $name + * @param array $list + * @param array $options + * + * @return string + */ + public function select($name, $list=[], $options=[]){ + $options = $this->prepareInputOptions($name, $options); + return FormBuilder::select($this->getInputName($name), $list, $this->getInputValue($name), $options); + } + + /** + * Create a date input field. + * + * @param string $name + * @param array $options + * + * @return string + */ + public function date($name, $options=[]){ + return $this->input('date',$name, $options); + } + + /** + * Create a submit button element. + * + * @param string $value + * @param string $name + * @param array $options + * + * @return string + */ + public function submit($value=null, $name=null, $options=[]){ + return FormBuilder::submit($value, $name, $options); + } + + /** + * Get the VALUE attribute for a field name. + * + * @param string $name + * @param array $options + * + * @return string + */ + protected function getInputValue($name, $options=[]){ + if (isset($options['value'])){ + $value = $options['value']; + unset($options['value']); + return $value; + }else { + return $this->model->getAttribute($name); + } + } + + /** + * Prepare input options. This method do add ID and not-valid class + * + * @param string $name + * @param array $options + * + * @return array + */ + protected function prepareInputOptions($name, $options){ + if (!isset($options['id'])){ + $options['id'] = $this->getInputId($name); + } + if (isset($this->model->errors) and + isset($this->model->errors[$this->getModelName().'.'.$name]) and + count($this->model->errors[$this->getModelName().'.'.$name]) > 0){ + $options['class'] = isset($options['class']) ? $options['class'] . ' not-valid' : 'not-valid'; + } + return $options; + } + + /** + * Prepare label options. This method do add required class by model rules + * + * @param string $name + * @param array $options + * + * @return array + */ + protected function prepareLabelOptions($name, $options){ + if (isset($this->model->validation_rules) and is_array($this->model->validation_rules) and + isset($this->model->validation_rules[$name]) and + str_contains($this->model->validation_rules[$name], 'required')){ + $options['class'] = isset($options['class']) ? $options['class'] . ' required' : 'required'; + } + return $options; + } + + /** + * Get the NAME attribute for a field name. + * + * @param string $name + * + * @return string + */ + protected function getInputName($name){ + if ($this->prefix_fields_name){ + return $this->prefix_fields_name . + '['.($this->relation_name ? $this->relation_name : $this->getModelName()) . ']' . + (($this->index_field !== null and $this->index_field !== false) ? "[{$this->index_field}]" : '') . "[{$name}]"; + }else { + return $this->getModelName() . "[{$name}]"; + } + } + + /** + * Get the ID attribute for a field name. + * + * @param string $name + * + * @return string + */ + protected function getInputId($name){ + return str_replace(']','',str_replace('[','_',$this->getInputName($name))); + } + + /** + * Get model name for field. + * + * @return string + */ + protected function getModelName(){ + return snake_case(class_basename($this->model)); + } + + /** + * Open form in blade + * + * @return string + */ + public function __toString() { + return $this->open($this->open_form_options); + } +} \ No newline at end of file diff --git a/src/SkeletonClass.php b/src/SkeletonClass.php new file mode 100644 index 0000000..7d7ae47 --- /dev/null +++ b/src/SkeletonClass.php @@ -0,0 +1,26 @@ +errors) > 0 ? true : false; + } + + /** + * Check valid model + * + * @return bool + */ + public function isValid(){ + $myself = get_called_class(); + if (isset($myself::$rules) and count($myself::$rules) > 0){ + $attrs = []; + $rules = []; + foreach ($myself::$rules as $attr=>$rule){ + $attrs[$this->getModelName().'.'.$attr] = $this->getAttribute($attr); + $rules[$this->getModelName().'.'.$attr] = $rule; + } + $validator = Validator::make( + $attrs, + $rules + ); + if ($validator->fails()){ + $this->errors = $validator->messages()->getMessages(); + return false; + }else{ + $this->errors = []; + } + } + return true; + } + + /** + * Model name + * + * @return string + */ + protected function getModelName(){ + return snake_case(class_basename($this)); + } +} \ No newline at end of file diff --git a/src/WaveModel.php b/src/WaveModel.php new file mode 100644 index 0000000..ab8057f --- /dev/null +++ b/src/WaveModel.php @@ -0,0 +1,581 @@ +relation->model + public $is_saved = true; + + # declaration relations + public $relations_rules = []; + + # relation models + protected $relations_data = [ + self::BELONGS_TO => [], + self::HAS_MANY => [], + self::MORPH_TO => [], + self::MORPH_MANY => [], + self::HAS_ONE => [], + ]; + + # validation rules + public $validation_rules = []; + + /** + * Constructor + * + * @param array $attributes + * + * @return void + */ + public function __construct($attributes = array()) { + parent::__construct($attributes); + + if ($this->sti_field) { + $this->setAttribute($this->sti_field, get_class($this)); + } + } + + /** + * Check valid errors + * + * @return bool + */ + public function hasErrors(){ + return count($this->errors) > 0 ? true : false; + } + + /** + * Redefined for STI pattern + * + * @return mixed + */ + public function newQuery() { + $builder = parent::newQuery(); + + if ($this->sti_field) { + $builder->where($this->sti_field, get_class($this)); + } + + return $builder; + } + + /** + * Register callbacks after/before Save and other + * + * @return void + */ + public static function boot() { + parent::boot(); + $myself = get_called_class(); + $hooks = array('before' => 'ing', 'after' => 'ed'); + $radicals = array('sav', 'validat', 'creat', 'updat', 'delet'); + foreach ($radicals as $rad) { + foreach ($hooks as $hook => $event) { + $method = $hook.ucfirst($rad).'e'; + if (method_exists($myself, $method)) { + $eventMethod = $rad.$event; + self::$eventMethod(function($model) use ($method){ + return $model->$method($model); + }); + } + } + } + } + + /** + * Check model and relations validation and set foreign key for belongsTo + * + * @return bool + */ + public function beforeSave(){ + if ($this->isValid()) { + foreach ($this->relations_data[self::BELONGS_TO] as $relation_name=>$model){ + $this->saveRelationModelBeforeSave($relation_name, $model); + $relation = $this->getRelationObject($relation_name); + $this->setAttribute($relation->getForeignKey(), $model->getAttribute($model->getKeyName())); + } + foreach ($this->relations_data[self::MORPH_TO] as $relation_name=>$model){ + $this->saveRelationModelBeforeSave($relation_name, $model); + $this->{$relation_name.'_type'} = get_class($model); + $this->{$relation_name.'_id'} = $model->id; + } + return true; + } + return false; + } + + /** + * Save relation model before save this + * + * @param string $relation_name + * @param Model $model + * + * @return void + */ + protected function saveRelationModelBeforeSave($relation_name, Model $model){ + if ($model->is_saved == false) { + if (array_get($this->relations_rules[$relation_name], 'validate', false)) { + $model->save(); + } else { + $model->forceSave(); + } + } + } + + /** + * Save without validation + * + * @return mixed + */ + public function forceSave(){ + $this->force_save = true; + return $this->save(); + } + + /** + * Save has Many relations + * + * @return void + */ + public function afterSave(){ + $this->is_saved=true; + # save has many and morph many relations + $relation_types = [self::HAS_MANY, self::MORPH_MANY, self::HAS_ONE]; + foreach ($relation_types as $relation_type) { + foreach ($this->relations_data[$relation_type] as $relation_name=>$models) { + if ($relation_type == self::HAS_ONE){ + $models = array($models); + } + foreach ($models as $k=>$model){ + if ($model->_destroy) { + if ($model->id) $model->delete(); + if ($relation_name != self::HAS_ONE) { + unset($this->relations_data[$relation_type][$relation_name][$k]); + } + }elseif($this->isReject($relation_type, $model)===false){ + if (in_array($relation_type, [self::HAS_MANY, self::HAS_ONE])) { + $relation = $this->getRelationObject($relation_name); + $foreign_key = last(explode('.', $relation->getForeignKey())); + $model->setAttribute($foreign_key, $this->getAttribute($this->getKeyName())); + } + if (array_get($this->relations_rules[$relation_name], 'validate', false)) { + $model->save(); + } else { + $model->forceSave(); + } + } + } + } + } + $this->clearRelations(); + } + + public function beforeCreate(){} + public function afterCreate(){} + public function beforeUpdate(){} + public function afterUpdate(){} + public function beforeDelete(){} + public function afterDelete(){} + + /** + * Clear relations data after save has_many/morph_many relations + * + * @return void + */ + protected function clearRelations(){ + foreach ($this->relations_data as $relation_name=>$val){ + $this->relations_data[$relation_name] = []; + } + } + + /** + * Return attribute or relation model if his exists + * + * @param string $name + * + * @return mixed + */ + public function getAttribute($name){ + if (isset($this->relations_rules[$name])){ + list($relation_method) = $this->relations_rules[$name]; + + if (in_array($relation_method, [self::BELONGS_TO, self::MORPH_TO, self::HAS_ONE])){ + return $this->getRelationOne($name); + }elseif ($relation_method === self::HAS_MANY or $relation_method === self::MORPH_MANY){ + return $this->getRelationMany($name); + } + }elseif($name == '_destroy'){ + # for destroy checkbox + return $this->_destroy; + } + + return parent::getAttribute($name); + } + + /** + * Get belongs_to/morph_to model + * + * @param string $name + * + * @return Model + */ + protected function getRelationOne($name){ + list($relation_method) = $this->relations_rules[$name]; + if (isset($this->relations_data[$relation_method][$name])){ + return $this->relations_data[$relation_method][$name]; + }else{ + return $this->getRelationObject($name)->first(); + } + } + + /** + * Get has_many/morph_many models + * + * @param string $name + * + * @return mixed + */ + protected function getRelationMany($name){ + list($relation_method) = $this->relations_rules[$name]; + if (isset($this->relations_data[$relation_method][$name]) and count($this->relations_data[$relation_method][$name]) > 0){ + $relation_data_ids=[]; + foreach ($this->relations_data[$relation_method][$name] as $model){ + if ($model->id) { + $relation_data_ids[] = $model->id; + } + } + $models = $this->getRelationObject($name)->whereNotIn('id',$relation_data_ids)->get(); + + foreach ($this->relations_data[$relation_method][$name] as $model){ + $models->add($model); + } + return $models; + }else{ + return $this->getRelationObject($name)->get(); + } + } + + /** + * Set attribute or relation if him exists + * + * @param string $name + * @param mixed $value + * + * @return void + */ + public function setAttribute($name, $value){ + $this->is_saved = false; + + if (isset($this->relations_rules[$name])) { + list($relation_method) = $this->relations_rules[$name]; + + switch($relation_method){ + case self::BELONGS_TO: + case self::MORPH_TO: + case self::HAS_ONE: + $this->setRelationOne($name, $value); + break; + case self::HAS_MANY: + case self::MORPH_MANY: + $this->setRelationMany($name, $value); + break; + + } + }elseif($name == '_destroy') { + $this->_destroy = $value; + }else{ + parent::setAttribute($name,$value); + } + } + + /** + * Set belongs_to/morph_to relation models + * + * @param string $name + * @param mixed $value + * + * @return mixed + */ + protected function setRelationOne($name, $value){ + list($relation_method) = $this->relations_rules[$name]; + + if ($value instanceof Model){ + $model = $value; + }elseif (is_array($value)){ + if (in_array($relation_method, [self::BELONGS_TO, self::HAS_ONE])) { + $model_class = $this->getRelationObject($name)->getRelated(); + }else{ # morph to + $model_class = $value[$this->getRelationObject($name)->getMorphType().'_type']; + } + $primary_key_name = $model_class->getKeyName(); + if (isset($value[$primary_key_name])){ + $model = $model_class::find($value[$primary_key_name]); + $model->fill($value); + }else { + $model = new $model_class($value); + } + }elseif ($value == null) { + $model=null; + }else{ + throw new \Exception('Incorrect relation value'); + } + $this->relations_data[$relation_method][$name] = $model; + } + + /** + * Set has_many/morph_many relation models + * + * @param string $name + * @param mixed $value + * + * @return mixed + */ + protected function setRelationMany($name, $values){ + list($relation_method) = $this->relations_rules[$name]; + + $relation = $this->getRelationObject($name); + $model_class = $relation->getRelated(); + $this->relations_data[$relation_method][$name] = []; + $primary_key_name = $model_class->getKeyName(); + + foreach ($values as $value) { + $model = null; + if (is_array($value)) { + if (isset($value[$primary_key_name])) { + $model = $model_class::find($value[$primary_key_name]); + $model->fill($value); + }else { + $model = new $model_class($value); + } + }elseif($value instanceof Model) { + $model = $value; + }else{ + throw new \Exception('Incorrect relation value'); + } + if ($model != null){ + if ($relation_method == self::MORPH_MANY){ + list($relation_method, $relation_model, $relation_key) = $this->relations_rules[$name]; + $model->setAttribute($relation_key, $this); + }else{ # HAS MANY + $model->setAttribute($this->getModelName($this), $this); + } + } + + $this->relations_data[$relation_method][$name][] = $model; + } + } + + /** + * Get relation object + * + * @param string $name + * + * @return Relation + */ + protected function getRelationObject($name){ + list($relation_method) = $this->relations_rules[$name]; + + if ($relation_method == self::BELONGS_TO) { + list($relation_method, $relation_model) = $this->relations_rules[$name]; + $other_key = array_get($this->relations_rules[$name],'other_key', 'id'); + $foreign_key = array_get($this->relations_rules[$name],'foreign_key', str_singular($name) . '_id'); + + return $this->$relation_method($relation_model, $foreign_key, $other_key, $name); + }elseif(in_array($relation_method, [self::HAS_MANY, self::HAS_ONE])) { + list($relation_method, $relation_model) = $this->relations_rules[$name]; + $local_key = array_get($this->relations_rules[$name],'local_key', 'id'); + $foreign_key = array_get($this->relations_rules[$name],'foreign_key', $this->getModelName() . '_id'); + + return $this->$relation_method($relation_model, $foreign_key, $local_key); + }elseif($relation_method == self::MORPH_TO) { + return $this->$relation_method($name); + }elseif($relation_method == self::MORPH_MANY){ + list($relation_method, $relation_model, $field_name) = $this->relations_rules[$name]; + return $this->$relation_method($relation_model, $field_name); + }else{ + throw new Exception("Invalid relation type " . $relation_method); + } + } + + /** + * Check valid model with relations + * + * @return bool + */ + public function isValid(){ + $this->errors = []; + + $is_valid = $this->force_save ? true : $this->isModelAndRelationsValid(); + $this->force_save = false; + return $is_valid; + } + + /** + * Check valid model and relations + * + * @return bool + */ + protected function isModelAndRelationsValid(){ + $is_model_valid = $this->isModelValid(); + $is_relations_valid = $this->isRelationsValid(); + return ($is_model_valid and $is_relations_valid); + } + + /** + * Check valid model + * + * @return bool + */ + public function isModelValid(){ + if ($this->force_save){ + $this->force_save=false; + return true; + } + if (isset($this->validation_rules) and count($this->validation_rules) > 0){ + $attrs = []; + $rules = []; + foreach ($this->validation_rules as $attr=>$rule){ + $attrs[$this->getModelName() . '.' . $attr] = $this->getAttribute($attr); + $rules[$this->getModelName() . '.' . $attr] = $rule; + } + + $validator = Validator::make( + $attrs, + $rules + ); + if ($validator->fails()){ + $this->errors = $validator->messages()->getMessages(); + return false; + } + } + return true; + } + + /** + * Check valid relations if option validate exists + * + * @return bool + */ + protected function isRelationsValid() { + $is_relations_valid = true; + + foreach ($this->relations_data as $relation_type=>$relations){ + foreach ($relations as $relation_name => $models){ + $_models = []; + if ($models instanceof Model) { + $_models = [$models]; + } elseif (is_array($_models)) { + $_models = $models; + } else { + throw new Exception("Invalid model in {__FILE__} in {__LINE__}"); + } + foreach ($_models as $model) { + if (array_get($this->relations_rules[$relation_name], 'validate', false) and + $this->isReject($relation_name, $model) === false + ) { + $is_relations_valid = ($is_relations_valid == true ? $this->isRelationModelValid($model) : false); + } + } + } + } + + return $is_relations_valid; + } + + /** + * Reject model if + * + * @param string $relation_name + * @param Model $model + * + * @return bool + */ + protected function isReject($relation_name, $model){ + if (isset($this->relations_rules[$relation_name]['reject_if'])){ + $func = $this->relations_rules[$relation_name]['reject_if']; + + if (static::$func($model)){ + return true; + } + } + return false; + } + + /** + * Check valid relation model + * + * @param Model $model + * + * @return bool + */ + protected function isRelationModelValid($model){ + if (method_exists($model, 'isModelValid') and !$model->_destroy) { + if (!$model->isModelValid()) { + if (!isset($this->errors['relations'])) { + $this->errors['relations'] = []; + } + $model_name = snake_case(class_basename($model)); + if (count($model->errors) > 0){ + if (!isset($this->errors['relations'][$model_name])){ + $this->errors['relations'][$model_name] = []; + } + } + $this->errors['relations'][$model_name] = array_merge($this->errors['relations'][$model_name],$model->errors); + + return false; + } + } + return true; + } + + /** + * Model name + * + * @return string + */ + protected function getModelName(){ + return snake_case(class_basename($this)); + } + + /** + * Return relations + * + * @param string $name + * @param array $arguments + * + * @return mixed + */ + public function __call($name, $arguments) { + if (isset($this->relations_rules[$name])){ + return $this->getRelationObject($name); + }else { + return parent::__call($name, $arguments); + } + } + +} diff --git a/src/WavelaravelServiceProvider.php b/src/WavelaravelServiceProvider.php new file mode 100644 index 0000000..bf950d9 --- /dev/null +++ b/src/WavelaravelServiceProvider.php @@ -0,0 +1,28 @@ +