Skip to content

Commit 4116da8

Browse files
Md. Touhidur RahmanMd. Touhidur Rahman
Md. Touhidur Rahman
authored and
Md. Touhidur Rahman
committed
initial release
0 parents  commit 4116da8

17 files changed

+845
-0
lines changed

.gitattributes

Whitespace-only changes.

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.DS_Store
2+
/vendor
3+
/build
4+
composer.lock
5+
.phpunit.result.cache

.travis.yml

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
language: php
2+
3+
php:
4+
- 7.3
5+
- 7.4
6+
- 8.0
7+
8+
env:
9+
matrix:
10+
- COMPOSER_FLAGS="--prefer-lowest"
11+
- COMPOSER_FLAGS=""
12+
13+
before_script:
14+
- travis_retry composer update ${COMPOSER_FLAGS}
15+
16+
script:
17+
- vendor/bin/phpunit

CHANGELOG.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Changelog
2+
All notable changes to this project will be documented in this file.
3+
4+
## [Unreleased]
5+
6+
7+
## [1.0.0] - 2021-08-14
8+
- Initial release

LICENSE.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) Touhidur Rahman Abir
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Laravel Model UUID
2+
3+
A simple package to sanitize model data to create/update table records.
4+
5+
## Installation
6+
7+
Require the package using composer:
8+
9+
```bash
10+
composer require touhidurabir/laravel-model-sanitize
11+
```
12+
13+
## What is does ?
14+
The **Sanitize** package sanitize the passed **attributes** to proper model fillables at create or update.
15+
16+
A model has multiple table schema based attributed associated with it. When we try to create a new model record or update an existing model record, we must provide the an array attributes that is propelry mapped to those arrtibute or table columns names . For example
17+
18+
```php
19+
$user = User::create([
20+
'email' => '[email protected]',
21+
'password' => Hash::make('password')
22+
]);
23+
```
24+
25+
The above code will run without any issue as both the **email** and **password** column presents in the users table . But for the following code
26+
27+
```php
28+
User::create([
29+
'email' => '[email protected]',
30+
'password' => 'password',
31+
'data' => 'some data'
32+
]);
33+
```
34+
35+
It will throw an **\Illuminate\Database\QueryException** if the **data** column not present in the users table.
36+
37+
```bash
38+
Illuminate\Database\QueryException with message 'SQLSTATE[HY000] [2002] Connection refused (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values ([email protected], password, 2021-08-23 10:15:25, 2021-08-23 10:15:25))'
39+
```
40+
41+
The **Sanitize** package target to make it easier to handle such case as follow by including the **Sanitizable** trait in the models
42+
43+
```php
44+
$data = [
45+
'email' => '[email protected]',
46+
'password' => 'password',
47+
'data' => 'some data'
48+
];
49+
50+
User::create($data);
51+
```
52+
The above code will work if the **Sanitizable** trait is used in the **User** model class. it will sanitize the passed attributed to model fillables and table columns, thus removing the extra or non useable attributes from it .
53+
54+
## How it will be helpful ?
55+
56+
A great use case of this package is where one need to create multiple model instances from validated request data . For example
57+
58+
```php
59+
$validated = $request->validated();
60+
61+
$user = User::create($validated);
62+
63+
$profile = $user->profile->create($validated);
64+
```
65+
I personally use this appraoch in many of my laravel apps .
66+
67+
## Usage
68+
69+
Use the trait **Sanitizable** in model where uuid needed to attach
70+
71+
```php
72+
use Touhidurabir\ModelSanitize\Sanitizable;
73+
use Illuminate\Database\Eloquent\Model;
74+
75+
class User extends Model {
76+
77+
use Sanitizable;
78+
}
79+
```
80+
81+
And thats all . it will automatically work for all the following methods
82+
- **updateOrCreate**
83+
- **firstOrCreate**
84+
- **firstOrNew**
85+
- **create**
86+
- **forceCreate**
87+
- **update**
88+
89+
This package also includes some helper methods that can be used to handle the sanitization process manually.
90+
91+
The **sanitize** static method will sanitize the given attributes list and retuen back the useable and valid attributes as an array
92+
93+
```php
94+
$data = [
95+
'email' => '[email protected]',
96+
'password' => 'password',
97+
'data' => 'some data',
98+
'name' => 'Test User'
99+
];
100+
101+
User::sanitize($data);
102+
```
103+
104+
This will return back as such :
105+
```php
106+
[
107+
'email' => '[email protected]',
108+
'password' => 'password',
109+
'name' => 'Test User'
110+
]
111+
```
112+
113+
The **gibberish** static method will sanitize the given attributes list and retuen back the gibberish/non userbale attributes as an array
114+
115+
```php
116+
$data = [
117+
'email' => '[email protected]',
118+
'password' => 'password',
119+
'data' => 'some data',
120+
'name' => 'Test User'
121+
];
122+
123+
User::gibberish($data);
124+
```
125+
126+
This will return back as such :
127+
```php
128+
[
129+
'data' => 'some data',
130+
]
131+
```
132+
133+
The **sanitize** and **gibberish** methods can be used to check or manually sanitize and evaluate the in valid data that can be passed to create/update model records.
134+
135+
## Contributing
136+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
137+
138+
Please make sure to update tests as appropriate.
139+
140+
## License
141+
[MIT](./LICENSE.md)

