Initial Release
This commit is contained in:
62
src/Traits/CollectionCollapse.php
Normal file
62
src/Traits/CollectionCollapse.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Collapse a collection, by summing up fields.
|
||||
*/
|
||||
namespace Leenooks\Traits;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
trait CollectionCollapse {
|
||||
/**
|
||||
* Collapse a collection by summing up records according to a given key
|
||||
*
|
||||
* @param Collection $c Collection to collapse
|
||||
* @param array $id To use as the group by key
|
||||
* @param array $consolidateKeys Keys that should be summed up during the process
|
||||
* @return Collection
|
||||
*/
|
||||
protected function collapse(Collection $c,array $id,array $consolidateKeys=[])
|
||||
{
|
||||
return $c->groupBy(function ($item,$key) use ($id) {
|
||||
$string = '';
|
||||
|
||||
foreach ($id as $key) {
|
||||
if ($string AND array_get($item,$key))
|
||||
$string .= '.';
|
||||
|
||||
$string .= $item[$key];
|
||||
}
|
||||
|
||||
return $string;
|
||||
|
||||
})->transform(function ($items,$key) use ($consolidateKeys) {
|
||||
$newitem = [];
|
||||
|
||||
if ($items->count()) {
|
||||
$c = 0;
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (! $c++) {
|
||||
$newitem = $item;
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($item as $k => $v) {
|
||||
// Add these values to the existing ones
|
||||
if (in_array($k, $consolidateKeys)) {
|
||||
if (!isset($newitem[$k]))
|
||||
$newitem[$k] = 0;
|
||||
$newitem[$k] += $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
$newitem = $items;
|
||||
}
|
||||
|
||||
return $newitem;
|
||||
});
|
||||
}
|
||||
}
|
19
src/Traits/ModelCache.php
Normal file
19
src/Traits/ModelCache.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Traits adds our standing cache functions
|
||||
*/
|
||||
namespace Leenooks\Traits;
|
||||
|
||||
trait ModelCache
|
||||
{
|
||||
// Time to cache calculations for
|
||||
private $cachetime = 10080; // a week
|
||||
|
||||
/**
|
||||
* Auto calculate a cache key
|
||||
*/
|
||||
private function cachekey($method,$one,$two=NULL) {
|
||||
return md5(sprintf('%s:%s:%s',$method,$one,$two ? $two : $this->id));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user