Exemplo n.º 1
0
 /**
  * @param EventInterface $value
  * @throws \Exception
  */
 public function onNext($value)
 {
     $uri = $value->getName();
     // TODO add route cache
     foreach ($this->routing as $subject) {
         /* @var ReplaySubject $subject */
         $routes = $this->routing->offsetGet($subject);
         foreach ($routes as $data) {
             if (!preg_match($data['regex'], $uri, $matches)) {
                 continue;
             }
             $vars = [];
             $i = 0;
             foreach ($data['routeMap'] as $varName) {
                 $vars[$varName] = $matches[++$i];
             }
             $labels = $value->getLabels();
             $labels = array_merge($labels, $vars);
             $value->setLabels($labels);
             $subject->onNext($value);
             return;
         }
     }
     throw new \Exception("not found");
 }
Exemplo n.º 2
0
 /**
  * @param \AGmakonts\STL\String\Text $entityType
  *
  * @return AbstractRepository
  * @throws \AGmakonts\DddBricks\Repository\Exception\HelperException
  */
 protected function getHelperForEntityType(Text $entityType)
 {
     if (FALSE === $this->_helpers->offsetExists($entityType)) {
         throw new HelperException(HelperException::HELPER_UNKNOWN);
     }
     return $this->_helpers->offsetGet($entityType);
 }
Exemplo n.º 3
0
 /**
  * @param Peer $peer
  * @return PeerState
  */
 public function fetch(Peer $peer)
 {
     if (!$this->storage->contains($peer)) {
         $state = $this->createState($peer);
     } else {
         $state = $this->storage->offsetGet($peer);
     }
     return $state;
 }
