silverstripe-framework/src/Security/InheritedPermissionFlusher.php

105 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Security;
use Psr\Log\InvalidArgumentException;
use SilverStripe\Core\Flushable;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
2017-12-07 04:07:40 +01:00
use SilverStripe\Core\Cache\MemberCacheFlusher;
class InheritedPermissionFlusher extends DataExtension implements Flushable
{
/**
2017-12-07 04:12:05 +01:00
* @var MemberCacheFlusher[]
*/
protected $services = [];
/**
* Flush all CacheFlusher services
*/
public static function flush()
{
singleton(__CLASS__)->flushCache();
}
/**
* @param DataObject $owner
*/
public function setOwner($owner)
{
if (!$owner instanceof Member && !$owner instanceof Group) {
throw new InvalidArgumentException(sprintf(
'%s can only be applied to %s or %s',
__CLASS__,
Member::class,
Group::class
));
}
parent::setOwner($owner);
}
/**
2017-12-07 04:12:05 +01:00
* @param MemberCacheFlusher[]
2017-12-06 10:03:05 +01:00
* @throws InvalidArgumentException
* @return $this
*/
public function setServices($services)
{
foreach ($services as $service) {
2017-12-07 04:07:40 +01:00
if (!$service instanceof MemberCacheFlusher) {
throw new InvalidArgumentException(sprintf(
'%s.services must contain only %s instances. %s provided.',
__CLASS__,
2017-12-07 04:07:40 +01:00
MemberCacheFlusher::class,
get_class($service)
));
}
}
$this->services = $services;
2017-12-06 10:03:05 +01:00
return $this;
}
/**
2017-12-07 04:12:05 +01:00
* @return MemberCacheFlusher[]
*/
public function getServices()
{
return $this->services;
}
/**
2017-12-07 04:12:05 +01:00
* Flushes all registered MemberCacheFlusher services
*/
public function flushCache()
{
$ids = $this->getMemberIDList();
2017-12-11 04:46:21 +01:00
foreach ($this->getServices() as $service) {
2017-12-07 04:07:40 +01:00
$service->flushMemberCache($ids);
}
}
/**
* Get a list of member IDs that need their permissions flushed
*
* @return array|null
*/
protected function getMemberIDList()
{
2017-12-06 10:03:05 +01:00
if (!$this->owner || !$this->owner->exists()) {
return null;
}
if ($this->owner instanceof Group) {
return $this->owner->Members()->exists()
? $this->owner->Members()->column('ID')
: null;
}
return [$this->owner->ID];
}
2017-12-11 04:46:21 +01:00
}