Last active
June 26, 2020 02:00
-
-
Save LucianoCharlesdeSouza/008b7cb353fee101e850ee6d482badfe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Model | |
{ | |
protected $attributes, $fillable, $guarded; | |
public function fill(array $attributes) | |
{ | |
$totallyGuarded = $this->totallyGuarded(); | |
foreach ($this->fillableFromArray($attributes) as $key => $value) | |
{ | |
$key = $this->removeTableFromKey($key); | |
if ($this->isFillable($key)) | |
{ | |
$this->setAttribute($key, $value); | |
} | |
elseif ($totallyGuarded) | |
{ | |
throw new Exception(sprintf( | |
'Adicione à propriedade [%s] em fillable para permitir a atribuição em massa em [%s].', | |
$key, get_class($this) | |
)); | |
} | |
} | |
return $this->attributes; | |
} | |
public function isFillable($key) | |
{ | |
if (in_array($key, $this->fillable)) return true; | |
if ($this->isGuarded($key)) return false; | |
return empty($this->fillable); | |
} | |
public function isGuarded($key) | |
{ | |
return in_array($key, $this->guarded) || $this->guarded == array('*'); | |
} | |
protected function setAttribute($key, $value) | |
{ | |
$this->attributes[$key] = $value; | |
} | |
protected function last($array) | |
{ | |
return end($array); | |
} | |
protected function removeTableFromKey($key) | |
{ | |
return $this->contains($key, '.') ? $this->last(explode('.', $key)) : $key; | |
} | |
protected function contains($haystack, $needles) | |
{ | |
foreach ((array) $needles as $needle) { | |
if ($needle !== '' && mb_strpos($haystack, $needle) !== false) { | |
return true; | |
} | |
} | |
return false; | |
} | |
protected function totallyGuarded() | |
{ | |
return count($this->getFillable()) === 0 && $this->getGuarded() == ['*']; | |
} | |
protected function getFillable() | |
{ | |
return $this->fillable; | |
} | |
protected function getGuarded() | |
{ | |
return $this->guarded; | |
} | |
protected function fillableFromArray(array $attributes) | |
{ | |
if (count($this->fillable) > 0) | |
{ | |
return array_intersect_key($attributes, array_flip($this->fillable)); | |
} | |
return $attributes; | |
} | |
} | |
class User extends Model | |
{ | |
protected $fillable = []; | |
protected $guarded = []; | |
} | |
require 'Model.php'; | |
require 'User.php'; | |
$user = new User(); | |
var_dump($user->fill(['name'=>'fulano', 'age' => 99, 'genre' => 'masc'])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment