forked from devsam/core
Illuminate: ready. (critical)
- DB에서 illuminate를 가져올 수 있도록 설정 - 업그레이듵 불가, RootDB, DB를 직접 수정해야함
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
trait GuardsAttributes
|
||||
{
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $fillable = [];
|
||||
|
||||
/**
|
||||
* The attributes that aren't mass assignable.
|
||||
*
|
||||
* @var string[]|bool
|
||||
*/
|
||||
protected $guarded = ['*'];
|
||||
|
||||
/**
|
||||
* Indicates if all mass assignment is enabled.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $unguarded = false;
|
||||
|
||||
/**
|
||||
* The actual columns that exist on the database and can be guarded.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $guardableColumns = [];
|
||||
|
||||
/**
|
||||
* Get the fillable attributes for the model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFillable()
|
||||
{
|
||||
return $this->fillable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the fillable attributes for the model.
|
||||
*
|
||||
* @param array $fillable
|
||||
* @return $this
|
||||
*/
|
||||
public function fillable(array $fillable)
|
||||
{
|
||||
$this->fillable = $fillable;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new fillable attributes with existing fillable attributes on the model.
|
||||
*
|
||||
* @param array $fillable
|
||||
* @return $this
|
||||
*/
|
||||
public function mergeFillable(array $fillable)
|
||||
{
|
||||
$this->fillable = array_merge($this->fillable, $fillable);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the guarded attributes for the model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getGuarded()
|
||||
{
|
||||
return $this->guarded === false
|
||||
? []
|
||||
: $this->guarded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the guarded attributes for the model.
|
||||
*
|
||||
* @param array $guarded
|
||||
* @return $this
|
||||
*/
|
||||
public function guard(array $guarded)
|
||||
{
|
||||
$this->guarded = $guarded;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new guarded attributes with existing guarded attributes on the model.
|
||||
*
|
||||
* @param array $guarded
|
||||
* @return $this
|
||||
*/
|
||||
public function mergeGuarded(array $guarded)
|
||||
{
|
||||
$this->guarded = array_merge($this->guarded, $guarded);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable all mass assignable restrictions.
|
||||
*
|
||||
* @param bool $state
|
||||
* @return void
|
||||
*/
|
||||
public static function unguard($state = true)
|
||||
{
|
||||
static::$unguarded = $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the mass assignment restrictions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function reguard()
|
||||
{
|
||||
static::$unguarded = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the current state is "unguarded".
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isUnguarded()
|
||||
{
|
||||
return static::$unguarded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the given callable while being unguarded.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return mixed
|
||||
*/
|
||||
public static function unguarded(callable $callback)
|
||||
{
|
||||
if (static::$unguarded) {
|
||||
return $callback();
|
||||
}
|
||||
|
||||
static::unguard();
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
static::reguard();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given attribute may be mass assigned.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function isFillable($key)
|
||||
{
|
||||
if (static::$unguarded) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the key is in the "fillable" array, we can of course assume that it's
|
||||
// a fillable attribute. Otherwise, we will check the guarded array when
|
||||
// we need to determine if the attribute is black-listed on the model.
|
||||
if (in_array($key, $this->getFillable())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the attribute is explicitly listed in the "guarded" array then we can
|
||||
// return false immediately. This means this attribute is definitely not
|
||||
// fillable and there is no point in going any further in this method.
|
||||
if ($this->isGuarded($key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return empty($this->getFillable()) &&
|
||||
strpos($key, '.') === false &&
|
||||
! Str::startsWith($key, '_');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given key is guarded.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function isGuarded($key)
|
||||
{
|
||||
if (empty($this->getGuarded())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->getGuarded() == ['*'] ||
|
||||
! empty(preg_grep('/^'.preg_quote($key).'$/i', $this->getGuarded())) ||
|
||||
! $this->isGuardableColumn($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given column is a valid, guardable column.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
protected function isGuardableColumn($key)
|
||||
{
|
||||
if (! isset(static::$guardableColumns[get_class($this)])) {
|
||||
static::$guardableColumns[get_class($this)] = $this->getConnection()
|
||||
->getSchemaBuilder()
|
||||
->getColumnListing($this->getTable());
|
||||
}
|
||||
|
||||
return in_array($key, static::$guardableColumns[get_class($this)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model is totally guarded.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function totallyGuarded()
|
||||
{
|
||||
return count($this->getFillable()) === 0 && $this->getGuarded() == ['*'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the fillable attributes of a given array.
|
||||
*
|
||||
* @param array $attributes
|
||||
* @return array
|
||||
*/
|
||||
protected function fillableFromArray(array $attributes)
|
||||
{
|
||||
if (count($this->getFillable()) > 0 && ! static::$unguarded) {
|
||||
return array_intersect_key($attributes, array_flip($this->getFillable()));
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,1781 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Contracts\Database\Eloquent\Castable;
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
|
||||
use Illuminate\Contracts\Support\Arrayable;
|
||||
use Illuminate\Database\Eloquent\InvalidCastException;
|
||||
use Illuminate\Database\Eloquent\JsonEncodingException;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Database\LazyLoadingViolationException;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection as BaseCollection;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
|
||||
trait HasAttributes
|
||||
{
|
||||
/**
|
||||
* The model's attributes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $attributes = [];
|
||||
|
||||
/**
|
||||
* The model attribute's original state.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $original = [];
|
||||
|
||||
/**
|
||||
* The changed model attributes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $changes = [];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $casts = [];
|
||||
|
||||
/**
|
||||
* The attributes that have been cast using custom classes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $classCastCache = [];
|
||||
|
||||
/**
|
||||
* The built-in, primitive cast types supported by Eloquent.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected static $primitiveCastTypes = [
|
||||
'array',
|
||||
'bool',
|
||||
'boolean',
|
||||
'collection',
|
||||
'custom_datetime',
|
||||
'date',
|
||||
'datetime',
|
||||
'decimal',
|
||||
'double',
|
||||
'encrypted',
|
||||
'encrypted:array',
|
||||
'encrypted:collection',
|
||||
'encrypted:json',
|
||||
'encrypted:object',
|
||||
'float',
|
||||
'immutable_date',
|
||||
'immutable_datetime',
|
||||
'immutable_custom_datetime',
|
||||
'int',
|
||||
'integer',
|
||||
'json',
|
||||
'object',
|
||||
'real',
|
||||
'string',
|
||||
'timestamp',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be mutated to dates.
|
||||
*
|
||||
* @deprecated Use the "casts" property
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dates = [];
|
||||
|
||||
/**
|
||||
* The storage format of the model's date columns.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $dateFormat;
|
||||
|
||||
/**
|
||||
* The accessors to append to the model's array form.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $appends = [];
|
||||
|
||||
/**
|
||||
* Indicates whether attributes are snake cased on arrays.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public static $snakeAttributes = true;
|
||||
|
||||
/**
|
||||
* The cache of the mutated attributes for each class.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $mutatorCache = [];
|
||||
|
||||
/**
|
||||
* The encrypter instance that is used to encrypt attributes.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Encryption\Encrypter
|
||||
*/
|
||||
public static $encrypter;
|
||||
|
||||
/**
|
||||
* Convert the model's attributes to an array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function attributesToArray()
|
||||
{
|
||||
// If an attribute is a date, we will cast it to a string after converting it
|
||||
// to a DateTime / Carbon instance. This is so we will get some consistent
|
||||
// formatting while accessing attributes vs. arraying / JSONing a model.
|
||||
$attributes = $this->addDateAttributesToArray(
|
||||
$attributes = $this->getArrayableAttributes()
|
||||
);
|
||||
|
||||
$attributes = $this->addMutatedAttributesToArray(
|
||||
$attributes, $mutatedAttributes = $this->getMutatedAttributes()
|
||||
);
|
||||
|
||||
// Next we will handle any casts that have been setup for this model and cast
|
||||
// the values to their appropriate type. If the attribute has a mutator we
|
||||
// will not perform the cast on those attributes to avoid any confusion.
|
||||
$attributes = $this->addCastAttributesToArray(
|
||||
$attributes, $mutatedAttributes
|
||||
);
|
||||
|
||||
// Here we will grab all of the appended, calculated attributes to this model
|
||||
// as these attributes are not really in the attributes array, but are run
|
||||
// when we need to array or JSON the model for convenience to the coder.
|
||||
foreach ($this->getArrayableAppends() as $key) {
|
||||
$attributes[$key] = $this->mutateAttributeForArray($key, null);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the date attributes to the attributes array.
|
||||
*
|
||||
* @param array $attributes
|
||||
* @return array
|
||||
*/
|
||||
protected function addDateAttributesToArray(array $attributes)
|
||||
{
|
||||
foreach ($this->getDates() as $key) {
|
||||
if (! isset($attributes[$key])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes[$key] = $this->serializeDate(
|
||||
$this->asDateTime($attributes[$key])
|
||||
);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the mutated attributes to the attributes array.
|
||||
*
|
||||
* @param array $attributes
|
||||
* @param array $mutatedAttributes
|
||||
* @return array
|
||||
*/
|
||||
protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes)
|
||||
{
|
||||
foreach ($mutatedAttributes as $key) {
|
||||
// We want to spin through all the mutated attributes for this model and call
|
||||
// the mutator for the attribute. We cache off every mutated attributes so
|
||||
// we don't have to constantly check on attributes that actually change.
|
||||
if (! array_key_exists($key, $attributes)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Next, we will call the mutator for this attribute so that we can get these
|
||||
// mutated attribute's actual values. After we finish mutating each of the
|
||||
// attributes we will return this final array of the mutated attributes.
|
||||
$attributes[$key] = $this->mutateAttributeForArray(
|
||||
$key, $attributes[$key]
|
||||
);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the casted attributes to the attributes array.
|
||||
*
|
||||
* @param array $attributes
|
||||
* @param array $mutatedAttributes
|
||||
* @return array
|
||||
*/
|
||||
protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes)
|
||||
{
|
||||
foreach ($this->getCasts() as $key => $value) {
|
||||
if (! array_key_exists($key, $attributes) ||
|
||||
in_array($key, $mutatedAttributes)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Here we will cast the attribute. Then, if the cast is a date or datetime cast
|
||||
// then we will serialize the date for the array. This will convert the dates
|
||||
// to strings based on the date format specified for these Eloquent models.
|
||||
$attributes[$key] = $this->castAttribute(
|
||||
$key, $attributes[$key]
|
||||
);
|
||||
|
||||
// If the attribute cast was a date or a datetime, we will serialize the date as
|
||||
// a string. This allows the developers to customize how dates are serialized
|
||||
// into an array without affecting how they are persisted into the storage.
|
||||
if ($attributes[$key] && in_array($value, ['date', 'datetime', 'immutable_date', 'immutable_datetime'])) {
|
||||
$attributes[$key] = $this->serializeDate($attributes[$key]);
|
||||
}
|
||||
|
||||
if ($attributes[$key] && ($this->isCustomDateTimeCast($value) ||
|
||||
$this->isImmutableCustomDateTimeCast($value))) {
|
||||
$attributes[$key] = $attributes[$key]->format(explode(':', $value, 2)[1]);
|
||||
}
|
||||
|
||||
if ($attributes[$key] && $attributes[$key] instanceof DateTimeInterface &&
|
||||
$this->isClassCastable($key)) {
|
||||
$attributes[$key] = $this->serializeDate($attributes[$key]);
|
||||
}
|
||||
|
||||
if ($attributes[$key] && $this->isClassSerializable($key)) {
|
||||
$attributes[$key] = $this->serializeClassCastableAttribute($key, $attributes[$key]);
|
||||
}
|
||||
|
||||
if ($attributes[$key] instanceof Arrayable) {
|
||||
$attributes[$key] = $attributes[$key]->toArray();
|
||||
}
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute array of all arrayable attributes.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getArrayableAttributes()
|
||||
{
|
||||
return $this->getArrayableItems($this->getAttributes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all of the appendable values that are arrayable.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getArrayableAppends()
|
||||
{
|
||||
if (! count($this->appends)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->getArrayableItems(
|
||||
array_combine($this->appends, $this->appends)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the model's relationships in array form.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function relationsToArray()
|
||||
{
|
||||
$attributes = [];
|
||||
|
||||
foreach ($this->getArrayableRelations() as $key => $value) {
|
||||
// If the values implements the Arrayable interface we can just call this
|
||||
// toArray method on the instances which will convert both models and
|
||||
// collections to their proper array form and we'll set the values.
|
||||
if ($value instanceof Arrayable) {
|
||||
$relation = $value->toArray();
|
||||
}
|
||||
|
||||
// If the value is null, we'll still go ahead and set it in this list of
|
||||
// attributes since null is used to represent empty relationships if
|
||||
// if it a has one or belongs to type relationships on the models.
|
||||
elseif (is_null($value)) {
|
||||
$relation = $value;
|
||||
}
|
||||
|
||||
// If the relationships snake-casing is enabled, we will snake case this
|
||||
// key so that the relation attribute is snake cased in this returned
|
||||
// array to the developers, making this consistent with attributes.
|
||||
if (static::$snakeAttributes) {
|
||||
$key = Str::snake($key);
|
||||
}
|
||||
|
||||
// If the relation value has been set, we will set it on this attributes
|
||||
// list for returning. If it was not arrayable or null, we'll not set
|
||||
// the value on the array because it is some type of invalid value.
|
||||
if (isset($relation) || is_null($value)) {
|
||||
$attributes[$key] = $relation;
|
||||
}
|
||||
|
||||
unset($relation);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute array of all arrayable relations.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getArrayableRelations()
|
||||
{
|
||||
return $this->getArrayableItems($this->relations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute array of all arrayable values.
|
||||
*
|
||||
* @param array $values
|
||||
* @return array
|
||||
*/
|
||||
protected function getArrayableItems(array $values)
|
||||
{
|
||||
if (count($this->getVisible()) > 0) {
|
||||
$values = array_intersect_key($values, array_flip($this->getVisible()));
|
||||
}
|
||||
|
||||
if (count($this->getHidden()) > 0) {
|
||||
$values = array_diff_key($values, array_flip($this->getHidden()));
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute from the model.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function getAttribute($key)
|
||||
{
|
||||
if (! $key) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the attribute exists in the attribute array or has a "get" mutator we will
|
||||
// get the attribute's value. Otherwise, we will proceed as if the developers
|
||||
// are asking for a relationship's value. This covers both types of values.
|
||||
if (array_key_exists($key, $this->attributes) ||
|
||||
array_key_exists($key, $this->casts) ||
|
||||
$this->hasGetMutator($key) ||
|
||||
$this->isClassCastable($key)) {
|
||||
return $this->getAttributeValue($key);
|
||||
}
|
||||
|
||||
// Here we will determine if the model base class itself contains this given key
|
||||
// since we don't want to treat any of those methods as relationships because
|
||||
// they are all intended as helper methods and none of these are relations.
|
||||
if (method_exists(self::class, $key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return $this->getRelationValue($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a plain attribute (not a relationship).
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function getAttributeValue($key)
|
||||
{
|
||||
return $this->transformModelValue($key, $this->getAttributeFromArray($key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute from the $attributes array.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getAttributeFromArray($key)
|
||||
{
|
||||
return $this->getAttributes()[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a relationship.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function getRelationValue($key)
|
||||
{
|
||||
// If the key already exists in the relationships array, it just means the
|
||||
// relationship has already been loaded, so we'll just return it out of
|
||||
// here because there is no need to query within the relations twice.
|
||||
if ($this->relationLoaded($key)) {
|
||||
return $this->relations[$key];
|
||||
}
|
||||
|
||||
if (! $this->isRelation($key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->preventsLazyLoading) {
|
||||
$this->handleLazyLoadingViolation($key);
|
||||
}
|
||||
|
||||
// If the "attribute" exists as a method on the model, we will just assume
|
||||
// it is a relationship and will load and return results from the query
|
||||
// and hydrate the relationship's value on the "relationships" array.
|
||||
return $this->getRelationshipFromMethod($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given key is a relationship method on the model.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function isRelation($key)
|
||||
{
|
||||
return method_exists($this, $key) ||
|
||||
(static::$relationResolvers[get_class($this)][$key] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a lazy loading violation.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
protected function handleLazyLoadingViolation($key)
|
||||
{
|
||||
if (isset(static::$lazyLoadingViolationCallback)) {
|
||||
return call_user_func(static::$lazyLoadingViolationCallback, $this, $key);
|
||||
}
|
||||
|
||||
throw new LazyLoadingViolationException($this, $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a relationship value from a method.
|
||||
*
|
||||
* @param string $method
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
protected function getRelationshipFromMethod($method)
|
||||
{
|
||||
$relation = $this->$method();
|
||||
|
||||
if (! $relation instanceof Relation) {
|
||||
if (is_null($relation)) {
|
||||
throw new LogicException(sprintf(
|
||||
'%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?', static::class, $method
|
||||
));
|
||||
}
|
||||
|
||||
throw new LogicException(sprintf(
|
||||
'%s::%s must return a relationship instance.', static::class, $method
|
||||
));
|
||||
}
|
||||
|
||||
return tap($relation->getResults(), function ($results) use ($method) {
|
||||
$this->setRelation($method, $results);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a get mutator exists for an attribute.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function hasGetMutator($key)
|
||||
{
|
||||
return method_exists($this, 'get'.Str::studly($key).'Attribute');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of an attribute using its mutator.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function mutateAttribute($key, $value)
|
||||
{
|
||||
return $this->{'get'.Str::studly($key).'Attribute'}($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of an attribute using its mutator for array conversion.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function mutateAttributeForArray($key, $value)
|
||||
{
|
||||
$value = $this->isClassCastable($key)
|
||||
? $this->getClassCastableAttributeValue($key, $value)
|
||||
: $this->mutateAttribute($key, $value);
|
||||
|
||||
return $value instanceof Arrayable ? $value->toArray() : $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new casts with existing casts on the model.
|
||||
*
|
||||
* @param array $casts
|
||||
* @return $this
|
||||
*/
|
||||
public function mergeCasts($casts)
|
||||
{
|
||||
$this->casts = array_merge($this->casts, $casts);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast an attribute to a native PHP type.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function castAttribute($key, $value)
|
||||
{
|
||||
$castType = $this->getCastType($key);
|
||||
|
||||
if (is_null($value) && in_array($castType, static::$primitiveCastTypes)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// If the key is one of the encrypted castable types, we'll first decrypt
|
||||
// the value and update the cast type so we may leverage the following
|
||||
// logic for casting this value to any additionally specified types.
|
||||
if ($this->isEncryptedCastable($key)) {
|
||||
$value = $this->fromEncryptedString($value);
|
||||
|
||||
$castType = Str::after($castType, 'encrypted:');
|
||||
}
|
||||
|
||||
switch ($castType) {
|
||||
case 'int':
|
||||
case 'integer':
|
||||
return (int) $value;
|
||||
case 'real':
|
||||
case 'float':
|
||||
case 'double':
|
||||
return $this->fromFloat($value);
|
||||
case 'decimal':
|
||||
return $this->asDecimal($value, explode(':', $this->getCasts()[$key], 2)[1]);
|
||||
case 'string':
|
||||
return (string) $value;
|
||||
case 'bool':
|
||||
case 'boolean':
|
||||
return (bool) $value;
|
||||
case 'object':
|
||||
return $this->fromJson($value, true);
|
||||
case 'array':
|
||||
case 'json':
|
||||
return $this->fromJson($value);
|
||||
case 'collection':
|
||||
return new BaseCollection($this->fromJson($value));
|
||||
case 'date':
|
||||
return $this->asDate($value);
|
||||
case 'datetime':
|
||||
case 'custom_datetime':
|
||||
return $this->asDateTime($value);
|
||||
case 'immutable_date':
|
||||
return $this->asDate($value)->toImmutable();
|
||||
case 'immutable_custom_datetime':
|
||||
case 'immutable_datetime':
|
||||
return $this->asDateTime($value)->toImmutable();
|
||||
case 'timestamp':
|
||||
return $this->asTimestamp($value);
|
||||
}
|
||||
|
||||
if ($this->isClassCastable($key)) {
|
||||
return $this->getClassCastableAttributeValue($key, $value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast the given attribute using a custom cast class.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getClassCastableAttributeValue($key, $value)
|
||||
{
|
||||
if (isset($this->classCastCache[$key])) {
|
||||
return $this->classCastCache[$key];
|
||||
} else {
|
||||
$caster = $this->resolveCasterClass($key);
|
||||
|
||||
$value = $caster instanceof CastsInboundAttributes
|
||||
? $value
|
||||
: $caster->get($this, $key, $value, $this->attributes);
|
||||
|
||||
if ($caster instanceof CastsInboundAttributes || ! is_object($value)) {
|
||||
unset($this->classCastCache[$key]);
|
||||
} else {
|
||||
$this->classCastCache[$key] = $value;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the type of cast for a model attribute.
|
||||
*
|
||||
* @param string $key
|
||||
* @return string
|
||||
*/
|
||||
protected function getCastType($key)
|
||||
{
|
||||
if ($this->isCustomDateTimeCast($this->getCasts()[$key])) {
|
||||
return 'custom_datetime';
|
||||
}
|
||||
|
||||
if ($this->isImmutableCustomDateTimeCast($this->getCasts()[$key])) {
|
||||
return 'immutable_custom_datetime';
|
||||
}
|
||||
|
||||
if ($this->isDecimalCast($this->getCasts()[$key])) {
|
||||
return 'decimal';
|
||||
}
|
||||
|
||||
return trim(strtolower($this->getCasts()[$key]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment or decrement the given attribute using the custom cast class.
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function deviateClassCastableAttribute($method, $key, $value)
|
||||
{
|
||||
return $this->resolveCasterClass($key)->{$method}(
|
||||
$this, $key, $value, $this->attributes
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given attribute using the custom cast class.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function serializeClassCastableAttribute($key, $value)
|
||||
{
|
||||
return $this->resolveCasterClass($key)->serialize(
|
||||
$this, $key, $value, $this->attributes
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the cast type is a custom date time cast.
|
||||
*
|
||||
* @param string $cast
|
||||
* @return bool
|
||||
*/
|
||||
protected function isCustomDateTimeCast($cast)
|
||||
{
|
||||
return strncmp($cast, 'date:', 5) === 0 ||
|
||||
strncmp($cast, 'datetime:', 9) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the cast type is an immutable custom date time cast.
|
||||
*
|
||||
* @param string $cast
|
||||
* @return bool
|
||||
*/
|
||||
protected function isImmutableCustomDateTimeCast($cast)
|
||||
{
|
||||
return strncmp($cast, 'immutable_date:', 15) === 0 ||
|
||||
strncmp($cast, 'immutable_datetime:', 19) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the cast type is a decimal cast.
|
||||
*
|
||||
* @param string $cast
|
||||
* @return bool
|
||||
*/
|
||||
protected function isDecimalCast($cast)
|
||||
{
|
||||
return strncmp($cast, 'decimal:', 8) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a given attribute on the model.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setAttribute($key, $value)
|
||||
{
|
||||
// First we will check for the presence of a mutator for the set operation
|
||||
// which simply lets the developers tweak the attribute as it is set on
|
||||
// this model, such as "json_encoding" a listing of data for storage.
|
||||
if ($this->hasSetMutator($key)) {
|
||||
return $this->setMutatedAttributeValue($key, $value);
|
||||
}
|
||||
|
||||
// If an attribute is listed as a "date", we'll convert it from a DateTime
|
||||
// instance into a form proper for storage on the database tables using
|
||||
// the connection grammar's date format. We will auto set the values.
|
||||
elseif ($value && $this->isDateAttribute($key)) {
|
||||
$value = $this->fromDateTime($value);
|
||||
}
|
||||
|
||||
if ($this->isClassCastable($key)) {
|
||||
$this->setClassCastableAttribute($key, $value);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (! is_null($value) && $this->isJsonCastable($key)) {
|
||||
$value = $this->castAttributeAsJson($key, $value);
|
||||
}
|
||||
|
||||
// If this attribute contains a JSON ->, we'll set the proper value in the
|
||||
// attribute's underlying array. This takes care of properly nesting an
|
||||
// attribute in the array's value in the case of deeply nested items.
|
||||
if (Str::contains($key, '->')) {
|
||||
return $this->fillJsonAttribute($key, $value);
|
||||
}
|
||||
|
||||
if (! is_null($value) && $this->isEncryptedCastable($key)) {
|
||||
$value = $this->castAttributeAsEncryptedString($key, $value);
|
||||
}
|
||||
|
||||
$this->attributes[$key] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a set mutator exists for an attribute.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function hasSetMutator($key)
|
||||
{
|
||||
return method_exists($this, 'set'.Str::studly($key).'Attribute');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of an attribute using its mutator.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function setMutatedAttributeValue($key, $value)
|
||||
{
|
||||
return $this->{'set'.Str::studly($key).'Attribute'}($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given attribute is a date or date castable.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
protected function isDateAttribute($key)
|
||||
{
|
||||
return in_array($key, $this->getDates(), true) ||
|
||||
$this->isDateCastable($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a given JSON attribute on the model.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function fillJsonAttribute($key, $value)
|
||||
{
|
||||
[$key, $path] = explode('->', $key, 2);
|
||||
|
||||
$value = $this->asJson($this->getArrayAttributeWithValue(
|
||||
$path, $key, $value
|
||||
));
|
||||
|
||||
$this->attributes[$key] = $this->isEncryptedCastable($key)
|
||||
? $this->castAttributeAsEncryptedString($key, $value)
|
||||
: $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of a class castable attribute.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return void
|
||||
*/
|
||||
protected function setClassCastableAttribute($key, $value)
|
||||
{
|
||||
$caster = $this->resolveCasterClass($key);
|
||||
|
||||
if (is_null($value)) {
|
||||
$this->attributes = array_merge($this->attributes, array_map(
|
||||
function () {
|
||||
},
|
||||
$this->normalizeCastClassResponse($key, $caster->set(
|
||||
$this, $key, $this->{$key}, $this->attributes
|
||||
))
|
||||
));
|
||||
} else {
|
||||
$this->attributes = array_merge(
|
||||
$this->attributes,
|
||||
$this->normalizeCastClassResponse($key, $caster->set(
|
||||
$this, $key, $value, $this->attributes
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
if ($caster instanceof CastsInboundAttributes || ! is_object($value)) {
|
||||
unset($this->classCastCache[$key]);
|
||||
} else {
|
||||
$this->classCastCache[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array attribute with the given key and value set.
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
protected function getArrayAttributeWithValue($path, $key, $value)
|
||||
{
|
||||
return tap($this->getArrayAttributeByKey($key), function (&$array) use ($path, $value) {
|
||||
Arr::set($array, str_replace('->', '.', $path), $value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array attribute or return an empty array if it is not set.
|
||||
*
|
||||
* @param string $key
|
||||
* @return array
|
||||
*/
|
||||
protected function getArrayAttributeByKey($key)
|
||||
{
|
||||
if (! isset($this->attributes[$key])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->fromJson(
|
||||
$this->isEncryptedCastable($key)
|
||||
? $this->fromEncryptedString($this->attributes[$key])
|
||||
: $this->attributes[$key]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast the given attribute to JSON.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return string
|
||||
*/
|
||||
protected function castAttributeAsJson($key, $value)
|
||||
{
|
||||
$value = $this->asJson($value);
|
||||
|
||||
if ($value === false) {
|
||||
throw JsonEncodingException::forAttribute(
|
||||
$this, $key, json_last_error_msg()
|
||||
);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the given value as JSON.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return string
|
||||
*/
|
||||
protected function asJson($value)
|
||||
{
|
||||
return json_encode($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the given JSON back into an array or object.
|
||||
*
|
||||
* @param string $value
|
||||
* @param bool $asObject
|
||||
* @return mixed
|
||||
*/
|
||||
public function fromJson($value, $asObject = false)
|
||||
{
|
||||
return json_decode($value, ! $asObject);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt the given encrypted string.
|
||||
*
|
||||
* @param string $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function fromEncryptedString($value)
|
||||
{
|
||||
return (static::$encrypter ?? Crypt::getFacadeRoot())->decrypt($value, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast the given attribute to an encrypted string.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return string
|
||||
*/
|
||||
protected function castAttributeAsEncryptedString($key, $value)
|
||||
{
|
||||
return (static::$encrypter ?? Crypt::getFacadeRoot())->encrypt($value, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the encrypter instance that will be used to encrypt attributes.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
|
||||
* @return void
|
||||
*/
|
||||
public static function encryptUsing($encrypter)
|
||||
{
|
||||
static::$encrypter = $encrypter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the given float.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function fromFloat($value)
|
||||
{
|
||||
switch ((string) $value) {
|
||||
case 'Infinity':
|
||||
return INF;
|
||||
case '-Infinity':
|
||||
return -INF;
|
||||
case 'NaN':
|
||||
return NAN;
|
||||
default:
|
||||
return (float) $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a decimal as string.
|
||||
*
|
||||
* @param float $value
|
||||
* @param int $decimals
|
||||
* @return string
|
||||
*/
|
||||
protected function asDecimal($value, $decimals)
|
||||
{
|
||||
return number_format($value, $decimals, '.', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a timestamp as DateTime object with time set to 00:00:00.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Support\Carbon
|
||||
*/
|
||||
protected function asDate($value)
|
||||
{
|
||||
return $this->asDateTime($value)->startOfDay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a timestamp as DateTime object.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Support\Carbon
|
||||
*/
|
||||
protected function asDateTime($value)
|
||||
{
|
||||
// If this value is already a Carbon instance, we shall just return it as is.
|
||||
// This prevents us having to re-instantiate a Carbon instance when we know
|
||||
// it already is one, which wouldn't be fulfilled by the DateTime check.
|
||||
if ($value instanceof CarbonInterface) {
|
||||
return Date::instance($value);
|
||||
}
|
||||
|
||||
// If the value is already a DateTime instance, we will just skip the rest of
|
||||
// these checks since they will be a waste of time, and hinder performance
|
||||
// when checking the field. We will just return the DateTime right away.
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
return Date::parse(
|
||||
$value->format('Y-m-d H:i:s.u'), $value->getTimezone()
|
||||
);
|
||||
}
|
||||
|
||||
// If this value is an integer, we will assume it is a UNIX timestamp's value
|
||||
// and format a Carbon object from this timestamp. This allows flexibility
|
||||
// when defining your date fields as they might be UNIX timestamps here.
|
||||
if (is_numeric($value)) {
|
||||
return Date::createFromTimestamp($value);
|
||||
}
|
||||
|
||||
// If the value is in simply year, month, day format, we will instantiate the
|
||||
// Carbon instances from that format. Again, this provides for simple date
|
||||
// fields on the database, while still supporting Carbonized conversion.
|
||||
if ($this->isStandardDateFormat($value)) {
|
||||
return Date::instance(Carbon::createFromFormat('Y-m-d', $value)->startOfDay());
|
||||
}
|
||||
|
||||
$format = $this->getDateFormat();
|
||||
|
||||
// Finally, we will just assume this date is in the format used by default on
|
||||
// the database connection and use that format to create the Carbon object
|
||||
// that is returned back out to the developers after we convert it here.
|
||||
try {
|
||||
$date = Date::createFromFormat($format, $value);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$date = false;
|
||||
}
|
||||
|
||||
return $date ?: Date::parse($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given value is a standard date format.
|
||||
*
|
||||
* @param string $value
|
||||
* @return bool
|
||||
*/
|
||||
protected function isStandardDateFormat($value)
|
||||
{
|
||||
return preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DateTime to a storable string.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return string|null
|
||||
*/
|
||||
public function fromDateTime($value)
|
||||
{
|
||||
return empty($value) ? $value : $this->asDateTime($value)->format(
|
||||
$this->getDateFormat()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a timestamp as unix timestamp.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return int
|
||||
*/
|
||||
protected function asTimestamp($value)
|
||||
{
|
||||
return $this->asDateTime($value)->getTimestamp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a date for array / JSON serialization.
|
||||
*
|
||||
* @param \DateTimeInterface $date
|
||||
* @return string
|
||||
*/
|
||||
protected function serializeDate(DateTimeInterface $date)
|
||||
{
|
||||
return $date instanceof \DateTimeImmutable ?
|
||||
CarbonImmutable::instance($date)->toJSON() :
|
||||
Carbon::instance($date)->toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be converted to dates.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDates()
|
||||
{
|
||||
if (! $this->usesTimestamps()) {
|
||||
return $this->dates;
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
$this->getCreatedAtColumn(),
|
||||
$this->getUpdatedAtColumn(),
|
||||
];
|
||||
|
||||
return array_unique(array_merge($this->dates, $defaults));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the format for database stored dates.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getDateFormat()
|
||||
{
|
||||
return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the date format used by the model.
|
||||
*
|
||||
* @param string $format
|
||||
* @return $this
|
||||
*/
|
||||
public function setDateFormat($format)
|
||||
{
|
||||
$this->dateFormat = $format;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether an attribute should be cast to a native type.
|
||||
*
|
||||
* @param string $key
|
||||
* @param array|string|null $types
|
||||
* @return bool
|
||||
*/
|
||||
public function hasCast($key, $types = null)
|
||||
{
|
||||
if (array_key_exists($key, $this->getCasts())) {
|
||||
return $types ? in_array($this->getCastType($key), (array) $types, true) : true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the casts array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCasts()
|
||||
{
|
||||
if ($this->getIncrementing()) {
|
||||
return array_merge([$this->getKeyName() => $this->getKeyType()], $this->casts);
|
||||
}
|
||||
|
||||
return $this->casts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a value is Date / DateTime castable for inbound manipulation.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
protected function isDateCastable($key)
|
||||
{
|
||||
return $this->hasCast($key, ['date', 'datetime', 'custom_datetime', 'immutable_date', 'immutable_datetime', 'immutable_custom_datetime']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a value is JSON castable for inbound manipulation.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
protected function isJsonCastable($key)
|
||||
{
|
||||
return $this->hasCast($key, ['array', 'json', 'object', 'collection', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a value is an encrypted castable for inbound manipulation.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
protected function isEncryptedCastable($key)
|
||||
{
|
||||
return $this->hasCast($key, ['encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given key is cast using a custom class.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*
|
||||
* @throws \Illuminate\Database\Eloquent\InvalidCastException
|
||||
*/
|
||||
protected function isClassCastable($key)
|
||||
{
|
||||
if (! array_key_exists($key, $this->getCasts())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$castType = $this->parseCasterClass($this->getCasts()[$key]);
|
||||
|
||||
if (in_array($castType, static::$primitiveCastTypes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (class_exists($castType)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new InvalidCastException($this->getModel(), $key, $castType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the key is deviable using a custom class.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*
|
||||
* @throws \Illuminate\Database\Eloquent\InvalidCastException
|
||||
*/
|
||||
protected function isClassDeviable($key)
|
||||
{
|
||||
return $this->isClassCastable($key) &&
|
||||
method_exists($castType = $this->parseCasterClass($this->getCasts()[$key]), 'increment') &&
|
||||
method_exists($castType, 'decrement');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the key is serializable using a custom class.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*
|
||||
* @throws \Illuminate\Database\Eloquent\InvalidCastException
|
||||
*/
|
||||
protected function isClassSerializable($key)
|
||||
{
|
||||
return $this->isClassCastable($key) &&
|
||||
method_exists($this->parseCasterClass($this->getCasts()[$key]), 'serialize');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the custom caster class for a given key.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
protected function resolveCasterClass($key)
|
||||
{
|
||||
$castType = $this->getCasts()[$key];
|
||||
|
||||
$arguments = [];
|
||||
|
||||
if (is_string($castType) && strpos($castType, ':') !== false) {
|
||||
$segments = explode(':', $castType, 2);
|
||||
|
||||
$castType = $segments[0];
|
||||
$arguments = explode(',', $segments[1]);
|
||||
}
|
||||
|
||||
if (is_subclass_of($castType, Castable::class)) {
|
||||
$castType = $castType::castUsing($arguments);
|
||||
}
|
||||
|
||||
if (is_object($castType)) {
|
||||
return $castType;
|
||||
}
|
||||
|
||||
return new $castType(...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given caster class, removing any arguments.
|
||||
*
|
||||
* @param string $class
|
||||
* @return string
|
||||
*/
|
||||
protected function parseCasterClass($class)
|
||||
{
|
||||
return strpos($class, ':') === false
|
||||
? $class
|
||||
: explode(':', $class, 2)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the cast class attributes back into the model.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function mergeAttributesFromClassCasts()
|
||||
{
|
||||
foreach ($this->classCastCache as $key => $value) {
|
||||
$caster = $this->resolveCasterClass($key);
|
||||
|
||||
$this->attributes = array_merge(
|
||||
$this->attributes,
|
||||
$caster instanceof CastsInboundAttributes
|
||||
? [$key => $value]
|
||||
: $this->normalizeCastClassResponse($key, $caster->set($this, $key, $value, $this->attributes))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the response from a custom class caster.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return array
|
||||
*/
|
||||
protected function normalizeCastClassResponse($key, $value)
|
||||
{
|
||||
return is_array($value) ? $value : [$key => $value];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all of the current attributes on the model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getAttributes()
|
||||
{
|
||||
$this->mergeAttributesFromClassCasts();
|
||||
|
||||
return $this->attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all of the current attributes on the model for an insert operation.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getAttributesForInsert()
|
||||
{
|
||||
return $this->getAttributes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the array of model attributes. No checking is done.
|
||||
*
|
||||
* @param array $attributes
|
||||
* @param bool $sync
|
||||
* @return $this
|
||||
*/
|
||||
public function setRawAttributes(array $attributes, $sync = false)
|
||||
{
|
||||
$this->attributes = $attributes;
|
||||
|
||||
if ($sync) {
|
||||
$this->syncOriginal();
|
||||
}
|
||||
|
||||
$this->classCastCache = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the model's original attribute values.
|
||||
*
|
||||
* @param string|null $key
|
||||
* @param mixed $default
|
||||
* @return mixed|array
|
||||
*/
|
||||
public function getOriginal($key = null, $default = null)
|
||||
{
|
||||
return (new static)->setRawAttributes(
|
||||
$this->original, $sync = true
|
||||
)->getOriginalWithoutRewindingModel($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the model's original attribute values.
|
||||
*
|
||||
* @param string|null $key
|
||||
* @param mixed $default
|
||||
* @return mixed|array
|
||||
*/
|
||||
protected function getOriginalWithoutRewindingModel($key = null, $default = null)
|
||||
{
|
||||
if ($key) {
|
||||
return $this->transformModelValue(
|
||||
$key, Arr::get($this->original, $key, $default)
|
||||
);
|
||||
}
|
||||
|
||||
return collect($this->original)->mapWithKeys(function ($value, $key) {
|
||||
return [$key => $this->transformModelValue($key, $value)];
|
||||
})->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the model's raw original attribute values.
|
||||
*
|
||||
* @param string|null $key
|
||||
* @param mixed $default
|
||||
* @return mixed|array
|
||||
*/
|
||||
public function getRawOriginal($key = null, $default = null)
|
||||
{
|
||||
return Arr::get($this->original, $key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a subset of the model's attributes.
|
||||
*
|
||||
* @param array|mixed $attributes
|
||||
* @return array
|
||||
*/
|
||||
public function only($attributes)
|
||||
{
|
||||
$results = [];
|
||||
|
||||
foreach (is_array($attributes) ? $attributes : func_get_args() as $attribute) {
|
||||
$results[$attribute] = $this->getAttribute($attribute);
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync the original attributes with the current.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function syncOriginal()
|
||||
{
|
||||
$this->original = $this->getAttributes();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync a single original attribute with its current value.
|
||||
*
|
||||
* @param string $attribute
|
||||
* @return $this
|
||||
*/
|
||||
public function syncOriginalAttribute($attribute)
|
||||
{
|
||||
return $this->syncOriginalAttributes($attribute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync multiple original attribute with their current values.
|
||||
*
|
||||
* @param array|string $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function syncOriginalAttributes($attributes)
|
||||
{
|
||||
$attributes = is_array($attributes) ? $attributes : func_get_args();
|
||||
|
||||
$modelAttributes = $this->getAttributes();
|
||||
|
||||
foreach ($attributes as $attribute) {
|
||||
$this->original[$attribute] = $modelAttributes[$attribute];
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync the changed attributes.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function syncChanges()
|
||||
{
|
||||
$this->changes = $this->getDirty();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model or any of the given attribute(s) have been modified.
|
||||
*
|
||||
* @param array|string|null $attributes
|
||||
* @return bool
|
||||
*/
|
||||
public function isDirty($attributes = null)
|
||||
{
|
||||
return $this->hasChanges(
|
||||
$this->getDirty(), is_array($attributes) ? $attributes : func_get_args()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model or all the given attribute(s) have remained the same.
|
||||
*
|
||||
* @param array|string|null $attributes
|
||||
* @return bool
|
||||
*/
|
||||
public function isClean($attributes = null)
|
||||
{
|
||||
return ! $this->isDirty(...func_get_args());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model or any of the given attribute(s) have been modified.
|
||||
*
|
||||
* @param array|string|null $attributes
|
||||
* @return bool
|
||||
*/
|
||||
public function wasChanged($attributes = null)
|
||||
{
|
||||
return $this->hasChanges(
|
||||
$this->getChanges(), is_array($attributes) ? $attributes : func_get_args()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if any of the given attributes were changed.
|
||||
*
|
||||
* @param array $changes
|
||||
* @param array|string|null $attributes
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasChanges($changes, $attributes = null)
|
||||
{
|
||||
// If no specific attributes were provided, we will just see if the dirty array
|
||||
// already contains any attributes. If it does we will just return that this
|
||||
// count is greater than zero. Else, we need to check specific attributes.
|
||||
if (empty($attributes)) {
|
||||
return count($changes) > 0;
|
||||
}
|
||||
|
||||
// Here we will spin through every attribute and see if this is in the array of
|
||||
// dirty attributes. If it is, we will return true and if we make it through
|
||||
// all of the attributes for the entire array we will return false at end.
|
||||
foreach (Arr::wrap($attributes) as $attribute) {
|
||||
if (array_key_exists($attribute, $changes)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that have been changed since the last sync.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDirty()
|
||||
{
|
||||
$dirty = [];
|
||||
|
||||
foreach ($this->getAttributes() as $key => $value) {
|
||||
if (! $this->originalIsEquivalent($key)) {
|
||||
$dirty[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $dirty;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that were changed.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getChanges()
|
||||
{
|
||||
return $this->changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the new and old values for a given key are equivalent.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function originalIsEquivalent($key)
|
||||
{
|
||||
if (! array_key_exists($key, $this->original)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$attribute = Arr::get($this->attributes, $key);
|
||||
$original = Arr::get($this->original, $key);
|
||||
|
||||
if ($attribute === $original) {
|
||||
return true;
|
||||
} elseif (is_null($attribute)) {
|
||||
return false;
|
||||
} elseif ($this->isDateAttribute($key) || $this->isDateCastable($key)) {
|
||||
return $this->fromDateTime($attribute) ===
|
||||
$this->fromDateTime($original);
|
||||
} elseif ($this->hasCast($key, ['object', 'collection'])) {
|
||||
return $this->castAttribute($key, $attribute) ==
|
||||
$this->castAttribute($key, $original);
|
||||
} elseif ($this->hasCast($key, ['real', 'float', 'double'])) {
|
||||
if (($attribute === null && $original !== null) || ($attribute !== null && $original === null)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return abs($this->castAttribute($key, $attribute) - $this->castAttribute($key, $original)) < PHP_FLOAT_EPSILON * 4;
|
||||
} elseif ($this->hasCast($key, static::$primitiveCastTypes)) {
|
||||
return $this->castAttribute($key, $attribute) ===
|
||||
$this->castAttribute($key, $original);
|
||||
}
|
||||
|
||||
return is_numeric($attribute) && is_numeric($original)
|
||||
&& strcmp((string) $attribute, (string) $original) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a raw model value using mutators, casts, etc.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function transformModelValue($key, $value)
|
||||
{
|
||||
// If the attribute has a get mutator, we will call that then return what
|
||||
// it returns as the value, which is useful for transforming values on
|
||||
// retrieval from the model to a form that is more useful for usage.
|
||||
if ($this->hasGetMutator($key)) {
|
||||
return $this->mutateAttribute($key, $value);
|
||||
}
|
||||
|
||||
// If the attribute exists within the cast array, we will convert it to
|
||||
// an appropriate native PHP type dependent upon the associated value
|
||||
// given with the key in the pair. Dayle made this comment line up.
|
||||
if ($this->hasCast($key)) {
|
||||
return $this->castAttribute($key, $value);
|
||||
}
|
||||
|
||||
// If the attribute is listed as a date, we will convert it to a DateTime
|
||||
// instance on retrieval, which makes it quite convenient to work with
|
||||
// date fields without having to create a mutator for each property.
|
||||
if ($value !== null
|
||||
&& \in_array($key, $this->getDates(), false)) {
|
||||
return $this->asDateTime($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append attributes to query when building a query.
|
||||
*
|
||||
* @param array|string $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function append($attributes)
|
||||
{
|
||||
$this->appends = array_unique(
|
||||
array_merge($this->appends, is_string($attributes) ? func_get_args() : $attributes)
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the accessors to append to model arrays.
|
||||
*
|
||||
* @param array $appends
|
||||
* @return $this
|
||||
*/
|
||||
public function setAppends(array $appends)
|
||||
{
|
||||
$this->appends = $appends;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether the accessor attribute has been appended.
|
||||
*
|
||||
* @param string $attribute
|
||||
* @return bool
|
||||
*/
|
||||
public function hasAppended($attribute)
|
||||
{
|
||||
return in_array($attribute, $this->appends);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the mutated attributes for a given instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getMutatedAttributes()
|
||||
{
|
||||
$class = static::class;
|
||||
|
||||
if (! isset(static::$mutatorCache[$class])) {
|
||||
static::cacheMutatedAttributes($class);
|
||||
}
|
||||
|
||||
return static::$mutatorCache[$class];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract and cache all the mutated attributes of a class.
|
||||
*
|
||||
* @param string $class
|
||||
* @return void
|
||||
*/
|
||||
public static function cacheMutatedAttributes($class)
|
||||
{
|
||||
static::$mutatorCache[$class] = collect(static::getMutatorMethods($class))->map(function ($match) {
|
||||
return lcfirst(static::$snakeAttributes ? Str::snake($match) : $match);
|
||||
})->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all of the attribute mutator methods.
|
||||
*
|
||||
* @param mixed $class
|
||||
* @return array
|
||||
*/
|
||||
protected static function getMutatorMethods($class)
|
||||
{
|
||||
preg_match_all('/(?<=^|;)get([^;]+?)Attribute(;|$)/', implode(';', get_class_methods($class)), $matches);
|
||||
|
||||
return $matches[1];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Events\NullDispatcher;
|
||||
use Illuminate\Support\Arr;
|
||||
use InvalidArgumentException;
|
||||
|
||||
trait HasEvents
|
||||
{
|
||||
/**
|
||||
* The event map for the model.
|
||||
*
|
||||
* Allows for object-based events for native Eloquent events.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dispatchesEvents = [];
|
||||
|
||||
/**
|
||||
* User exposed observable events.
|
||||
*
|
||||
* These are extra user-defined events observers may subscribe to.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $observables = [];
|
||||
|
||||
/**
|
||||
* Register observers with the model.
|
||||
*
|
||||
* @param object|array|string $classes
|
||||
* @return void
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function observe($classes)
|
||||
{
|
||||
$instance = new static;
|
||||
|
||||
foreach (Arr::wrap($classes) as $class) {
|
||||
$instance->registerObserver($class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a single observer with the model.
|
||||
*
|
||||
* @param object|string $class
|
||||
* @return void
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
protected function registerObserver($class)
|
||||
{
|
||||
$className = $this->resolveObserverClassName($class);
|
||||
|
||||
// When registering a model observer, we will spin through the possible events
|
||||
// and determine if this observer has that method. If it does, we will hook
|
||||
// it into the model's event system, making it convenient to watch these.
|
||||
foreach ($this->getObservableEvents() as $event) {
|
||||
if (method_exists($class, $event)) {
|
||||
static::registerModelEvent($event, $className.'@'.$event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the observer's class name from an object or string.
|
||||
*
|
||||
* @param object|string $class
|
||||
* @return string
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
private function resolveObserverClassName($class)
|
||||
{
|
||||
if (is_object($class)) {
|
||||
return get_class($class);
|
||||
}
|
||||
|
||||
if (class_exists($class)) {
|
||||
return $class;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Unable to find observer: '.$class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the observable event names.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getObservableEvents()
|
||||
{
|
||||
return array_merge(
|
||||
[
|
||||
'retrieved', 'creating', 'created', 'updating', 'updated',
|
||||
'saving', 'saved', 'restoring', 'restored', 'replicating',
|
||||
'deleting', 'deleted', 'forceDeleted',
|
||||
],
|
||||
$this->observables
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the observable event names.
|
||||
*
|
||||
* @param array $observables
|
||||
* @return $this
|
||||
*/
|
||||
public function setObservableEvents(array $observables)
|
||||
{
|
||||
$this->observables = $observables;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an observable event name.
|
||||
*
|
||||
* @param array|mixed $observables
|
||||
* @return void
|
||||
*/
|
||||
public function addObservableEvents($observables)
|
||||
{
|
||||
$this->observables = array_unique(array_merge(
|
||||
$this->observables, is_array($observables) ? $observables : func_get_args()
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an observable event name.
|
||||
*
|
||||
* @param array|mixed $observables
|
||||
* @return void
|
||||
*/
|
||||
public function removeObservableEvents($observables)
|
||||
{
|
||||
$this->observables = array_diff(
|
||||
$this->observables, is_array($observables) ? $observables : func_get_args()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a model event with the dispatcher.
|
||||
*
|
||||
* @param string $event
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
protected static function registerModelEvent($event, $callback)
|
||||
{
|
||||
if (isset(static::$dispatcher)) {
|
||||
$name = static::class;
|
||||
|
||||
static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire the given event for the model.
|
||||
*
|
||||
* @param string $event
|
||||
* @param bool $halt
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fireModelEvent($event, $halt = true)
|
||||
{
|
||||
if (! isset(static::$dispatcher)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// First, we will get the proper method to call on the event dispatcher, and then we
|
||||
// will attempt to fire a custom, object based event for the given event. If that
|
||||
// returns a result we can return that result, or we'll call the string events.
|
||||
$method = $halt ? 'until' : 'dispatch';
|
||||
|
||||
$result = $this->filterModelEventResults(
|
||||
$this->fireCustomModelEvent($event, $method)
|
||||
);
|
||||
|
||||
if ($result === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! empty($result) ? $result : static::$dispatcher->{$method}(
|
||||
"eloquent.{$event}: ".static::class, $this
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire a custom model event for the given event.
|
||||
*
|
||||
* @param string $event
|
||||
* @param string $method
|
||||
* @return mixed|null
|
||||
*/
|
||||
protected function fireCustomModelEvent($event, $method)
|
||||
{
|
||||
if (! isset($this->dispatchesEvents[$event])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));
|
||||
|
||||
if (! is_null($result)) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the model event results.
|
||||
*
|
||||
* @param mixed $result
|
||||
* @return mixed
|
||||
*/
|
||||
protected function filterModelEventResults($result)
|
||||
{
|
||||
if (is_array($result)) {
|
||||
$result = array_filter($result, function ($response) {
|
||||
return ! is_null($response);
|
||||
});
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a retrieved model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function retrieved($callback)
|
||||
{
|
||||
static::registerModelEvent('retrieved', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a saving model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function saving($callback)
|
||||
{
|
||||
static::registerModelEvent('saving', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a saved model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function saved($callback)
|
||||
{
|
||||
static::registerModelEvent('saved', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an updating model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function updating($callback)
|
||||
{
|
||||
static::registerModelEvent('updating', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an updated model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function updated($callback)
|
||||
{
|
||||
static::registerModelEvent('updated', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a creating model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function creating($callback)
|
||||
{
|
||||
static::registerModelEvent('creating', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a created model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function created($callback)
|
||||
{
|
||||
static::registerModelEvent('created', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a replicating model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function replicating($callback)
|
||||
{
|
||||
static::registerModelEvent('replicating', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a deleting model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function deleting($callback)
|
||||
{
|
||||
static::registerModelEvent('deleting', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a deleted model event with the dispatcher.
|
||||
*
|
||||
* @param \Closure|string $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function deleted($callback)
|
||||
{
|
||||
static::registerModelEvent('deleted', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all of the event listeners for the model.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function flushEventListeners()
|
||||
{
|
||||
if (! isset(static::$dispatcher)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$instance = new static;
|
||||
|
||||
foreach ($instance->getObservableEvents() as $event) {
|
||||
static::$dispatcher->forget("eloquent.{$event}: ".static::class);
|
||||
}
|
||||
|
||||
foreach (array_values($instance->dispatchesEvents) as $event) {
|
||||
static::$dispatcher->forget($event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the event dispatcher instance.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Events\Dispatcher
|
||||
*/
|
||||
public static function getEventDispatcher()
|
||||
{
|
||||
return static::$dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the event dispatcher instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
|
||||
* @return void
|
||||
*/
|
||||
public static function setEventDispatcher(Dispatcher $dispatcher)
|
||||
{
|
||||
static::$dispatcher = $dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unset the event dispatcher for models.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function unsetEventDispatcher()
|
||||
{
|
||||
static::$dispatcher = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a callback without firing any model events for any model type.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return mixed
|
||||
*/
|
||||
public static function withoutEvents(callable $callback)
|
||||
{
|
||||
$dispatcher = static::getEventDispatcher();
|
||||
|
||||
if ($dispatcher) {
|
||||
static::setEventDispatcher(new NullDispatcher($dispatcher));
|
||||
}
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
if ($dispatcher) {
|
||||
static::setEventDispatcher($dispatcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
use Illuminate\Support\Arr;
|
||||
use InvalidArgumentException;
|
||||
|
||||
trait HasGlobalScopes
|
||||
{
|
||||
/**
|
||||
* Register a new global scope on the model.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Scope|\Closure|string $scope
|
||||
* @param \Closure|null $implementation
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function addGlobalScope($scope, Closure $implementation = null)
|
||||
{
|
||||
if (is_string($scope) && ! is_null($implementation)) {
|
||||
return static::$globalScopes[static::class][$scope] = $implementation;
|
||||
} elseif ($scope instanceof Closure) {
|
||||
return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
|
||||
} elseif ($scope instanceof Scope) {
|
||||
return static::$globalScopes[static::class][get_class($scope)] = $scope;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a model has a global scope.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Scope|string $scope
|
||||
* @return bool
|
||||
*/
|
||||
public static function hasGlobalScope($scope)
|
||||
{
|
||||
return ! is_null(static::getGlobalScope($scope));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a global scope registered with the model.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Scope|string $scope
|
||||
* @return \Illuminate\Database\Eloquent\Scope|\Closure|null
|
||||
*/
|
||||
public static function getGlobalScope($scope)
|
||||
{
|
||||
if (is_string($scope)) {
|
||||
return Arr::get(static::$globalScopes, static::class.'.'.$scope);
|
||||
}
|
||||
|
||||
return Arr::get(
|
||||
static::$globalScopes, static::class.'.'.get_class($scope)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the global scopes for this class instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getGlobalScopes()
|
||||
{
|
||||
return Arr::get(static::$globalScopes, static::class, []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,875 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\ClassMorphViolationException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphOne;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
trait HasRelationships
|
||||
{
|
||||
/**
|
||||
* The loaded relationships for the model.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $relations = [];
|
||||
|
||||
/**
|
||||
* The relationships that should be touched on save.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $touches = [];
|
||||
|
||||
/**
|
||||
* The many to many relationship methods.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
public static $manyMethods = [
|
||||
'belongsToMany', 'morphToMany', 'morphedByMany',
|
||||
];
|
||||
|
||||
/**
|
||||
* The relation resolver callbacks.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $relationResolvers = [];
|
||||
|
||||
/**
|
||||
* Define a dynamic relation resolver.
|
||||
*
|
||||
* @param string $name
|
||||
* @param \Closure $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function resolveRelationUsing($name, Closure $callback)
|
||||
{
|
||||
static::$relationResolvers = array_replace_recursive(
|
||||
static::$relationResolvers,
|
||||
[static::class => [$name => $callback]]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a one-to-one relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string|null $foreignKey
|
||||
* @param string|null $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOne
|
||||
*/
|
||||
public function hasOne($related, $foreignKey = null, $localKey = null)
|
||||
{
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
$foreignKey = $foreignKey ?: $this->getForeignKey();
|
||||
|
||||
$localKey = $localKey ?: $this->getKeyName();
|
||||
|
||||
return $this->newHasOne($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new HasOne relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOne
|
||||
*/
|
||||
protected function newHasOne(Builder $query, Model $parent, $foreignKey, $localKey)
|
||||
{
|
||||
return new HasOne($query, $parent, $foreignKey, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a has-one-through relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $through
|
||||
* @param string|null $firstKey
|
||||
* @param string|null $secondKey
|
||||
* @param string|null $localKey
|
||||
* @param string|null $secondLocalKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOneThrough
|
||||
*/
|
||||
public function hasOneThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null)
|
||||
{
|
||||
$through = new $through;
|
||||
|
||||
$firstKey = $firstKey ?: $this->getForeignKey();
|
||||
|
||||
$secondKey = $secondKey ?: $through->getForeignKey();
|
||||
|
||||
return $this->newHasOneThrough(
|
||||
$this->newRelatedInstance($related)->newQuery(), $this, $through,
|
||||
$firstKey, $secondKey, $localKey ?: $this->getKeyName(),
|
||||
$secondLocalKey ?: $through->getKeyName()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new HasOneThrough relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $farParent
|
||||
* @param \Illuminate\Database\Eloquent\Model $throughParent
|
||||
* @param string $firstKey
|
||||
* @param string $secondKey
|
||||
* @param string $localKey
|
||||
* @param string $secondLocalKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOneThrough
|
||||
*/
|
||||
protected function newHasOneThrough(Builder $query, Model $farParent, Model $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey)
|
||||
{
|
||||
return new HasOneThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic one-to-one relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $name
|
||||
* @param string|null $type
|
||||
* @param string|null $id
|
||||
* @param string|null $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
|
||||
*/
|
||||
public function morphOne($related, $name, $type = null, $id = null, $localKey = null)
|
||||
{
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
[$type, $id] = $this->getMorphs($name, $type, $id);
|
||||
|
||||
$table = $instance->getTable();
|
||||
|
||||
$localKey = $localKey ?: $this->getKeyName();
|
||||
|
||||
return $this->newMorphOne($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new MorphOne relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @param string $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
|
||||
*/
|
||||
protected function newMorphOne(Builder $query, Model $parent, $type, $id, $localKey)
|
||||
{
|
||||
return new MorphOne($query, $parent, $type, $id, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define an inverse one-to-one or many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string|null $foreignKey
|
||||
* @param string|null $ownerKey
|
||||
* @param string|null $relation
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
|
||||
{
|
||||
// If no relation name was given, we will use this debug backtrace to extract
|
||||
// the calling method's name and use that as the relationship name as most
|
||||
// of the time this will be what we desire to use for the relationships.
|
||||
if (is_null($relation)) {
|
||||
$relation = $this->guessBelongsToRelation();
|
||||
}
|
||||
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
// If no foreign key was supplied, we can use a backtrace to guess the proper
|
||||
// foreign key name by using the name of the relationship function, which
|
||||
// when combined with an "_id" should conventionally match the columns.
|
||||
if (is_null($foreignKey)) {
|
||||
$foreignKey = Str::snake($relation).'_'.$instance->getKeyName();
|
||||
}
|
||||
|
||||
// Once we have the foreign key names, we'll just create a new Eloquent query
|
||||
// for the related models and returns the relationship instance which will
|
||||
// actually be responsible for retrieving and hydrating every relations.
|
||||
$ownerKey = $ownerKey ?: $instance->getKeyName();
|
||||
|
||||
return $this->newBelongsTo(
|
||||
$instance->newQuery(), $this, $foreignKey, $ownerKey, $relation
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new BelongsTo relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $child
|
||||
* @param string $foreignKey
|
||||
* @param string $ownerKey
|
||||
* @param string $relation
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
protected function newBelongsTo(Builder $query, Model $child, $foreignKey, $ownerKey, $relation)
|
||||
{
|
||||
return new BelongsTo($query, $child, $foreignKey, $ownerKey, $relation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic, inverse one-to-one or many relationship.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @param string|null $type
|
||||
* @param string|null $id
|
||||
* @param string|null $ownerKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
public function morphTo($name = null, $type = null, $id = null, $ownerKey = null)
|
||||
{
|
||||
// If no name is provided, we will use the backtrace to get the function name
|
||||
// since that is most likely the name of the polymorphic interface. We can
|
||||
// use that to get both the class and foreign key that will be utilized.
|
||||
$name = $name ?: $this->guessBelongsToRelation();
|
||||
|
||||
[$type, $id] = $this->getMorphs(
|
||||
Str::snake($name), $type, $id
|
||||
);
|
||||
|
||||
// If the type value is null it is probably safe to assume we're eager loading
|
||||
// the relationship. In this case we'll just pass in a dummy query where we
|
||||
// need to remove any eager loads that may already be defined on a model.
|
||||
return is_null($class = $this->getAttributeFromArray($type)) || $class === ''
|
||||
? $this->morphEagerTo($name, $type, $id, $ownerKey)
|
||||
: $this->morphInstanceTo($class, $name, $type, $id, $ownerKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic, inverse one-to-one or many relationship.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @param string $ownerKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
protected function morphEagerTo($name, $type, $id, $ownerKey)
|
||||
{
|
||||
return $this->newMorphTo(
|
||||
$this->newQuery()->setEagerLoads([]), $this, $id, $ownerKey, $type, $name
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic, inverse one-to-one or many relationship.
|
||||
*
|
||||
* @param string $target
|
||||
* @param string $name
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @param string $ownerKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
protected function morphInstanceTo($target, $name, $type, $id, $ownerKey)
|
||||
{
|
||||
$instance = $this->newRelatedInstance(
|
||||
static::getActualClassNameForMorph($target)
|
||||
);
|
||||
|
||||
return $this->newMorphTo(
|
||||
$instance->newQuery(), $this, $id, $ownerKey ?? $instance->getKeyName(), $type, $name
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new MorphTo relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $foreignKey
|
||||
* @param string $ownerKey
|
||||
* @param string $type
|
||||
* @param string $relation
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
protected function newMorphTo(Builder $query, Model $parent, $foreignKey, $ownerKey, $type, $relation)
|
||||
{
|
||||
return new MorphTo($query, $parent, $foreignKey, $ownerKey, $type, $relation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the actual class name for a given morph class.
|
||||
*
|
||||
* @param string $class
|
||||
* @return string
|
||||
*/
|
||||
public static function getActualClassNameForMorph($class)
|
||||
{
|
||||
return Arr::get(Relation::morphMap() ?: [], $class, $class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess the "belongs to" relationship name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function guessBelongsToRelation()
|
||||
{
|
||||
[$one, $two, $caller] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
|
||||
|
||||
return $caller['function'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a one-to-many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string|null $foreignKey
|
||||
* @param string|null $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
*/
|
||||
public function hasMany($related, $foreignKey = null, $localKey = null)
|
||||
{
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
$foreignKey = $foreignKey ?: $this->getForeignKey();
|
||||
|
||||
$localKey = $localKey ?: $this->getKeyName();
|
||||
|
||||
return $this->newHasMany(
|
||||
$instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new HasMany relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
*/
|
||||
protected function newHasMany(Builder $query, Model $parent, $foreignKey, $localKey)
|
||||
{
|
||||
return new HasMany($query, $parent, $foreignKey, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a has-many-through relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $through
|
||||
* @param string|null $firstKey
|
||||
* @param string|null $secondKey
|
||||
* @param string|null $localKey
|
||||
* @param string|null $secondLocalKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
|
||||
*/
|
||||
public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null)
|
||||
{
|
||||
$through = new $through;
|
||||
|
||||
$firstKey = $firstKey ?: $this->getForeignKey();
|
||||
|
||||
$secondKey = $secondKey ?: $through->getForeignKey();
|
||||
|
||||
return $this->newHasManyThrough(
|
||||
$this->newRelatedInstance($related)->newQuery(),
|
||||
$this,
|
||||
$through,
|
||||
$firstKey,
|
||||
$secondKey,
|
||||
$localKey ?: $this->getKeyName(),
|
||||
$secondLocalKey ?: $through->getKeyName()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new HasManyThrough relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $farParent
|
||||
* @param \Illuminate\Database\Eloquent\Model $throughParent
|
||||
* @param string $firstKey
|
||||
* @param string $secondKey
|
||||
* @param string $localKey
|
||||
* @param string $secondLocalKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
|
||||
*/
|
||||
protected function newHasManyThrough(Builder $query, Model $farParent, Model $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey)
|
||||
{
|
||||
return new HasManyThrough($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic one-to-many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $name
|
||||
* @param string|null $type
|
||||
* @param string|null $id
|
||||
* @param string|null $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
*/
|
||||
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
|
||||
{
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
// Here we will gather up the morph type and ID for the relationship so that we
|
||||
// can properly query the intermediate table of a relation. Finally, we will
|
||||
// get the table and create the relationship instances for the developers.
|
||||
[$type, $id] = $this->getMorphs($name, $type, $id);
|
||||
|
||||
$table = $instance->getTable();
|
||||
|
||||
$localKey = $localKey ?: $this->getKeyName();
|
||||
|
||||
return $this->newMorphMany($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new MorphMany relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @param string $localKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
*/
|
||||
protected function newMorphMany(Builder $query, Model $parent, $type, $id, $localKey)
|
||||
{
|
||||
return new MorphMany($query, $parent, $type, $id, $localKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a many-to-many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string|null $table
|
||||
* @param string|null $foreignPivotKey
|
||||
* @param string|null $relatedPivotKey
|
||||
* @param string|null $parentKey
|
||||
* @param string|null $relatedKey
|
||||
* @param string|null $relation
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
||||
*/
|
||||
public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
|
||||
$parentKey = null, $relatedKey = null, $relation = null)
|
||||
{
|
||||
// If no relationship name was passed, we will pull backtraces to get the
|
||||
// name of the calling function. We will use that function name as the
|
||||
// title of this relation since that is a great convention to apply.
|
||||
if (is_null($relation)) {
|
||||
$relation = $this->guessBelongsToManyRelation();
|
||||
}
|
||||
|
||||
// First, we'll need to determine the foreign key and "other key" for the
|
||||
// relationship. Once we have determined the keys we'll make the query
|
||||
// instances as well as the relationship instances we need for this.
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
|
||||
|
||||
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
|
||||
|
||||
// If no table name was provided, we can guess it by concatenating the two
|
||||
// models using underscores in alphabetical order. The two model names
|
||||
// are transformed to snake case from their default CamelCase also.
|
||||
if (is_null($table)) {
|
||||
$table = $this->joiningTable($related, $instance);
|
||||
}
|
||||
|
||||
return $this->newBelongsToMany(
|
||||
$instance->newQuery(), $this, $table, $foreignPivotKey,
|
||||
$relatedPivotKey, $parentKey ?: $this->getKeyName(),
|
||||
$relatedKey ?: $instance->getKeyName(), $relation
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new BelongsToMany relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $table
|
||||
* @param string $foreignPivotKey
|
||||
* @param string $relatedPivotKey
|
||||
* @param string $parentKey
|
||||
* @param string $relatedKey
|
||||
* @param string|null $relationName
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
||||
*/
|
||||
protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey,
|
||||
$parentKey, $relatedKey, $relationName = null)
|
||||
{
|
||||
return new BelongsToMany($query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic many-to-many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $name
|
||||
* @param string|null $table
|
||||
* @param string|null $foreignPivotKey
|
||||
* @param string|null $relatedPivotKey
|
||||
* @param string|null $parentKey
|
||||
* @param string|null $relatedKey
|
||||
* @param bool $inverse
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
|
||||
*/
|
||||
public function morphToMany($related, $name, $table = null, $foreignPivotKey = null,
|
||||
$relatedPivotKey = null, $parentKey = null,
|
||||
$relatedKey = null, $inverse = false)
|
||||
{
|
||||
$caller = $this->guessBelongsToManyRelation();
|
||||
|
||||
// First, we will need to determine the foreign key and "other key" for the
|
||||
// relationship. Once we have determined the keys we will make the query
|
||||
// instances, as well as the relationship instances we need for these.
|
||||
$instance = $this->newRelatedInstance($related);
|
||||
|
||||
$foreignPivotKey = $foreignPivotKey ?: $name.'_id';
|
||||
|
||||
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
|
||||
|
||||
// Now we're ready to create a new query builder for this related model and
|
||||
// the relationship instances for this relation. This relations will set
|
||||
// appropriate query constraints then entirely manages the hydrations.
|
||||
if (! $table) {
|
||||
$words = preg_split('/(_)/u', $name, -1, PREG_SPLIT_DELIM_CAPTURE);
|
||||
|
||||
$lastWord = array_pop($words);
|
||||
|
||||
$table = implode('', $words).Str::plural($lastWord);
|
||||
}
|
||||
|
||||
return $this->newMorphToMany(
|
||||
$instance->newQuery(), $this, $name, $table,
|
||||
$foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(),
|
||||
$relatedKey ?: $instance->getKeyName(), $caller, $inverse
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate a new MorphToMany relationship.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param \Illuminate\Database\Eloquent\Model $parent
|
||||
* @param string $name
|
||||
* @param string $table
|
||||
* @param string $foreignPivotKey
|
||||
* @param string $relatedPivotKey
|
||||
* @param string $parentKey
|
||||
* @param string $relatedKey
|
||||
* @param string|null $relationName
|
||||
* @param bool $inverse
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
|
||||
*/
|
||||
protected function newMorphToMany(Builder $query, Model $parent, $name, $table, $foreignPivotKey,
|
||||
$relatedPivotKey, $parentKey, $relatedKey,
|
||||
$relationName = null, $inverse = false)
|
||||
{
|
||||
return new MorphToMany($query, $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey,
|
||||
$relationName, $inverse);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a polymorphic, inverse many-to-many relationship.
|
||||
*
|
||||
* @param string $related
|
||||
* @param string $name
|
||||
* @param string|null $table
|
||||
* @param string|null $foreignPivotKey
|
||||
* @param string|null $relatedPivotKey
|
||||
* @param string|null $parentKey
|
||||
* @param string|null $relatedKey
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
|
||||
*/
|
||||
public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null,
|
||||
$relatedPivotKey = null, $parentKey = null, $relatedKey = null)
|
||||
{
|
||||
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
|
||||
|
||||
// For the inverse of the polymorphic many-to-many relations, we will change
|
||||
// the way we determine the foreign and other keys, as it is the opposite
|
||||
// of the morph-to-many method since we're figuring out these inverses.
|
||||
$relatedPivotKey = $relatedPivotKey ?: $name.'_id';
|
||||
|
||||
return $this->morphToMany(
|
||||
$related, $name, $table, $foreignPivotKey,
|
||||
$relatedPivotKey, $parentKey, $relatedKey, true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the relationship name of the belongsToMany relationship.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function guessBelongsToManyRelation()
|
||||
{
|
||||
$caller = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) {
|
||||
return ! in_array(
|
||||
$trace['function'],
|
||||
array_merge(static::$manyMethods, ['guessBelongsToManyRelation'])
|
||||
);
|
||||
});
|
||||
|
||||
return ! is_null($caller) ? $caller['function'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the joining table name for a many-to-many relation.
|
||||
*
|
||||
* @param string $related
|
||||
* @param \Illuminate\Database\Eloquent\Model|null $instance
|
||||
* @return string
|
||||
*/
|
||||
public function joiningTable($related, $instance = null)
|
||||
{
|
||||
// The joining table name, by convention, is simply the snake cased models
|
||||
// sorted alphabetically and concatenated with an underscore, so we can
|
||||
// just sort the models and join them together to get the table name.
|
||||
$segments = [
|
||||
$instance ? $instance->joiningTableSegment()
|
||||
: Str::snake(class_basename($related)),
|
||||
$this->joiningTableSegment(),
|
||||
];
|
||||
|
||||
// Now that we have the model names in an array we can just sort them and
|
||||
// use the implode function to join them together with an underscores,
|
||||
// which is typically used by convention within the database system.
|
||||
sort($segments);
|
||||
|
||||
return strtolower(implode('_', $segments));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this model's half of the intermediate table name for belongsToMany relationships.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function joiningTableSegment()
|
||||
{
|
||||
return Str::snake(class_basename($this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model touches a given relation.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return bool
|
||||
*/
|
||||
public function touches($relation)
|
||||
{
|
||||
return in_array($relation, $this->getTouchedRelations());
|
||||
}
|
||||
|
||||
/**
|
||||
* Touch the owning relations of the model.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function touchOwners()
|
||||
{
|
||||
foreach ($this->getTouchedRelations() as $relation) {
|
||||
$this->$relation()->touch();
|
||||
|
||||
if ($this->$relation instanceof self) {
|
||||
$this->$relation->fireModelEvent('saved', false);
|
||||
|
||||
$this->$relation->touchOwners();
|
||||
} elseif ($this->$relation instanceof Collection) {
|
||||
$this->$relation->each->touchOwners();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the polymorphic relationship columns.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @return array
|
||||
*/
|
||||
protected function getMorphs($name, $type, $id)
|
||||
{
|
||||
return [$type ?: $name.'_type', $id ?: $name.'_id'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class name for polymorphic relations.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getMorphClass()
|
||||
{
|
||||
$morphMap = Relation::morphMap();
|
||||
|
||||
if (! empty($morphMap) && in_array(static::class, $morphMap)) {
|
||||
return array_search(static::class, $morphMap, true);
|
||||
}
|
||||
|
||||
if (Relation::requiresMorphMap()) {
|
||||
throw new ClassMorphViolationException($this);
|
||||
}
|
||||
|
||||
return static::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new model instance for a related model.
|
||||
*
|
||||
* @param string $class
|
||||
* @return mixed
|
||||
*/
|
||||
protected function newRelatedInstance($class)
|
||||
{
|
||||
return tap(new $class, function ($instance) {
|
||||
if (! $instance->getConnectionName()) {
|
||||
$instance->setConnection($this->connection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the loaded relations for the instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRelations()
|
||||
{
|
||||
return $this->relations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specified relationship.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return mixed
|
||||
*/
|
||||
public function getRelation($relation)
|
||||
{
|
||||
return $this->relations[$relation];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given relation is loaded.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool
|
||||
*/
|
||||
public function relationLoaded($key)
|
||||
{
|
||||
return array_key_exists($key, $this->relations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the given relationship on the model.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function setRelation($relation, $value)
|
||||
{
|
||||
$this->relations[$relation] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unset a loaded relationship.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return $this
|
||||
*/
|
||||
public function unsetRelation($relation)
|
||||
{
|
||||
unset($this->relations[$relation]);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the entire relations array on the model.
|
||||
*
|
||||
* @param array $relations
|
||||
* @return $this
|
||||
*/
|
||||
public function setRelations(array $relations)
|
||||
{
|
||||
$this->relations = $relations;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicate the instance and unset all the loaded relations.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function withoutRelations()
|
||||
{
|
||||
$model = clone $this;
|
||||
|
||||
return $model->unsetRelations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Unset all the loaded relations for the instance.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function unsetRelations()
|
||||
{
|
||||
$this->relations = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the relationships that are touched on save.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getTouchedRelations()
|
||||
{
|
||||
return $this->touches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the relationships that are touched on save.
|
||||
*
|
||||
* @param array $touches
|
||||
* @return $this
|
||||
*/
|
||||
public function setTouchedRelations(array $touches)
|
||||
{
|
||||
$this->touches = $touches;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
trait HasTimestamps
|
||||
{
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
/**
|
||||
* Update the model's update timestamp.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function touch()
|
||||
{
|
||||
if (! $this->usesTimestamps()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->updateTimestamps();
|
||||
|
||||
return $this->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the creation and update timestamps.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function updateTimestamps()
|
||||
{
|
||||
$time = $this->freshTimestamp();
|
||||
|
||||
$updatedAtColumn = $this->getUpdatedAtColumn();
|
||||
|
||||
if (! is_null($updatedAtColumn) && ! $this->isDirty($updatedAtColumn)) {
|
||||
$this->setUpdatedAt($time);
|
||||
}
|
||||
|
||||
$createdAtColumn = $this->getCreatedAtColumn();
|
||||
|
||||
if (! $this->exists && ! is_null($createdAtColumn) && ! $this->isDirty($createdAtColumn)) {
|
||||
$this->setCreatedAt($time);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of the "created at" attribute.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function setCreatedAt($value)
|
||||
{
|
||||
$this->{$this->getCreatedAtColumn()} = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of the "updated at" attribute.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function setUpdatedAt($value)
|
||||
{
|
||||
$this->{$this->getUpdatedAtColumn()} = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a fresh timestamp for the model.
|
||||
*
|
||||
* @return \Illuminate\Support\Carbon
|
||||
*/
|
||||
public function freshTimestamp()
|
||||
{
|
||||
return Date::now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a fresh timestamp for the model.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function freshTimestampString()
|
||||
{
|
||||
return $this->fromDateTime($this->freshTimestamp());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the model uses timestamps.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function usesTimestamps()
|
||||
{
|
||||
return $this->timestamps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the "created at" column.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCreatedAtColumn()
|
||||
{
|
||||
return static::CREATED_AT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the "updated at" column.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUpdatedAtColumn()
|
||||
{
|
||||
return static::UPDATED_AT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the fully qualified "created at" column.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getQualifiedCreatedAtColumn()
|
||||
{
|
||||
return $this->qualifyColumn($this->getCreatedAtColumn());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the fully qualified "updated at" column.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getQualifiedUpdatedAtColumn()
|
||||
{
|
||||
return $this->qualifyColumn($this->getUpdatedAtColumn());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Closure;
|
||||
|
||||
trait HidesAttributes
|
||||
{
|
||||
/**
|
||||
* The attributes that should be hidden for serialization.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $hidden = [];
|
||||
|
||||
/**
|
||||
* The attributes that should be visible in serialization.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $visible = [];
|
||||
|
||||
/**
|
||||
* Get the hidden attributes for the model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getHidden()
|
||||
{
|
||||
return $this->hidden;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the hidden attributes for the model.
|
||||
*
|
||||
* @param array $hidden
|
||||
* @return $this
|
||||
*/
|
||||
public function setHidden(array $hidden)
|
||||
{
|
||||
$this->hidden = $hidden;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the visible attributes for the model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getVisible()
|
||||
{
|
||||
return $this->visible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the visible attributes for the model.
|
||||
*
|
||||
* @param array $visible
|
||||
* @return $this
|
||||
*/
|
||||
public function setVisible(array $visible)
|
||||
{
|
||||
$this->visible = $visible;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the given, typically hidden, attributes visible.
|
||||
*
|
||||
* @param array|string|null $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function makeVisible($attributes)
|
||||
{
|
||||
$attributes = is_array($attributes) ? $attributes : func_get_args();
|
||||
|
||||
$this->hidden = array_diff($this->hidden, $attributes);
|
||||
|
||||
if (! empty($this->visible)) {
|
||||
$this->visible = array_merge($this->visible, $attributes);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the given, typically hidden, attributes visible if the given truth test passes.
|
||||
*
|
||||
* @param bool|Closure $condition
|
||||
* @param array|string|null $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function makeVisibleIf($condition, $attributes)
|
||||
{
|
||||
return value($condition, $this) ? $this->makeVisible($attributes) : $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the given, typically visible, attributes hidden.
|
||||
*
|
||||
* @param array|string|null $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function makeHidden($attributes)
|
||||
{
|
||||
$this->hidden = array_merge(
|
||||
$this->hidden, is_array($attributes) ? $attributes : func_get_args()
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the given, typically visible, attributes hidden if the given truth test passes.
|
||||
*
|
||||
* @param bool|Closure $condition
|
||||
* @param array|string|null $attributes
|
||||
* @return $this
|
||||
*/
|
||||
public function makeHiddenIf($condition, $attributes)
|
||||
{
|
||||
return value($condition, $this) ? $this->makeHidden($attributes) : $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Database\Eloquent\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Database\Query\Expression;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
trait QueriesRelationships
|
||||
{
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\Relation|string $relation
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @param string $boolean
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
|
||||
{
|
||||
if (is_string($relation)) {
|
||||
if (strpos($relation, '.') !== false) {
|
||||
return $this->hasNested($relation, $operator, $count, $boolean, $callback);
|
||||
}
|
||||
|
||||
$relation = $this->getRelationWithoutConstraints($relation);
|
||||
}
|
||||
|
||||
if ($relation instanceof MorphTo) {
|
||||
return $this->hasMorph($relation, ['*'], $operator, $count, $boolean, $callback);
|
||||
}
|
||||
|
||||
// If we only need to check for the existence of the relation, then we can optimize
|
||||
// the subquery to only run a "where exists" clause instead of this full "count"
|
||||
// clause. This will make these queries run much faster compared with a count.
|
||||
$method = $this->canUseExistsForExistenceCheck($operator, $count)
|
||||
? 'getRelationExistenceQuery'
|
||||
: 'getRelationExistenceCountQuery';
|
||||
|
||||
$hasQuery = $relation->{$method}(
|
||||
$relation->getRelated()->newQueryWithoutRelationships(), $this
|
||||
);
|
||||
|
||||
// Next we will call any given callback as an "anonymous" scope so they can get the
|
||||
// proper logical grouping of the where clauses if needed by this Eloquent query
|
||||
// builder. Then, we will be ready to finalize and return this query instance.
|
||||
if ($callback) {
|
||||
$hasQuery->callScope($callback);
|
||||
}
|
||||
|
||||
return $this->addHasWhere(
|
||||
$hasQuery, $relation, $operator, $count, $boolean
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add nested relationship count / exists conditions to the query.
|
||||
*
|
||||
* Sets up recursive call to whereHas until we finish the nested relation.
|
||||
*
|
||||
* @param string $relations
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @param string $boolean
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
protected function hasNested($relations, $operator = '>=', $count = 1, $boolean = 'and', $callback = null)
|
||||
{
|
||||
$relations = explode('.', $relations);
|
||||
|
||||
$doesntHave = $operator === '<' && $count === 1;
|
||||
|
||||
if ($doesntHave) {
|
||||
$operator = '>=';
|
||||
$count = 1;
|
||||
}
|
||||
|
||||
$closure = function ($q) use (&$closure, &$relations, $operator, $count, $callback) {
|
||||
// In order to nest "has", we need to add count relation constraints on the
|
||||
// callback Closure. We'll do this by simply passing the Closure its own
|
||||
// reference to itself so it calls itself recursively on each segment.
|
||||
count($relations) > 1
|
||||
? $q->whereHas(array_shift($relations), $closure)
|
||||
: $q->has(array_shift($relations), $operator, $count, 'and', $callback);
|
||||
};
|
||||
|
||||
return $this->has(array_shift($relations), $doesntHave ? '<' : '>=', 1, $boolean, $closure);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with an "or".
|
||||
*
|
||||
* @param string $relation
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orHas($relation, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->has($relation, $operator, $count, 'or');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param string $boolean
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function doesntHave($relation, $boolean = 'and', Closure $callback = null)
|
||||
{
|
||||
return $this->has($relation, '<', 1, $boolean, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with an "or".
|
||||
*
|
||||
* @param string $relation
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orDoesntHave($relation)
|
||||
{
|
||||
return $this->doesntHave($relation, 'or');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with where clauses.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|null $callback
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->has($relation, $operator, $count, 'and', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with where clauses and an "or".
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|null $callback
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->has($relation, $operator, $count, 'or', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with where clauses.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereDoesntHave($relation, Closure $callback = null)
|
||||
{
|
||||
return $this->doesntHave($relation, 'and', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a relationship count / exists condition to the query with where clauses and an "or".
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereDoesntHave($relation, Closure $callback = null)
|
||||
{
|
||||
return $this->doesntHave($relation, 'or', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @param string $boolean
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
|
||||
{
|
||||
if (is_string($relation)) {
|
||||
$relation = $this->getRelationWithoutConstraints($relation);
|
||||
}
|
||||
|
||||
$types = (array) $types;
|
||||
|
||||
if ($types === ['*']) {
|
||||
$types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->filter()->all();
|
||||
}
|
||||
|
||||
foreach ($types as &$type) {
|
||||
$type = Relation::getMorphedModel($type) ?? $type;
|
||||
}
|
||||
|
||||
return $this->where(function ($query) use ($relation, $callback, $operator, $count, $types) {
|
||||
foreach ($types as $type) {
|
||||
$query->orWhere(function ($query) use ($relation, $callback, $operator, $count, $type) {
|
||||
$belongsTo = $this->getBelongsToRelation($relation, $type);
|
||||
|
||||
if ($callback) {
|
||||
$callback = function ($query) use ($callback, $type) {
|
||||
return $callback($query, $type);
|
||||
};
|
||||
}
|
||||
|
||||
$query->where($this->qualifyColumn($relation->getMorphType()), '=', (new $type)->getMorphClass())
|
||||
->whereHas($belongsTo, $callback, $operator, $count);
|
||||
});
|
||||
}
|
||||
}, null, null, $boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the BelongsTo relationship for a single polymorphic type.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo $relation
|
||||
* @param string $type
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
protected function getBelongsToRelation(MorphTo $relation, $type)
|
||||
{
|
||||
$belongsTo = Relation::noConstraints(function () use ($relation, $type) {
|
||||
return $this->model->belongsTo(
|
||||
$type,
|
||||
$relation->getForeignKeyName(),
|
||||
$relation->getOwnerKeyName()
|
||||
);
|
||||
});
|
||||
|
||||
$belongsTo->getQuery()->mergeConstraintsFrom($relation->getQuery());
|
||||
|
||||
return $belongsTo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with an "or".
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orHasMorph($relation, $types, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->hasMorph($relation, $types, $operator, $count, 'or');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param string $boolean
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function doesntHaveMorph($relation, $types, $boolean = 'and', Closure $callback = null)
|
||||
{
|
||||
return $this->hasMorph($relation, $types, '<', 1, $boolean, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with an "or".
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orDoesntHaveMorph($relation, $types)
|
||||
{
|
||||
return $this->doesntHaveMorph($relation, $types, 'or');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with where clauses.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|null $callback
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereHasMorph($relation, $types, Closure $callback = null, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->hasMorph($relation, $types, $operator, $count, 'and', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with where clauses and an "or".
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|null $callback
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereHasMorph($relation, $types, Closure $callback = null, $operator = '>=', $count = 1)
|
||||
{
|
||||
return $this->hasMorph($relation, $types, $operator, $count, 'or', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with where clauses.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereDoesntHaveMorph($relation, $types, Closure $callback = null)
|
||||
{
|
||||
return $this->doesntHaveMorph($relation, $types, 'and', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship count / exists condition to the query with where clauses and an "or".
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|null $callback
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereDoesntHaveMorph($relation, $types, Closure $callback = null)
|
||||
{
|
||||
return $this->doesntHaveMorph($relation, $types, 'or', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a basic where clause to a relationship query.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|string|array|\Illuminate\Database\Query\Expression $column
|
||||
* @param mixed $operator
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereRelation($relation, $column, $operator = null, $value = null)
|
||||
{
|
||||
return $this->whereHas($relation, function ($query) use ($column, $operator, $value) {
|
||||
$query->where($column, $operator, $value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an "or where" clause to a relationship query.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param \Closure|string|array|\Illuminate\Database\Query\Expression $column
|
||||
* @param mixed $operator
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereRelation($relation, $column, $operator = null, $value = null)
|
||||
{
|
||||
return $this->orWhereHas($relation, function ($query) use ($column, $operator, $value) {
|
||||
$query->where($column, $operator, $value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship condition to the query with a where clause.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|string|array|\Illuminate\Database\Query\Expression $column
|
||||
* @param mixed $operator
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereMorphRelation($relation, $types, $column, $operator = null, $value = null)
|
||||
{
|
||||
return $this->whereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) {
|
||||
$query->where($column, $operator, $value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a polymorphic relationship condition to the query with an "or where" clause.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param string|array $types
|
||||
* @param \Closure|string|array|\Illuminate\Database\Query\Expression $column
|
||||
* @param mixed $operator
|
||||
* @param mixed $value
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereMorphRelation($relation, $types, $column, $operator = null, $value = null)
|
||||
{
|
||||
return $this->orWhereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) {
|
||||
$query->where($column, $operator, $value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a morph-to relationship condition to the query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param \Illuminate\Database\Eloquent\Model|string $model
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function whereMorphedTo($relation, $model, $boolean = 'and')
|
||||
{
|
||||
if (is_string($relation)) {
|
||||
$relation = $this->getRelationWithoutConstraints($relation);
|
||||
}
|
||||
|
||||
if (is_string($model)) {
|
||||
$morphMap = Relation::morphMap();
|
||||
|
||||
if (! empty($morphMap) && in_array($model, $morphMap)) {
|
||||
$model = array_search($model, $morphMap, true);
|
||||
}
|
||||
|
||||
return $this->where($relation->getMorphType(), $model, null, $boolean);
|
||||
}
|
||||
|
||||
return $this->where(function ($query) use ($relation, $model) {
|
||||
$query->where($relation->getMorphType(), $model->getMorphClass())
|
||||
->where($relation->getForeignKeyName(), $model->getKey());
|
||||
}, null, null, $boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a morph-to relationship condition to the query with an "or where" clause.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation
|
||||
* @param \Illuminate\Database\Eloquent\Model|string $model
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function orWhereMorphedTo($relation, $model)
|
||||
{
|
||||
return $this->whereMorphedTo($relation, $model, 'or');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include an aggregate value for a relationship.
|
||||
*
|
||||
* @param mixed $relations
|
||||
* @param string $column
|
||||
* @param string $function
|
||||
* @return $this
|
||||
*/
|
||||
public function withAggregate($relations, $column, $function = null)
|
||||
{
|
||||
if (empty($relations)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_null($this->query->columns)) {
|
||||
$this->query->select([$this->query->from.'.*']);
|
||||
}
|
||||
|
||||
$relations = is_array($relations) ? $relations : [$relations];
|
||||
|
||||
foreach ($this->parseWithRelations($relations) as $name => $constraints) {
|
||||
// First we will determine if the name has been aliased using an "as" clause on the name
|
||||
// and if it has we will extract the actual relationship name and the desired name of
|
||||
// the resulting column. This allows multiple aggregates on the same relationships.
|
||||
$segments = explode(' ', $name);
|
||||
|
||||
unset($alias);
|
||||
|
||||
if (count($segments) === 3 && Str::lower($segments[1]) === 'as') {
|
||||
[$name, $alias] = [$segments[0], $segments[2]];
|
||||
}
|
||||
|
||||
$relation = $this->getRelationWithoutConstraints($name);
|
||||
|
||||
if ($function) {
|
||||
$hashedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from
|
||||
? "{$relation->getRelationCountHash(false)}.$column"
|
||||
: $column;
|
||||
|
||||
$wrappedColumn = $this->getQuery()->getGrammar()->wrap(
|
||||
$column === '*' ? $column : $relation->getRelated()->qualifyColumn($hashedColumn)
|
||||
);
|
||||
|
||||
$expression = $function === 'exists' ? $wrappedColumn : sprintf('%s(%s)', $function, $wrappedColumn);
|
||||
} else {
|
||||
$expression = $column;
|
||||
}
|
||||
|
||||
// Here, we will grab the relationship sub-query and prepare to add it to the main query
|
||||
// as a sub-select. First, we'll get the "has" query and use that to get the relation
|
||||
// sub-query. We'll format this relationship name and append this column if needed.
|
||||
$query = $relation->getRelationExistenceQuery(
|
||||
$relation->getRelated()->newQuery(), $this, new Expression($expression)
|
||||
)->setBindings([], 'select');
|
||||
|
||||
$query->callScope($constraints);
|
||||
|
||||
$query = $query->mergeConstraintsFrom($relation->getQuery())->toBase();
|
||||
|
||||
// If the query contains certain elements like orderings / more than one column selected
|
||||
// then we will remove those elements from the query so that it will execute properly
|
||||
// when given to the database. Otherwise, we may receive SQL errors or poor syntax.
|
||||
$query->orders = null;
|
||||
$query->setBindings([], 'order');
|
||||
|
||||
if (count($query->columns) > 1) {
|
||||
$query->columns = [$query->columns[0]];
|
||||
$query->bindings['select'] = [];
|
||||
}
|
||||
|
||||
// Finally, we will make the proper column alias to the query and run this sub-select on
|
||||
// the query builder. Then, we will return the builder instance back to the developer
|
||||
// for further constraint chaining that needs to take place on the query as needed.
|
||||
$alias = $alias ?? Str::snake(
|
||||
preg_replace('/[^[:alnum:][:space:]_]/u', '', "$name $function $column")
|
||||
);
|
||||
|
||||
if ($function === 'exists') {
|
||||
$this->selectRaw(
|
||||
sprintf('exists(%s) as %s', $query->toSql(), $this->getQuery()->grammar->wrap($alias)),
|
||||
$query->getBindings()
|
||||
)->withCasts([$alias => 'bool']);
|
||||
} else {
|
||||
$this->selectSub(
|
||||
$function ? $query : $query->limit(1),
|
||||
$alias
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to count the relations.
|
||||
*
|
||||
* @param mixed $relations
|
||||
* @return $this
|
||||
*/
|
||||
public function withCount($relations)
|
||||
{
|
||||
return $this->withAggregate(is_array($relations) ? $relations : func_get_args(), '*', 'count');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include the max of the relation's column.
|
||||
*
|
||||
* @param string|array $relation
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function withMax($relation, $column)
|
||||
{
|
||||
return $this->withAggregate($relation, $column, 'max');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include the min of the relation's column.
|
||||
*
|
||||
* @param string|array $relation
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function withMin($relation, $column)
|
||||
{
|
||||
return $this->withAggregate($relation, $column, 'min');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include the sum of the relation's column.
|
||||
*
|
||||
* @param string|array $relation
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function withSum($relation, $column)
|
||||
{
|
||||
return $this->withAggregate($relation, $column, 'sum');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include the average of the relation's column.
|
||||
*
|
||||
* @param string|array $relation
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function withAvg($relation, $column)
|
||||
{
|
||||
return $this->withAggregate($relation, $column, 'avg');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add subselect queries to include the existence of related models.
|
||||
*
|
||||
* @param string|array $relation
|
||||
* @return $this
|
||||
*/
|
||||
public function withExists($relation)
|
||||
{
|
||||
return $this->withAggregate($relation, '*', 'exists');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the "has" condition where clause to the query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $hasQuery
|
||||
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @param string $boolean
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
protected function addHasWhere(Builder $hasQuery, Relation $relation, $operator, $count, $boolean)
|
||||
{
|
||||
$hasQuery->mergeConstraintsFrom($relation->getQuery());
|
||||
|
||||
return $this->canUseExistsForExistenceCheck($operator, $count)
|
||||
? $this->addWhereExistsQuery($hasQuery->toBase(), $boolean, $operator === '<' && $count === 1)
|
||||
: $this->addWhereCountQuery($hasQuery->toBase(), $operator, $count, $boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the where constraints from another query to the current query.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $from
|
||||
* @return \Illuminate\Database\Eloquent\Builder|static
|
||||
*/
|
||||
public function mergeConstraintsFrom(Builder $from)
|
||||
{
|
||||
$whereBindings = $from->getQuery()->getRawBindings()['where'] ?? [];
|
||||
|
||||
// Here we have some other query that we want to merge the where constraints from. We will
|
||||
// copy over any where constraints on the query as well as remove any global scopes the
|
||||
// query might have removed. Then we will return ourselves with the finished merging.
|
||||
return $this->withoutGlobalScopes(
|
||||
$from->removedScopes()
|
||||
)->mergeWheres(
|
||||
$from->getQuery()->wheres, $whereBindings
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a sub-query count clause to this query.
|
||||
*
|
||||
* @param \Illuminate\Database\Query\Builder $query
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @param string $boolean
|
||||
* @return $this
|
||||
*/
|
||||
protected function addWhereCountQuery(QueryBuilder $query, $operator = '>=', $count = 1, $boolean = 'and')
|
||||
{
|
||||
$this->query->addBinding($query->getBindings(), 'where');
|
||||
|
||||
return $this->where(
|
||||
new Expression('('.$query->toSql().')'),
|
||||
$operator,
|
||||
is_numeric($count) ? new Expression($count) : $count,
|
||||
$boolean
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the "has relation" base query instance.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return \Illuminate\Database\Eloquent\Relations\Relation
|
||||
*/
|
||||
protected function getRelationWithoutConstraints($relation)
|
||||
{
|
||||
return Relation::noConstraints(function () use ($relation) {
|
||||
return $this->getModel()->{$relation}();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we can run an "exists" query to optimize performance.
|
||||
*
|
||||
* @param string $operator
|
||||
* @param int $count
|
||||
* @return bool
|
||||
*/
|
||||
protected function canUseExistsForExistenceCheck($operator, $count)
|
||||
{
|
||||
return ($operator === '>=' || $operator === '<') && $count === 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user