akaunting/app/Traits/Scopes.php

122 lines
2.9 KiB
PHP
Raw Normal View History

2020-12-26 16:13:34 +03:00
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
2020-12-26 16:13:34 +03:00
trait Scopes
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function applyNotRecurringScope(Builder $builder, Model $model)
2020-12-26 16:13:34 +03:00
{
// Skip if recurring already in query
if ($this->scopeValueExists($builder, 'type', '-recurring')) {
2020-12-27 02:19:50 +03:00
return;
}
// Apply not recurring scope
$builder->isNotRecurring();
}
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function applyNotSplitScope(Builder $builder, Model $model)
{
// Skip if split already in query
if ($this->scopeValueExists($builder, 'type', '-split')) {
2020-12-28 14:50:32 +03:00
return;
}
// Apply not split scope
$builder->isNotSplit();
2020-12-26 16:13:34 +03:00
}
/**
* Check if scope exists.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param $column
* @return boolean
*/
public function scopeColumnExists($builder, $column)
2020-12-26 16:13:34 +03:00
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where) {
if (empty($where) || empty($where['column'])) {
continue;
}
if (strstr($where['column'], '.')) {
$whr = explode('.', $where['column']);
$where['column'] = $whr[1];
}
if ($where['column'] != $column) {
continue;
}
return true;
}
return false;
}
2020-12-26 21:01:11 +03:00
/**
* Check if scope has the exact value.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param $column
* @param $value
* @return boolean
*/
public function scopeValueExists($builder, $column, $value)
2020-12-26 21:01:11 +03:00
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where) {
if (empty($where) || empty($where['column']) || empty($where['value'])) {
continue;
}
if (strstr($where['column'], '.')) {
$whr = explode('.', $where['column']);
$where['column'] = $whr[1];
}
if ($where['column'] != $column) {
continue;
}
2020-12-26 21:01:11 +03:00
if (! Str::endsWith($where['value'], $value)) {
continue;
}
return true;
}
return false;
2020-12-26 21:01:11 +03:00
}
// @deprecated version 3.0.0
public function scopeExists($builder, $column)
{
return $this->scopeColumnExists($builder, $column);
}
2020-12-26 16:13:34 +03:00
}