gravatar bug fixes

This commit is contained in:
sujitprasad
2015-12-01 16:45:35 +05:30
parent 8806809114
commit 29c1cd1826
47 changed files with 5295 additions and 3 deletions

View File

@@ -0,0 +1,553 @@
<?php namespace Chumper\Datatable\Engines;
use Exception;
use Assetic\Extension\Twig\AsseticFilterFunction;
use Chumper\Datatable\Columns\DateColumn;
use Chumper\Datatable\Columns\FunctionColumn;
use Chumper\Datatable\Columns\TextColumn;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Config;
/**
* Class BaseEngine
* @package Chumper\Datatable\Engines
*/
abstract class BaseEngine {
const ORDER_ASC = 'asc';
const ORDER_DESC = 'desc';
/**
* @var array
*/
protected $config = array();
/**
* @var mixed
*/
protected $rowClass = null;
/**
* @var mixed
*/
protected $rowId = null;
/**
* @var array
*/
protected $rowData = null;
/**
* @var array
*/
protected $columnSearches = array();
/**
* @var array
* support for DB::raw fields on where
*/
protected $fieldSearches = array();
/**
* @var array
* support for DB::raw fields on where
* sburkett - added for column-based exact matching
*/
protected $columnSearchExact = array();
/**
* @var
*/
protected $sEcho;
/**
* @var \Illuminate\Support\Collection
*/
protected $columns;
/**
* @var array
*/
protected $searchColumns = array();
/**
* @var array
*/
protected $showColumns = array();
/**
* @var array
*/
protected $orderColumns = array();
/**
* @var int
*/
protected $skip = 0;
/**
* @var null
*/
protected $limit = null;
/**
* @var null
*/
protected $search = null;
/**
* @var null
* Will be an array if order is set
* array(
* 0 => column
* 1 => name:cast:length
* )
*/
protected $orderColumn = null;
/**
* @var string
*/
protected $orderDirection = BaseEngine::ORDER_ASC;
/**
* @var boolean If the return should be alias mapped
*/
protected $aliasMapping = false;
/**
* @var bool If the search should be done with exact matching
*/
protected $exactWordSearch = false;
function __construct()
{
$this->columns = new Collection();
$this->config = Config::get('chumper.datatable.engine');
$this->setExactWordSearch( $this->config['exactWordSearch'] );
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function addColumn()
{
if(func_num_args() != 2 && func_num_args() != 1)
throw new Exception('Invalid number of arguments');
if(func_num_args() == 1)
{
//add a predefined column
$this->columns->put(func_get_arg(0)->getName(), func_get_arg(0));
}
else if(is_callable(func_get_arg(1)))
{
$this->columns->put(func_get_arg(0), new FunctionColumn(func_get_arg(0), func_get_arg(1)));
}
else
{
$this->columns->put(func_get_arg(0), new TextColumn(func_get_arg(0),func_get_arg(1)));
}
return $this;
}
/**
* @param $name
* @return mixed
*/
public function getColumn($name)
{
return $this->columns->get($name,null);
}
/**
* @return array
*/
public function getOrder()
{
return array_keys($this->columns->toArray());
}
/**
* @return array
*/
public function getOrderingColumns()
{
return $this->orderColumns;
}
/**
* @return array
*/
public function getSearchingColumns()
{
return $this->searchColumns;
}
/**
* @return $this
*/
public function clearColumns()
{
$this->columns = new Collection();
return $this;
}
/**
* @param $cols
* @return $this
*/
public function showColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
foreach ($cols as $property) {
//quick fix for created_at and updated_at columns
if(in_array($property, array('created_at', 'updated_at')))
{
$this->columns->put($property, new DateColumn($property, DateColumn::DAY_DATE));
}
else
{
$this->columns->put($property, new FunctionColumn($property, function($model) use($property){
try{return is_array($model)?$model[$property]:$model->$property;}catch(Exception $e){return null;}
}));
}
$this->showColumns[] = $property;
}
return $this;
}
/**
* @return \Illuminate\Http\JsonResponse
*/
public function make()
{
//TODO Handle all inputs
$this->handleInputs();
$this->prepareSearchColumns();
$output = array(
"aaData" => $this->internalMake($this->columns, $this->searchColumns)->toArray(),
"sEcho" => intval($this->sEcho),
"iTotalRecords" => $this->totalCount(),
"iTotalDisplayRecords" => $this->count(),
);
return Response::json($output);
}
/**
* @param $cols
* @return $this
*/
public function searchColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
$this->searchColumns = $cols;
return $this;
}
/**
* @param $cols
* @return $this
*/
public function orderColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
if (count($cols) == 1 && $cols[0] == '*')
$cols = $this->showColumns;
$this->orderColumns = $cols;
return $this;
}
/**
* @param $function Set a function for a dynamic row class
* @return $this
*/
public function setRowClass($function)
{
$this->rowClass = $function;
return $this;
}
/**
* @param $function Set a function for a dynamic row id
* @return $this
*/
public function setRowId($function)
{
$this->rowId = $function;
return $this;
}
/**
* @param $function Set a function for dynamic html5 data attributes
* @return $this
*/
public function setRowData($function)
{
$this->rowData = $function;
return $this;
}
public function setAliasMapping($value = true)
{
$this->aliasMapping = $value;
return $this;
}
public function setExactWordSearch($value = true)
{
$this->exactWordSearch = $value;
return $this;
}
/**
* @param $columnNames Sets up a lookup table for which columns should use exact matching -sburkett
* @return $this
*/
public function setExactMatchColumns($columnNames)
{
foreach($columnNames as $columnIndex)
$this->columnSearchExact[ $columnIndex ] = true;
return $this;
}
public function getRowClass()
{
return $this->rowClass;
}
public function getRowId()
{
return $this->rowId;
}
public function getRowData()
{
return $this->rowData;
}
public function getAliasMapping()
{
return $this->aliasMapping;
}
//-------------protected functionS-------------------
/**
* @param $value
*/
protected function handleiDisplayStart($value)
{
//skip
$this->skip($value);
}
/**
* @param $value
*/
protected function handleiDisplayLength($value)
{
//limit nicht am query, sondern den ganzen
//holen und dann dynamisch in der Collection taken und skippen
$this->take($value);
}
/**
* @param $value
*/
protected function handlesEcho($value)
{
$this->sEcho = $value;
}
/**
* @param $value
*/
protected function handlesSearch($value)
{
//handle search on columns sSearch, bRegex
$this->search($value);
}
/**
* @param $value
*/
protected function handleiSortCol_0($value)
{
if(Input::get('sSortDir_0') == 'desc')
$direction = BaseEngine::ORDER_DESC;
else
$direction = BaseEngine::ORDER_ASC;
//check if order is allowed
if(empty($this->orderColumns))
{
$this->order(array(0 => $value, 1 => $this->getNameByIndex($value)), $direction);
return;
}
//prepare order array
$cleanNames = array();
foreach($this->orderColumns as $c)
{
if(strpos($c,':') !== FALSE)
{
$cleanNames[] = substr($c, 0, strpos($c,':'));
}
else
{
$cleanNames[] = $c;
}
}
$i = 0;
foreach($this->columns as $name => $column)
{
if($i == $value && in_array($name, $cleanNames))
{
$this->order(array(0 => $value, 1 => $this->orderColumns[array_search($name,$cleanNames)]), $direction);
return;
}
$i++;
}
}
/**
* @param int $columnIndex
* @param string $searchValue
*
* @return void
*/
protected function handleSingleColumnSearch($columnIndex, $searchValue)
{
//dd($columnIndex, $searchValue, $this->searchColumns);
if (!isset($this->searchColumns[$columnIndex])) return;
if (empty($searchValue) && $searchValue !== '0') return;
$columnName = $this->searchColumns[$columnIndex];
$this->searchOnColumn($columnName, $searchValue);
}
/**
*
*/
protected function handleInputs()
{
//Handle all inputs magically
foreach (Input::all() as $key => $input) {
// handle single column search
if ($this->isParameterForSingleColumnSearch($key))
{
$columnIndex = str_replace('sSearch_','',$key);
$this->handleSingleColumnSearch($columnIndex, $input);
continue;
}
if(method_exists($this, $function = 'handle'.$key))
$this->$function($input);
}
}
/**
* @param $parameterName
*
* @return bool
*/
protected function isParameterForSingleColumnSearch($parameterName)
{
static $parameterNamePrefix = 'sSearch_';
return str_contains($parameterName, $parameterNamePrefix);
}
protected function prepareSearchColumns()
{
if(count($this->searchColumns) == 0 || empty($this->searchColumns))
$this->searchColumns = $this->showColumns;
}
/**
* @param $column
* @param $order
*/
protected function order($column, $order = BaseEngine::ORDER_ASC)
{
$this->orderColumn = $column;
$this->orderDirection = $order;
}
/**
* @param $value
*/
protected function search($value)
{
$this->search = $value;
}
/**
* @param string $columnName
* @param mixed $value
*/
protected function searchOnColumn($columnName, $value)
{
$this->fieldSearches[] = $columnName;
$this->columnSearches[] = $value;
}
/**
* @param $value
*/
protected function skip($value)
{
$this->skip = $value;
}
/**
* @param $value
*/
protected function take($value)
{
$this->limit = $value;
}
public function getNameByIndex($index)
{
$i = 0;
foreach($this->columns as $name => $col)
{
if($index == $i)
{
return $name;
}
$i++;
}
}
public function getExactWordSearch()
{
return $this->exactWordSearch;
}
abstract protected function totalCount();
abstract protected function count();
abstract protected function internalMake(Collection $columns, array $searchColumns = array());
}

