Skip to content

Instantly share code, notes, and snippets.

@sunnysideup
Last active October 26, 2022 01:25
Show Gist options
  • Save sunnysideup/eb2c518a979e60cb15e7ac3b26430bfa to your computer and use it in GitHub Desktop.
Save sunnysideup/eb2c518a979e60cb15e7ac3b26430bfa to your computer and use it in GitHub Desktop.
Log Runnner - running only a few at the time for Silverstripe
<?php
namespace MyAmazingWebsite\App\Model\Logs;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Flushable;
class LogRunnerCache extends DataObject implements Flushable
{
private static $table_name = 'LogRunnerCache';
private static $db = [
'Title' => 'Varchar',
'Ids' => 'Text',
];
private static $indexes = [
'Title' => true,
];
public function canCreate($member = null, $context = [])
{
return false;
}
public function canEdit($member = null)
{
return false;
}
public function canDelete($member = null)
{
return false;
}
public static function queue_list(DataList $list, string $functionName)
{
$originalList = $list;
$list = $list->exclude(['ID' => self::get_ids($functionName)]);
if($list->count() === 0) {
self::clear($functionName);
return $originalList;
} else {
self::add_ids($functionName, $list->columnUnique('ID'));
return $list;
}
}
public static function clear_all() : void
{
$objects = LogRunnerCache::get();
foreach($objects as $obj) {
$obj->delete();
}
}
public static function clear(string $functionName) : void
{
$objects = LogRunnerCache::get()->filter(['Title' => $functionName]);
foreach($objects as $obj) {
$obj->delete();
}
}
private static function get_ids(string $functionName) : array
{
$obj = self::get_object_by_fx($functionName);
return array_filter(array_unique(explode(',', $obj->Ids))) + [-1 => 0];
}
private static function add_ids(string $functionName, array $ids)
{
$obj = self::get_object_by_fx($functionName);
$oldIds = self::get_ids($functionName);
$newIds = array_filter(array_unique(array_merge($oldIds, $ids)));
if(empty($newIds)) {
$newIds = [-1 => 0];
}
$obj->Ids = implode(',', $newIds);
$obj->write();
}
private static function get_object_by_fx(string $functionName) : LogRunnerCache
{
$filter = ['Title' => $functionName];
$obj = LogRunnerCache::get()->filter($filter)->first();
if(! $obj) {
$obj = LogRunnerCache::create($filter);
$obj->write();
}
return $obj;
}
public static function flush()
{
$tables = DB::table_list();
if(array_key_exists(strtolower('LogRunnerCache'), $tables)) {
self::clear_all();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment