openstamanager/src/Traits/LocalPoolTrait.php

114 lines
2.9 KiB
PHP
Raw Normal View History

<?php
2020-09-07 15:04:06 +02:00
/*
* OpenSTAManager: il software gestionale open source per l'assistenza tecnica e la fatturazione
2021-01-20 15:08:51 +01:00
* Copyright (C) DevCode s.r.l.
2020-09-07 15:04:06 +02:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Traits;
use Illuminate\Support\Collection;
trait LocalPoolTrait
{
/** @var Collection Collezione degli oggetti disponibili */
protected static $collection = null;
/** @var bool Controllo sul salvataggio globale */
protected static $all = false;
2018-09-05 10:36:41 +02:00
/** @var int Identificatore dell'oggetto in utilizzo */
protected static $current;
/** @var string Nome della colonna "id" (Primary Key) */
protected static $id = 'id';
/** @var string Nome della colonna "name" */
protected static $name = 'name';
/**
* Restituisce tutti gli oggetti.
*
* @return Collection
*/
public static function getAll()
{
if (!self::$all) {
self::$collection = self::all();
self::$all = true;
}
return self::$collection;
}
/**
* Restituisce l'oggetto relativo all'identificativo specificato.
*
* @param string|int $identifier
*
* @return static
*/
public static function pool($identifier)
{
// Inizializzazione
if (!isset(self::$collection)) {
self::$collection = collect();
}
// Ricerca
$result = self::$collection->first(function ($item) use ($identifier) {
return $item->{self::$name} == $identifier || $item->{self::$id} == $identifier;
});
if (!empty($result)) {
return $result;
}
// Consultazione Database
$result = self::where(self::$id, $identifier)
->orWhere(self::$name, $identifier)
->first();
2019-07-30 16:50:10 +02:00
if (!empty($result)) {
self::$collection->push($result);
}
return $result;
}
2018-09-05 10:36:41 +02:00
/**
* Restituisce l'oggetto attualmente impostato.
*
* @return static
2018-09-05 10:36:41 +02:00
*/
public static function getCurrent()
{
2018-09-25 16:47:44 +02:00
if (!isset(self::$current)) {
2018-09-19 10:44:32 +02:00
return null;
}
return self::pool(self::$current);
2018-09-05 10:36:41 +02:00
}
/**
* Imposta il modulo attualmente in utilizzo.
*
* @param int $id
*/
public static function setCurrent($id)
{
self::$current = $id;
}
}