Exemplo n.º 4
0
 /**
  * @param HandlerInterface $handler
  * @param array            $categories
  */
 public function attach(HandlerInterface $handler, array $categories = array())
 {
     if ($this->handlers->contains($handler)) {
         $handlerCategories = $this->handlers->offsetGet($handler);
         $this->handlers->offsetSet($handler, array_merge((array) $handlerCategories, $categories));
     } else {
         $this->handlers->attach($handler, $categories);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function finish(RequestInterface $request, ResponseInterface $response)
 {
     if ($this->isTerminableKernel) {
         list($sfRequest, $sfResponse) = $this->requestMapping->offsetGet($request);
         $this->requestMapping->detach($request);
         $kernel = $this->kernel;
         /* @var $kernel TerminableInterface */
         $kernel->terminate($sfRequest, $sfResponse);
     }
 }
Exemplo n.º 6
0
 /**
  * Triggered when a client sends data through the socket
  * @param  \Ratchet\ConnectionInterface $from The socket/connection that sent the message to your application
  * @param  string $msg The message received
  * @throws \Exception
  *
  * expects:
  * { 'cmd': "identifier", 'payload': {<data>}}
  * could use bson instead
  */
 function onMessage(ConnectionInterface $from, $msg)
 {
     $from = $this->connections->offsetGet($from);
     if (null === ($json = @json_decode($msg, true))) {
         throw new JsonException();
     }
     if (!is_array($json)) {
         throw new Exception("Invalid message");
     }
     $this->wrapped->onMessage($from, $json);
 }
Exemplo n.º 7
0
 /**
  * Returns list of observers for subject
  *
  * @param SubjectInterface $s
  *
  * @return \SplObjectStorage|ObserverInterface[]
  */
 protected function getObservers(SubjectInterface $s)
 {
     if ($this->perSubjectObservers === null) {
         $this->perSubjectObservers = new \SplObjectStorage();
     }
     if (!isset($this->perSubjectObservers[$s])) {
         $observers = new \SplObjectStorage();
         $this->perSubjectObservers->offsetSet($s, $observers);
     } else {
         $observers = $this->perSubjectObservers->offsetGet($s);
     }
     return $observers;
 }
Exemplo n.º 8
0
 /**
  * @return bool
  */
 public function save()
 {
     $pkField = self::getAutoIncrementField();
     if ($this->isNewRecord()) {
         if (($id = $this->insertGetId((array) $this)) > 0) {
             $this->{$pkField} = $id;
             return true;
         }
         return false;
     } else {
         $original = unserialize(static::$modelStorage->offsetGet($this));
         return 1 == $this->where($pkField . '=?', array($original[$pkField]))->update((array) $this);
     }
 }
Exemplo n.º 9
0
 /**
  * Returns the validation groups of the given form.
  *
  * @param  FormInterface $form The form.
  *
  * @return array The validation groups.
  */
 private static function getValidationGroups(FormInterface $form)
 {
     $root = $form->getRoot();
     // Determine the clicked button of the complete form tree
     if (!static::$clickedButtons->contains($root)) {
         // Only call findClickedButton() once to prevent an exponential
         // runtime
         // https://github.com/symfony/symfony/issues/8317
         static::$clickedButtons->attach($root, self::findClickedButton($root));
     }
     $button = static::$clickedButtons->offsetGet($root);
     if (null !== $button) {
         $groups = $button->getConfig()->getOption('validation_groups');
         if (null !== $groups) {
             return self::resolveValidationGroups($groups, $form);
         }
     }
     do {
         $groups = $form->getConfig()->getOption('validation_groups');
         if (null !== $groups) {
             return self::resolveValidationGroups($groups, $form);
         }
         $form = $form->getParent();
     } while (null !== $form);
     return array(Constraint::DEFAULT_GROUP);
 }
 /**
  * Call the view helper associated with this object.
  *
  * First, it evaluates the arguments of the view helper.
  *
  * If the view helper implements \TYPO3\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface,
  * it calls setChildNodes(array childNodes) on the view helper.
  *
  * Afterwards, checks that the view helper did not leave a variable lying around.
  *
  * @param RenderingContextInterface $renderingContext
  * @return object evaluated node after the view helper has been called.
  */
 public function evaluate(RenderingContextInterface $renderingContext)
 {
     if ($this->viewHelpersByContext->contains($renderingContext)) {
         $viewHelper = $this->viewHelpersByContext->offsetGet($renderingContext);
         $viewHelper->resetState();
     } else {
         $viewHelper = clone $this->uninitializedViewHelper;
         $this->viewHelpersByContext->attach($renderingContext, $viewHelper);
     }
     $evaluatedArguments = array();
     if (count($viewHelper->prepareArguments())) {
         /** @var $argumentDefinition ArgumentDefinition */
         foreach ($viewHelper->prepareArguments() as $argumentName => $argumentDefinition) {
             if (isset($this->arguments[$argumentName])) {
                 /** @var $argumentValue NodeInterface */
                 $argumentValue = $this->arguments[$argumentName];
                 $evaluatedArguments[$argumentName] = $argumentValue->evaluate($renderingContext);
             } else {
                 $evaluatedArguments[$argumentName] = $argumentDefinition->getDefaultValue();
             }
         }
     }
     $viewHelper->setArguments($evaluatedArguments);
     $viewHelper->setViewHelperNode($this);
     $viewHelper->setRenderingContext($renderingContext);
     if ($viewHelper instanceof ChildNodeAccessInterface) {
         $viewHelper->setChildNodes($this->childNodes);
     }
     $output = $viewHelper->initializeArgumentsAndRender();
     return $output;
 }
Exemplo n.º 11
0
 /**
  * @param \Sitemapper\SitemapInterface $sitemap
  */
 protected function saveSitemap(SitemapInterface $sitemap)
 {
     if ($this->sitemaps->contains($sitemap)) {
         $index = $this->sitemaps->offsetGet($sitemap);
         $this->saveFile($this->getPathname($index), $sitemap->getOutput());
         $this->savedSitemaps->attach($sitemap);
     }
 }
Exemplo n.º 12
0
 /**
  * @param WebSocketObservableTable $table
  *
  * @return Vector|WebSocketConnection[]
  */
 private function getConnectionsSubscribedToTable(WebSocketObservableTable $table)
 {
     try {
         return $this->tableConnectionMap->offsetGet($table);
     } catch (\Exception $e) {
         return new Vector();
     }
 }
Exemplo n.º 13
0
 /**
  * getData()
  *
  * gets the data set of a given route
  *
  * @param \Naquadria\Components\Routing\Route $route
  * @throws \Naquadria\Components\Routing\Exceptions\RouteNotFoundException
  * @return mixed
  */
 public function getData(Route $route)
 {
     if (!parent::contains($route)) {
         throw new RouteNotFoundException('Unknown route instance');
     }
     $current = parent::offsetGet($route);
     return $current['data'];
 }
Exemplo n.º 14
0
 public function handleItems($object, array $items, SerializationContext $context)
 {
     if ($this->deferredData->contains($object)) {
         $items = array_merge($this->deferredData->offsetGet($object), $items);
         $this->deferredData->detach($object);
     }
     $parentObjectInlining = $this->getParentObjectInlining($object, $context);
     if (null === $parentObjectInlining) {
         return $items;
     }
     if ($this->deferredData->contains($parentObjectInlining)) {
         $items = array_merge($items, $this->deferredData->offsetGet($parentObjectInlining));
     }
     // We need to defer the links serialization to the $parentObject
     $this->deferredData->attach($parentObjectInlining, $items);
     return array();
 }
Exemplo n.º 15
0
 /**
  * Send data to database
  *
  * @return \Sokil\Mongo\Persistence
  */
 public function flush()
 {
     /** @var $document \Sokil\Mongo\Document */
     foreach ($this->_pool as $document) {
         switch ($this->_pool->offsetGet($document)) {
             case self::STATE_SAVE:
                 $document->save();
                 break;
             case self::STATE_REMOVE:
                 // delete document form db
                 $document->delete();
                 // remove link form pool
                 $this->detach($document);
                 break;
         }
     }
     return $this;
 }
Exemplo n.º 16
0
 /**
  * @param object $object
  *
  * @return \Kdyby\Doctrine\Forms\EntityContainer|\Kdyby\Doctrine\Forms\CollectionContainer
  */
 public function getComponent($object)
 {
     if ($this->entities->contains($object)) {
         return $this->entities->offsetGet($object);
     } elseif ($this->collections->contains($object)) {
         return $this->collections->offsetGet($object);
     }
     return NULL;
 }
Exemplo n.º 17
0
 private function eventsToPublishOn(EventMessageInterface $event, EventBusInterface $eventBus)
 {
     if (!$this->eventsToPublish->contains($eventBus)) {
         $this->eventsToPublish->attach($eventBus, array($event));
         return;
     }
     $events = $this->eventsToPublish->offsetGet($eventBus);
     $events[] = $event;
     $this->eventsToPublish->offsetSet($eventBus, $events);
 }
Exemplo n.º 18
0
 /**
  * @param BlockHeaderInterface $header
  * @return BlockIndexInterface|bool
  */
 public function hasBlockTip(BlockHeaderInterface $header)
 {
     echo "CheckHashBlockTip - " . count($this->segments) . PHP_EOL;
     foreach ($this->segments as $segment) {
         /** @var BlockIndexInterface $segBlock */
         $segBlock = $this->segmentBlock->offsetGet($segment);
         if ($header->getPrevBlock()->equals($segBlock->getHash())) {
             return $segBlock;
         }
     }
     return false;
 }
Exemplo n.º 19
0
 /**
  * @param Type $type
  * The element type for an array.
  *
  * @return GenericArrayType
  * Get a type representing an array of the given type
  */
 public static function fromElementType(Type $type) : GenericArrayType
 {
     // Make sure we only ever create exactly one
     // object for any unique type
     static $canonical_object_map = null;
     if (!$canonical_object_map) {
         $canonical_object_map = new \SplObjectStorage();
     }
     if (!$canonical_object_map->contains($type)) {
         $canonical_object_map->attach($type, new GenericArrayType($type));
     }
     return $canonical_object_map->offsetGet($type);
 }
Exemplo n.º 20
0
 /**
  * Returns the current focused model, sets the focus if $class is specified
  *
  * @param Yada_Model|string $model
  * @return Yada_Model
  */
 public function model($model = NULL)
 {
     if ($model instanceof Yada_Model) {
         if (!$this->_models->contains($model)) {
             $this->attach($model);
         } else {
             $this->_current = $model;
             $this->_meta = $this->_models->offsetGet($this->_current);
         }
     } elseif (is_string($model)) {
         // Attach and initialize unknown models
         $model = Yada::model($model);
         $this->attach($model);
     }
     // Return the current Model object
     return $this->_current;
 }
Exemplo n.º 21
0
 /**
  * Offset to retrieve
  * @link http://php.net/manual/en/arrayaccess.offsetget.php
  * @param mixed $offset <p>
  * The offset to retrieve.
  * </p>
  * @return mixed Can return all value types.
  * @since 5.0.0
  */
 public function offsetGet($offset)
 {
     if (is_scalar($offset)) {
         return $this->scalarStore[$offset];
     }
     if (is_object($offset)) {
         return $this->objectStore->offsetGet($offset);
     }
     if (is_array($offset)) {
         // offsetGet is often called directly after offsetExists, so optimize to avoid second loop:
         if ($this->lastArrayKey === $offset) {
             return $this->lastArrayValue;
         }
         foreach ($this->arrayKeys as $index => $entry) {
             if ($entry === $offset) {
                 return $this->arrayValues[$index];
             }
         }
     }
     return null;
 }
Exemplo n.º 22
0
 /**
  * This method is called to hydrate ACLs and ACEs.
  *
  * This method was designed for performance; thus, a lot of code has been
  * inlined at the cost of readability, and maintainability.
  *
  * 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
  * @throws \RuntimeException
  * @return \SplObjectStorage
  */
 protected function hydrateObjectIdentities(Statement $stmt, array $oidLookup, array $sids)
 {
     $parentIdToFill = new \SplObjectStorage();
     $acls = $aces = $emptyArray = array();
     $oidCache = $oidLookup;
     $result = new \SplObjectStorage();
     $loadedAces =& $this->loadedAces;
     $loadedAcls =& $this->loadedAcls;
     $permissionGrantingStrategy = $this->permissionGrantingStrategy;
     // we need these to set protected properties on hydrated objects
     $aclReflection = new \ReflectionClass('Symfony\\Component\\Security\\Acl\\Domain\\Acl');
     $aclClassAcesProperty = $aclReflection->getProperty('classAces');
     $aclClassAcesProperty->setAccessible(true);
     $aclClassFieldAcesProperty = $aclReflection->getProperty('classFieldAces');
     $aclClassFieldAcesProperty->setAccessible(true);
     $aclObjectAcesProperty = $aclReflection->getProperty('objectAces');
     $aclObjectAcesProperty->setAccessible(true);
     $aclObjectFieldAcesProperty = $aclReflection->getProperty('objectFieldAces');
     $aclObjectFieldAcesProperty->setAccessible(true);
     $aclParentAclProperty = $aclReflection->getProperty('parentAcl');
     $aclParentAclProperty->setAccessible(true);
     // fetchAll() consumes more memory than consecutive calls to fetch(),
     // but it is faster
     foreach ($stmt->fetchAll(\PDO::FETCH_NUM) as $data) {
         list($aclId, $objectIdentifier, $parentObjectIdentityId, $entriesInheriting, $classType, $aceId, $objectIdentityId, $fieldName, $aceOrder, $mask, $granting, $grantingStrategy, $auditSuccess, $auditFailure, $username, $securityIdentifier) = $data;
         // has the ACL been hydrated during this hydration cycle?
         if (isset($acls[$aclId])) {
             $acl = $acls[$aclId];
         } else {
             if (isset($loadedAcls[$classType][$objectIdentifier])) {
                 $acl = $loadedAcls[$classType][$objectIdentifier];
                 // keep reference in local array (saves us some hash calculations)
                 $acls[$aclId] = $acl;
                 // attach ACL to the result set; even though we do not enforce that every
                 // object identity has only one instance, we must make sure to maintain
                 // referential equality with the oids passed to findAcls()
                 if (!isset($oidCache[$objectIdentifier . $classType])) {
                     $oidCache[$objectIdentifier . $classType] = $acl->getObjectIdentity();
                 }
                 $result->attach($oidCache[$objectIdentifier . $classType], $acl);
             } else {
                 // create object identity if we haven't done so yet
                 $oidLookupKey = $objectIdentifier . $classType;
                 if (!isset($oidCache[$oidLookupKey])) {
                     $oidCache[$oidLookupKey] = new ObjectIdentity($objectIdentifier, $classType);
                 }
                 $acl = new Acl((int) $aclId, $oidCache[$oidLookupKey], $permissionGrantingStrategy, $emptyArray, !!$entriesInheriting);
                 // keep a local, and global reference to this ACL
                 $loadedAcls[$classType][$objectIdentifier] = $acl;
                 $acls[$aclId] = $acl;
                 // try to fill in parent ACL, or defer until all ACLs have been hydrated
                 if (null !== $parentObjectIdentityId) {
                     if (isset($acls[$parentObjectIdentityId])) {
                         $aclParentAclProperty->setValue($acl, $acls[$parentObjectIdentityId]);
                     } else {
                         $parentIdToFill->attach($acl, $parentObjectIdentityId);
                     }
                 }
                 $result->attach($oidCache[$oidLookupKey], $acl);
             }
         }
         // check if this row contains an ACE record
         if (null !== $aceId) {
             // have we already hydrated ACEs for this ACL?
             if (!isset($aces[$aclId])) {
                 $aces[$aclId] = array($emptyArray, $emptyArray, $emptyArray, $emptyArray);
             }
             // has this ACE already been hydrated during a previous cycle, or
             // possible been loaded from cache?
             // It is important to only ever have one ACE instance per actual row since
             // some ACEs are shared between ACL instances
             if (!isset($loadedAces[$aceId])) {
                 if (!isset($sids[$key = ($username ? '1' : '0') . $securityIdentifier])) {
                     if ($username) {
                         $sids[$key] = new UserSecurityIdentity(substr($securityIdentifier, 1 + ($pos = strpos($securityIdentifier, '-'))), substr($securityIdentifier, 0, $pos));
                     } else {
                         $sids[$key] = new RoleSecurityIdentity($securityIdentifier);
                     }
                 }
                 if (null === $fieldName) {
                     $loadedAces[$aceId] = new Entry((int) $aceId, $acl, $sids[$key], $grantingStrategy, (int) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
                 } else {
                     $loadedAces[$aceId] = new FieldEntry((int) $aceId, $acl, $fieldName, $sids[$key], $grantingStrategy, (int) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
                 }
             }
             $ace = $loadedAces[$aceId];
             // assign ACE to the correct property
             if (null === $objectIdentityId) {
                 if (null === $fieldName) {
                     $aces[$aclId][0][$aceOrder] = $ace;
                 } else {
                     $aces[$aclId][1][$fieldName][$aceOrder] = $ace;
                 }
             } else {
                 if (null === $fieldName) {
                     $aces[$aclId][2][$aceOrder] = $ace;
                 } else {
                     $aces[$aclId][3][$fieldName][$aceOrder] = $ace;
                 }
             }
         }
     }
     // We do not sort on database level since we only want certain subsets to be sorted,
     // and we are going to read the entire result set anyway.
     // Sorting on DB level increases query time by an order of magnitude while it is
     // almost negligible when we use PHPs array sort functions.
     foreach ($aces as $aclId => $aceData) {
         $acl = $acls[$aclId];
         ksort($aceData[0]);
         $aclClassAcesProperty->setValue($acl, $aceData[0]);
         foreach (array_keys($aceData[1]) as $fieldName) {
             ksort($aceData[1][$fieldName]);
         }
         $aclClassFieldAcesProperty->setValue($acl, $aceData[1]);
         ksort($aceData[2]);
         $aclObjectAcesProperty->setValue($acl, $aceData[2]);
         foreach (array_keys($aceData[3]) as $fieldName) {
             ksort($aceData[3][$fieldName]);
         }
         $aclObjectFieldAcesProperty->setValue($acl, $aceData[3]);
     }
     // fill-in parent ACLs where this hasn't been done yet cause the parent ACL was not
     // yet available
     $processed = 0;
     foreach ($parentIdToFill as $acl) {
         $parentId = $parentIdToFill->offsetGet($acl);
         // let's see if we have already hydrated this
         if (isset($acls[$parentId])) {
             $aclParentAclProperty->setValue($acl, $acls[$parentId]);
             $processed += 1;
             continue;
         }
     }
     // reset reflection changes
     $aclClassAcesProperty->setAccessible(false);
     $aclClassFieldAcesProperty->setAccessible(false);
     $aclObjectAcesProperty->setAccessible(false);
     $aclObjectFieldAcesProperty->setAccessible(false);
     $aclParentAclProperty->setAccessible(false);
     // this should never be true if the database integrity hasn't been compromised
     if ($processed < count($parentIdToFill)) {
         throw new \RuntimeException('Not all parent ids were populated. This implies an integrity problem.');
     }
     return $result;
 }
Exemplo n.º 23
0
 public function offsetUnset($index)
 {
     $this->validateIndex($index);
     // Decrement counters when replacing existing item
     if (parent::offsetExists($index)) {
         $oldResult = parent::offsetGet($index);
         if ($oldResult instanceof Success) {
             $this->countSuccess--;
         } elseif ($oldResult instanceof Failure) {
             $this->countFailure--;
         } elseif ($oldResult instanceof Warning) {
             $this->countWarning--;
         } else {
             $this->countUnknown--;
         }
     }
     parent::offsetUnset($index);
 }
Exemplo n.º 24
0
    /**
     * Generates the inline definition of a service.
     *
     * @param string     $id
     * @param Definition $definition
     *
     * @return string
     *
     * @throws RuntimeException                  When the factory definition is incomplete
     * @throws ServiceCircularReferenceException When a circular reference is detected
     */
    private function addServiceInlinedDefinitions($id, $definition)
    {
        $code = '';
        $variableMap = $this->definitionVariables;
        $nbOccurrences = new \SplObjectStorage();
        $processed = new \SplObjectStorage();
        $inlinedDefinitions = $this->getInlinedDefinitions($definition);

        foreach ($inlinedDefinitions as $definition) {
            if (false === $nbOccurrences->contains($definition)) {
                $nbOccurrences->offsetSet($definition, 1);
            } else {
                $i = $nbOccurrences->offsetGet($definition);
                $nbOccurrences->offsetSet($definition, $i + 1);
            }
        }

        foreach ($inlinedDefinitions as $sDefinition) {
            if ($processed->contains($sDefinition)) {
                continue;
            }
            $processed->offsetSet($sDefinition);

            $class = $this->dumpValue($sDefinition->getClass());
            if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) {
                $name = $this->getNextVariableName();
                $variableMap->offsetSet($sDefinition, new Variable($name));

                // a construct like:
                // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a);
                // this is an indication for a wrong implementation, you can circumvent this problem
                // by setting up your service structure like this:
                // $b = new ServiceB();
                // $a = new ServiceA(ServiceB $b);
                // $b->setServiceA(ServiceA $a);
                if ($this->hasReference($id, $sDefinition->getArguments())) {
                    throw new ServiceCircularReferenceException($id, array($id));
                }

                $code .= $this->addNewInstance($id, $sDefinition, '$'.$name, ' = ');

                if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) {
                    $code .= $this->addServiceMethodCalls(null, $sDefinition, $name);
                    $code .= $this->addServiceProperties(null, $sDefinition, $name);
                    $code .= $this->addServiceConfigurator(null, $sDefinition, $name);
                }

                $code .= "\n";
            }
        }

        return $code;
    }
Exemplo n.º 25
0
 private function updateAce(\SplObjectStorage $aces, $ace)
 {
     $propertyChanges = $aces->offsetGet($ace);
     $sets = array();
     if (isset($propertyChanges['aceOrder']) && $propertyChanges['aceOrder'][1] > $propertyChanges['aceOrder'][0] && $propertyChanges == $aces->offsetGet($ace)) {
         $aces->next();
         if ($aces->valid()) {
             $this->updateAce($aces, $aces->current());
         }
     }
     if (isset($propertyChanges['mask'])) {
         $sets[] = sprintf('mask = %d', $propertyChanges['mask'][1]);
     }
     if (isset($propertyChanges['strategy'])) {
         $sets[] = sprintf('granting_strategy = %s', $this->connection->quote($propertyChanges['strategy']));
     }
     if (isset($propertyChanges['aceOrder'])) {
         $sets[] = sprintf('ace_order = %d', $propertyChanges['aceOrder'][1]);
     }
     if (isset($propertyChanges['auditSuccess'])) {
         $sets[] = sprintf('audit_success = %s', $this->connection->getDatabasePlatform()->convertBooleans($propertyChanges['auditSuccess'][1]));
     }
     if (isset($propertyChanges['auditFailure'])) {
         $sets[] = sprintf('audit_failure = %s', $this->connection->getDatabasePlatform()->convertBooleans($propertyChanges['auditFailure'][1]));
     }
     $this->connection->executeQuery($this->getUpdateAccessControlEntrySql($ace->getId(), $sets));
 }
Exemplo n.º 26
0
 /**
  * Gets ACL associated with the given object identity from the collections specified in $acls argument.
  *
  * @param \SplObjectStorage $acls
  * @param OID $oid
  * @return AclInterface|null
  */
 protected function findAclByOid(\SplObjectStorage $acls, ObjectIdentity $oid)
 {
     $result = null;
     foreach ($acls as $aclOid) {
         if ($oid->equals($aclOid)) {
             $result = $acls->offsetGet($aclOid);
             break;
         }
     }
     return $result;
 }
Exemplo n.º 27
0
 /**
  * This method is called to hydrate ACLs and ACEs.
  *
  * This method was designed for performance; thus, a lot of code has been
  * inlined at the cost of readability, and maintainability.
  *
  * Keep in mind that changes to this method might severely reduce the
  * performance of the entire ACL system.
  *
  * @param Cursor $cursor
  * @param Cursor $objectIdentities
  * @param array $oidLookup
  * @param array $sids
  * @throws \RuntimeException
  * @return \SplObjectStorage
  */
 protected function hydrateObjectIdentities(Cursor $entryCursor, Cursor $objectCursor, array $oidLookup, array $sids)
 {
     $parentIdToFill = new \SplObjectStorage();
     $acls = $aces = $emptyArray = array();
     $oidCache = $oidLookup;
     $result = new \SplObjectStorage();
     $loadedAces =& $this->loadedAces;
     $loadedAcls =& $this->loadedAcls;
     $permissionGrantingStrategy = $this->permissionGrantingStrategy;
     // we need these to set protected properties on hydrated objects
     $aclReflection = new \ReflectionClass('Symfony\\Component\\Security\\Acl\\Domain\\Acl');
     $aclClassAcesProperty = $aclReflection->getProperty('classAces');
     $aclClassAcesProperty->setAccessible(true);
     $aclClassFieldAcesProperty = $aclReflection->getProperty('classFieldAces');
     $aclClassFieldAcesProperty->setAccessible(true);
     $aclObjectAcesProperty = $aclReflection->getProperty('objectAces');
     $aclObjectAcesProperty->setAccessible(true);
     $aclObjectFieldAcesProperty = $aclReflection->getProperty('objectFieldAces');
     $aclObjectFieldAcesProperty->setAccessible(true);
     $aclParentAclProperty = $aclReflection->getProperty('parentAcl');
     $aclParentAclProperty->setAccessible(true);
     $entries = $classEntries = array();
     /**
      * using iterator_to_array is faster, but could cause potential problems with low memory, high data set
      * if it does in the foreach()
      * use $entryCursor instead of $entryData
      * use $objectCursor instead of $objectData
      *
      * TODO: should this be configurable?
      */
     $entryData = iterator_to_array($entryCursor);
     foreach ($entryData as $entry) {
         $eid = (string) $entry['_id'];
         if (isset($entry['objectIdentity'])) {
             $objectId = (string) $entry['objectIdentity']['$id'];
             $entries[$objectId][$eid] = $entry;
         } elseif (isset($entry['class'])) {
             $class = (string) $entry['class'];
             $classEntries[$class][$eid] = $entry;
         }
     }
     $objectData = iterator_to_array($objectCursor);
     foreach ($objectData as $curObject) {
         $aclId = (string) $curObject['_id'];
         $type = (string) $curObject['type'];
         $oid[$aclId] = $curObject;
         if (!isset($entries[$aclId])) {
             $parent = $curObject;
             while ((string) $parent['_id'] != $aclId && isset($parent['parent'])) {
                 if (isset($parent['parent'])) {
                     $parent = $parent['parent'];
                 }
             }
             $entries[$aclId][0] = array('objectIdentity' => $parent, 'fieldName' => null, 'aceOrder' => null, 'grantingStrategy' => null, 'mask' => null, 'granting' => null, 'auditFailure' => null, 'auditSuccess' => null);
         }
         //Attach the class aces to the right entry if the type of current object matches class
         if (array_key_exists($type, $classEntries)) {
             foreach ($classEntries[$type] as $entry) {
                 $eid = (string) $entry['_id'];
                 $entries[$aclId][$eid] = $entry;
             }
         }
         foreach ($entries[$aclId] as $aceId => $entry) {
             $objectIdentity = $oid[$aclId];
             $classType = $objectIdentity['type'];
             $objectIdentifier = $objectIdentity['identifier'];
             $entryObjectIdentity = isset($entry['objectIdentity']) ? $entry['objectIdentity'] : null;
             $fieldName = isset($entry['fieldName']) ? $entry['fieldName'] : null;
             $aceOrder = $entry['aceOrder'];
             $grantingStrategy = $entry['grantingStrategy'];
             $mask = (int) $entry['mask'];
             $granting = $entry['granting'];
             $auditFailure = $entry['auditFailure'];
             $auditSuccess = $entry['auditSuccess'];
             if (isset($acls[$aclId])) {
                 // the ACL been hydrated during this hydration cycle
                 $acl = $acls[$aclId];
             } else {
                 if (isset($loadedAcls[$classType][$objectIdentifier])) {
                     // the ACL been hydrated during any previous cycle or loaded from cache
                     $acl = $loadedAcls[$classType][$objectIdentifier];
                     // keep reference in local array (saves us some hash calculations)
                     $acls[$aclId] = $acl;
                     // attach ACL to the result set; even though we do not enforce that every
                     // object identity has only one instance, we must make sure to maintain
                     // referential equality with the oids passed to findAcls()
                     $oidLookupKey = $objectIdentifier . $classType;
                     if (!isset($oidCache[$oidLookupKey])) {
                         $oidCache[$oidLookupKey] = $acl->getObjectIdentity();
                     }
                     $result->attach($oidCache[$oidLookupKey], $acl);
                 } else {
                     // this hasn't been hydrated yet
                     // create object identity if we haven't done so yet
                     $oidLookupKey = $objectIdentifier . $classType;
                     if (!isset($oidCache[$oidLookupKey])) {
                         $oidCache[$oidLookupKey] = new ObjectIdentity($objectIdentifier, $classType);
                     }
                     $acl = new Acl($aclId, $oidCache[$oidLookupKey], $permissionGrantingStrategy, $emptyArray, !!$objectIdentity['entriesInheriting']);
                     // keep a local, and global reference to this ACL
                     $loadedAcls[$classType][$objectIdentifier] = $acl;
                     $acls[$aclId] = $acl;
                     // try to fill in parent ACL, or defer until all ACLs have been hydrated
                     if (isset($objectIdentity['parent'])) {
                         $parentObjectIdentityId = (string) $objectIdentity['parent']['_id'];
                         if (isset($acls[$parentObjectIdentityId])) {
                             $aclParentAclProperty->setValue($acl, $acls[$parentObjectIdentityId]);
                         } else {
                             $parentIdToFill->attach($acl, $parentObjectIdentityId);
                         }
                     }
                     $result->attach($oidCache[$oidLookupKey], $acl);
                 }
             }
             // check if this row contains an ACE record
             if (0 !== $aceId) {
                 // have we already hydrated ACEs for this ACL?
                 if (!isset($aces[$aclId])) {
                     $aces[$aclId] = array($emptyArray, $emptyArray, $emptyArray, $emptyArray);
                 }
                 // has this ACE already been hydrated during a previous cycle, or
                 // possible been loaded from cache?
                 // It is important to only ever have one ACE instance per actual row since
                 // some ACEs are shared between ACL instances
                 if (!isset($loadedAces[$aceId])) {
                     if (isset($entry['securityIdentity']['username'])) {
                         $securityId = '1' . $entry['securityIdentity']['username'];
                         if (!isset($sids[$securityId])) {
                             $sids[$securityId] = new UserSecurityIdentity($entry['securityIdentity']['username'], $entry['securityIdentity']['class']);
                         }
                     } else {
                         $securityId = '0' . $entry['securityIdentity']['role'];
                         if (!isset($sids[$securityId])) {
                             $sids[$securityId] = new RoleSecurityIdentity($entry['securityIdentity']['role']);
                         }
                     }
                     if (null === $fieldName) {
                         $loadedAces[$aceId] = new Entry($aceId, $acl, $sids[$securityId], $grantingStrategy, (int) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
                     } else {
                         $loadedAces[$aceId] = new FieldEntry($aceId, $acl, $fieldName, $sids[$securityId], $grantingStrategy, (int) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
                     }
                 }
                 $ace = $loadedAces[$aceId];
                 // assign ACE to the correct property
                 if (null === $entryObjectIdentity) {
                     if (null === $fieldName) {
                         $aces[$aclId][0][$aceOrder] = $ace;
                     } else {
                         $aces[$aclId][1][$fieldName][$aceOrder] = $ace;
                     }
                 } else {
                     if (null === $fieldName) {
                         $aces[$aclId][2][$aceOrder] = $ace;
                     } else {
                         $aces[$aclId][3][$fieldName][$aceOrder] = $ace;
                     }
                 }
             }
         }
     }
     // We do not sort on database level since we only want certain subsets to be sorted,
     // and we are going to read the entire result set anyway.
     // Sorting on DB level increases query time by an order of magnitude while it is
     // almost negligible when we use PHPs array sort functions.
     foreach ($aces as $aclId => $aceData) {
         $acl = $acls[$aclId];
         ksort($aceData[0]);
         $aclClassAcesProperty->setValue($acl, $aceData[0]);
         foreach (array_keys($aceData[1]) as $fieldName) {
             ksort($aceData[1][$fieldName]);
         }
         $aclClassFieldAcesProperty->setValue($acl, $aceData[1]);
         ksort($aceData[2]);
         $aclObjectAcesProperty->setValue($acl, $aceData[2]);
         foreach (array_keys($aceData[3]) as $fieldName) {
             ksort($aceData[3][$fieldName]);
         }
         $aclObjectFieldAcesProperty->setValue($acl, $aceData[3]);
     }
     // fill-in parent ACLs where this hasn't been done yet cause the parent ACL was not yet available
     $processed = 0;
     foreach ($parentIdToFill as $acl) {
         $parentId = $parentIdToFill->offsetGet($acl);
         // let's see if we have already hydrated this
         if (isset($acls[$parentId])) {
             $aclParentAclProperty->setValue($acl, $acls[$parentId]);
             $processed += 1;
             continue;
         }
     }
     // reset reflection changes
     $aclClassAcesProperty->setAccessible(false);
     $aclClassFieldAcesProperty->setAccessible(false);
     $aclObjectAcesProperty->setAccessible(false);
     $aclObjectFieldAcesProperty->setAccessible(false);
     $aclParentAclProperty->setAccessible(false);
     // this should never be true if the database integrity hasn't been compromised
     if ($processed < count($parentIdToFill)) {
         throw new \RuntimeException('Not all parent ids were populated. This implies an integrity problem.');
     }
     return $result;
 }
 public function offsetGet($object)
 {
     $this->initialize();
     return parent::offsetGet($object);
 }
Exemplo n.º 29
0
 /**
  * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
  */
 public function offsetGet($object)
 {
     @trigger_error('The ' . __METHOD__ . ' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
     return parent::offsetGet($object);
 }
Exemplo n.º 30
0
 /**
  * Generates the inline definition of a service.
  *
  * @param string     $id
  * @param Definition $definition
  *
  * @return string
  *
  * @throws \RuntimeException When the factory definition is incomplete
  * @throws ServiceCircularReferenceException When a circular reference is detected
  */
 private function addServiceInlinedDefinitions($id, $definition)
 {
     $code = '';
     $variableMap = $this->definitionVariables;
     $nbOccurrences = new \SplObjectStorage();
     $processed = new \SplObjectStorage();
     $inlinedDefinitions = $this->getInlinedDefinitions($definition);
     foreach ($inlinedDefinitions as $definition) {
         if (false === $nbOccurrences->contains($definition)) {
             $nbOccurrences->offsetSet($definition, 1);
         } else {
             $i = $nbOccurrences->offsetGet($definition);
             $nbOccurrences->offsetSet($definition, $i + 1);
         }
     }
     foreach ($inlinedDefinitions as $sDefinition) {
         if ($processed->contains($sDefinition)) {
             continue;
         }
         $processed->offsetSet($sDefinition);
         $class = $this->dumpValue($sDefinition->getClass());
         if ($nbOccurrences->offsetGet($sDefinition) > 1 || count($sDefinition->getMethodCalls()) > 0 || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) {
             $name = $this->getNextVariableName();
             $variableMap->offsetSet($sDefinition, new Variable($name));
             // a construct like:
             // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a);
             // this is an indication for a wrong implementation, you can circumvent this problem
             // by setting up your service structure like this:
             // $b = new ServiceB();
             // $a = new ServiceA(ServiceB $b);
             // $b->setServiceA(ServiceA $a);
             if ($this->hasReference($id, $sDefinition->getArguments())) {
                 throw new ServiceCircularReferenceException($id, array($id));
             }
             $arguments = array();
             foreach ($sDefinition->getArguments() as $argument) {
                 $arguments[] = $this->dumpValue($argument);
             }
             if (null !== $sDefinition->getFactoryMethod()) {
                 if (null !== $sDefinition->getFactoryClass()) {
                     $code .= sprintf("        \$%s = call_user_func(array(%s, '%s')%s);\n", $name, $this->dumpValue($sDefinition->getFactoryClass()), $sDefinition->getFactoryMethod(), count($arguments) > 0 ? ', ' . implode(', ', $arguments) : '');
                 } elseif (null !== $sDefinition->getFactoryService()) {
                     $code .= sprintf("        \$%s = %s->%s(%s);\n", $name, $this->getServiceCall($sDefinition->getFactoryService()), $sDefinition->getFactoryMethod(), implode(', ', $arguments));
                 } else {
                     throw new RuntimeException('Factory service or factory class must be defined in service definition for ' . $id);
                 }
             } elseif (false !== strpos($class, '$')) {
                 $code .= sprintf("        \$class = %s;\n        \$%s = new \$class(%s);\n", $class, $name, implode(', ', $arguments));
             } else {
                 $code .= sprintf("        \$%s = new \\%s(%s);\n", $name, substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments));
             }
             if (!$this->hasReference($id, $sDefinition->getMethodCalls()) && !$this->hasReference($id, $sDefinition->getProperties())) {
                 $code .= $this->addServiceMethodCalls(null, $sDefinition, $name);
                 $code .= $this->addServiceProperties(null, $sDefinition, $name);
                 $code .= $this->addServiceConfigurator(null, $sDefinition, $name);
             }
             $code .= "\n";
         }
     }
     return $code;
 }