View File

@@ -0,0 +1,309 @@
<?php namespace Chumper\Datatable\Engines;
use Illuminate\Support\Collection;
/**
* This handles the collections,
* it needs to compile first, so we wait for the make command and then
* do all the operations
*
* Class CollectionEngine
* @package Chumper\Datatable\Engines
*/
class CollectionEngine extends BaseEngine {
/**
* Constant for OR queries in internal search
* @var string
*/
const OR_CONDITION = 'OR';
/**
* Constant for AND queries in internal search
* @var string
*/
const AND_CONDITION = 'AND';
/**
* @var \Illuminate\Support\Collection
*/
private $workingCollection;
/**
* @var \Illuminate\Support\Collection
*/
private $collection;
/**
* @var array Different options
*/
private $options = array(
'stripOrder' => false,
'stripSearch' => false,
'caseSensitive' => false,
);
/**
* @param Collection $collection
*/
function __construct(Collection $collection)
{
parent::__construct();
$this->collection = $collection;
$this->workingCollection = $collection;
}
/**
* @return int
*/
public function count()
{
return $this->workingCollection->count();
}
/**
* @return int
*/
public function totalCount()
{
return $this->collection->count();
}
/**
* @return array
*/
public function getArray()
{
$this->handleInputs();
$this->compileArray($this->columns);
$this->doInternalSearch(new Collection(), array());
$this->doInternalOrder();
return array_values($this->workingCollection
->slice($this->skip,$this->limit)
->toArray()
);
}
/**
* Resets all operations performed on the collection
*/
public function reset()
{
$this->workingCollection = $this->collection;
return $this;
}
public function stripSearch()
{
$this->options['stripSearch'] = true;
return $this;
}
public function stripOrder($callback = true)
{
$this->options['stripOrder'] = $callback;
return $this;
}
public function setSearchStrip()
{
$this->options['stripSearch'] = true;
return $this;
}
public function setOrderStrip($callback = true)
{
return $this->stripOrder($callback);
}
public function setCaseSensitive($value)
{
$this->options['caseSensitive'] = $value;
return $this;
}
public function getOption($value)
{
return $this->options[$value];
}
//--------------PRIVATE FUNCTIONS-----------------
protected function internalMake(Collection $columns, array $searchColumns = array())
{
$this->compileArray($columns);
$this->doInternalSearch($columns, $searchColumns);
$this->doInternalOrder();
return $this->workingCollection->slice($this->skip,$this->limit);
}
/**
* Filter a collection based on the DataTables search parameters (sSearch_0 etc)
* See http://legacy.datatables.net/usage/server-side
*
* @param Collection $columns All the columns in the DataTable
* @param array $searchColumns Columns to search on - values are case-sensitive (must match definition from $columns)
*/
private function doInternalSearch(Collection $columns, array $searchColumns)
{
if((is_null($this->search) || empty($this->search)) && empty($this->fieldSearches))
return;
$value = $this->search;
$caseSensitive = $this->options['caseSensitive'];
$toSearch = array();
$searchType = self::AND_CONDITION;
// Map the searchColumns to the real columns
$ii = 0;
foreach($columns as $i => $col)
{
if(in_array($columns->get($i)->getName(), $searchColumns) || in_array($columns->get($i)->getName(), $this->fieldSearches))
{
// map values to columns, where there is no value use the global value
if(($field = array_search($columns->get($i)->getName(), $this->fieldSearches)) !== FALSE)
{
$toSearch[$ii] = $this->columnSearches[$field];
}
else
{
if($value)
$searchType = self::OR_CONDITION;
$toSearch[$ii] = $value;
}
}
$ii++;
}
$self = $this;
$this->workingCollection = $this->workingCollection->filter(function($row) use ($toSearch, $caseSensitive, $self, $searchType)
{
for($i=0, $stack=array(), $nb=count($row); $i<$nb; $i++)
{
if(!array_key_exists($i, $toSearch))
continue;
$column = $i;
if($self->getAliasMapping())
{
$column = $self->getNameByIndex($i);
}
if($self->getOption('stripSearch'))
{
$search = strip_tags($row[$column]);
}
else
{
$search = $row[$column];
}
if($caseSensitive)
{
if($self->exactWordSearch)
{
if($toSearch[$i] === $search)
$stack[$i] = true;
}
else
{
if(str_contains($search,$toSearch[$i]))
$stack[$i] = true;
}
}
else
{
if($self->getExactWordSearch())
{
if(mb_strtolower($toSearch[$i]) === mb_strtolower($search))
$stack[$i] = true;
}
else
{
if(str_contains(mb_strtolower($search),mb_strtolower($toSearch[$i])))
$stack[$i] = true;
}
}
}
if($searchType == $self::AND_CONDITION)
{
$result = array_diff_key(array_filter($toSearch), $stack);
if(empty($result))
return true;
}
else
{
if(!empty($stack))
return true;
}
});
}
private function doInternalOrder()
{
if(is_null($this->orderColumn))
return;
$column = $this->orderColumn[0];
$stripOrder = $this->options['stripOrder'];
$self = $this;
$this->workingCollection = $this->workingCollection->sortBy(function($row) use ($column,$stripOrder,$self) {
if($self->getAliasMapping())
{
$column = $self->getNameByIndex($column);
}
if($stripOrder)
{
if(is_callable($stripOrder)){
return $stripOrder($row, $column);
}else{
return strip_tags($row[$column]);
}
}
else
{
return $row[$column];
}
}, SORT_NATURAL);
if($this->orderDirection == BaseEngine::ORDER_DESC)
$this->workingCollection = $this->workingCollection->reverse();
}
private function compileArray($columns)
{
$self = $this;
$this->workingCollection = $this->collection->map(function($row) use ($columns, $self) {
$entry = array();
// add class and id if needed
if(!is_null($self->getRowClass()) && is_callable($self->getRowClass()))
{
$entry['DT_RowClass'] = call_user_func($self->getRowClass(),$row);
}
if(!is_null($self->getRowId()) && is_callable($self->getRowId()))
{
$entry['DT_RowId'] = call_user_func($self->getRowId(),$row);
}
if(!is_null($self->getRowData()) && is_callable($self->getRowData()))
{
$entry['DT_RowData'] = call_user_func($self->getRowData(),$row);
}
$i=0;
foreach ($columns as $col)
{
if($self->getAliasMapping())
{
$entry[$col->getName()] = $col->run($row);
}
else
{
$entry[$i] = $col->run($row);
}
$i++;
}
return $entry;
});
}
}