composer.json

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"name": "touhidurabir/laravel-model-sanitize",
3+
"description": "A laravel package to handle sanitize process of model data to create/update model records.",
4+
"type": "library",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "Touhidur Rahman",
9+
"email": "[email protected]"
10+
}
11+
],
12+
"require": {
13+
"php": ">=7.2.0"
14+
},
15+
"autoload" : {
16+
"psr-4" : {
17+
"Touhidurabir\\ModelSanitize\\": "src/"
18+
}
19+
},
20+
"autoload-dev" : {
21+
"psr-4" : {
22+
"Touhidurabir\\ModelSanitize\\Tests\\": "tests/"
23+
}
24+
},
25+
"require-dev": {
26+
"phpunit/phpunit": "^9.5",
27+
"orchestra/testbench": "^6.20",
28+
"illuminate/support": "^8.54",
29+
"illuminate/container": "^8.54",
30+
"illuminate/database": "^8.54",
31+
"illuminate/events": "^8.54"
32+
},
33+
"extra": {
34+
"laravel": {
35+
"providers": [
36+
"Touhidurabir\\ModelSanitize\\ModelSanitizeServiceProvider"
37+
],
38+
"aliases": {
39+
"ModelUuid": "Touhidurabir\\ModelSanitize\\Facades\\ModelSanitize"
40+
}
41+
}
42+
}
43+
}

phpunit.xml.dist

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit bootstrap="vendor/autoload.php"
3+
backupGlobals="false"
4+
backupStaticAttributes="false"
5+
colors="true"
6+
verbose="true"
7+
convertErrorsToExceptions="true"
8+
convertNoticesToExceptions="true"
9+
convertWarningsToExceptions="true"
10+
processIsolation="false"
11+
stopOnFailure="false">
12+
<testsuites>
13+
<testsuite name="Laravel Model Sanitize TestSuite">
14+
<directory>tests</directory>
15+
</testsuite>
16+
</testsuites>
17+
<coverage processUncoveredFiles="true">
18+
<include>
19+
<directory suffix=".php">src/</directory>
20+
</include>
21+
</coverage>
22+
<php>
23+
<env name="APP_ENV" value="testing"/>
24+
<env name="DB_CONNECTION" value="sqlite"/>
25+
<env name="DB_DATABASE" value=":memory:"/>
26+
<env name="CACHE_DRIVER" value="array"/>
27+
<env name="SESSION_DRIVER" value="array"/>
28+
<env name="QUEUE_DRIVER" value="sync"/>
29+
</php>
30+
<logging>
31+
<log type="tap" target="build/report.tap"/>
32+
<log type="junit" target="build/report.junit.xml"/>
33+
<log type="coverage-text" target="build/coverage.txt"/>
34+
<log type="coverage-clover" target="build/logs/clover.xml"/>
35+
</logging>
36+
</phpunit>
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<?php
2+
3+
namespace Touhidurabir\ModelSanitize\Builder;
4+
5+
use Illuminate\Database\Eloquent\Builder as BaseBuilder;
6+
7+
class SanitizableQueryBuilder extends BaseBuilder {
8+
9+
/**
10+
* Create or update a record matching the attributes, and fill it with values.
11+
*
12+
* @param array $attributes
13+
* @param array $values
14+
* @return \Illuminate\Database\Eloquent\Model|static
15+
*/
16+
public function updateOrCreate(array $attributes, array $values = [])
17+
{
18+
return parent::updateOrCreate($attributes, $this->model->sanitizeToModelFillable($values));
19+
}
20+
21+
22+
/**
23+
* Get the first record matching the attributes or create it.
24+
*
25+
* @param array $attributes
26+
* @param array $values
27+
* @return \Illuminate\Database\Eloquent\Model|static
28+
*/
29+
public function firstOrCreate(array $attributes = [], array $values = [])
30+
{
31+
return parent::firstOrCreate($attributes, $this->model->sanitizeToModelFillable($values));
32+
}
33+
34+
35+
/**
36+
* Get the first record matching the attributes or instantiate it.
37+
*
38+
* @param array $attributes
39+
* @param array $values
40+
* @return \Illuminate\Database\Eloquent\Model|static
41+
*/
42+
public function firstOrNew(array $attributes = [], array $values = [])
43+
{
44+
return parent::firstOrNew($attributes, $this->model->sanitizeToModelFillable($values));
45+
}
46+
47+
48+
/**
49+
* Save a new model and return the instance.
50+
*
51+
* @param array $attributes
52+
* @return \Illuminate\Database\Eloquent\Model|$this
53+
*/
54+
public function create(array $attributes = [])
55+
{
56+
return parent::create($this->model->sanitizeToModelFillable($attributes));
57+
}
58+
59+
60+
/**
61+
* Save a new model and return the instance. Allow mass-assignment.
62+
*
63+
* @param array $attributes
64+
* @return \Illuminate\Database\Eloquent\Model|$this
65+
*/
66+
public function forceCreate(array $attributes)
67+
{
68+
return parent::forceCreate($this->model->sanitizeToModelFillable($attributes));
69+
}
70+
71+
72+
/**
73+
* Update records in the database.
74+
*
75+
* @param array $values
76+
* @return int
77+
*/
78+
public function update(array $values)
79+
{
80+
return parent::update($this->model->sanitizeToModelFillable($values));
81+
}
82+
}

src/Facades/ModelSanitize.php

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Touhidurabir\ModelSanitize\Facades;
4+
5+
use Illuminate\Support\Facades\Facade;
6+
7+
class ModelSanitize extends Facade {
8+
9+
/**
10+
* Get the registered name of the component.
11+
*
12+
* @return string
13+
*/
14+
protected static function getFacadeAccessor() {
15+
16+
return 'model-sanitize';
17+
}
18+
}

0 commit comments

Comments
 (0)