Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
+2
View File
@@ -1,3 +1,5 @@
vendor/
composer.lock
phpunit.xml
.phpunit.result.cache
.php_cs.cache
+34 -56
View File
@@ -12,8 +12,7 @@
namespace Symfony\Component\Security\Acl\Dbal;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Doctrine\DBAL\Result;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\Entry;
use Symfony\Component\Security\Acl\Domain\FieldEntry;
@@ -23,6 +22,7 @@ use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException;
use Symfony\Component\Security\Acl\Model\AclCacheInterface;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Symfony\Component\Security\Acl\Model\AclProviderInterface;
use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
use Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface;
@@ -47,8 +47,8 @@ class AclProvider implements AclProviderInterface
* @var Connection
*/
protected $connection;
protected $loadedAces = array();
protected $loadedAcls = array();
protected $loadedAces = [];
protected $loadedAcls = [];
protected $options;
/**
@@ -59,10 +59,7 @@ class AclProvider implements AclProviderInterface
/**
* Constructor.
*
* @param Connection $connection
* @param PermissionGrantingStrategyInterface $permissionGrantingStrategy
* @param array $options
* @param AclCacheInterface $cache
* @param AclCacheInterface $cache
*/
public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $cache = null)
{
@@ -79,8 +76,8 @@ class AclProvider implements AclProviderInterface
{
$sql = $this->getFindChildrenSql($parentOid, $directChildrenOnly);
$children = array();
foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) {
$children = [];
foreach ($this->connection->executeQuery($sql)->fetchAllAssociative() as $data) {
$children[] = new ObjectIdentity($data['object_identifier'], $data['class_type']);
}
@@ -90,21 +87,21 @@ class AclProvider implements AclProviderInterface
/**
* {@inheritdoc}
*/
public function findAcl(ObjectIdentityInterface $oid, array $sids = array())
public function findAcl(ObjectIdentityInterface $oid, array $sids = [])
{
return $this->findAcls(array($oid), $sids)->offsetGet($oid);
return $this->findAcls([$oid], $sids)->offsetGet($oid);
}
/**
* {@inheritdoc}
*/
public function findAcls(array $oids, array $sids = array())
public function findAcls(array $oids, array $sids = [])
{
$result = new \SplObjectStorage();
$currentBatch = array();
$oidLookup = array();
$currentBatch = [];
$oidLookup = [];
for ($i = 0, $c = count($oids); $i < $c; ++$i) {
for ($i = 0, $c = \count($oids); $i < $c; ++$i) {
$oid = $oids[$i];
$oidLookupKey = $oid->getIdentifier().$oid->getType();
$oidLookup[$oidLookupKey] = $oid;
@@ -173,7 +170,7 @@ class AclProvider implements AclProviderInterface
}
// Is it time to load the current batch?
$currentBatchesCount = count($currentBatch);
$currentBatchesCount = \count($currentBatch);
if ($currentBatchesCount > 0 && (self::MAX_BATCH_SIZE === $currentBatchesCount || ($i + 1) === $c)) {
try {
$loadedBatch = $this->lookupObjectIdentities($currentBatch, $sids, $oidLookup);
@@ -198,15 +195,15 @@ class AclProvider implements AclProviderInterface
}
}
$currentBatch = array();
$currentBatch = [];
}
}
// check that we got ACLs for all the identities
foreach ($oids as $oid) {
if (!$result->contains($oid)) {
if (1 === count($oids)) {
$objectName = method_exists($oid, '__toString') ? $oid : get_class($oid);
if (1 === \count($oids)) {
$objectName = method_exists($oid, '__toString') ? $oid : \get_class($oid);
throw new AclNotFoundException(sprintf('No ACL found for %s.', $objectName));
}
@@ -224,8 +221,6 @@ class AclProvider implements AclProviderInterface
* Constructs the query used for looking up object identities and associated
* ACEs, and security identities.
*
* @param array $ancestorIds
*
* @return string
*/
protected function getLookupSql(array $ancestorIds)
@@ -279,8 +274,8 @@ SELECTCLAUSE;
WHERE (
SELECTCLAUSE;
$types = array();
$count = count($batch);
$types = [];
$count = \count($batch);
for ($i = 0; $i < $count; ++$i) {
if (!isset($types[$batch[$i]->getType()])) {
$types[$batch[$i]->getType()] = true;
@@ -288,14 +283,14 @@ SELECTCLAUSE;
// if there is more than one type we can safely break out of the
// loop, because it is the differentiator factor on whether to
// query for only one or more class types
if (count($types) > 1) {
if (\count($types) > 1) {
break;
}
}
}
if (1 === count($types)) {
$ids = array();
if (1 === \count($types)) {
$ids = [];
for ($i = 0; $i < $count; ++$i) {
$identifier = (string) $batch[$i]->getIdentifier();
$ids[] = $this->connection->quote($identifier);
@@ -330,8 +325,7 @@ SELECTCLAUSE;
* Constructs the SQL for retrieving child object identities for the given
* object identities.
*
* @param ObjectIdentityInterface $oid
* @param bool $directChildrenOnly
* @param bool $directChildrenOnly
*
* @return string
*/
@@ -363,8 +357,6 @@ FINDCHILDREN;
* Constructs the SQL for retrieving the primary key of the given object
* identity.
*
* @param ObjectIdentityInterface $oid
*
* @return string
*/
protected function getSelectObjectIdentityIdSql(ObjectIdentityInterface $oid)
@@ -388,23 +380,19 @@ QUERY;
/**
* Returns the primary key of the passed object identity.
*
* @param ObjectIdentityInterface $oid
*
* @return int
*/
final protected function retrieveObjectIdentityPrimaryKey(ObjectIdentityInterface $oid)
{
return $this->connection->executeQuery($this->getSelectObjectIdentityIdSql($oid))->fetchColumn();
return $this->connection->executeQuery($this->getSelectObjectIdentityIdSql($oid))->fetchOne();
}
/**
* This method is called when an ACL instance is retrieved from the cache.
*
* @param AclInterface $acl
*/
private function updateAceIdentityMap(AclInterface $acl)
{
foreach (array('classAces', 'classFieldAces', 'objectAces', 'objectFieldAces') as $property) {
foreach (['classAces', 'classFieldAces', 'objectAces', 'objectFieldAces'] as $property) {
$reflection = new \ReflectionProperty($acl, $property);
$reflection->setAccessible(true);
$value = $reflection->getValue($acl);
@@ -426,16 +414,14 @@ QUERY;
* Retrieves all the ids which need to be queried from the database
* including the ids of parent ACLs.
*
* @param array $batch
*
* @return array
*/
private function getAncestorIds(array $batch)
{
$sql = $this->getAncestorLookupSql($batch);
$ancestorIds = array();
foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) {
$ancestorIds = [];
foreach ($this->connection->executeQuery($sql)->fetchAllAssociative() as $data) {
// FIXME: skip ancestors which are cached
// Fix: Oracle returns keys in uppercase
$ancestorIds[] = reset($data);
@@ -465,10 +451,6 @@ QUERY;
* This method is called for object identities which could not be retrieved
* from the cache, and for which thus a database query is required.
*
* @param array $batch
* @param array $sids
* @param array $oidLookup
*
* @return \SplObjectStorage mapping object identities to ACL instances
*
* @throws AclNotFoundException
@@ -495,18 +477,14 @@ QUERY;
* Keep in mind that changes to this method might severely reduce the
* performance of the entire ACL system.
*
* @param Statement $stmt
* @param array $oidLookup
* @param array $sids
*
* @return \SplObjectStorage
*
* @throws \RuntimeException
*/
private function hydrateObjectIdentities(Statement $stmt, array $oidLookup, array $sids)
private function hydrateObjectIdentities(Result $stmt, array $oidLookup, array $sids)
{
$parentIdToFill = new \SplObjectStorage();
$acls = $aces = $emptyArray = array();
$acls = $aces = $emptyArray = [];
$oidCache = $oidLookup;
$result = new \SplObjectStorage();
$loadedAces = &$this->loadedAces;
@@ -528,8 +506,8 @@ QUERY;
// fetchAll() consumes more memory than consecutive calls to fetch(),
// but it is faster
foreach ($stmt->fetchAll(\PDO::FETCH_NUM) as $data) {
list($aclId,
foreach ($stmt->fetchAllNumeric() as $data) {
[$aclId,
$objectIdentifier,
$parentObjectIdentityId,
$entriesInheriting,
@@ -544,7 +522,7 @@ QUERY;
$auditSuccess,
$auditFailure,
$username,
$securityIdentifier) = array_values($data);
$securityIdentifier] = array_values($data);
// has the ACL been hydrated during this hydration cycle?
if (isset($acls[$aclId])) {
@@ -595,7 +573,7 @@ QUERY;
if (null !== $aceId) {
// have we already hydrated ACEs for this ACL?
if (!isset($aces[$aclId])) {
$aces[$aclId] = array($emptyArray, $emptyArray, $emptyArray, $emptyArray);
$aces[$aclId] = [$emptyArray, $emptyArray, $emptyArray, $emptyArray];
}
// has this ACE already been hydrated during a previous cycle, or
@@ -686,7 +664,7 @@ QUERY;
$aclParentAclProperty->setAccessible(false);
// this should never be true if the database integrity hasn't been compromised
if ($processed < count($parentIdToFill)) {
if ($processed < \count($parentIdToFill)) {
throw new \RuntimeException('Not all parent ids were populated. This implies an integrity problem.');
}
+61 -85
View File
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Acl\Dbal;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\PropertyChangedListener;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException;
@@ -51,7 +51,7 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
public function createAcl(ObjectIdentityInterface $oid)
{
if (false !== $this->retrieveObjectIdentityPrimaryKey($oid)) {
$objectName = method_exists($oid, '__toString') ? $oid : get_class($oid);
$objectName = method_exists($oid, '__toString') ? $oid : \get_class($oid);
throw new AclAlreadyExistsException(sprintf('%s is already associated with an ACL.', $objectName));
}
@@ -60,7 +60,7 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
$this->createObjectIdentity($oid);
$pk = $this->retrieveObjectIdentityPrimaryKey($oid);
$this->connection->executeQuery($this->getInsertObjectIdentityRelationSql($pk, $pk));
$this->connection->executeStatement($this->getInsertObjectIdentityRelationSql($pk, $pk));
$this->connection->commit();
} catch (\Exception $e) {
@@ -113,19 +113,17 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
* Deletes the security identity from the database.
* ACL entries have the CASCADE option on their foreign key so they will also get deleted.
*
* @param SecurityIdentityInterface $sid
*
* @throws \InvalidArgumentException
*/
public function deleteSecurityIdentity(SecurityIdentityInterface $sid)
{
$this->connection->executeQuery($this->getDeleteSecurityIdentityIdSql($sid));
$this->connection->executeStatement($this->getDeleteSecurityIdentityIdSql($sid));
}
/**
* {@inheritdoc}
*/
public function findAcls(array $oids, array $sids = array())
public function findAcls(array $oids, array $sids = [])
{
$result = parent::findAcls($oids, $sids);
@@ -134,14 +132,14 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
if (false === $this->propertyChanges->contains($acl) && $acl instanceof MutableAclInterface) {
$acl->addPropertyChangedListener($this);
$this->propertyChanges->attach($acl, array());
$this->propertyChanges->attach($acl, []);
}
$parentAcl = $acl->getParentAcl();
while (null !== $parentAcl) {
if (false === $this->propertyChanges->contains($parentAcl) && $acl instanceof MutableAclInterface) {
$parentAcl->addPropertyChangedListener($this);
$this->propertyChanges->attach($parentAcl, array());
$this->propertyChanges->attach($parentAcl, []);
}
$parentAcl = $parentAcl->getParentAcl();
@@ -192,35 +190,35 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
if ($oldValue === $newValue) {
unset($propertyChanges[$propertyName]);
} else {
$propertyChanges[$propertyName] = array($oldValue, $newValue);
$propertyChanges[$propertyName] = [$oldValue, $newValue];
}
} else {
$propertyChanges[$propertyName] = array($oldValue, $newValue);
$propertyChanges[$propertyName] = [$oldValue, $newValue];
}
} else {
if (!isset($propertyChanges['aces'])) {
$propertyChanges['aces'] = new \SplObjectStorage();
}
$acePropertyChanges = $propertyChanges['aces']->contains($ace) ? $propertyChanges['aces']->offsetGet($ace) : array();
$acePropertyChanges = $propertyChanges['aces']->contains($ace) ? $propertyChanges['aces']->offsetGet($ace) : [];
if (isset($acePropertyChanges[$propertyName])) {
$oldValue = $acePropertyChanges[$propertyName][0];
if ($oldValue === $newValue) {
unset($acePropertyChanges[$propertyName]);
} else {
$acePropertyChanges[$propertyName] = array($oldValue, $newValue);
$acePropertyChanges[$propertyName] = [$oldValue, $newValue];
}
} else {
$acePropertyChanges[$propertyName] = array($oldValue, $newValue);
$acePropertyChanges[$propertyName] = [$oldValue, $newValue];
}
if (count($acePropertyChanges) > 0) {
if (\count($acePropertyChanges) > 0) {
$propertyChanges['aces']->offsetSet($ace, $acePropertyChanges);
} else {
$propertyChanges['aces']->offsetUnset($ace);
if (0 === count($propertyChanges['aces'])) {
if (0 === \count($propertyChanges['aces'])) {
unset($propertyChanges['aces']);
}
}
@@ -240,11 +238,11 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
$propertyChanges = $this->propertyChanges->offsetGet($acl);
// check if any changes were made to this ACL
if (0 === count($propertyChanges)) {
if (0 === \count($propertyChanges)) {
return;
}
$sets = $sharedPropertyChanges = array();
$sets = $sharedPropertyChanges = [];
$this->connection->beginTransaction();
try {
@@ -307,7 +305,7 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
// if there have been changes to shared properties, we need to synchronize other
// ACL instances for object identities of the same type that are already in-memory
if (count($sharedPropertyChanges) > 0) {
if (\count($sharedPropertyChanges) > 0) {
$classAcesProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Acl', 'classAces');
$classAcesProperty->setAccessible(true);
$classFieldAcesProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Acl', 'classFieldAces');
@@ -333,8 +331,8 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
}
// persist any changes to the acl_object_identities table
if (count($sets) > 0) {
$this->connection->executeQuery($this->getUpdateObjectIdentitySql($acl->getId(), $sets));
if (\count($sets) > 0) {
$this->connection->executeStatement($this->getUpdateObjectIdentitySql($acl->getId(), $sets));
}
$this->connection->commit();
@@ -344,10 +342,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
throw $e;
}
$this->propertyChanges->offsetSet($acl, array());
$this->propertyChanges->offsetSet($acl, []);
if (null !== $this->cache) {
if (count($sharedPropertyChanges) > 0) {
if (\count($sharedPropertyChanges) > 0) {
// FIXME: Currently, there is no easy way to clear the cache for ACLs
// of a certain type. The problem here is that we need to make
// sure to clear the cache of all child ACLs as well, and these
@@ -368,12 +366,11 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
/**
* Updates a user security identity when the user's username changes.
*
* @param UserSecurityIdentity $usid
* @param string $oldUsername
* @param string $oldUsername
*/
public function updateUserSecurityIdentity(UserSecurityIdentity $usid, $oldUsername)
{
$this->connection->executeQuery($this->getUpdateUserSecurityIdentitySql($usid, $oldUsername));
$this->connection->executeStatement($this->getUpdateUserSecurityIdentitySql($usid, $oldUsername));
}
/**
@@ -552,8 +549,6 @@ QUERY;
/**
* Constructs the SQL for inserting a security identity.
*
* @param SecurityIdentityInterface $sid
*
* @throws \InvalidArgumentException
*
* @return string
@@ -624,8 +619,6 @@ QUERY;
/**
* Constructs the SQL for selecting the primary key of a security identity.
*
* @param SecurityIdentityInterface $sid
*
* @throws \InvalidArgumentException
*
* @return string
@@ -653,8 +646,6 @@ QUERY;
/**
* Constructs the SQL to delete a security identity.
*
* @param SecurityIdentityInterface $sid
*
* @throws \InvalidArgumentException
*
* @return string
@@ -670,8 +661,7 @@ QUERY;
/**
* Constructs the SQL for updating an object identity.
*
* @param int $pk
* @param array $changes
* @param int $pk
*
* @throws \InvalidArgumentException
*
@@ -679,7 +669,7 @@ QUERY;
*/
protected function getUpdateObjectIdentitySql($pk, array $changes)
{
if (0 === count($changes)) {
if (0 === \count($changes)) {
throw new \InvalidArgumentException('There are no changes.');
}
@@ -694,8 +684,7 @@ QUERY;
/**
* Constructs the SQL for updating a user security identity.
*
* @param UserSecurityIdentity $usid
* @param string $oldUsername
* @param string $oldUsername
*
* @return string
*/
@@ -720,8 +709,7 @@ QUERY;
/**
* Constructs the SQL for updating an ACE.
*
* @param int $pk
* @param array $sets
* @param int $pk
*
* @throws \InvalidArgumentException
*
@@ -729,7 +717,7 @@ QUERY;
*/
protected function getUpdateAccessControlEntrySql($pk, array $sets)
{
if (0 === count($sets)) {
if (0 === \count($sets)) {
throw new \InvalidArgumentException('There are no changes.');
}
@@ -743,14 +731,12 @@ QUERY;
/**
* Creates the ACL for the passed object identity.
*
* @param ObjectIdentityInterface $oid
*/
private function createObjectIdentity(ObjectIdentityInterface $oid)
{
$classId = $this->createOrRetrieveClassId($oid->getType());
$this->connection->executeQuery($this->getInsertObjectIdentitySql($oid->getIdentifier(), $classId, true));
$this->connection->executeStatement($this->getInsertObjectIdentitySql($oid->getIdentifier(), $classId, true));
}
/**
@@ -764,13 +750,13 @@ QUERY;
*/
private function createOrRetrieveClassId($classType)
{
if (false !== $id = $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn()) {
if (false !== $id = $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchOne()) {
return $id;
}
$this->connection->executeQuery($this->getInsertClassSql($classType));
$this->connection->executeStatement($this->getInsertClassSql($classType));
return $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn();
return $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchOne();
}
/**
@@ -779,19 +765,17 @@ QUERY;
* If the security identity does not yet exist in the database, it will be
* created.
*
* @param SecurityIdentityInterface $sid
*
* @return int
*/
private function createOrRetrieveSecurityIdentityId(SecurityIdentityInterface $sid)
{
if (false !== $id = $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn()) {
if (false !== $id = $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchOne()) {
return $id;
}
$this->connection->executeQuery($this->getInsertSecurityIdentitySql($sid));
$this->connection->executeStatement($this->getInsertSecurityIdentitySql($sid));
return $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn();
return $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchOne();
}
/**
@@ -801,7 +785,7 @@ QUERY;
*/
private function deleteAccessControlEntries($oidPK)
{
$this->connection->executeQuery($this->getDeleteAccessControlEntriesSql($oidPK));
$this->connection->executeStatement($this->getDeleteAccessControlEntriesSql($oidPK));
}
/**
@@ -811,7 +795,7 @@ QUERY;
*/
private function deleteObjectIdentity($pk)
{
$this->connection->executeQuery($this->getDeleteObjectIdentitySql($pk));
$this->connection->executeStatement($this->getDeleteObjectIdentitySql($pk));
}
/**
@@ -821,23 +805,21 @@ QUERY;
*/
private function deleteObjectIdentityRelations($pk)
{
$this->connection->executeQuery($this->getDeleteObjectIdentityRelationsSql($pk));
$this->connection->executeStatement($this->getDeleteObjectIdentityRelationsSql($pk));
}
/**
* This regenerates the ancestor table which is used for fast read access.
*
* @param AclInterface $acl
*/
private function regenerateAncestorRelations(AclInterface $acl)
{
$pk = $acl->getId();
$this->connection->executeQuery($this->getDeleteObjectIdentityRelationsSql($pk));
$this->connection->executeQuery($this->getInsertObjectIdentityRelationSql($pk, $pk));
$this->connection->executeStatement($this->getDeleteObjectIdentityRelationsSql($pk));
$this->connection->executeStatement($this->getInsertObjectIdentityRelationSql($pk, $pk));
$parentAcl = $acl->getParentAcl();
while (null !== $parentAcl) {
$this->connection->executeQuery($this->getInsertObjectIdentityRelationSql($pk, $parentAcl->getId()));
$this->connection->executeStatement($this->getInsertObjectIdentityRelationSql($pk, $parentAcl->getId()));
$parentAcl = $parentAcl->getParentAcl();
}
@@ -847,14 +829,13 @@ QUERY;
* This processes new entries changes on an ACE related property (classFieldAces, or objectFieldAces).
*
* @param string $name
* @param array $changes
*/
private function updateNewFieldAceProperty($name, array $changes)
{
$sids = new \SplObjectStorage();
$classIds = new \SplObjectStorage();
foreach ($changes[1] as $field => $new) {
for ($i = 0, $c = count($new); $i < $c; ++$i) {
for ($i = 0, $c = \count($new); $i < $c; ++$i) {
$ace = $new[$i];
if (null === $ace->getId()) {
@@ -871,10 +852,10 @@ QUERY;
$classId = $this->createOrRetrieveClassId($oid->getType());
}
$objectIdentityId = $name === 'classFieldAces' ? null : $ace->getAcl()->getId();
$objectIdentityId = 'classFieldAces' === $name ? null : $ace->getAcl()->getId();
$this->connection->executeQuery($this->getInsertAccessControlEntrySql($classId, $objectIdentityId, $field, $i, $sid, $ace->getStrategy(), $ace->getMask(), $ace->isGranting(), $ace->isAuditSuccess(), $ace->isAuditFailure()));
$aceId = $this->connection->executeQuery($this->getSelectAccessControlEntryIdSql($classId, $objectIdentityId, $field, $i))->fetchColumn();
$this->connection->executeStatement($this->getInsertAccessControlEntrySql($classId, $objectIdentityId, $field, $i, $sid, $ace->getStrategy(), $ace->getMask(), $ace->isGranting(), $ace->isAuditSuccess(), $ace->isAuditFailure()));
$aceId = $this->connection->executeQuery($this->getSelectAccessControlEntryIdSql($classId, $objectIdentityId, $field, $i))->fetchOne();
$this->loadedAces[$aceId] = $ace;
$aceIdProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Entry', 'id');
@@ -889,13 +870,12 @@ QUERY;
* This processes old entries changes on an ACE related property (classFieldAces, or objectFieldAces).
*
* @param string $name
* @param array $changes
*/
private function updateOldFieldAceProperty($name, array $changes)
{
$currentIds = array();
$currentIds = [];
foreach ($changes[1] as $field => $new) {
for ($i = 0, $c = count($new); $i < $c; ++$i) {
for ($i = 0, $c = \count($new); $i < $c; ++$i) {
$ace = $new[$i];
if (null !== $ace->getId()) {
@@ -905,11 +885,11 @@ QUERY;
}
foreach ($changes[0] as $old) {
for ($i = 0, $c = count($old); $i < $c; ++$i) {
for ($i = 0, $c = \count($old); $i < $c; ++$i) {
$ace = $old[$i];
if (!isset($currentIds[$ace->getId()])) {
$this->connection->executeQuery($this->getDeleteAccessControlEntrySql($ace->getId()));
$this->connection->executeStatement($this->getDeleteAccessControlEntrySql($ace->getId()));
unset($this->loadedAces[$ace->getId()]);
}
}
@@ -920,15 +900,14 @@ QUERY;
* This processes new entries changes on an ACE related property (classAces, or objectAces).
*
* @param string $name
* @param array $changes
*/
private function updateNewAceProperty($name, array $changes)
{
list($old, $new) = $changes;
[$old, $new] = $changes;
$sids = new \SplObjectStorage();
$classIds = new \SplObjectStorage();
for ($i = 0, $c = count($new); $i < $c; ++$i) {
for ($i = 0, $c = \count($new); $i < $c; ++$i) {
$ace = $new[$i];
if (null === $ace->getId()) {
@@ -945,10 +924,10 @@ QUERY;
$classId = $this->createOrRetrieveClassId($oid->getType());
}
$objectIdentityId = $name === 'classAces' ? null : $ace->getAcl()->getId();
$objectIdentityId = 'classAces' === $name ? null : $ace->getAcl()->getId();
$this->connection->executeQuery($this->getInsertAccessControlEntrySql($classId, $objectIdentityId, null, $i, $sid, $ace->getStrategy(), $ace->getMask(), $ace->isGranting(), $ace->isAuditSuccess(), $ace->isAuditFailure()));
$aceId = $this->connection->executeQuery($this->getSelectAccessControlEntryIdSql($classId, $objectIdentityId, null, $i))->fetchColumn();
$this->connection->executeStatement($this->getInsertAccessControlEntrySql($classId, $objectIdentityId, null, $i, $sid, $ace->getStrategy(), $ace->getMask(), $ace->isGranting(), $ace->isAuditSuccess(), $ace->isAuditFailure()));
$aceId = $this->connection->executeQuery($this->getSelectAccessControlEntryIdSql($classId, $objectIdentityId, null, $i))->fetchOne();
$this->loadedAces[$aceId] = $ace;
$aceIdProperty = new \ReflectionProperty($ace, 'id');
@@ -962,14 +941,13 @@ QUERY;
* This processes old entries changes on an ACE related property (classAces, or objectAces).
*
* @param string $name
* @param array $changes
*/
private function updateOldAceProperty($name, array $changes)
{
list($old, $new) = $changes;
$currentIds = array();
[$old, $new] = $changes;
$currentIds = [];
for ($i = 0, $c = count($new); $i < $c; ++$i) {
for ($i = 0, $c = \count($new); $i < $c; ++$i) {
$ace = $new[$i];
if (null !== $ace->getId()) {
@@ -977,11 +955,11 @@ QUERY;
}
}
for ($i = 0, $c = count($old); $i < $c; ++$i) {
for ($i = 0, $c = \count($old); $i < $c; ++$i) {
$ace = $old[$i];
if (!isset($currentIds[$ace->getId()])) {
$this->connection->executeQuery($this->getDeleteAccessControlEntrySql($ace->getId()));
$this->connection->executeStatement($this->getDeleteAccessControlEntrySql($ace->getId()));
unset($this->loadedAces[$ace->getId()]);
}
}
@@ -989,8 +967,6 @@ QUERY;
/**
* Persists the changes which were made to ACEs to the database.
*
* @param \SplObjectStorage $aces
*/
private function updateAces(\SplObjectStorage $aces)
{
@@ -1002,7 +978,7 @@ QUERY;
private function updateAce(\SplObjectStorage $aces, $ace)
{
$propertyChanges = $aces->offsetGet($ace);
$sets = array();
$sets = [];
if (isset($propertyChanges['aceOrder'])
&& $propertyChanges['aceOrder'][1] > $propertyChanges['aceOrder'][0]
@@ -1029,6 +1005,6 @@ QUERY;
$sets[] = sprintf('audit_failure = %s', $this->connection->getDatabasePlatform()->convertBooleans($propertyChanges['auditFailure'][1]));
}
$this->connection->executeQuery($this->getUpdateAccessControlEntrySql($ace->getId(), $sets));
$this->connection->executeStatement($this->getUpdateAccessControlEntrySql($ace->getId(), $sets));
}
}
+36 -38
View File
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Acl\Dbal;
use Doctrine\DBAL\Schema\Schema as BaseSchema;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema as BaseSchema;
/**
* The schema used for the ACL system.
@@ -33,7 +33,7 @@ final class Schema extends BaseSchema
{
$schemaConfig = null === $connection ? null : $connection->getSchemaManager()->createSchemaConfig();
parent::__construct(array(), array(), $schemaConfig);
parent::__construct([], [], $schemaConfig);
$this->options = $options;
@@ -46,8 +46,6 @@ final class Schema extends BaseSchema
/**
* Merges ACL schema with the given schema.
*
* @param BaseSchema $schema
*/
public function addToSchema(BaseSchema $schema)
{
@@ -66,10 +64,10 @@ final class Schema extends BaseSchema
protected function addClassTable()
{
$table = $this->createTable($this->options['class_table_name']);
$table->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('class_type', 'string', array('length' => 200));
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('class_type'));
$table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
$table->addColumn('class_type', 'string', ['length' => 200]);
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['class_type']);
}
/**
@@ -79,25 +77,25 @@ final class Schema extends BaseSchema
{
$table = $this->createTable($this->options['entry_table_name']);
$table->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('class_id', 'integer', array('unsigned' => true));
$table->addColumn('object_identity_id', 'integer', array('unsigned' => true, 'notnull' => false));
$table->addColumn('field_name', 'string', array('length' => 50, 'notnull' => false));
$table->addColumn('ace_order', 'smallint', array('unsigned' => true));
$table->addColumn('security_identity_id', 'integer', array('unsigned' => true));
$table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
$table->addColumn('class_id', 'integer', ['unsigned' => true]);
$table->addColumn('object_identity_id', 'integer', ['unsigned' => true, 'notnull' => false]);
$table->addColumn('field_name', 'string', ['length' => 50, 'notnull' => false]);
$table->addColumn('ace_order', 'smallint', ['unsigned' => true]);
$table->addColumn('security_identity_id', 'integer', ['unsigned' => true]);
$table->addColumn('mask', 'integer');
$table->addColumn('granting', 'boolean');
$table->addColumn('granting_strategy', 'string', array('length' => 30));
$table->addColumn('granting_strategy', 'string', ['length' => 30]);
$table->addColumn('audit_success', 'boolean');
$table->addColumn('audit_failure', 'boolean');
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('class_id', 'object_identity_id', 'field_name', 'ace_order'));
$table->addIndex(array('class_id', 'object_identity_id', 'security_identity_id'));
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['class_id', 'object_identity_id', 'field_name', 'ace_order']);
$table->addIndex(['class_id', 'object_identity_id', 'security_identity_id']);
$table->addForeignKeyConstraint($this->getTable($this->options['class_table_name']), array('class_id'), array('id'), array('onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE'));
$table->addForeignKeyConstraint($this->getTable($this->options['oid_table_name']), array('object_identity_id'), array('id'), array('onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE'));
$table->addForeignKeyConstraint($this->getTable($this->options['sid_table_name']), array('security_identity_id'), array('id'), array('onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE'));
$table->addForeignKeyConstraint($this->getTable($this->options['class_table_name']), ['class_id'], ['id'], ['onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE']);
$table->addForeignKeyConstraint($this->getTable($this->options['oid_table_name']), ['object_identity_id'], ['id'], ['onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE']);
$table->addForeignKeyConstraint($this->getTable($this->options['sid_table_name']), ['security_identity_id'], ['id'], ['onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE']);
}
/**
@@ -107,17 +105,17 @@ final class Schema extends BaseSchema
{
$table = $this->createTable($this->options['oid_table_name']);
$table->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('class_id', 'integer', array('unsigned' => true));
$table->addColumn('object_identifier', 'string', array('length' => 100));
$table->addColumn('parent_object_identity_id', 'integer', array('unsigned' => true, 'notnull' => false));
$table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
$table->addColumn('class_id', 'integer', ['unsigned' => true]);
$table->addColumn('object_identifier', 'string', ['length' => 100]);
$table->addColumn('parent_object_identity_id', 'integer', ['unsigned' => true, 'notnull' => false]);
$table->addColumn('entries_inheriting', 'boolean');
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('object_identifier', 'class_id'));
$table->addIndex(array('parent_object_identity_id'));
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['object_identifier', 'class_id']);
$table->addIndex(['parent_object_identity_id']);
$table->addForeignKeyConstraint($table, array('parent_object_identity_id'), array('id'));
$table->addForeignKeyConstraint($table, ['parent_object_identity_id'], ['id']);
}
/**
@@ -127,14 +125,14 @@ final class Schema extends BaseSchema
{
$table = $this->createTable($this->options['oid_ancestors_table_name']);
$table->addColumn('object_identity_id', 'integer', array('unsigned' => true));
$table->addColumn('ancestor_id', 'integer', array('unsigned' => true));
$table->addColumn('object_identity_id', 'integer', ['unsigned' => true]);
$table->addColumn('ancestor_id', 'integer', ['unsigned' => true]);
$table->setPrimaryKey(array('object_identity_id', 'ancestor_id'));
$table->setPrimaryKey(['object_identity_id', 'ancestor_id']);
$oidTable = $this->getTable($this->options['oid_table_name']);
$table->addForeignKeyConstraint($oidTable, array('object_identity_id'), array('id'), array('onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE'));
$table->addForeignKeyConstraint($oidTable, array('ancestor_id'), array('id'), array('onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE'));
$table->addForeignKeyConstraint($oidTable, ['object_identity_id'], ['id'], ['onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE']);
$table->addForeignKeyConstraint($oidTable, ['ancestor_id'], ['id'], ['onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE']);
}
/**
@@ -144,11 +142,11 @@ final class Schema extends BaseSchema
{
$table = $this->createTable($this->options['sid_table_name']);
$table->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('identifier', 'string', array('length' => 200));
$table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
$table->addColumn('identifier', 'string', ['length' => 200]);
$table->addColumn('username', 'boolean');
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('identifier', 'username'));
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['identifier', 'username']);
}
}
+52 -61
View File
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Acl\Domain;
use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\PropertyChangedListener;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Symfony\Component\Security\Acl\Model\AuditableAclInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
@@ -38,23 +38,20 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
private $parentAcl;
private $permissionGrantingStrategy;
private $objectIdentity;
private $classAces = array();
private $classFieldAces = array();
private $objectAces = array();
private $objectFieldAces = array();
private $classAces = [];
private $classFieldAces = [];
private $objectAces = [];
private $objectFieldAces = [];
private $id;
private $loadedSids;
private $entriesInheriting;
private $listeners = array();
private $listeners = [];
/**
* Constructor.
*
* @param int $id
* @param ObjectIdentityInterface $objectIdentity
* @param PermissionGrantingStrategyInterface $permissionGrantingStrategy
* @param array $loadedSids
* @param bool $entriesInheriting
* @param int $id
* @param bool $entriesInheriting
*/
public function __construct($id, ObjectIdentityInterface $objectIdentity, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $loadedSids, $entriesInheriting)
{
@@ -67,8 +64,6 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
/**
* Adds a property changed listener.
*
* @param PropertyChangedListener $listener
*/
public function addPropertyChangedListener(PropertyChangedListener $listener)
{
@@ -120,7 +115,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
*/
public function getClassFieldAces($field)
{
return isset($this->classFieldAces[$field]) ? $this->classFieldAces[$field] : array();
return $this->classFieldAces[$field] ?? [];
}
/**
@@ -136,7 +131,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
*/
public function getObjectFieldAces($field)
{
return isset($this->objectFieldAces[$field]) ? $this->objectFieldAces[$field] : array();
return $this->objectFieldAces[$field] ?? [];
}
/**
@@ -228,14 +223,13 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
return true;
}
if (!is_array($sids)) {
$sids = array($sids);
if (!\is_array($sids)) {
$sids = [$sids];
}
foreach ($sids as $sid) {
if (!$sid instanceof SecurityIdentityInterface) {
throw new \InvalidArgumentException(
'$sid must be an instance of SecurityIdentityInterface.');
throw new \InvalidArgumentException('$sid must be an instance of SecurityIdentityInterface.');
}
foreach ($this->loadedSids as $loadedSid) {
@@ -257,7 +251,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
*/
public function serialize()
{
return serialize(array(
return serialize([
null === $this->parentAcl ? null : $this->parentAcl->getId(),
$this->objectIdentity,
$this->classAces,
@@ -267,7 +261,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$this->id,
$this->loadedSids,
$this->entriesInheriting,
));
]);
}
/**
@@ -277,7 +271,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
*/
public function unserialize($serialized)
{
list($this->parentAcl,
[$this->parentAcl,
$this->objectIdentity,
$this->classAces,
$this->classFieldAces,
@@ -286,9 +280,9 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$this->id,
$this->loadedSids,
$this->entriesInheriting
) = unserialize($serialized);
] = unserialize($serialized);
$this->listeners = array();
$this->listeners = [];
}
/**
@@ -409,7 +403,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$this->$property = array_values($this->$property);
$this->onPropertyChanged($property, $oldValue, $this->$property);
for ($i = $index, $c = count($this->$property); $i < $c; ++$i) {
for ($i = $index, $c = \count($this->$property); $i < $c; ++$i) {
$this->onEntryPropertyChanged($aces[$i], 'aceOrder', $i + 1, $i);
}
}
@@ -435,7 +429,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$aces[$field] = array_values($aces[$field]);
$this->onPropertyChanged($property, $oldValue, $this->$property);
for ($i = $index, $c = count($aces[$field]); $i < $c; ++$i) {
for ($i = $index, $c = \count($aces[$field]); $i < $c; ++$i) {
$this->onEntryPropertyChanged($aces[$field][$i], 'aceOrder', $i + 1, $i);
}
}
@@ -443,23 +437,22 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
/**
* Inserts an ACE.
*
* @param string $property
* @param int $index
* @param int $mask
* @param SecurityIdentityInterface $sid
* @param bool $granting
* @param string $strategy
* @param string $property
* @param int $index
* @param int $mask
* @param bool $granting
* @param string $strategy
*
* @throws \OutOfBoundsException
* @throws \InvalidArgumentException
*/
private function insertAce($property, $index, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null)
{
if ($index < 0 || $index > count($this->$property)) {
throw new \OutOfBoundsException(sprintf('The index must be in the interval [0, %d].', count($this->$property)));
if ($index < 0 || $index > \count($this->$property)) {
throw new \OutOfBoundsException(sprintf('The index must be in the interval [0, %d].', \count($this->$property)));
}
if (!is_int($mask)) {
if (!\is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}
@@ -475,12 +468,12 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$oldValue = $this->$property;
if (isset($aces[$index])) {
$this->$property = array_merge(
array_slice($this->$property, 0, $index),
array(true),
array_slice($this->$property, $index)
\array_slice($this->$property, 0, $index),
[true],
\array_slice($this->$property, $index)
);
for ($i = $index, $c = count($this->$property) - 1; $i < $c; ++$i) {
for ($i = $index, $c = \count($this->$property) - 1; $i < $c; ++$i) {
$this->onEntryPropertyChanged($aces[$i + 1], 'aceOrder', $i, $i + 1);
}
}
@@ -492,24 +485,23 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
/**
* Inserts a field-based ACE.
*
* @param string $property
* @param int $index
* @param string $field
* @param int $mask
* @param SecurityIdentityInterface $sid
* @param bool $granting
* @param string $strategy
* @param string $property
* @param int $index
* @param string $field
* @param int $mask
* @param bool $granting
* @param string $strategy
*
* @throws \InvalidArgumentException
* @throws \OutOfBoundsException
*/
private function insertFieldAce($property, $index, $field, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null)
{
if (0 === strlen($field)) {
if (0 === \strlen($field)) {
throw new \InvalidArgumentException('$field cannot be empty.');
}
if (!is_int($mask)) {
if (!\is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}
@@ -523,22 +515,22 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
$aces = &$this->$property;
if (!isset($aces[$field])) {
$aces[$field] = array();
$aces[$field] = [];
}
if ($index < 0 || $index > count($aces[$field])) {
throw new \OutOfBoundsException(sprintf('The index must be in the interval [0, %d].', count($this->$property)));
if ($index < 0 || $index > \count($aces[$field])) {
throw new \OutOfBoundsException(sprintf('The index must be in the interval [0, %d].', \count($this->$property)));
}
$oldValue = $aces;
if (isset($aces[$field][$index])) {
$aces[$field] = array_merge(
array_slice($aces[$field], 0, $index),
array(true),
array_slice($aces[$field], $index)
\array_slice($aces[$field], 0, $index),
[true],
\array_slice($aces[$field], $index)
);
for ($i = $index, $c = count($aces[$field]) - 1; $i < $c; ++$i) {
for ($i = $index, $c = \count($aces[$field]) - 1; $i < $c; ++$i) {
$this->onEntryPropertyChanged($aces[$field][$i + 1], 'aceOrder', $i, $i + 1);
}
}
@@ -616,7 +608,7 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
*/
private function updateFieldAce($property, $index, $field, $mask, $strategy = null)
{
if (0 === strlen($field)) {
if (0 === \strlen($field)) {
throw new \InvalidArgumentException('$field cannot be empty.');
}
@@ -653,10 +645,9 @@ class Acl implements AuditableAclInterface, NotifyPropertyChanged
/**
* Called when a property of an ACE associated with this ACL changes.
*
* @param EntryInterface $entry
* @param string $name
* @param mixed $oldValue
* @param mixed $newValue
* @param string $name
* @param mixed $oldValue
* @param mixed $newValue
*/
private function onEntryPropertyChanged(EntryInterface $entry, $name, $oldValue, $newValue)
{
+3 -7
View File
@@ -29,10 +29,6 @@ class AclCollectionCache
/**
* Constructor.
*
* @param AclProviderInterface $aclProvider
* @param ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy
* @param SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy
*/
public function __construct(AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy, SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy)
{
@@ -48,14 +44,14 @@ class AclCollectionCache
* @param mixed $collection anything that can be passed to foreach()
* @param TokenInterface[] $tokens an array of TokenInterface implementations
*/
public function cache($collection, array $tokens = array())
public function cache($collection, array $tokens = [])
{
$sids = array();
$sids = [];
foreach ($tokens as $token) {
$sids = array_merge($sids, $this->securityIdentityRetrievalStrategy->getSecurityIdentities($token));
}
$oids = array();
$oids = [];
foreach ($collection as $domainObject) {
$oids[] = $this->objectIdentityRetrievalStrategy->getObjectIdentity($domainObject);
}
+3 -5
View File
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Acl\Domain;
use Symfony\Component\Security\Acl\Model\AuditableEntryInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
use Symfony\Component\Security\Acl\Model\AuditLoggerInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
/**
* Base audit logger implementation.
@@ -25,8 +25,7 @@ abstract class AuditLogger implements AuditLoggerInterface
/**
* Performs some checks if logging was requested.
*
* @param bool $granted
* @param EntryInterface $ace
* @param bool $granted
*/
public function logIfNeeded($granted, EntryInterface $ace)
{
@@ -44,8 +43,7 @@ abstract class AuditLogger implements AuditLoggerInterface
/**
* This method is only called when logging is needed.
*
* @param bool $granted
* @param EntryInterface $ace
* @param bool $granted
*/
abstract protected function doLog($granted, EntryInterface $ace);
}
+2 -6
View File
@@ -34,15 +34,13 @@ class DoctrineAclCache implements AclCacheInterface
/**
* Constructor.
*
* @param Cache $cache
* @param PermissionGrantingStrategyInterface $permissionGrantingStrategy
* @param string $prefix
* @param string $prefix
*
* @throws \InvalidArgumentException
*/
public function __construct(Cache $cache, PermissionGrantingStrategyInterface $permissionGrantingStrategy, $prefix = self::PREFIX)
{
if (0 === strlen($prefix)) {
if (0 === \strlen($prefix)) {
throw new \InvalidArgumentException('$prefix cannot be empty.');
}
@@ -205,8 +203,6 @@ class DoctrineAclCache implements AclCacheInterface
/**
* Returns the key for the object identity.
*
* @param ObjectIdentityInterface $oid
*
* @return string
*/
private function getDataKeyByIdentity(ObjectIdentityInterface $oid)
+10 -12
View File
@@ -34,14 +34,12 @@ class Entry implements AuditableEntryInterface
/**
* Constructor.
*
* @param int $id
* @param AclInterface $acl
* @param SecurityIdentityInterface $sid
* @param string $strategy
* @param int $mask
* @param bool $granting
* @param bool $auditFailure
* @param bool $auditSuccess
* @param int $id
* @param string $strategy
* @param int $mask
* @param bool $granting
* @param bool $auditFailure
* @param bool $auditSuccess
*/
public function __construct($id, AclInterface $acl, SecurityIdentityInterface $sid, $strategy, $mask, $granting, $auditFailure, $auditSuccess)
{
@@ -178,7 +176,7 @@ class Entry implements AuditableEntryInterface
*/
public function serialize()
{
return serialize(array(
return serialize([
$this->mask,
$this->id,
$this->securityIdentity,
@@ -186,7 +184,7 @@ class Entry implements AuditableEntryInterface
$this->auditFailure,
$this->auditSuccess,
$this->granting,
));
]);
}
/**
@@ -196,13 +194,13 @@ class Entry implements AuditableEntryInterface
*/
public function unserialize($serialized)
{
list($this->mask,
[$this->mask,
$this->id,
$this->securityIdentity,
$this->strategy,
$this->auditFailure,
$this->auditSuccess,
$this->granting
) = unserialize($serialized);
] = unserialize($serialized);
}
}
+13 -12
View File
@@ -27,15 +27,13 @@ class FieldEntry extends Entry implements FieldEntryInterface
/**
* Constructor.
*
* @param int $id
* @param AclInterface $acl
* @param string $field
* @param SecurityIdentityInterface $sid
* @param string $strategy
* @param int $mask
* @param bool $granting
* @param bool $auditFailure
* @param bool $auditSuccess
* @param int $id
* @param string $field
* @param string $strategy
* @param int $mask
* @param bool $granting
* @param bool $auditFailure
* @param bool $auditSuccess
*/
public function __construct($id, AclInterface $acl, $field, SecurityIdentityInterface $sid, $strategy, $mask, $granting, $auditFailure, $auditSuccess)
{
@@ -57,10 +55,10 @@ class FieldEntry extends Entry implements FieldEntryInterface
*/
public function serialize()
{
return serialize(array(
return serialize([
$this->field,
parent::serialize(),
));
]);
}
/**
@@ -68,7 +66,10 @@ class FieldEntry extends Entry implements FieldEntryInterface
*/
public function unserialize($serialized)
{
list($this->field, $parentStr) = unserialize($serialized);
[$this->field, $parentStr] = unserialize($serialized);
if (!\is_string($parentStr)) {
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
parent::unserialize($parentStr);
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ final class ObjectIdentity implements ObjectIdentityInterface
*/
public static function fromDomainObject($domainObject)
{
if (!is_object($domainObject)) {
if (!\is_object($domainObject)) {
throw new InvalidDomainObjectException('$domainObject must be an object.');
}
@@ -33,8 +33,6 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
/**
* Sets the audit logger.
*
* @param AuditLoggerInterface $auditLogger
*/
public function setAuditLogger(AuditLoggerInterface $auditLogger)
{
@@ -124,13 +122,12 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
* permission/identity combinations are left. Finally, we will either throw
* an NoAceFoundException, or deny access.
*
* @param AclInterface $acl
* @param EntryInterface[] $aces An array of ACE to check against
* @param array $masks An array of permission masks
* @param SecurityIdentityInterface[] $sids An array of SecurityIdentityInterface implementations
* @param bool $administrativeMode True turns off audit logging
*
* @return bool true, or false; either granting, or denying access respectively.
* @return bool true, or false; either granting, or denying access respectively
*
* @throws NoAceFoundException
*/
@@ -188,8 +185,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
* Strategy EQUAL:
* The ACE will be considered applicable when the bitmasks are equal.
*
* @param int $requiredMask
* @param EntryInterface $ace
* @param int $requiredMask
*
* @return bool
*
@@ -11,13 +11,13 @@
namespace Symfony\Component\Security\Acl\Domain;
use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
/**
* Strategy for retrieving security identities.
@@ -31,9 +31,6 @@ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStra
/**
* Constructor.
*
* @param RoleHierarchyInterface $roleHierarchy
* @param AuthenticationTrustResolverInterface $authenticationTrustResolver
*/
public function __construct(RoleHierarchyInterface $roleHierarchy, AuthenticationTrustResolverInterface $authenticationTrustResolver)
{
@@ -46,7 +43,7 @@ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStra
*/
public function getSecurityIdentities(TokenInterface $token)
{
$sids = array();
$sids = [];
// add user security identity
if (!$token instanceof AnonymousToken) {
@@ -50,8 +50,6 @@ final class UserSecurityIdentity implements SecurityIdentityInterface
/**
* Creates a user security identity from a UserInterface.
*
* @param UserInterface $user
*
* @return UserSecurityIdentity
*/
public static function fromAccount(UserInterface $user)
@@ -62,8 +60,6 @@ final class UserSecurityIdentity implements SecurityIdentityInterface
/**
* Creates a user security identity from a TokenInterface.
*
* @param TokenInterface $token
*
* @return UserSecurityIdentity
*/
public static function fromToken(TokenInterface $token)
@@ -74,7 +70,7 @@ final class UserSecurityIdentity implements SecurityIdentityInterface
return self::fromAccount($user);
}
return new self((string) $user, is_object($user) ? ClassUtils::getRealClass($user) : ClassUtils::getRealClass($token));
return new self((string) $user, \is_object($user) ? ClassUtils::getRealClass($user) : ClassUtils::getRealClass($token));
}
/**
@@ -26,8 +26,6 @@ class NotAllAclsFoundException extends AclNotFoundException
/**
* Sets the partial result.
*
* @param \SplObjectStorage $result
*/
public function setPartialResult(\SplObjectStorage $result)
{
+2 -8
View File
@@ -29,8 +29,6 @@ interface AclCacheInterface
* Removes an ACL from the cache.
*
* The ACL which is returned, must reference the passed object identity.
*
* @param ObjectIdentityInterface $oid
*/
public function evictFromCacheByIdentity(ObjectIdentityInterface $oid);
@@ -39,23 +37,19 @@ interface AclCacheInterface
*
* @param int $primaryKey
*
* @return AclInterface
* @return AclInterface|null
*/
public function getFromCacheById($primaryKey);
/**
* Retrieves an ACL for the given object identity from the cache.
*
* @param ObjectIdentityInterface $oid
*
* @return AclInterface
* @return AclInterface|null
*/
public function getFromCacheByIdentity(ObjectIdentityInterface $oid);
/**
* Stores a new ACL in the cache.
*
* @param AclInterface $acl
*/
public function putInCache(AclInterface $acl);
+1 -5
View File
@@ -82,8 +82,6 @@ interface AclInterface extends \Serializable
* Determines whether field access is granted.
*
* @param string $field
* @param array $masks
* @param array $securityIdentities
* @param bool $administrativeMode
*
* @return bool
@@ -93,9 +91,7 @@ interface AclInterface extends \Serializable
/**
* Determines whether access is granted.
*
* @param array $masks
* @param array $securityIdentities
* @param bool $administrativeMode
* @param bool $administrativeMode
*
* @throws NoAceFoundException when no ACE was applicable for this request
*
+3 -5
View File
@@ -23,8 +23,7 @@ interface AclProviderInterface
/**
* Retrieves all child object identities from the database.
*
* @param ObjectIdentityInterface $parentOid
* @param bool $directChildrenOnly
* @param bool $directChildrenOnly
*
* @return array returns an array of child 'ObjectIdentity's
*/
@@ -33,14 +32,13 @@ interface AclProviderInterface
/**
* Returns the ACL that belongs to the given object identity.
*
* @param ObjectIdentityInterface $oid
* @param SecurityIdentityInterface[] $sids
*
* @return AclInterface
*
* @throws AclNotFoundException when there is no ACL
*/
public function findAcl(ObjectIdentityInterface $oid, array $sids = array());
public function findAcl(ObjectIdentityInterface $oid, array $sids = []);
/**
* Returns the ACLs that belong to the given object identities.
@@ -52,5 +50,5 @@ interface AclProviderInterface
*
* @throws AclNotFoundException when we cannot find an ACL for all identities
*/
public function findAcls(array $oids, array $sids = array());
public function findAcls(array $oids, array $sids = []);
}
+1 -2
View File
@@ -22,8 +22,7 @@ interface AuditLoggerInterface
* This method is called whenever access is granted, or denied, and
* administrative mode is turned off.
*
* @param bool $granted
* @param EntryInterface $ace
* @param bool $granted
*/
public function logIfNeeded($granted, EntryInterface $ace);
}
+18 -24
View File
@@ -61,46 +61,42 @@ interface MutableAclInterface extends AclInterface
/**
* Inserts a class-based ACE.
*
* @param SecurityIdentityInterface $sid
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
*/
public function insertClassAce(SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null);
/**
* Inserts a class-field-based ACE.
*
* @param string $field
* @param SecurityIdentityInterface $sid
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
* @param string $field
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
*/
public function insertClassFieldAce($field, SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null);
/**
* Inserts an object-based ACE.
*
* @param SecurityIdentityInterface $sid
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
*/
public function insertObjectAce(SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null);
/**
* Inserts an object-field-based ACE.
*
* @param string $field
* @param SecurityIdentityInterface $sid
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
* @param string $field
* @param int $mask
* @param int $index
* @param bool $granting
* @param string $strategy
*/
public function insertObjectFieldAce($field, SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null);
@@ -113,8 +109,6 @@ interface MutableAclInterface extends AclInterface
/**
* Sets the parent ACL.
*
* @param AclInterface|null $acl
*/
public function setParentAcl(AclInterface $acl = null);
@@ -23,8 +23,6 @@ interface MutableAclProviderInterface extends AclProviderInterface
/**
* Creates a new ACL for the given object identity.
*
* @param ObjectIdentityInterface $oid
*
* @throws AclAlreadyExistsException when there already is an ACL for the given
* object identity
*
@@ -37,8 +35,6 @@ interface MutableAclProviderInterface extends AclProviderInterface
*
* This will automatically trigger a delete for any child ACLs. If you don't
* want child ACLs to be deleted, you will have to set their parent ACL to null.
*
* @param ObjectIdentityInterface $oid
*/
public function deleteAcl(ObjectIdentityInterface $oid);
@@ -47,8 +43,6 @@ interface MutableAclProviderInterface extends AclProviderInterface
* access control entries.
*
* Changes to parent ACLs are not persisted.
*
* @param MutableAclInterface $acl
*/
public function updateAcl(MutableAclInterface $acl);
}
@@ -27,11 +27,9 @@ interface ObjectIdentityInterface
* Referential Equality: $object1 === $object2
* Example for Object Equality: $object1->getId() === $object2->getId()
*
* @param ObjectIdentityInterface $identity
*
* @return bool
*/
public function equals(ObjectIdentityInterface $identity);
public function equals(self $identity);
/**
* Obtains a unique identifier for this object. The identifier must not be
@@ -21,10 +21,7 @@ interface PermissionGrantingStrategyInterface
/**
* Determines whether access to a domain object is to be granted.
*
* @param AclInterface $acl
* @param array $masks
* @param array $sids
* @param bool $administrativeMode
* @param bool $administrativeMode
*
* @return bool
*/
@@ -33,11 +30,8 @@ interface PermissionGrantingStrategyInterface
/**
* Determines whether access to a domain object's field is to be granted.
*
* @param AclInterface $acl
* @param string $field
* @param array $masks
* @param array $sids
* @param bool $administrativeMode
* @param string $field
* @param bool $administrativeMode
*
* @return bool
*/
@@ -23,8 +23,6 @@ interface SecurityIdentityInterface
/**
* This method is used to compare two security identities in order to
* not rely on referential equality.
*
* @param SecurityIdentityInterface $identity
*/
public function equals(SecurityIdentityInterface $identity);
public function equals(self $identity);
}
@@ -27,8 +27,6 @@ interface SecurityIdentityRetrievalStrategyInterface
* Typically, security identities should be ordered from most specific to
* least specific.
*
* @param TokenInterface $token
*
* @return SecurityIdentityInterface[] An array of SecurityIdentityInterface implementations
*/
public function getSecurityIdentities(TokenInterface $token);
@@ -36,7 +36,7 @@ abstract class AbstractMaskBuilder implements MaskBuilderInterface
*/
public function set($mask)
{
if (!is_int($mask)) {
if (!\is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}
+18 -18
View File
@@ -32,58 +32,58 @@ class BasicPermissionMap implements PermissionMapInterface, MaskBuilderRetrieval
public function __construct()
{
$this->map = array(
self::PERMISSION_VIEW => array(
$this->map = [
self::PERMISSION_VIEW => [
MaskBuilder::MASK_VIEW,
MaskBuilder::MASK_EDIT,
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_EDIT => array(
self::PERMISSION_EDIT => [
MaskBuilder::MASK_EDIT,
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_CREATE => array(
self::PERMISSION_CREATE => [
MaskBuilder::MASK_CREATE,
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_DELETE => array(
self::PERMISSION_DELETE => [
MaskBuilder::MASK_DELETE,
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_UNDELETE => array(
self::PERMISSION_UNDELETE => [
MaskBuilder::MASK_UNDELETE,
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_OPERATOR => array(
self::PERMISSION_OPERATOR => [
MaskBuilder::MASK_OPERATOR,
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_MASTER => array(
self::PERMISSION_MASTER => [
MaskBuilder::MASK_MASTER,
MaskBuilder::MASK_OWNER,
),
],
self::PERMISSION_OWNER => array(
self::PERMISSION_OWNER => [
MaskBuilder::MASK_OWNER,
),
);
],
];
}
/**
+10 -10
View File
@@ -75,8 +75,8 @@ class MaskBuilder extends AbstractMaskBuilder
public function getPattern()
{
$pattern = self::ALL_OFF;
$length = strlen($pattern);
$bitmask = str_pad(decbin($this->mask), $length, '0', STR_PAD_LEFT);
$length = \strlen($pattern);
$bitmask = str_pad(decbin($this->mask), $length, '0', \STR_PAD_LEFT);
for ($i = $length - 1; $i >= 0; --$i) {
if ('1' === $bitmask[$i]) {
@@ -103,21 +103,21 @@ class MaskBuilder extends AbstractMaskBuilder
*/
public static function getCode($mask)
{
if (!is_int($mask)) {
if (!\is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}
$reflection = new \ReflectionClass(get_called_class());
$reflection = new \ReflectionClass(static::class);
foreach ($reflection->getConstants() as $name => $cMask) {
if (0 !== strpos($name, 'MASK_') || $mask !== $cMask) {
continue;
}
if (!defined($cName = 'static::CODE_'.substr($name, 5))) {
if (!\defined($cName = 'static::CODE_'.substr($name, 5))) {
throw new \RuntimeException('There was no code defined for this mask.');
}
return constant($cName);
return \constant($cName);
}
throw new \InvalidArgumentException(sprintf('The mask "%d" is not supported.', $mask));
@@ -134,15 +134,15 @@ class MaskBuilder extends AbstractMaskBuilder
*/
public function resolveMask($code)
{
if (is_string($code)) {
if (!defined($name = sprintf('static::MASK_%s', strtoupper($code)))) {
if (\is_string($code)) {
if (!\defined($name = sprintf('static::MASK_%s', strtoupper($code)))) {
throw new \InvalidArgumentException(sprintf('The code "%s" is not supported', $code));
}
return constant($name);
return \constant($name);
}
if (!is_int($code)) {
if (!\is_int($code)) {
throw new \InvalidArgumentException('$code must be an integer.');
}
@@ -27,7 +27,7 @@ interface PermissionMapInterface
* @param string $permission
* @param object $object
*
* @return array may return null if permission/object combination is not supported
* @return array|null may return null if permission/object combination is not supported
*/
public function getMasks($permission, $object);
+3 -15
View File
@@ -9,35 +9,23 @@
* file that was distributed with this source code.
*/
require_once __DIR__.'/../../../../ClassLoader/ClassLoader.php';
require_once __DIR__.'/../../vendor/autoload.php';
use Symfony\Component\ClassLoader\ClassLoader;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Security\Acl\Dbal\Schema;
$loader = new ClassLoader();
$loader->addPrefixes(array(
'Symfony' => __DIR__.'/../../../../../..',
'Doctrine\\Common' => __DIR__.'/../../../../../../../vendor/doctrine-common/lib',
'Doctrine\\DBAL\\Migrations' => __DIR__.'/../../../../../../../vendor/doctrine-migrations/lib',
'Doctrine\\DBAL' => __DIR__.'/../../../../../../../vendor/doctrine/dbal/lib',
'Doctrine' => __DIR__.'/../../../../../../../vendor/doctrine/lib',
));
$loader->register();
$schema = new Schema(array(
$schema = new Schema([
'class_table_name' => 'acl_classes',
'entry_table_name' => 'acl_entries',
'oid_table_name' => 'acl_object_identities',
'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
'sid_table_name' => 'acl_security_identities',
));
]);
$reflection = new ReflectionClass('Doctrine\\DBAL\\Platforms\\AbstractPlatform');
$finder = new Finder();
$finder->name('*Platform.php')->in(dirname($reflection->getFileName()));
foreach ($finder as $file) {
require_once $file->getPathName();
$className = 'Doctrine\\DBAL\\Platforms\\'.$file->getBasename('.php');
$reflection = new ReflectionClass($className);
+10
View File
@@ -6,12 +6,16 @@ CREATE TABLE acl_security_identities (id INTEGER GENERATED BY DEFAULT AS IDENTIT
CREATE UNIQUE INDEX UNIQ_8835EE78772E836AF85E0677 ON acl_security_identities (identifier, username)
COMMENT ON COLUMN acl_security_identities.username IS '(DC2Type:boolean)'
CREATE TABLE acl_object_identities (id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, parent_object_identity_id INTEGER DEFAULT NULL, class_id INTEGER NOT NULL, object_identifier VARCHAR(100) NOT NULL, entries_inheriting SMALLINT NOT NULL, PRIMARY KEY(id))
CREATE UNIQUE INDEX UNIQ_9407E5494B12AD6EA000B10 ON acl_object_identities (object_identifier, class_id)
CREATE INDEX IDX_9407E54977FA751A ON acl_object_identities (parent_object_identity_id)
COMMENT ON COLUMN acl_object_identities.entries_inheriting IS '(DC2Type:boolean)'
CREATE TABLE acl_object_identity_ancestors (object_identity_id INTEGER NOT NULL, ancestor_id INTEGER NOT NULL, PRIMARY KEY(object_identity_id, ancestor_id))
CREATE INDEX IDX_825DE2993D9AB4A6 ON acl_object_identity_ancestors (object_identity_id)
@@ -30,6 +34,12 @@ CREATE INDEX IDX_46C8B8063D9AB4A6 ON acl_entries (object_identity_id)
CREATE INDEX IDX_46C8B806DF9183C9 ON acl_entries (security_identity_id)
COMMENT ON COLUMN acl_entries.granting IS '(DC2Type:boolean)'
COMMENT ON COLUMN acl_entries.audit_success IS '(DC2Type:boolean)'
COMMENT ON COLUMN acl_entries.audit_failure IS '(DC2Type:boolean)'
ALTER TABLE acl_object_identities ADD CONSTRAINT FK_9407E54977FA751A FOREIGN KEY (parent_object_identity_id) REFERENCES acl_object_identities (id)
ALTER TABLE acl_object_identity_ancestors ADD CONSTRAINT FK_825DE2993D9AB4A6 FOREIGN KEY (object_identity_id) REFERENCES acl_object_identities (id) ON UPDATE CASCADE ON DELETE CASCADE
+5 -5
View File
@@ -1,12 +1,12 @@
CREATE TABLE acl_classes (id INT UNSIGNED AUTO_INCREMENT NOT NULL, class_type VARCHAR(200) NOT NULL, UNIQUE INDEX UNIQ_69DD750638A36066 (class_type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE acl_classes (id INT UNSIGNED AUTO_INCREMENT NOT NULL, class_type VARCHAR(200) NOT NULL, UNIQUE INDEX UNIQ_69DD750638A36066 (class_type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB
CREATE TABLE acl_security_identities (id INT UNSIGNED AUTO_INCREMENT NOT NULL, identifier VARCHAR(200) NOT NULL, username TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_8835EE78772E836AF85E0677 (identifier, username), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE acl_security_identities (id INT UNSIGNED AUTO_INCREMENT NOT NULL, identifier VARCHAR(200) NOT NULL, username TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_8835EE78772E836AF85E0677 (identifier, username), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB
CREATE TABLE acl_object_identities (id INT UNSIGNED AUTO_INCREMENT NOT NULL, parent_object_identity_id INT UNSIGNED DEFAULT NULL, class_id INT UNSIGNED NOT NULL, object_identifier VARCHAR(100) NOT NULL, entries_inheriting TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_9407E5494B12AD6EA000B10 (object_identifier, class_id), INDEX IDX_9407E54977FA751A (parent_object_identity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE acl_object_identities (id INT UNSIGNED AUTO_INCREMENT NOT NULL, parent_object_identity_id INT UNSIGNED DEFAULT NULL, class_id INT UNSIGNED NOT NULL, object_identifier VARCHAR(100) NOT NULL, entries_inheriting TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_9407E5494B12AD6EA000B10 (object_identifier, class_id), INDEX IDX_9407E54977FA751A (parent_object_identity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB
CREATE TABLE acl_object_identity_ancestors (object_identity_id INT UNSIGNED NOT NULL, ancestor_id INT UNSIGNED NOT NULL, INDEX IDX_825DE2993D9AB4A6 (object_identity_id), INDEX IDX_825DE299C671CEA1 (ancestor_id), PRIMARY KEY(object_identity_id, ancestor_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE acl_object_identity_ancestors (object_identity_id INT UNSIGNED NOT NULL, ancestor_id INT UNSIGNED NOT NULL, INDEX IDX_825DE2993D9AB4A6 (object_identity_id), INDEX IDX_825DE299C671CEA1 (ancestor_id), PRIMARY KEY(object_identity_id, ancestor_id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB
CREATE TABLE acl_entries (id INT UNSIGNED AUTO_INCREMENT NOT NULL, class_id INT UNSIGNED NOT NULL, object_identity_id INT UNSIGNED DEFAULT NULL, security_identity_id INT UNSIGNED NOT NULL, field_name VARCHAR(50) DEFAULT NULL, ace_order SMALLINT UNSIGNED NOT NULL, mask INT NOT NULL, granting TINYINT(1) NOT NULL, granting_strategy VARCHAR(30) NOT NULL, audit_success TINYINT(1) NOT NULL, audit_failure TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_46C8B806EA000B103D9AB4A64DEF17BCE4289BF4 (class_id, object_identity_id, field_name, ace_order), INDEX IDX_46C8B806EA000B103D9AB4A6DF9183C9 (class_id, object_identity_id, security_identity_id), INDEX IDX_46C8B806EA000B10 (class_id), INDEX IDX_46C8B8063D9AB4A6 (object_identity_id), INDEX IDX_46C8B806DF9183C9 (security_identity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE acl_entries (id INT UNSIGNED AUTO_INCREMENT NOT NULL, class_id INT UNSIGNED NOT NULL, object_identity_id INT UNSIGNED DEFAULT NULL, security_identity_id INT UNSIGNED NOT NULL, field_name VARCHAR(50) DEFAULT NULL, ace_order SMALLINT UNSIGNED NOT NULL, mask INT NOT NULL, granting TINYINT(1) NOT NULL, granting_strategy VARCHAR(30) NOT NULL, audit_success TINYINT(1) NOT NULL, audit_failure TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_46C8B806EA000B103D9AB4A64DEF17BCE4289BF4 (class_id, object_identity_id, field_name, ace_order), INDEX IDX_46C8B806EA000B103D9AB4A6DF9183C9 (class_id, object_identity_id, security_identity_id), INDEX IDX_46C8B806EA000B10 (class_id), INDEX IDX_46C8B8063D9AB4A6 (object_identity_id), INDEX IDX_46C8B806DF9183C9 (security_identity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB
ALTER TABLE acl_object_identities ADD CONSTRAINT FK_9407E54977FA751A FOREIGN KEY (parent_object_identity_id) REFERENCES acl_object_identities (id)
+5 -5
View File
@@ -1,24 +1,24 @@
CREATE TABLE acl_classes (id INTEGER NOT NULL, class_type VARCHAR(200) NOT NULL, PRIMARY KEY(id))
CREATE TABLE acl_classes (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, class_type VARCHAR(200) NOT NULL)
CREATE UNIQUE INDEX UNIQ_69DD750638A36066 ON acl_classes (class_type)
CREATE TABLE acl_security_identities (id INTEGER NOT NULL, identifier VARCHAR(200) NOT NULL, username BOOLEAN NOT NULL, PRIMARY KEY(id))
CREATE TABLE acl_security_identities (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, identifier VARCHAR(200) NOT NULL, username BOOLEAN NOT NULL)
CREATE UNIQUE INDEX UNIQ_8835EE78772E836AF85E0677 ON acl_security_identities (identifier, username)
CREATE TABLE acl_object_identities (id INTEGER NOT NULL, parent_object_identity_id INTEGER UNSIGNED DEFAULT NULL, class_id INTEGER UNSIGNED NOT NULL, object_identifier VARCHAR(100) NOT NULL, entries_inheriting BOOLEAN NOT NULL, PRIMARY KEY(id), CONSTRAINT FK_9407E54977FA751A FOREIGN KEY (parent_object_identity_id) REFERENCES acl_object_identities (id) NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE TABLE acl_object_identities (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, parent_object_identity_id INTEGER UNSIGNED DEFAULT NULL, class_id INTEGER UNSIGNED NOT NULL, object_identifier VARCHAR(100) NOT NULL, entries_inheriting BOOLEAN NOT NULL, CONSTRAINT FK_9407E54977FA751A FOREIGN KEY (parent_object_identity_id) REFERENCES acl_object_identities (id) NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE UNIQUE INDEX UNIQ_9407E5494B12AD6EA000B10 ON acl_object_identities (object_identifier, class_id)
CREATE INDEX IDX_9407E54977FA751A ON acl_object_identities (parent_object_identity_id)
CREATE TABLE acl_object_identity_ancestors (object_identity_id INTEGER UNSIGNED NOT NULL, ancestor_id INTEGER UNSIGNED NOT NULL, PRIMARY KEY(object_identity_id, ancestor_id), CONSTRAINT FK_825DE2993D9AB4A6 FOREIGN KEY (object_identity_id) REFERENCES acl_object_identities (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_825DE299C671CEA1 FOREIGN KEY (ancestor_id) REFERENCES acl_object_identities (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE TABLE acl_object_identity_ancestors (object_identity_id INTEGER UNSIGNED NOT NULL, ancestor_id INTEGER UNSIGNED NOT NULL, PRIMARY KEY(object_identity_id, ancestor_id), CONSTRAINT FK_825DE2993D9AB4A6 FOREIGN KEY (object_identity_id) REFERENCES acl_object_identities (id) ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_825DE299C671CEA1 FOREIGN KEY (ancestor_id) REFERENCES acl_object_identities (id) ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE INDEX IDX_825DE2993D9AB4A6 ON acl_object_identity_ancestors (object_identity_id)
CREATE INDEX IDX_825DE299C671CEA1 ON acl_object_identity_ancestors (ancestor_id)
CREATE TABLE acl_entries (id INTEGER NOT NULL, class_id INTEGER UNSIGNED NOT NULL, object_identity_id INTEGER UNSIGNED DEFAULT NULL, security_identity_id INTEGER UNSIGNED NOT NULL, field_name VARCHAR(50) DEFAULT NULL, ace_order SMALLINT UNSIGNED NOT NULL, mask INTEGER NOT NULL, granting BOOLEAN NOT NULL, granting_strategy VARCHAR(30) NOT NULL, audit_success BOOLEAN NOT NULL, audit_failure BOOLEAN NOT NULL, PRIMARY KEY(id), CONSTRAINT FK_46C8B806EA000B10 FOREIGN KEY (class_id) REFERENCES acl_classes (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_46C8B8063D9AB4A6 FOREIGN KEY (object_identity_id) REFERENCES acl_object_identities (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_46C8B806DF9183C9 FOREIGN KEY (security_identity_id) REFERENCES acl_security_identities (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE TABLE acl_entries (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, class_id INTEGER UNSIGNED NOT NULL, object_identity_id INTEGER UNSIGNED DEFAULT NULL, security_identity_id INTEGER UNSIGNED NOT NULL, field_name VARCHAR(50) DEFAULT NULL, ace_order SMALLINT UNSIGNED NOT NULL, mask INTEGER NOT NULL, granting BOOLEAN NOT NULL, granting_strategy VARCHAR(30) NOT NULL, audit_success BOOLEAN NOT NULL, audit_failure BOOLEAN NOT NULL, CONSTRAINT FK_46C8B806EA000B10 FOREIGN KEY (class_id) REFERENCES acl_classes (id) ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_46C8B8063D9AB4A6 FOREIGN KEY (object_identity_id) REFERENCES acl_object_identities (id) ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE, CONSTRAINT FK_46C8B806DF9183C9 FOREIGN KEY (security_identity_id) REFERENCES acl_security_identities (id) ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE)
CREATE UNIQUE INDEX UNIQ_46C8B806EA000B103D9AB4A64DEF17BCE4289BF4 ON acl_entries (class_id, object_identity_id, field_name, ace_order)
@@ -11,43 +11,45 @@
namespace Symfony\Component\Security\Acl\Tests\Dbal;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
/**
* @group benchmark
*/
class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
class AclProviderBenchmarkTest extends TestCase
{
/** @var \Doctrine\DBAL\Connection */
protected $con;
/** @var Connection */
protected $connection;
protected $insertClassStmt;
protected $insertSidStmt;
protected $insertOidAncestorStmt;
protected $insertOidStmt;
protected $insertEntryStmt;
protected function setUp()
protected function setUp(): void
{
try {
$this->con = DriverManager::getConnection(array(
$this->connection = DriverManager::getConnection([
'driver' => 'pdo_mysql',
'host' => 'localhost',
'user' => 'root',
'dbname' => 'testdb',
));
$this->con->connect();
]);
$this->connection->connect();
} catch (\Exception $e) {
$this->markTestSkipped('Unable to connect to the database: '.$e->getMessage());
}
}
protected function tearDown()
protected function tearDown(): void
{
$this->con = null;
$this->connection = null;
}
public function testFindAcls()
@@ -55,9 +57,9 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
// $this->generateTestData();
// get some random test object identities from the database
$oids = array();
$stmt = $this->con->executeQuery('SELECT object_identifier, class_type FROM acl_object_identities o INNER JOIN acl_classes c ON c.id = o.class_id ORDER BY RAND() LIMIT 25');
foreach ($stmt->fetchAll() as $oid) {
$oids = [];
$stmt = $this->connection->executeQuery('SELECT object_identifier, class_type FROM acl_object_identities o INNER JOIN acl_classes c ON c.id = o.class_id ORDER BY RAND() LIMIT 25');
foreach ($stmt->fetchAllAssociative() as $oid) {
$oids[] = new ObjectIdentity($oid['object_identifier'], $oid['class_type']);
}
@@ -75,22 +77,22 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
*/
protected function generateTestData()
{
$sm = $this->con->getSchemaManager();
$sm = $this->connection->createSchemaManager();
$sm->dropAndCreateDatabase('testdb');
$this->con->exec('USE testdb');
$this->connection->executeStatement('USE testdb');
// import the schema
$schema = new Schema($options = $this->getOptions());
foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
$this->con->exec($sql);
foreach ($schema->toSql($this->connection->getDatabasePlatform()) as $sql) {
$this->connection->executeStatement($sql);
}
// setup prepared statements
$this->insertClassStmt = $this->con->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
$this->insertSidStmt = $this->con->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
$this->insertOidStmt = $this->con->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
$this->insertEntryStmt = $this->con->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$this->insertOidAncestorStmt = $this->con->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');
$this->insertClassStmt = $this->connection->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
$this->insertSidStmt = $this->connection->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
$this->insertOidStmt = $this->connection->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
$this->insertEntryStmt = $this->connection->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$this->insertOidAncestorStmt = $this->connection->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');
for ($i = 0; $i < 40000; ++$i) {
$this->generateAclHierarchy();
@@ -99,19 +101,19 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
protected function generateAclHierarchy()
{
$rootId = $this->generateAcl($this->chooseClassId(), null, array());
$rootId = $this->generateAcl($this->chooseClassId(), null, []);
$this->generateAclLevel(rand(1, 15), $rootId, array($rootId));
$this->generateAclLevel(rand(1, 15), $rootId, [$rootId]);
}
protected function generateAclLevel($depth, $parentId, $ancestors)
{
$level = count($ancestors);
$level = \count($ancestors);
for ($i = 0, $t = rand(1, 10); $i < $t; ++$i) {
$id = $this->generateAcl($this->chooseClassId(), $parentId, $ancestors);
if ($level < $depth) {
$this->generateAclLevel($depth, $id, array_merge($ancestors, array($id)));
$this->generateAclLevel($depth, $id, array_merge($ancestors, [$id]));
}
}
}
@@ -120,8 +122,8 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
{
static $id = 1000;
if ($id === 1000 || ($id < 1500 && rand(0, 1))) {
$this->insertClassStmt->execute(array($id, $this->getRandomString(rand(20, 100), 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\_')));
if (1000 === $id || ($id < 1500 && rand(0, 1))) {
$this->insertClassStmt->executeStatement([$id, $this->getRandomString(rand(20, 100), 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\_')]);
++$id;
return $id - 1;
@@ -134,17 +136,17 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
{
static $id = 1000;
$this->insertOidStmt->execute(array(
$this->insertOidStmt->executeStatement([
$id,
$classId,
$this->getRandomString(rand(20, 50)),
$parentId,
rand(0, 1),
));
]);
$this->insertOidAncestorStmt->execute(array($id, $id));
$this->insertOidAncestorStmt->executeStatement([$id, $id]);
foreach ($ancestors as $ancestor) {
$this->insertOidAncestorStmt->execute(array($id, $ancestor));
$this->insertOidAncestorStmt->executeStatement([$id, $ancestor]);
}
$this->generateAces($classId, $id);
@@ -157,12 +159,12 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
{
static $id = 1000;
if ($id === 1000 || ($id < 11000 && rand(0, 1))) {
$this->insertSidStmt->execute(array(
if (1000 === $id || ($id < 11000 && rand(0, 1))) {
$this->insertSidStmt->executeStatement([
$id,
$this->getRandomString(rand(5, 30)),
rand(0, 1),
));
]);
++$id;
return $id - 1;
@@ -175,33 +177,33 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
{
static $id = 1000;
$sids = array();
$fieldOrder = array();
$sids = [];
$fieldOrder = [];
for ($i = 0; $i <= 30; ++$i) {
$fieldName = rand(0, 1) ? null : $this->getRandomString(rand(10, 20));
do {
$sid = $this->chooseSid();
} while (array_key_exists($sid, $sids) && in_array($fieldName, $sids[$sid], true));
} while (\array_key_exists($sid, $sids) && \in_array($fieldName, $sids[$sid], true));
$fieldOrder[$fieldName] = array_key_exists($fieldName, $fieldOrder) ? $fieldOrder[$fieldName] + 1 : 0;
$fieldOrder[$fieldName] = \array_key_exists($fieldName, $fieldOrder) ? $fieldOrder[$fieldName] + 1 : 0;
if (!isset($sids[$sid])) {
$sids[$sid] = array();
$sids[$sid] = [];
}
$sids[$sid][] = $fieldName;
$strategy = rand(0, 2);
if ($strategy === 0) {
if (0 === $strategy) {
$strategy = PermissionGrantingStrategy::ALL;
} elseif ($strategy === 1) {
} elseif (1 === $strategy) {
$strategy = PermissionGrantingStrategy::ANY;
} else {
$strategy = PermissionGrantingStrategy::EQUAL;
}
// id, cid, oid, field, order, sid, mask, granting, strategy, a success, a failure
$this->insertEntryStmt->execute(array(
$this->insertEntryStmt->executeStatement([
$id,
$classId,
rand(0, 5) ? $objectId : null,
@@ -213,7 +215,7 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
$strategy,
rand(0, 1),
rand(0, 1),
));
]);
++$id;
}
@@ -235,9 +237,9 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
protected function getRandomString($length, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
$s = '';
$cLength = strlen($chars);
$cLength = \strlen($chars);
while (strlen($s) < $length) {
while (\strlen($s) < $length) {
$s .= $chars[mt_rand(0, $cLength - 1)];
}
@@ -246,13 +248,13 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
protected function getOptions()
{
return array(
return [
'oid_table_name' => 'acl_object_identities',
'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
'class_table_name' => 'acl_classes',
'sid_table_name' => 'acl_security_identities',
'entry_table_name' => 'acl_entries',
);
];
}
protected function getStrategy()
@@ -262,6 +264,6 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
protected function getProvider()
{
return new AclProvider($this->con, $this->getStrategy(), $this->getOptions());
return new AclProvider($this->connection, $this->getStrategy(), $this->getOptions());
}
}
+75 -78
View File
@@ -11,36 +11,33 @@
namespace Symfony\Component\Security\Acl\Tests\Dbal;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\DriverManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
/**
* @requires extension pdo_sqlite
*/
class AclProviderTest extends \PHPUnit_Framework_TestCase
class AclProviderTest extends TestCase
{
protected $con;
protected $insertClassStmt;
protected $insertEntryStmt;
protected $insertOidStmt;
protected $insertOidAncestorStmt;
protected $insertSidStmt;
private $connection;
/**
* @expectedException \Symfony\Component\Security\Acl\Exception\AclNotFoundException
* @expectedMessage There is no ACL for the given object identity.
*/
public function testFindAclThrowsExceptionWhenNoAclExists()
{
$this->expectException(\Symfony\Component\Security\Acl\Exception\AclNotFoundException::class);
$this->getProvider()->findAcl(new ObjectIdentity('foo', 'foo'));
}
public function testFindAclsThrowsExceptionUnlessAnACLIsFoundForEveryOID()
{
$oids = array();
$oids = [];
$oids[] = new ObjectIdentity('1', 'foo');
$oids[] = new ObjectIdentity('foo', 'foo');
@@ -60,7 +57,7 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase
public function testFindAcls()
{
$oids = array();
$oids = [];
$oids[] = new ObjectIdentity('1', 'foo');
$oids[] = new ObjectIdentity('2', 'foo');
@@ -77,7 +74,7 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase
public function testFindAclsWithDifferentTypes()
{
$oids = array();
$oids = [];
$oids[] = new ObjectIdentity('123', 'Bundle\SomeVendor\MyBundle\Entity\SomeEntity');
$oids[] = new ObjectIdentity('123', 'Bundle\MyBundle\Entity\AnotherEntity');
@@ -142,49 +139,49 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('SomeClass', $sid->getClass());
}
protected function setUp()
protected function setUp(): void
{
$this->con = DriverManager::getConnection(array(
$this->connection = DriverManager::getConnection([
'driver' => 'pdo_sqlite',
'memory' => true,
));
]);
// import the schema
$schema = new Schema($options = $this->getOptions());
foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
$this->con->exec($sql);
$schema = new Schema($this->getOptions());
foreach ($schema->toSql($this->connection->getDatabasePlatform()) as $sql) {
$this->connection->executeStatement($sql);
}
// populate the schema with some test data
$this->insertClassStmt = $this->con->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
$insertClassStmt = $this->connection->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
foreach ($this->getClassData() as $data) {
$this->insertClassStmt->execute($data);
$insertClassStmt->executeStatement($data);
}
$this->insertSidStmt = $this->con->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
$insertSidStmt = $this->connection->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
foreach ($this->getSidData() as $data) {
$this->insertSidStmt->execute($data);
$insertSidStmt->executeStatement($data);
}
$this->insertOidStmt = $this->con->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
$insertOidStmt = $this->connection->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
foreach ($this->getOidData() as $data) {
$this->insertOidStmt->execute($data);
$insertOidStmt->executeStatement($data);
}
$this->insertEntryStmt = $this->con->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$insertEntryStmt = $this->connection->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach ($this->getEntryData() as $data) {
$this->insertEntryStmt->execute($data);
$insertEntryStmt->executeStatement($data);
}
$this->insertOidAncestorStmt = $this->con->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');
$insertOidAncestorStmt = $this->connection->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');
foreach ($this->getOidAncestorData() as $data) {
$this->insertOidAncestorStmt->execute($data);
$insertOidAncestorStmt->executeStatement($data);
}
}
protected function tearDown()
protected function tearDown(): void
{
$this->con = null;
$this->connection = null;
}
protected function getField($object, $field)
@@ -198,83 +195,83 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase
protected function getEntryData()
{
// id, cid, oid, field, order, sid, mask, granting, strategy, a success, a failure
return array(
array(1, 1, 1, null, 0, 1, 1, 1, 'all', 1, 1),
array(2, 1, 1, null, 1, 2, 1 << 2 | 1 << 1, 0, 'any', 0, 0),
array(3, 3, 4, null, 0, 1, 2, 1, 'all', 1, 1),
array(4, 3, 4, null, 2, 2, 1, 1, 'all', 1, 1),
array(5, 3, 4, null, 1, 3, 1, 1, 'all', 1, 1),
);
return [
[1, 1, 1, null, 0, 1, 1, 1, 'all', 1, 1],
[2, 1, 1, null, 1, 2, 1 << 2 | 1 << 1, 0, 'any', 0, 0],
[3, 3, 4, null, 0, 1, 2, 1, 'all', 1, 1],
[4, 3, 4, null, 2, 2, 1, 1, 'all', 1, 1],
[5, 3, 4, null, 1, 3, 1, 1, 'all', 1, 1],
];
}
protected function getOidData()
{
// id, cid, oid, parent_oid, entries_inheriting
return array(
array(1, 1, '123', null, 1),
array(2, 2, '123', 1, 1),
array(3, 2, 'i:3:123', 1, 1),
array(4, 3, '1', 2, 1),
array(5, 3, '2', 2, 1),
);
return [
[1, 1, '123', null, 1],
[2, 2, '123', 1, 1],
[3, 2, 'i:3:123', 1, 1],
[4, 3, '1', 2, 1],
[5, 3, '2', 2, 1],
];
}
protected function getOidAncestorData()
{
return array(
array(1, 1),
array(2, 1),
array(2, 2),
array(3, 1),
array(3, 3),
array(4, 2),
array(4, 1),
array(4, 4),
array(5, 2),
array(5, 1),
array(5, 5),
);
return [
[1, 1],
[2, 1],
[2, 2],
[3, 1],
[3, 3],
[4, 2],
[4, 1],
[4, 4],
[5, 2],
[5, 1],
[5, 5],
];
}
protected function getSidData()
{
return array(
array(1, 'SomeClass-john.doe', 1),
array(2, 'MyClass-john.doe@foo.com', 1),
array(3, 'FooClass-123', 1),
array(4, 'MooClass-ROLE_USER', 1),
array(5, 'ROLE_USER', 0),
array(6, 'IS_AUTHENTICATED_FULLY', 0),
);
return [
[1, 'SomeClass-john.doe', 1],
[2, 'MyClass-john.doe@foo.com', 1],
[3, 'FooClass-123', 1],
[4, 'MooClass-ROLE_USER', 1],
[5, 'ROLE_USER', 0],
[6, 'IS_AUTHENTICATED_FULLY', 0],
];
}
protected function getClassData()
{
return array(
array(1, 'Bundle\SomeVendor\MyBundle\Entity\SomeEntity'),
array(2, 'Bundle\MyBundle\Entity\AnotherEntity'),
array(3, 'foo'),
);
return [
[1, 'Bundle\SomeVendor\MyBundle\Entity\SomeEntity'],
[2, 'Bundle\MyBundle\Entity\AnotherEntity'],
[3, 'foo'],
];
}
protected function getOptions()
{
return array(
return [
'oid_table_name' => 'acl_object_identities',
'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
'class_table_name' => 'acl_classes',
'sid_table_name' => 'acl_security_identities',
'entry_table_name' => 'acl_entries',
);
];
}
protected function getStrategy()
protected function getStrategy(): PermissionGrantingStrategy
{
return new PermissionGrantingStrategy();
}
protected function getProvider()
protected function getProvider(): AclProvider
{
return new AclProvider($this->con, $this->getStrategy(), $this->getOptions());
return new AclProvider($this->connection, $this->getStrategy(), $this->getOptions());
}
}
@@ -11,34 +11,36 @@
namespace Symfony\Component\Security\Acl\Tests\Dbal;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Model\FieldEntryInterface;
use Symfony\Component\Security\Acl\Model\AuditableEntryInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
use Symfony\Component\Security\Acl\Domain\Entry;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\ConcurrentModificationException;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Dbal\MutableAclProvider;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\DriverManager;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\Entry;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\ConcurrentModificationException;
use Symfony\Component\Security\Acl\Model\AuditableEntryInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
use Symfony\Component\Security\Acl\Model\FieldEntryInterface;
/**
* @requires extension pdo_sqlite
*/
class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
class MutableAclProviderTest extends TestCase
{
protected $con;
protected $connection;
public static function assertAceEquals(EntryInterface $a, EntryInterface $b)
{
self::assertInstanceOf(get_class($a), $b);
self::assertInstanceOf(\get_class($a), $b);
foreach (array('getId', 'getMask', 'getStrategy', 'isGranting') as $getter) {
foreach (['getId', 'getMask', 'getStrategy', 'isGranting'] as $getter) {
self::assertSame($a->$getter(), $b->$getter());
}
@@ -55,11 +57,10 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
}
}
/**
* @expectedException \Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException
*/
public function testCreateAclThrowsExceptionWhenAclAlreadyExists()
{
$this->expectException(\Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException::class);
$provider = $this->getProvider();
$oid = new ObjectIdentity('123456', 'FOO');
$provider->createAcl($oid);
@@ -104,11 +105,10 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$provider->updateAcl($acl);
$provider->deleteAcl($parentAcl->getObjectIdentity());
try {
$provider->findAcl(new ObjectIdentity(1, 'Foo'));
$this->fail('Child-ACLs have not been deleted.');
} catch (AclNotFoundException $e) {
}
$this->expectException(AclNotFoundException::class);
$this->expectExceptionMessage('There is no ACL for the given object identity.');
$provider->findAcl(new ObjectIdentity(1, 'Foo'));
}
public function testFindAclsAddsPropertyListener()
@@ -119,7 +119,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$propertyChanges = $this->getField($provider, 'propertyChanges');
$this->assertCount(1, $propertyChanges);
$this->assertTrue($propertyChanges->contains($acl));
$this->assertEquals(array(), $propertyChanges->offsetGet($acl));
$this->assertEquals([], $propertyChanges->offsetGet($acl));
$listeners = $this->getField($acl, 'listeners');
$this->assertSame($provider, $listeners[0]);
@@ -134,7 +134,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$propertyChanges = $this->getField($provider, 'propertyChanges');
$this->assertCount(1, $propertyChanges);
$this->assertTrue($propertyChanges->contains($acl));
$this->assertEquals(array(), $propertyChanges->offsetGet($acl));
$this->assertEquals([], $propertyChanges->offsetGet($acl));
$listeners = $this->getField($acl, 'listeners');
$this->assertCount(1, $listeners);
@@ -144,17 +144,17 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
public function testFindAclsAddsPropertyListenerToParentAcls()
{
$provider = $this->getProvider();
$this->importAcls($provider, array(
'main' => array(
$this->importAcls($provider, [
'main' => [
'object_identifier' => '1',
'class_type' => 'foo',
'parent_acl' => 'parent',
),
'parent' => array(
],
'parent' => [
'object_identifier' => '1',
'class_type' => 'anotherFoo',
),
));
],
]);
$propertyChanges = $this->getField($provider, 'propertyChanges');
$this->assertCount(0, $propertyChanges);
@@ -165,15 +165,14 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($propertyChanges->contains($acl->getParentAcl()));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testPropertyChangedDoesNotTrackUnmanagedAcls()
{
$provider = $this->getProvider();
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), array(), false);
$this->expectException(\InvalidArgumentException::class);
$provider->propertyChanged($acl, 'classAces', array(), array('foo'));
$provider = $this->getProvider();
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), [], false);
$provider->propertyChanged($acl, 'classAces', [], ['foo']);
}
public function testPropertyChangedTracksChangesToAclProperties()
@@ -243,32 +242,32 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$this->assertFalse(isset($changes['aces']));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUpdateAclDoesNotAcceptUntrackedAcls()
{
$this->expectException(\InvalidArgumentException::class);
$provider = $this->getProvider();
$acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), array(), true);
$acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), [], true);
$provider->updateAcl($acl);
}
public function testUpdateDoesNothingWhenThereAreNoChanges()
{
$con = $this->getMock('Doctrine\DBAL\Connection', array(), array(), '', false);
$con = $this->createMock(Connection::class);
$con
->expects($this->never())
->method('beginTransaction')
;
$con
->expects($this->never())
->method('executeQuery')
->method('executeUpdate')
;
$provider = new MutableAclProvider($con, new PermissionGrantingStrategy(), array());
$acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), array(), true);
$provider = new MutableAclProvider($con, new PermissionGrantingStrategy(), []);
$acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), [], true);
$propertyChanges = $this->getField($provider, 'propertyChanges');
$propertyChanges->offsetSet($acl, array());
$propertyChanges->offsetSet($acl, []);
$provider->updateAcl($acl);
}
@@ -290,11 +289,11 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$acl1->insertClassAce($sid, 3);
$acl2->insertClassAce($sid, 5);
try {
$provider->updateAcl($acl1);
$this->fail('Provider failed to detect a concurrent modification.');
} catch (ConcurrentModificationException $e) {
}
$this->expectException(ConcurrentModificationException::class);
$this->expectExceptionMessage('The "classAces" property has been modified concurrently.');
$provider->updateAcl($acl1);
}
public function testUpdateAcl()
@@ -323,7 +322,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$aces = $acl->getObjectAces();
$reloadedAces = $reloadedAcl->getObjectAces();
$this->assertEquals(count($aces), count($reloadedAces));
$this->assertEquals(\count($aces), \count($reloadedAces));
foreach ($aces as $index => $ace) {
$this->assertAceEquals($ace, $reloadedAces[$index]);
}
@@ -385,6 +384,9 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$acl = $provider->findAcl($oid);
$acl->insertObjectFieldAce($fieldName, $sid3, 4);
$provider->updateAcl($acl);
$acls = $provider->findAcl($oid);
$this->assertCount(3, $acls->getObjectFieldAces($fieldName));
}
public function testUpdateAclDeletingObjectFieldAcesThrowsDBConstraintViolations()
@@ -411,6 +413,9 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$acl = $provider->findAcl($oid);
$acl->insertObjectFieldAce($fieldName, $sid3, 4);
$provider->updateAcl($acl);
$acls = $provider->findAcl($oid);
$this->assertCount(2, $acls->getObjectFieldAces($fieldName));
}
public function testUpdateUserSecurityIdentity()
@@ -437,7 +442,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
$aces = $acl->getObjectAces();
$reloadedAces = $reloadedAcl->getObjectAces();
$this->assertEquals(count($aces), count($reloadedAces));
$this->assertEquals(\count($aces), \count($reloadedAces));
foreach ($reloadedAces as $ace) {
$this->assertTrue($ace->getSecurityIdentity()->equals($newSid));
}
@@ -455,15 +460,12 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
* ),
* )
*
* @param AclProvider $provider
* @param array $data
*
* @throws \InvalidArgumentException
* @throws \Exception
*/
protected function importAcls(AclProvider $provider, array $data)
{
$aclIds = $parentAcls = array();
$aclIds = $parentAcls = [];
$con = $this->getField($provider, 'connection');
$con->beginTransaction();
try {
@@ -472,17 +474,17 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
throw new \InvalidArgumentException('"object_identifier", and "class_type" must be present.');
}
$this->callMethod($provider, 'createObjectIdentity', array(new ObjectIdentity($aclData['object_identifier'], $aclData['class_type'])));
$this->callMethod($provider, 'createObjectIdentity', [new ObjectIdentity($aclData['object_identifier'], $aclData['class_type'])]);
$aclId = $con->lastInsertId();
$aclIds[$name] = $aclId;
$sql = $this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclId));
$con->executeQuery($sql);
$sql = $this->callMethod($provider, 'getInsertObjectIdentityRelationSql', [$aclId, $aclId]);
$con->executeStatement($sql);
if (isset($aclData['parent_acl'])) {
if (isset($aclIds[$aclData['parent_acl']])) {
$con->executeQuery('UPDATE acl_object_identities SET parent_object_identity_id = '.$aclIds[$aclData['parent_acl']].' WHERE id = '.$aclId);
$con->executeQuery($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclIds[$aclData['parent_acl']])));
$con->executeStatement('UPDATE acl_object_identities SET parent_object_identity_id = '.$aclIds[$aclData['parent_acl']].' WHERE id = '.$aclId);
$con->executeStatement($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', [$aclId, $aclIds[$aclData['parent_acl']]]));
} else {
$parentAcls[$aclId] = $aclData['parent_acl'];
}
@@ -494,8 +496,8 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
throw new \InvalidArgumentException(sprintf('"%s" does not exist.', $name));
}
$con->executeQuery(sprintf('UPDATE acl_object_identities SET parent_object_identity_id = %d WHERE id = %d', $aclIds[$name], $aclId));
$con->executeQuery($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclIds[$name])));
$con->executeStatement(sprintf('UPDATE acl_object_identities SET parent_object_identity_id = %d WHERE id = %d', $aclIds[$name], $aclId));
$con->executeStatement($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', [$aclId, $aclIds[$name]]));
}
$con->commit();
@@ -514,23 +516,23 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
return $method->invokeArgs($object, $args);
}
protected function setUp()
protected function setUp(): void
{
$this->con = DriverManager::getConnection(array(
$this->connection = DriverManager::getConnection([
'driver' => 'pdo_sqlite',
'memory' => true,
));
]);
// import the schema
$schema = new Schema($this->getOptions());
foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
$this->con->exec($sql);
foreach ($schema->toSql($this->connection->getDatabasePlatform()) as $sql) {
$this->connection->executeStatement($sql);
}
}
protected function tearDown()
protected function tearDown(): void
{
$this->con = null;
$this->connection = null;
}
protected function getField($object, $field)
@@ -551,13 +553,13 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
protected function getOptions()
{
return array(
return [
'oid_table_name' => 'acl_object_identities',
'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
'class_table_name' => 'acl_classes',
'sid_table_name' => 'acl_security_identities',
'entry_table_name' => 'acl_entries',
);
];
}
protected function getStrategy()
@@ -567,6 +569,6 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
protected function getProvider($cache = null)
{
return new MutableAclProvider($this->con, $this->getStrategy(), $this->getOptions(), $cache);
return new MutableAclProvider($this->connection, $this->getStrategy(), $this->getOptions(), $cache);
}
}
+100 -89
View File
@@ -11,17 +11,18 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Doctrine\Persistence\PropertyChangedListener;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
class AclTest extends \PHPUnit_Framework_TestCase
class AclTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
$acl = new Acl(1, $oid = new ObjectIdentity('foo', 'foo'), $permissionStrategy = new PermissionGrantingStrategy(), array(), true);
$acl = new Acl(1, $oid = new ObjectIdentity('foo', 'foo'), $permissionStrategy = new PermissionGrantingStrategy(), [], true);
$this->assertSame(1, $acl->getId());
$this->assertSame($oid, $acl->getObjectIdentity());
@@ -30,11 +31,12 @@ class AclTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException \OutOfBoundsException
* @dataProvider getDeleteAceTests
*/
public function testDeleteAceThrowsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'delete'.$type.'Ace'}(0);
}
@@ -49,9 +51,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 2, 1);
$acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 3, 2);
$listener = $this->getListener(array(
$listener = $this->getListener([
$type.'Aces', 'aceOrder', 'aceOrder', $type.'Aces',
));
]);
$acl->addPropertyChangedListener($listener);
$this->assertCount(3, $acl->{'get'.$type.'Aces'}());
@@ -68,18 +70,19 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getDeleteAceTests()
{
return array(
array('class'),
array('object'),
);
return [
['class'],
['object'],
];
}
/**
* @expectedException \OutOfBoundsException
* @dataProvider getDeleteFieldAceTests
*/
public function testDeleteFieldAceThrowsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'delete'.$type.'Ace'}('foo', 0);
}
@@ -94,9 +97,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 2, 1);
$acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 3, 2);
$listener = $this->getListener(array(
$listener = $this->getListener([
$type.'Aces', 'aceOrder', 'aceOrder', $type.'Aces',
));
]);
$acl->addPropertyChangedListener($listener);
$this->assertCount(3, $acl->{'get'.$type.'Aces'}('foo'));
@@ -113,10 +116,10 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getDeleteFieldAceTests()
{
return array(
array('classField'),
array('objectField'),
);
return [
['classField'],
['objectField'],
];
}
/**
@@ -126,9 +129,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
{
$acl = $this->getAcl();
$listener = $this->getListener(array(
$listener = $this->getListener([
$property, 'aceOrder', $property, 'aceOrder', $property,
));
]);
$acl->addPropertyChangedListener($listener);
$sid = new RoleSecurityIdentity('foo');
@@ -143,21 +146,22 @@ class AclTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException \OutOfBoundsException
* @dataProvider getInsertAceTests
*/
public function testInsertClassAceThrowsExceptionOnInvalidIndex($property, $method)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->$method(new RoleSecurityIdentity('foo'), 1, 1);
}
public function getInsertAceTests()
{
return array(
array('classAces', 'insertClassAce'),
array('objectAces', 'insertObjectAce'),
);
return [
['classAces', 'insertClassAce'],
['objectAces', 'insertObjectAce'],
];
}
/**
@@ -167,10 +171,10 @@ class AclTest extends \PHPUnit_Framework_TestCase
{
$acl = $this->getAcl();
$listener = $this->getListener(array(
$listener = $this->getListener([
$property, $property, 'aceOrder', $property,
'aceOrder', 'aceOrder', $property,
));
]);
$acl->addPropertyChangedListener($listener);
$sid = new RoleSecurityIdentity('foo');
@@ -187,35 +191,36 @@ class AclTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException \OutOfBoundsException
* @dataProvider getInsertFieldAceTests
*/
public function testInsertClassFieldAceThrowsExceptionOnInvalidIndex($property, $method)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->$method('foo', new RoleSecurityIdentity('foo'), 1, 1);
}
public function getInsertFieldAceTests()
{
return array(
array('classFieldAces', 'insertClassFieldAce'),
array('objectFieldAces', 'insertObjectFieldAce'),
);
return [
['classFieldAces', 'insertClassFieldAce'],
['objectFieldAces', 'insertObjectFieldAce'],
];
}
public function testIsFieldGranted()
{
$sids = array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD'));
$masks = array(1, 2, 4);
$strategy = $this->getMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, array(), true);
$sids = [new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD')];
$masks = [1, 2, 4];
$strategy = $this->createMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, [], true);
$strategy
->expects($this->once())
->method('isFieldGranted')
->with($this->equalTo($acl), $this->equalTo('foo'), $this->equalTo($masks), $this->equalTo($sids), $this->isTrue())
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($acl->isFieldGranted('foo', $masks, $sids, true));
@@ -223,16 +228,16 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function testIsGranted()
{
$sids = array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD'));
$masks = array(1, 2, 4);
$strategy = $this->getMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, array(), true);
$sids = [new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD')];
$masks = [1, 2, 4];
$strategy = $this->createMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
$acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, [], true);
$strategy
->expects($this->once())
->method('isGranted')
->with($this->equalTo($acl), $this->equalTo($masks), $this->equalTo($sids), $this->isTrue())
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($acl->isGranted($masks, $sids, true));
@@ -243,7 +248,7 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl();
$parentAcl = $this->getAcl();
$listener = $this->getListener(array('parentAcl'));
$listener = $this->getListener(['parentAcl']);
$acl->addPropertyChangedListener($listener);
$this->assertNull($acl->getParentAcl());
@@ -258,7 +263,7 @@ class AclTest extends \PHPUnit_Framework_TestCase
{
$acl = $this->getAcl();
$listener = $this->getListener(array('entriesInheriting'));
$listener = $this->getListener(['entriesInheriting']);
$acl->addPropertyChangedListener($listener);
$this->assertTrue($acl->isEntriesInheriting());
@@ -276,29 +281,30 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function testIsSidLoaded()
{
$acl = new Acl(1, new ObjectIdentity('1', 'foo'), new PermissionGrantingStrategy(), array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('johannes', 'Bar')), true);
$acl = new Acl(1, new ObjectIdentity('1', 'foo'), new PermissionGrantingStrategy(), [new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('johannes', 'Bar')], true);
$this->assertTrue($acl->isSidLoaded(new UserSecurityIdentity('foo', 'Foo')));
$this->assertTrue($acl->isSidLoaded(new UserSecurityIdentity('johannes', 'Bar')));
$this->assertTrue($acl->isSidLoaded(array(
$this->assertTrue($acl->isSidLoaded([
new UserSecurityIdentity('foo', 'Foo'),
new UserSecurityIdentity('johannes', 'Bar'),
)));
]));
$this->assertFalse($acl->isSidLoaded(new RoleSecurityIdentity('ROLE_FOO')));
$this->assertFalse($acl->isSidLoaded(new UserSecurityIdentity('schmittjoh@gmail.com', 'Moo')));
$this->assertFalse($acl->isSidLoaded(array(
$this->assertFalse($acl->isSidLoaded([
new UserSecurityIdentity('foo', 'Foo'),
new UserSecurityIdentity('johannes', 'Bar'),
new RoleSecurityIdentity('ROLE_FOO'),
)));
]));
}
/**
* @dataProvider getUpdateAceTests
* @expectedException \OutOfBoundsException
*/
public function testUpdateAceThrowsOutOfBoundsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'update'.$type}(0, 1);
}
@@ -311,9 +317,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl();
$acl->{'insert'.$type}(new RoleSecurityIdentity('foo'), 1);
$listener = $this->getListener(array(
$listener = $this->getListener([
'mask', 'mask', 'strategy',
));
]);
$acl->addPropertyChangedListener($listener);
$aces = $acl->{'get'.$type.'s'}();
@@ -332,18 +338,19 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getUpdateAceTests()
{
return array(
array('classAce'),
array('objectAce'),
);
return [
['classAce'],
['objectAce'],
];
}
/**
* @dataProvider getUpdateFieldAceTests
* @expectedException \OutOfBoundsException
*/
public function testUpdateFieldAceThrowsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'update'.$type}(0, 'foo', 1);
}
@@ -356,9 +363,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl();
$acl->{'insert'.$type}('foo', new UserSecurityIdentity('foo', 'Foo'), 1);
$listener = $this->getListener(array(
$listener = $this->getListener([
'mask', 'mask', 'strategy',
));
]);
$acl->addPropertyChangedListener($listener);
$aces = $acl->{'get'.$type.'s'}('foo');
@@ -377,18 +384,19 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getUpdateFieldAceTests()
{
return array(
array('classFieldAce'),
array('objectFieldAce'),
);
return [
['classFieldAce'],
['objectFieldAce'],
];
}
/**
* @dataProvider getUpdateAuditingTests
* @expectedException \OutOfBoundsException
*/
public function testUpdateAuditingThrowsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'update'.$type.'Auditing'}(0, true, false);
}
@@ -401,9 +409,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl();
$acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 1);
$listener = $this->getListener(array(
$listener = $this->getListener([
'auditFailure', 'auditSuccess', 'auditFailure',
));
]);
$acl->addPropertyChangedListener($listener);
$aces = $acl->{'get'.$type.'Aces'}();
@@ -422,28 +430,30 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getUpdateAuditingTests()
{
return array(
array('class'),
array('object'),
);
return [
['class'],
['object'],
];
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider getUpdateFieldAuditingTests
*/
public function testUpdateFieldAuditingThrowsExceptionOnInvalidField($type)
{
$this->expectException(\InvalidArgumentException::class);
$acl = $this->getAcl();
$acl->{'update'.$type.'Auditing'}(0, 'foo', true, true);
}
/**
* @expectedException \OutOfBoundsException
* @dataProvider getUpdateFieldAuditingTests
*/
public function testUpdateFieldAuditingThrowsExceptionOnInvalidIndex($type)
{
$this->expectException(\OutOfBoundsException::class);
$acl = $this->getAcl();
$acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 1);
$acl->{'update'.$type.'Auditing'}(1, 'foo', true, false);
@@ -457,9 +467,9 @@ class AclTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl();
$acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 1);
$listener = $this->getListener(array(
$listener = $this->getListener([
'auditSuccess', 'auditSuccess', 'auditFailure',
));
]);
$acl->addPropertyChangedListener($listener);
$aces = $acl->{'get'.$type.'Aces'}('foo');
@@ -478,36 +488,37 @@ class AclTest extends \PHPUnit_Framework_TestCase
public function getUpdateFieldAuditingTests()
{
return array(
array('classField'),
array('objectField'),
);
return [
['classField'],
['objectField'],
];
}
protected function getListener($expectedChanges)
{
$aceProperties = array('aceOrder', 'mask', 'strategy', 'auditSuccess', 'auditFailure');
$aceProperties = ['aceOrder', 'mask', 'strategy', 'auditSuccess', 'auditFailure'];
$listener = $this->getMock('Doctrine\Common\PropertyChangedListener');
$arguments = [];
$listener = $this->createMock(PropertyChangedListener::class);
foreach ($expectedChanges as $index => $property) {
if (in_array($property, $aceProperties)) {
if (\in_array($property, $aceProperties)) {
$class = 'Symfony\Component\Security\Acl\Domain\Entry';
} else {
$class = 'Symfony\Component\Security\Acl\Domain\Acl';
}
$listener
->expects($this->at($index))
->method('propertyChanged')
->with($this->isInstanceOf($class), $this->equalTo($property))
;
$arguments[] = [$this->isInstanceOf($class), $this->equalTo($property)];
}
$listener
->method('propertyChanged')
->withConsecutive(...$arguments)
;
return $listener;
}
protected function getAcl()
{
return new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), array(), true);
return new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), [], true);
}
}
+10 -10
View File
@@ -11,7 +11,7 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
class AuditLoggerTest extends \PHPUnit_Framework_TestCase
class AuditLoggerTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider getTestLogData
@@ -25,7 +25,7 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
$ace
->expects($this->once())
->method('isAuditSuccess')
->will($this->returnValue($audit))
->willReturn($audit)
;
$ace
@@ -41,7 +41,7 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
$ace
->expects($this->once())
->method('isAuditFailure')
->will($this->returnValue($audit))
->willReturn($audit)
;
}
@@ -63,17 +63,17 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
public function getTestLogData()
{
return array(
array(true, false),
array(true, true),
array(false, false),
array(false, true),
);
return [
[true, false],
[true, true],
[false, false],
[false, true],
];
}
protected function getEntry()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface');
return $this->createMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface');
}
protected function getLogger()
@@ -11,33 +11,34 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Doctrine\Common\Cache\ArrayCache;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\DoctrineAclCache;
use Doctrine\Common\Cache\ArrayCache;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
class DoctrineAclCacheTest extends \PHPUnit_Framework_TestCase
class DoctrineAclCacheTest extends \PHPUnit\Framework\TestCase
{
protected $permissionGrantingStrategy;
/**
* @expectedException \InvalidArgumentException
* @dataProvider getEmptyValue
*/
public function testConstructorDoesNotAcceptEmptyPrefix($empty)
{
$this->expectException(\InvalidArgumentException::class);
new DoctrineAclCache(new ArrayCache(), $this->getPermissionGrantingStrategy(), $empty);
}
public function getEmptyValue()
{
return array(
array(null),
array(false),
array(''),
);
return [
[null],
[false],
[''],
];
}
public function test()
@@ -64,7 +65,7 @@ class DoctrineAclCacheTest extends \PHPUnit_Framework_TestCase
{
static $id = 1;
$acl = new Acl($id, new ObjectIdentity($id, 'foo'), $this->getPermissionGrantingStrategy(), array(), $depth > 0);
$acl = new Acl($id, new ObjectIdentity($id, 'foo'), $this->getPermissionGrantingStrategy(), [], $depth > 0);
// insert some ACEs
$sid = new UserSecurityIdentity('johannes', 'Foo');
+3 -3
View File
@@ -13,7 +13,7 @@ namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\Entry;
class EntryTest extends \PHPUnit_Framework_TestCase
class EntryTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
@@ -109,11 +109,11 @@ class EntryTest extends \PHPUnit_Framework_TestCase
protected function getAcl()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
return $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface');
}
protected function getSid()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
return $this->createMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
}
}
@@ -13,7 +13,7 @@ namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\FieldEntry;
class FieldEntryTest extends \PHPUnit_Framework_TestCase
class FieldEntryTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
@@ -64,11 +64,11 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase
protected function getAcl()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
return $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface');
}
protected function getSid()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
return $this->createMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
}
}
@@ -13,7 +13,7 @@ namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\ObjectIdentityRetrievalStrategy;
class ObjectIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
class ObjectIdentityRetrievalStrategyTest extends \PHPUnit\Framework\TestCase
{
public function testGetObjectIdentityReturnsNullForInvalidDomainObject()
{
@@ -28,7 +28,7 @@ class ObjectIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
$objectIdentity = $strategy->getObjectIdentity($domainObject);
$this->assertEquals($domainObject->getId(), $objectIdentity->getIdentifier());
$this->assertEquals(get_class($domainObject), $objectIdentity->getType());
$this->assertEquals(\get_class($domainObject), $objectIdentity->getType());
}
}
@@ -12,8 +12,9 @@
namespace Symfony\Component\Security\Acl\Tests\Domain
{
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Model\DomainObjectInterface;
class ObjectIdentityTest extends \PHPUnit_Framework_TestCase
class ObjectIdentityTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
@@ -34,17 +35,17 @@ namespace Symfony\Component\Security\Acl\Tests\Domain
public function testFromDomainObjectPrefersInterfaceOverGetId()
{
$domainObject = $this->getMock('Symfony\Component\Security\Acl\Model\DomainObjectInterface');
$domainObject
->expects($this->once())
->method('getObjectIdentifier')
->will($this->returnValue('getObjectIdentifier()'))
;
$domainObject
->expects($this->never())
->method('getId')
->will($this->returnValue('getId()'))
;
$domainObject = new class() implements DomainObjectInterface {
public function getObjectIdentifier()
{
return 'getObjectIdentifier()';
}
public function getId()
{
return 'getId()';
}
};
$id = ObjectIdentity::fromDomainObject($domainObject);
$this->assertEquals('getObjectIdentifier()', $id->getIdentifier());
@@ -98,12 +99,12 @@ namespace Symfony\Component\Security\Acl\Tests\Domain
public function getCompareData()
{
return array(
array(new ObjectIdentity('123', 'foo'), new ObjectIdentity('123', 'foo'), true),
array(new ObjectIdentity('123', 'foo'), new ObjectIdentity(123, 'foo'), true),
array(new ObjectIdentity('1', 'foo'), new ObjectIdentity('2', 'foo'), false),
array(new ObjectIdentity('1', 'bla'), new ObjectIdentity('1', 'blub'), false),
);
return [
[new ObjectIdentity('123', 'foo'), new ObjectIdentity('123', 'foo'), true],
[new ObjectIdentity('123', 'foo'), new ObjectIdentity(123, 'foo'), true],
[new ObjectIdentity('1', 'foo'), new ObjectIdentity('2', 'foo'), false],
[new ObjectIdentity('1', 'bla'), new ObjectIdentity('1', 'blub'), false],
];
}
}
@@ -11,14 +11,14 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
class PermissionGrantingStrategyTest extends \PHPUnit\Framework\TestCase
{
public function testIsGrantedObjectAcesHavePriority()
{
@@ -28,7 +28,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->insertClassAce($sid, 1);
$acl->insertObjectAce($sid, 1, 0, false);
$this->assertFalse($strategy->isGranted($acl, array(1), array($sid)));
$this->assertFalse($strategy->isGranted($acl, [1], [$sid]));
}
public function testIsGrantedFallsBackToClassAcesIfNoApplicableObjectAceWasFound()
@@ -38,7 +38,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$sid = new UserSecurityIdentity('johannes', 'Foo');
$acl->insertClassAce($sid, 1);
$this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
$this->assertTrue($strategy->isGranted($acl, [1], [$sid]));
}
public function testIsGrantedFavorsLocalAcesOverParentAclAces()
@@ -53,7 +53,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->setParentAcl($parentAcl);
$parentAcl->insertClassAce($sid, 1, 0, false);
$this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
$this->assertTrue($strategy->isGranted($acl, [1], [$sid]));
}
public function testIsGrantedFallsBackToParentAcesIfNoLocalAcesAreApplicable()
@@ -69,19 +69,18 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->setParentAcl($parentAcl);
$parentAcl->insertClassAce($sid, 1);
$this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
$this->assertTrue($strategy->isGranted($acl, [1], [$sid]));
}
/**
* @expectedException \Symfony\Component\Security\Acl\Exception\NoAceFoundException
*/
public function testIsGrantedReturnsExceptionIfNoAceIsFound()
{
$this->expectException(\Symfony\Component\Security\Acl\Exception\NoAceFoundException::class);
$strategy = new PermissionGrantingStrategy();
$acl = $this->getAcl($strategy);
$sid = new UserSecurityIdentity('johannes', 'Foo');
$strategy->isGranted($acl, array(1), array($sid));
$strategy->isGranted($acl, [1], [$sid]);
}
public function testIsGrantedFirstApplicableEntryMakesUltimateDecisionForPermissionIdentityCombination()
@@ -94,11 +93,11 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->insertClassAce($aSid, 1);
$acl->insertClassAce($sid, 1, 1, false);
$acl->insertClassAce($sid, 1, 2);
$this->assertFalse($strategy->isGranted($acl, array(1), array($sid, $aSid)));
$this->assertFalse($strategy->isGranted($acl, [1], [$sid, $aSid]));
$acl->insertObjectAce($sid, 1, 0, false);
$acl->insertObjectAce($aSid, 1, 1);
$this->assertFalse($strategy->isGranted($acl, array(1), array($sid, $aSid)));
$this->assertFalse($strategy->isGranted($acl, [1], [$sid, $aSid]));
}
public function testIsGrantedCallsAuditLoggerOnGrant()
@@ -107,7 +106,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl($strategy);
$sid = new UserSecurityIdentity('johannes', 'Foo');
$logger = $this->getMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
$logger = $this->createMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
$logger
->expects($this->once())
->method('logIfNeeded')
@@ -117,7 +116,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->insertObjectAce($sid, 1);
$acl->updateObjectAuditing(0, true, false);
$this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
$this->assertTrue($strategy->isGranted($acl, [1], [$sid]));
}
public function testIsGrantedCallsAuditLoggerOnDeny()
@@ -126,7 +125,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl = $this->getAcl($strategy);
$sid = new UserSecurityIdentity('johannes', 'Foo');
$logger = $this->getMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
$logger = $this->createMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
$logger
->expects($this->once())
->method('logIfNeeded')
@@ -136,7 +135,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->insertObjectAce($sid, 1, 0, false);
$acl->updateObjectAuditing(0, false, true);
$this->assertFalse($strategy->isGranted($acl, array(1), array($sid)));
$this->assertFalse($strategy->isGranted($acl, [1], [$sid]));
}
/**
@@ -151,36 +150,35 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
$acl->insertObjectAce($sid, $aceMask, 0, true, $maskStrategy);
if (false === $result) {
try {
$strategy->isGranted($acl, array($requiredMask), array($sid));
$this->fail('The ACE is not supposed to match.');
} catch (NoAceFoundException $e) {
}
$this->expectException(NoAceFoundException::class);
$this->expectExceptionMessage('No applicable ACE was found.');
$strategy->isGranted($acl, [$requiredMask], [$sid]);
} else {
$this->assertTrue($strategy->isGranted($acl, array($requiredMask), array($sid)));
$this->assertTrue($strategy->isGranted($acl, [$requiredMask], [$sid]));
}
}
public function getAllStrategyTests()
{
return array(
array('all', 1 << 0 | 1 << 1, 1 << 0, true),
array('all', 1 << 0 | 1 << 1, 1 << 2, false),
array('all', 1 << 0 | 1 << 10, 1 << 0 | 1 << 10, true),
array('all', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1 || 1 << 2, false),
array('any', 1 << 0 | 1 << 1, 1 << 0, true),
array('any', 1 << 0 | 1 << 1, 1 << 0 | 1 << 2, true),
array('any', 1 << 0 | 1 << 1, 1 << 2, false),
array('equal', 1 << 0 | 1 << 1, 1 << 0, false),
array('equal', 1 << 0 | 1 << 1, 1 << 1, false),
array('equal', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1, true),
);
return [
['all', 1 << 0 | 1 << 1, 1 << 0, true],
['all', 1 << 0 | 1 << 1, 1 << 2, false],
['all', 1 << 0 | 1 << 10, 1 << 0 | 1 << 10, true],
['all', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1 || 1 << 2, false],
['any', 1 << 0 | 1 << 1, 1 << 0, true],
['any', 1 << 0 | 1 << 1, 1 << 0 | 1 << 2, true],
['any', 1 << 0 | 1 << 1, 1 << 2, false],
['equal', 1 << 0 | 1 << 1, 1 << 0, false],
['equal', 1 << 0 | 1 << 1, 1 << 1, false],
['equal', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1, true],
];
}
protected function getAcl($strategy)
{
static $id = 1;
return new Acl($id++, new ObjectIdentity(1, 'Foo'), $strategy, array(), true);
return new Acl($id++, new ObjectIdentity(1, 'Foo'), $strategy, [], true);
}
}
@@ -11,11 +11,11 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
class RoleSecurityIdentityTest extends \PHPUnit_Framework_TestCase
class RoleSecurityIdentityTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
@@ -24,8 +24,15 @@ class RoleSecurityIdentityTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('ROLE_FOO', $id->getRole());
}
/**
* @group legacy
*/
public function testConstructorWithRoleInstance()
{
if (!class_exists(\Symfony\Component\Security\Core\Role\Role::class)) {
$this->markTestSkipped();
}
$id = new RoleSecurityIdentity(new Role('ROLE_FOO'));
$this->assertEquals('ROLE_FOO', $id->getRole());
@@ -43,13 +50,26 @@ class RoleSecurityIdentityTest extends \PHPUnit_Framework_TestCase
}
}
/**
* @group legacy
*/
public function testDeprecatedRoleClassEquals()
{
if (!class_exists(Role::class)) {
$this->markTestSkipped();
}
$id1 = new RoleSecurityIdentity('ROLE_FOO');
$id2 = new RoleSecurityIdentity(new Role('ROLE_FOO'));
$this->assertTrue($id1->equals($id2));
}
public function getCompareData()
{
return array(
array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_FOO'), true),
array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity(new Role('ROLE_FOO')), true),
array(new RoleSecurityIdentity('ROLE_USER'), new RoleSecurityIdentity('ROLE_FOO'), false),
array(new RoleSecurityIdentity('ROLE_FOO'), new UserSecurityIdentity('ROLE_FOO', 'Foo'), false),
);
return [
[new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_FOO'), true],
[new RoleSecurityIdentity('ROLE_USER'), new RoleSecurityIdentity('ROLE_FOO'), false],
[new RoleSecurityIdentity('ROLE_FOO'), new UserSecurityIdentity('ROLE_FOO', 'Foo'), false],
];
}
}
@@ -11,12 +11,17 @@
namespace Symfony\Component\Security\Acl\Tests\Domain;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\SecurityIdentityRetrievalStrategy;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
class SecurityIdentityRetrievalStrategyTest extends TestCase
{
/**
* @dataProvider getSecurityIdentityRetrievalTests
@@ -24,18 +29,18 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
public function testGetSecurityIdentities($user, array $roles, $authenticationStatus, array $sids)
{
if ('anonymous' === $authenticationStatus) {
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')
->disableOriginalConstructor()
->getMock();
$token = $this->getMockBuilder(AnonymousToken::class)
->disableOriginalConstructor()
->getMock();
} else {
$class = '';
if (is_string($user)) {
if (\is_string($user)) {
$class = 'MyCustomTokenImpl';
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')
->setMockClassName($class)
->getMock();
$token = $this->getMockBuilder(AbstractToken::class)
->setMockClassName($class)
->getMock();
}
if (method_exists($token, 'getRoleNames')) {
@@ -44,7 +49,7 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
$token
->expects($this->once())
->method('getRoleNames')
->will($this->returnValue(array('foo')))
->willReturn(['foo'])
;
} else {
$strategy = $this->getStrategy($roles, $authenticationStatus, true);
@@ -52,7 +57,7 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
$token
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array(new Role('foo'))))
->willReturn([new Role('foo')])
;
}
@@ -65,7 +70,7 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
}
@@ -84,55 +89,58 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
public function getSecurityIdentityRetrievalTests()
{
return array(
array($this->getAccount('johannes', 'FooUser'), array('ROLE_USER', 'ROLE_SUPERADMIN'), 'fullFledged', array(
return [
[$this->getAccount('johannes', 'FooUser'), ['ROLE_USER', 'ROLE_SUPERADMIN'], 'fullFledged', [
new UserSecurityIdentity('johannes', 'FooUser'),
new RoleSecurityIdentity('ROLE_USER'),
new RoleSecurityIdentity('ROLE_SUPERADMIN'),
new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
)),
array('johannes', array('ROLE_FOO'), 'fullFledged', array(
]],
['johannes', ['ROLE_FOO'], 'fullFledged', [
new UserSecurityIdentity('johannes', 'MyCustomTokenImpl'),
new RoleSecurityIdentity('ROLE_FOO'),
new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
)),
array(new CustomUserImpl('johannes'), array('ROLE_FOO'), 'fullFledged', array(
]],
[new CustomUserImpl('johannes'), ['ROLE_FOO'], 'fullFledged', [
new UserSecurityIdentity('johannes', 'Symfony\Component\Security\Acl\Tests\Domain\CustomUserImpl'),
new RoleSecurityIdentity('ROLE_FOO'),
new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
)),
array($this->getAccount('foo', 'FooBarUser'), array('ROLE_FOO'), 'rememberMe', array(
]],
[$this->getAccount('foo', 'FooBarUser'), ['ROLE_FOO'], 'rememberMe', [
new UserSecurityIdentity('foo', 'FooBarUser'),
new RoleSecurityIdentity('ROLE_FOO'),
new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
)),
array('guest', array('ROLE_FOO'), 'anonymous', array(
]],
['guest', ['ROLE_FOO'], 'anonymous', [
new RoleSecurityIdentity('ROLE_FOO'),
new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
)),
);
]],
];
}
protected function getAccount($username, $class)
{
$account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface', array(), array(), $class);
$account = $this->getMockBuilder(UserInterface::class)
->setMockClassName($class)
->getMock()
;
$account
->expects($this->any())
->method('getUsername')
->will($this->returnValue($username))
->willReturn($username)
;
return $account;
}
protected function getStrategy(array $roles = array(), $authenticationStatus = 'fullFledged', $isBC = false)
protected function getStrategy(array $roles = [], $authenticationStatus = 'fullFledged', $isBC = false)
{
$roleHierarchyBuilder = $this->getMockBuilder('Symfony\Component\Security\Core\Role\RoleHierarchyInterface')
->disableProxyingToOriginalMethods()
@@ -146,7 +154,7 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
->expects($this->any())
->method('getReachableRoles')
->with($this->equalTo([new Role('foo')]))
->will($this->returnValue($roles));
->willReturn($roles);
} else {
$roleHierarchy = $roleHierarchyBuilder->setMethods(['getReachableRoleNames'])
->getMockForAbstractClass();
@@ -155,23 +163,21 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
->expects($this->any())
->method('getReachableRoleNames')
->with($this->equalTo(['foo']))
->will($this->returnValue($roles));
->willReturn($roles);
}
$trustResolver = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface', array(), array('', ''));
$trustResolver = $this->createMock(AuthenticationTrustResolverInterface::class);
$trustResolver
->expects($this->at(0))
->method('isAnonymous')
->will($this->returnValue('anonymous' === $authenticationStatus))
->willReturn('anonymous' === $authenticationStatus)
;
if ('fullFledged' === $authenticationStatus) {
$trustResolver
->expects($this->once())
->method('isFullFledged')
->will($this->returnValue(true))
->willReturn(true)
;
$trustResolver
->expects($this->never())
@@ -181,28 +187,27 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
$trustResolver
->expects($this->once())
->method('isFullFledged')
->will($this->returnValue(false))
->willReturn(false)
;
$trustResolver
->expects($this->once())
->method('isRememberMe')
->will($this->returnValue(true))
->willReturn(true)
;
} else {
$trustResolver
->expects($this->at(1))
->method('isAnonymous')
->will($this->returnValue(true))
->willReturn(true)
;
$trustResolver
->expects($this->once())
->method('isFullFledged')
->will($this->returnValue(false))
->willReturn(false)
;
$trustResolver
->expects($this->once())
->method('isRememberMe')
->will($this->returnValue(false))
->willReturn(false)
;
}
@@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Acl\Tests\Domain;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
class UserSecurityIdentityTest extends \PHPUnit_Framework_TestCase
class UserSecurityIdentityTest extends \PHPUnit\Framework\TestCase
{
public function testConstructor()
{
@@ -49,25 +49,25 @@ class UserSecurityIdentityTest extends \PHPUnit_Framework_TestCase
$account
->expects($this->any())
->method('getUsername')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token
->expects($this->any())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
return array(
array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('foo', 'Foo'), true),
array(new UserSecurityIdentity('foo', 'Bar'), new UserSecurityIdentity('foo', 'Foo'), false),
array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('bar', 'Foo'), false),
array(new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromAccount($account), false),
array(new UserSecurityIdentity('bla', 'Foo'), new UserSecurityIdentity('blub', 'Foo'), false),
array(new UserSecurityIdentity('foo', 'Foo'), new RoleSecurityIdentity('foo'), false),
array(new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromToken($token), false),
array(new UserSecurityIdentity('foo', 'USI_AccountImpl'), UserSecurityIdentity::fromToken($token), true),
);
return [
[new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('foo', 'Foo'), true],
[new UserSecurityIdentity('foo', 'Bar'), new UserSecurityIdentity('foo', 'Foo'), false],
[new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('bar', 'Foo'), false],
[new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromAccount($account), false],
[new UserSecurityIdentity('bla', 'Foo'), new UserSecurityIdentity('blub', 'Foo'), false],
[new UserSecurityIdentity('foo', 'Foo'), new RoleSecurityIdentity('foo'), false],
[new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromToken($token), false],
[new UserSecurityIdentity('foo', 'USI_AccountImpl'), UserSecurityIdentity::fromToken($token), true],
];
}
}
@@ -13,7 +13,7 @@ namespace Symfony\Component\Security\Acl\Tests\Permission;
use Symfony\Component\Security\Acl\Permission\BasicPermissionMap;
class BasicPermissionMapTest extends \PHPUnit_Framework_TestCase
class BasicPermissionMapTest extends \PHPUnit\Framework\TestCase
{
public function testGetMasksReturnsNullWhenNotSupportedMask()
{
@@ -13,25 +13,26 @@ namespace Symfony\Component\Security\Acl\Tests\Permission;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
class MaskBuilderTest extends \PHPUnit_Framework_TestCase
class MaskBuilderTest extends \PHPUnit\Framework\TestCase
{
/**
* @expectedException \InvalidArgumentException
* @dataProvider getInvalidConstructorData
*/
public function testConstructorWithNonInteger($invalidMask)
{
$this->expectException(\InvalidArgumentException::class);
new MaskBuilder($invalidMask);
}
public function getInvalidConstructorData()
{
return array(
array(234.463),
array('asdgasdf'),
array(array()),
array(new \stdClass()),
);
return [
[234.463],
['asdgasdf'],
[[]],
[new \stdClass()],
];
}
public function testConstructorWithoutArguments()
+80 -80
View File
@@ -11,29 +11,29 @@
namespace Symfony\Component\Security\Acl\Tests\Voter;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use Symfony\Component\Security\Acl\Voter\AclVoter;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class AclVoterTest extends \PHPUnit_Framework_TestCase
class AclVoterTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider getSupportsAttributeTests
*/
public function testSupportsAttribute($attribute, $supported)
{
list($voter, , $permissionMap) = $this->getVoter(true, false);
[$voter, , $permissionMap] = $this->getVoter(true, false);
$permissionMap
->expects($this->once())
->method('contains')
->with($this->identicalTo($attribute))
->will($this->returnValue($supported))
->willReturn($supported)
;
$this->assertSame($supported, $voter->supportsAttribute($attribute));
@@ -44,27 +44,27 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testSupportsAttributeNonString($attribute)
{
list($voter) = $this->getVoter(true, false);
[$voter] = $this->getVoter(true, false);
$this->assertFalse($voter->supportsAttribute($attribute));
}
public function getSupportsAttributeTests()
{
return array(
array('foo', true),
array('foo', false),
);
return [
['foo', true],
['foo', false],
];
}
public function getSupportsAttributeNonStringTests()
{
return array(
array(new \stdClass()),
array(1),
array(true),
array(array()),
);
return [
[new \stdClass()],
[1],
[true],
[[]],
];
}
/**
@@ -72,30 +72,30 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testSupportsClass($class)
{
list($voter) = $this->getVoter();
[$voter] = $this->getVoter();
$this->assertTrue($voter->supportsClass($class));
}
public function getSupportsClassTests()
{
return array(
array('foo'),
array('bar'),
array('moo'),
);
return [
['foo'],
['bar'],
['moo'],
];
}
public function testVote()
{
list($voter, , $permissionMap) = $this->getVoter();
[$voter, , $permissionMap] = $this->getVoter();
$permissionMap
->expects($this->atLeastOnce())
->method('getMasks')
->will($this->returnValue(null))
->willReturn(null)
;
$this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($this->getToken(), null, array('VIEW', 'EDIT', 'DELETE')));
$this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($this->getToken(), null, ['VIEW', 'EDIT', 'DELETE']));
}
/**
@@ -103,11 +103,11 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testVoteWhenNoObjectIsPassed($allowIfObjectIdentityUnavailable)
{
list($voter, , $permissionMap) = $this->getVoter($allowIfObjectIdentityUnavailable);
[$voter, , $permissionMap] = $this->getVoter($allowIfObjectIdentityUnavailable);
$permissionMap
->expects($this->once())
->method('getMasks')
->will($this->returnValue(array()))
->willReturn([])
;
if ($allowIfObjectIdentityUnavailable) {
@@ -116,7 +116,7 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$vote = VoterInterface::ACCESS_ABSTAIN;
}
$this->assertSame($vote, $voter->vote($this->getToken(), null, array('VIEW')));
$this->assertSame($vote, $voter->vote($this->getToken(), null, ['VIEW']));
}
/**
@@ -124,17 +124,17 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testVoteWhenOidStrategyReturnsNull($allowIfUnavailable)
{
list($voter, , $permissionMap, $oidStrategy) = $this->getVoter($allowIfUnavailable);
[$voter, , $permissionMap, $oidStrategy] = $this->getVoter($allowIfUnavailable);
$permissionMap
->expects($this->once())
->method('getMasks')
->will($this->returnValue(array()))
->willReturn([])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue(null))
->willReturn(null)
;
if ($allowIfUnavailable) {
@@ -143,34 +143,34 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$vote = VoterInterface::ACCESS_ABSTAIN;
}
$this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
$this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), ['VIEW']));
}
public function getTrueFalseTests()
{
return array(array(true), array(false));
return [[true], [false]];
}
public function testVoteNoAclFound()
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$permissionMap
->expects($this->once())
->method('getMasks')
->will($this->returnValue(array()))
->willReturn([])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
->willReturn($oid = new ObjectIdentity('1', 'Foo'))
;
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
@@ -180,7 +180,7 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
->will($this->throwException(new AclNotFoundException('Not found.')))
;
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), ['VIEW']));
}
/**
@@ -188,39 +188,39 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testVoteGrantsAccess($grant)
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$permissionMap
->expects($this->once())
->method('getMasks')
->with($this->equalTo('VIEW'))
->will($this->returnValue($masks = array(1, 2, 3)))
->willReturn($masks = [1, 2, 3])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
->willReturn($oid = new ObjectIdentity('1', 'Foo'))
;
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
->expects($this->once())
->method('findAcl')
->with($this->equalTo($oid), $this->equalTo($sids))
->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
->willReturn($acl = $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface'))
;
$acl
->expects($this->once())
->method('isGranted')
->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
->will($this->returnValue($grant))
->willReturn($grant)
;
if ($grant) {
@@ -229,37 +229,37 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$vote = VoterInterface::ACCESS_DENIED;
}
$this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
$this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), ['VIEW']));
}
public function testVoteNoAceFound()
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$permissionMap
->expects($this->once())
->method('getMasks')
->with($this->equalTo('VIEW'))
->will($this->returnValue($masks = array(1, 2, 3)))
->willReturn($masks = [1, 2, 3])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
->willReturn($oid = new ObjectIdentity('1', 'Foo'))
;
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
->expects($this->once())
->method('findAcl')
->with($this->equalTo($oid), $this->equalTo($sids))
->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
->willReturn($acl = $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface'))
;
$acl
@@ -269,7 +269,7 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
->will($this->throwException(new NoAceFoundException('No ACE')))
;
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), ['VIEW']));
}
/**
@@ -277,39 +277,39 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
*/
public function testVoteGrantsFieldAccess($grant)
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$permissionMap
->expects($this->once())
->method('getMasks')
->with($this->equalTo('VIEW'))
->will($this->returnValue($masks = array(1, 2, 3)))
->willReturn($masks = [1, 2, 3])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
->willReturn($oid = new ObjectIdentity('1', 'Foo'))
;
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
->expects($this->once())
->method('findAcl')
->with($this->equalTo($oid), $this->equalTo($sids))
->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
->willReturn($acl = $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface'))
;
$acl
->expects($this->once())
->method('isFieldGranted')
->with($this->identicalTo('foo'), $this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
->will($this->returnValue($grant))
->willReturn($grant)
;
if ($grant) {
@@ -318,37 +318,37 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$vote = VoterInterface::ACCESS_DENIED;
}
$this->assertSame($vote, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
$this->assertSame($vote, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), ['VIEW']));
}
public function testVoteNoFieldAceFound()
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$permissionMap
->expects($this->once())
->method('getMasks')
->with($this->equalTo('VIEW'))
->will($this->returnValue($masks = array(1, 2, 3)))
->willReturn($masks = [1, 2, 3])
;
$oidStrategy
->expects($this->once())
->method('getObjectIdentity')
->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
->willReturn($oid = new ObjectIdentity('1', 'Foo'))
;
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
->expects($this->once())
->method('findAcl')
->with($this->equalTo($oid), $this->equalTo($sids))
->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
->willReturn($acl = $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface'))
;
$acl
@@ -358,12 +358,12 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
->will($this->throwException(new NoAceFoundException('No ACE')))
;
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), ['VIEW']));
}
public function testWhenReceivingAnObjectIdentityInterfaceWeDontRetrieveANewObjectIdentity()
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
[$voter, $provider, $permissionMap, $oidStrategy, $sidStrategy] = $this->getVoter();
$oid = new ObjectIdentity('someID', 'someType');
@@ -371,7 +371,7 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
->expects($this->once())
->method('getMasks')
->with($this->equalTo('VIEW'))
->will($this->returnValue($masks = array(1, 2, 3)))
->willReturn($masks = [1, 2, 3])
;
$oidStrategy
@@ -382,14 +382,14 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$sidStrategy
->expects($this->once())
->method('getSecurityIdentities')
->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
->willReturn($sids = [new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO')])
;
$provider
->expects($this->once())
->method('findAcl')
->with($this->equalTo($oid), $this->equalTo($sids))
->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
->willReturn($acl = $this->createMock('Symfony\Component\Security\Acl\Model\AclInterface'))
;
$acl
@@ -399,34 +399,34 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
->will($this->throwException(new NoAceFoundException('No ACE')))
;
$voter->vote($this->getToken(), $oid, array('VIEW'));
$voter->vote($this->getToken(), $oid, ['VIEW']);
}
protected function getToken()
{
return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
return $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
}
protected function getVoter($allowIfObjectIdentityUnavailable = true, $alwaysContains = true)
{
$provider = $this->getMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');
$permissionMap = $this->getMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');
$oidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');
$sidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');
$provider = $this->createMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');
$permissionMap = $this->createMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');
$oidStrategy = $this->createMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');
$sidStrategy = $this->createMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');
if ($alwaysContains) {
$permissionMap
->expects($this->any())
->method('contains')
->will($this->returnValue(true));
->willReturn(true);
}
return array(
return [
new AclVoter($provider, $oidStrategy, $sidStrategy, $permissionMap, null, $allowIfObjectIdentityUnavailable),
$provider,
$permissionMap,
$oidStrategy,
$sidStrategy,
);
];
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ final class ClassUtils
*/
public static function getRealClass($object)
{
$class = is_object($object) ? get_class($object) : $object;
$class = \is_object($object) ? \get_class($object) : $object;
if (class_exists('Doctrine\Common\Util\ClassUtils')) {
return DoctrineClassUtils::getRealClass($class);
+4 -4
View File
@@ -12,13 +12,13 @@
namespace Symfony\Component\Security\Acl\Voter;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use Symfony\Component\Security\Acl\Model\AclProviderInterface;
use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
use Symfony\Component\Security\Acl\Permission\PermissionMapInterface;
use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Acl\Permission\PermissionMapInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
@@ -48,7 +48,7 @@ class AclVoter implements VoterInterface
public function supportsAttribute($attribute)
{
return is_string($attribute) && $this->permissionMap->contains($attribute);
return \is_string($attribute) && $this->permissionMap->contains($attribute);
}
public function vote(TokenInterface $token, $object, array $attributes)
+11 -12
View File
@@ -16,30 +16,29 @@
}
],
"require": {
"php": ">=5.5.9",
"symfony/security-core": "^2.8|^3.0|^4.0|^5.0"
"php": ">=7.1.3",
"symfony/security-core": "^3.4|^4.4|^5.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^2.8|^3.0|^4.0|^5.0",
"doctrine/common": "~2.2",
"doctrine/dbal": "~2.2",
"symfony/finder": "^3.4|^4.4|^5.0",
"symfony/phpunit-bridge": "^5.2",
"doctrine/common": "^2.2|^3",
"doctrine/persistence": "^1.3.3|^2",
"doctrine/dbal": "^2.13.1|^3.1",
"psr/log": "~1.0"
},
"suggest": {
"symfony/class-loader": "For using the ACL generateSql script",
"symfony/finder": "For using the ACL generateSql script",
"doctrine/dbal": "For using the built-in ACL implementation"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Security\\Acl\\": "" },
"exclude-from-classmap": [
"/Tests/"
]
},
"minimum-stability": "dev",
"conflict": {
"doctrine/dbal": "<2.13.1|~3.0.0"
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
"dev-main": "3.x-dev"
}
}
}
+10 -7
View File
@@ -1,15 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />
@@ -31,4 +26,12 @@
</exclude>
</whitelist>
</filter>
<groups>
<exclude>
<group>benchmark</group>
</exclude>
</groups>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener"/>
</listeners>
</phpunit>