View File

@@ -0,0 +1,306 @@
<?php namespace Chumper\Datatable\Engines;
use Chumper\Datatable\Datatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;
class QueryEngine extends BaseEngine {
/**
* @var Builder
*/
public $builder;
/**
* @var Builder
*/
public $originalBuilder;
/**
* @var array single column searches
*/
public $columnSearches = array();
/**
* @var Collection the returning collection
*/
private $resultCollection;
/**
* @var Collection the resulting collection
*/
private $collection = null;
/**
* @var array Different options
*/
protected $options = array(
'searchOperator' => 'LIKE',
'searchWithAlias' => false,
'orderOrder' => null,
'counter' => 0,
'noGroupByOnCount' => false,
);
function __construct($builder)
{
parent::__construct();
if($builder instanceof Relation)
{
$this->builder = $builder->getBaseQuery();
$this->originalBuilder = clone $builder->getBaseQuery();
}
else
{
$this->builder = $builder;
$this->originalBuilder = clone $builder;
}
}
public function count()
{
return $this->options['counter'];
}
public function totalCount()
{
// Store temporary copy as we may modify it, we'd be stupid to modify
// the actual "original" copy...
$originalBuilder = $this->originalBuilder;
if ($this->options['noGroupByOnCount']) {
$originalBuilder = $this->removeGroupBy($originalBuilder);
}
return $originalBuilder->count();
}
public function getArray()
{
return $this->getCollection($this->builder)->toArray();
}
public function reset()
{
$this->builder = $this->originalBuilder;
return $this;
}
public function setSearchOperator($value = "LIKE")
{
$this->options['searchOperator'] = $value;
return $this;
}
public function setSearchWithAlias()
{
$this->options['searchWithAlias'] = true;
return $this;
}
public function setNoGroupByOnCount()
{
$this->options['noGroupByOnCount'] = true;
return $this;
}
//--------PRIVATE FUNCTIONS
protected function internalMake(Collection $columns, array $searchColumns = array())
{
$builder = clone $this->builder;
$countBuilder = clone $this->builder;
$builder = $this->doInternalSearch($builder, $searchColumns);
$countBuilder = $this->doInternalSearch($countBuilder, $searchColumns);
if($this->options['searchWithAlias'])
{
$this->options['counter'] = count($countBuilder->get());
}
else
{
// Remove the GROUP BY clause for the count
if ($this->options['noGroupByOnCount']) {
$countBuilder = $this->removeGroupBy($countBuilder);
}
$this->options['counter'] = $countBuilder->count();
}
$builder = $this->doInternalOrder($builder, $columns);
$collection = $this->compile($builder, $columns);
return $collection;
}
/**
* Remove the GROUP BY clause from a builder.
*
* @param Builder|QueryBuilder $builder
* @return Builder|QueryBuilder $builder with the groups property set to null.
*/
private function removeGroupBy($builder)
{
// Handle \Illuminate\Database\Eloquent\Builder
if ($builder instanceof Builder) {
$query = $builder->getQuery();
$query->groups = null;
$builder->setQuery($query);
}
// Handle \Illuminate\Database\Query\Builder
else {
$builder->groups = null;
}
return $builder;
}
/**
* @param $builder
* @return Collection
*/
private function getCollection($builder)
{
if($this->collection == null)
{
if($this->skip > 0)
{
$builder = $builder->skip($this->skip);
}
if($this->limit > 0)
{
$builder = $builder->take($this->limit);
}
//dd($this->builder->toSql());
$this->collection = $builder->get();
if(is_array($this->collection))
$this->collection = new Collection($this->collection);
}
return $this->collection;
}
private function doInternalSearch($builder, $columns)
{
if (!empty($this->search)) {
$this->buildSearchQuery($builder, $columns);
}
if (!empty($this->columnSearches)) {
$this->buildSingleColumnSearches($builder);
}
return $builder;
}
protected function buildSearchQuery($builder, $columns)
{
$like = $this->options['searchOperator'];
$search = $this->search;
$exact = $this->exactWordSearch;
$builder = $builder->where(function($query) use ($columns, $search, $like, $exact) {
foreach ($columns as $c) {
//column to search within relationships : relatedModel::column
if(strrpos($c, '::')) {
$c = explode('::', $c);
$query->orWhereHas($c[0], function($q) use($c, $like, $exact, $search){
$q->where($c[1], $like, $exact ? $search : '%' . $search . '%');
});
}
//column to CAST following the pattern column:newType:[maxlength]
elseif(strrpos($c, ':')){
$c = explode(':', $c);
if(isset($c[2]))
$c[1] .= "($c[2])";
$query->orWhereRaw("cast($c[0] as $c[1]) ".$like." ?", array($exact ? "$search" : "%$search%"));
}
else
$query->orWhere($c, $like, $exact ? $search : '%' . $search . '%');
}
});
return $builder;
}
/**
* @param $builder
* Modified by sburkett to facilitate individual exact match searching on individual columns (rather than for all columns)
*/
private function buildSingleColumnSearches($builder)
{
foreach ($this->columnSearches as $index => $searchValue) {
if(@$this->columnSearchExact[ $this->fieldSearches[$index] ] == 1) {
$builder->where($this->fieldSearches[$index], '=', $searchValue );
} else {
$builder->where($this->fieldSearches[$index], $this->options['searchOperator'], '%' . $searchValue . '%');
}
}
}
private function compile($builder, $columns)
{
$this->resultCollection = $this->getCollection($builder);
$self = $this;
$this->resultCollection = $this->resultCollection->map(function($row) use ($columns,$self) {
$entry = array();
// add class and id if needed
if(!is_null($self->getRowClass()) && is_callable($self->getRowClass()))
{
$entry['DT_RowClass'] = call_user_func($self->getRowClass(),$row);
}
if(!is_null($self->getRowId()) && is_callable($self->getRowId()))
{
$entry['DT_RowId'] = call_user_func($self->getRowId(),$row);
}
if(!is_null($self->getRowData()) && is_callable($self->getRowData()))
{
$entry['DT_RowData'] = call_user_func($self->getRowData(),$row);
}
$i = 0;
foreach ($columns as $col)
{
if($self->getAliasMapping())
{
$entry[$col->getName()] = $col->run($row);
}
else
{
$entry[$i] = $col->run($row);
}
$i++;
}
return $entry;
});
return $this->resultCollection;
}
private function doInternalOrder($builder, $columns)
{
//var_dump($this->orderColumn);
if(!is_null($this->orderColumn))
{
$i = 0;
foreach($columns as $col)
{
if($i === (int) $this->orderColumn[0])
{
if(strrpos($this->orderColumn[1], ':')){
$c = explode(':', $this->orderColumn[1]);
if(isset($c[2]))
$c[1] .= "($c[2])";
$builder = $builder->orderByRaw("cast($c[0] as $c[1]) ".$this->orderDirection);
}
else
$builder = $builder->orderBy($col->getName(), $this->orderDirection);
return $builder;
}
$i++;
}
}
return $builder;
}
}