Maslosoft Manganel API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
<?php
/**
* This software package is licensed under `AGPL, Commercial` license[s].
*
* @package maslosoft/manganel
* @license AGPL, Commercial
*
* @copyright Copyright (c) Peter Maselkowski <pmaselkowski@gmail.com>
* @link https://maslosoft.com/manganel/
*/
namespace Maslosoft\Manganel\Traits;
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
/**
* Use this trait to provide mutli-model feature to classes.
*
* NOTE: It will keep only one instance type in models
*
* @author Piotr Maselkowski <pmaselkowski at gmail.com>
*/
trait UniqueModelsAwareTrait
{
/**
* Annotated model
* @var AnnotatedInterface[]
*/
private $models = [];
/**
* Annotated models
* @var AnnotatedInterface[]
*/
public function getModels()
{
return $this->models;
}
/**
*
* @param AnnotatedInterface[] $models
* @return $this
*/
public function setModels($models)
{
// Unique based on class name
// See: http://stackoverflow.com/a/2561283/5444623
$map = function($value)
{
if (is_object($value))
{
return get_class($value);
}
return $value;
};
$unique = array_intersect_key($models, array_unique(array_map($map, $models)));
$this->models = array_values($unique);
return $this;
}
/**
* Add model to set but only if it's instance is not present in set.
*
* @param AnnotatedInterface $model
* @return boolean Whether model was added
*/
public function addModel(AnnotatedInterface $model)
{
if (!$this->hasModel($model))
{
$this->models[] = $model;
return true;
}
return false;
}
/**
* Remove model from set.
*
* @param AnnotatedInterface $model
* @return boolean Whether model was removed
*/
public function removeModel(AnnotatedInterface $model)
{
if (!$this->hasModel($model))
{
return false;
}
foreach ($this->models as $index => $existing)
{
if (get_class($existing) === get_class($model))
{
unset($this->models[$index]);
return true;
}
}
// Should not happen, model not found even if should exists
return false;
}
public function hasModel(AnnotatedInterface $model)
{
foreach ($this->models as $existing)
{
if (get_class($existing) === get_class($model))
{
return true;
}
}
return false;
}
}
API documentation generated by ApiGen