code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
protected function hydrateAllData() { return $this->doHydrateAllData(); }
Hydrates all rows from the current statement instance at once. @return mixed[]
hydrateAllData
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Hydration/HydratorCompat.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Hydration/HydratorCompat.php
MIT
public function getExecutor($statement) { return $this->doGetExecutorWithCompat($statement); }
Gets an executor that can be used to execute the result of this walker. @param SelectStatement|UpdateStatement|DeleteStatement $statement @return AbstractSqlExecutor
getExecutor
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkSelectClause($selectClause) { return $this->doWalkSelectClauseWithCompat($selectClause); }
Walks down a SelectClause AST node, thereby generating the appropriate SQL. @param SelectClause $selectClause @return string
walkSelectClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkFromClause($fromClause) { return $this->doWalkFromClauseWithCompat($fromClause); }
Walks down a FromClause AST node, thereby generating the appropriate SQL. @param FromClause $fromClause @return string
walkFromClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkOrderByClause($orderByClause) { return $this->doWalkOrderByClauseWithCompat($orderByClause); }
Walks down a OrderByClause AST node, thereby generating the appropriate SQL. @param OrderByClause $orderByClause @return string
walkOrderByClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkHavingClause($havingClause) { return $this->doWalkHavingClauseWithCompat($havingClause); }
Walks down a HavingClause AST node, thereby generating the appropriate SQL. @param HavingClause $havingClause @return string
walkHavingClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkSubselectFromClause($subselectFromClause) { return $this->doWalkSubselectFromClauseWithCompat($subselectFromClause); }
Walks down a SubselectFromClause AST node, thereby generating the appropriate SQL. @param SubselectFromClause $subselectFromClause @return string
walkSubselectFromClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkSimpleSelectClause($simpleSelectClause) { return $this->doWalkSimpleSelectClauseWithCompat($simpleSelectClause); }
Walks down a SimpleSelectClause AST node, thereby generating the appropriate SQL. @param SimpleSelectClause $simpleSelectClause @return string
walkSimpleSelectClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkGroupByClause($groupByClause) { return $this->doWalkGroupByClauseWithCompat($groupByClause); }
Walks down a GroupByClause AST node, thereby generating the appropriate SQL. @param GroupByClause $groupByClause @return string
walkGroupByClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkDeleteClause($deleteClause) { return $this->doWalkDeleteClauseWithCompat($deleteClause); }
Walks down a DeleteClause AST node, thereby generating the appropriate SQL. @param DeleteClause $deleteClause @return string
walkDeleteClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
public function walkWhereClause($whereClause) { return $this->doWalkWhereClauseWithCompat($whereClause); }
Walks down a WhereClause AST node, thereby generating the appropriate SQL. WhereClause or not, the appropriate discriminator sql is added. @param WhereClause|null $whereClause @return string
walkWhereClause
php
doctrine-extensions/DoctrineExtensions
src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Walker/SqlWalkerCompatForOrm2.php
MIT
protected function initialize() { if (!$this->initialized) { if ($this->object instanceof GhostObjectInterface) { $uow = $this->om->getUnitOfWork(); if (!$this->object->isProxyInitialized()) { $persister = $uow->getDocumentPersister($this->meta->getName()); $identifier = null; if ($uow->isInIdentityMap($this->object)) { $identifier = $this->getIdentifier(); } else { // this may not happen but in case $getIdentifier = \Closure::bind(fn () => $this->identifier, $this->object, get_class($this->object)); $identifier = $getIdentifier(); } $this->object->initializeProxy(); $persister->load($identifier, $this->object); } } } }
Initialize the document if it is proxy required when is detached or not initialized @return void
initialize
php
doctrine-extensions/DoctrineExtensions
src/Tool/Wrapper/MongoDocumentWrapper.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Wrapper/MongoDocumentWrapper.php
MIT
protected function initialize() { if (!$this->initialized) { if ($this->object instanceof PersistenceProxy) { if (!$this->object->__isInitialized()) { $this->object->__load(); } } } }
Initialize the entity if it is proxy required when is detached or not initialized @return void
initialize
php
doctrine-extensions/DoctrineExtensions
src/Tool/Wrapper/EntityWrapper.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Wrapper/EntityWrapper.php
MIT
public function __construct(AbstractPlatform $platform) { $this->platform = $platform; }
Initialize log listener with database platform, which is needed for parameter conversion
__construct
php
doctrine-extensions/DoctrineExtensions
src/Tool/Logging/DBAL/QueryAnalyzer.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Logging/DBAL/QueryAnalyzer.php
MIT
public function getOutput($dumpOnlySql = false) { $output = ''; if (!$dumpOnlySql) { $output .= 'Platform: '.$this->platform->getName().PHP_EOL; $output .= 'Executed queries: '.count($this->queries).', total time: '.$this->totalExecutionTime.' ms'.PHP_EOL; } foreach ($this->queries as $index => $sql) { if (!$dumpOnlySql) { $output .= 'Query('.($index + 1).') - '.$this->queryExecutionTimes[$index].' ms'.PHP_EOL; } $output .= $sql.';'.PHP_EOL; }
Dump the statistics of executed queries @param bool $dumpOnlySql @return string
getOutput
php
doctrine-extensions/DoctrineExtensions
src/Tool/Logging/DBAL/QueryAnalyzer.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Logging/DBAL/QueryAnalyzer.php
MIT
public function getSlowestQueryIndex() { $index = 0; $slowest = 0; foreach ($this->queryExecutionTimes as $i => $time) { if ($time > $slowest) { $slowest = $time; $index = $i; } } return $index; }
Index of the slowest query executed @return int
getSlowestQueryIndex
php
doctrine-extensions/DoctrineExtensions
src/Tool/Logging/DBAL/QueryAnalyzer.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Logging/DBAL/QueryAnalyzer.php
MIT
public function getTotalExecutionTime() { return $this->totalExecutionTime; }
Get total execution time of queries @return float
getTotalExecutionTime
php
doctrine-extensions/DoctrineExtensions
src/Tool/Logging/DBAL/QueryAnalyzer.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Logging/DBAL/QueryAnalyzer.php
MIT
public function getNumExecutedQueries() { return count($this->queries); }
Get number of executed queries @return int
getNumExecutedQueries
php
doctrine-extensions/DoctrineExtensions
src/Tool/Logging/DBAL/QueryAnalyzer.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/Logging/DBAL/QueryAnalyzer.php
MIT
public function getStrategy(ObjectManager $om, $class) { if (!isset($this->strategies[$class])) { $config = $this->getConfiguration($om, $class); if ([] === $config) { throw new UnexpectedValueException("Tree object class: {$class} must have tree metadata at this point"); } $managerName = 'UnsupportedManager'; if ($om instanceof EntityManagerInterface) { $managerName = 'ORM'; } elseif ($om instanceof DocumentManager) { $managerName = 'ODM\\MongoDB'; } if (!isset($this->strategyInstances[$config['strategy']])) { $strategyClass = $this->getNamespace().'\\Strategy\\'.$managerName.'\\'.ucfirst($config['strategy']); if (!class_exists($strategyClass)) { throw new InvalidArgumentException($managerName." TreeListener does not support tree type: {$config['strategy']}"); } $this->strategyInstances[$config['strategy']] = new $strategyClass($this); } $this->strategies[$class] = $config['strategy']; } return $this->strategyInstances[$this->strategies[$class]]; }
Get the used strategy for tree processing @param string $class @return Strategy
getStrategy
php
doctrine-extensions/DoctrineExtensions
src/Tree/TreeListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/TreeListener.php
MIT
public function postPersist(EventArgs $args) { $ea = $this->getEventAdapter($args); $om = $ea->getObjectManager(); $object = $ea->getObject(); $meta = $om->getClassMetadata(get_class($object)); if ($this->getConfiguration($om, $meta->getName())) { $this->getStrategy($om, $meta->getName())->processPostPersist($om, $object, $ea); } }
Checks for pending Nodes to fully synchronize the tree @param LifecycleEventArgs $args @phpstan-param LifecycleEventArgs<ObjectManager> $args @return void
postPersist
php
doctrine-extensions/DoctrineExtensions
src/Tree/TreeListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/TreeListener.php
MIT
protected function getStrategiesUsedForObjects(array $classes) { $strategies = []; foreach ($classes as $name => $opt) { if (isset($this->strategies[$name]) && !isset($strategies[$this->strategies[$name]])) { $strategies[$this->strategies[$name]] = $this->strategyInstances[$this->strategies[$name]]; } } return $strategies; }
Get the list of strategy instances used for given object classes @phpstan-param array<class-string, null> $classes @return array<string, Strategy> @phpstan-return array<value-of<self::strategies>, Strategy>
getStrategiesUsedForObjects
php
doctrine-extensions/DoctrineExtensions
src/Tree/TreeListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/TreeListener.php
MIT
protected function releaseTreeLocks(ObjectManager $om, AdapterInterface $ea) { // Do nothing by default }
Releases all trees which are locked @return void
releaseTreeLocks
php
doctrine-extensions/DoctrineExtensions
src/Tree/Strategy/AbstractMaterializedPath.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Strategy/AbstractMaterializedPath.php
MIT
public function shiftRL(EntityManagerInterface $em, $class, $first, $delta, $root = null) { $meta = $em->getClassMetadata($class); $config = $this->listener->getConfiguration($em, $class); $sign = ($delta >= 0) ? ' + ' : ' - '; $absDelta = abs($delta); $qb = $em->createQueryBuilder(); $qb->update($config['useObjectClass'], 'node') ->set('node.'.$config['left'], "node.{$config['left']} {$sign} {$absDelta}") ->where($qb->expr()->gte('node.'.$config['left'], $first)); if (isset($config['root'])) { $qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid')); $qb->setParameter('rid', $root); } $qb->getQuery()->getSingleScalarResult(); $qb = $em->createQueryBuilder(); $qb->update($config['useObjectClass'], 'node') ->set('node.'.$config['right'], "node.{$config['right']} {$sign} {$absDelta}") ->where($qb->expr()->gte('node.'.$config['right'], $first)); if (isset($config['root'])) { $qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid')); $qb->setParameter('rid', $root); } $qb->getQuery()->getSingleScalarResult(); // update in memory nodes increases performance, saves some IO foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) { // for inheritance mapped classes, only root is always in the identity map if ($className !== $meta->rootEntityName) { continue; } foreach ($nodes as $node) { if ($node instanceof Proxy && !$node->__isInitialized()) { continue; } assert(null !== $node); $nodeMeta = $em->getClassMetadata(get_class($node)); if (property_exists($nodeMeta, 'propertyAccessors')) { // ORM 3.4+ /** @phpstan-ignore-next-line method.NotFound Method introduced in ORM 3.4 */ if (!array_key_exists($config['left'], $nodeMeta->getPropertyAccessors())) { continue; } } else { // ORM 3.3- if (!array_key_exists($config['left'], $nodeMeta->getReflectionProperties())) { continue; } } $oid = spl_object_id($node); $left = $meta->getReflectionProperty($config['left'])->getValue($node); $currentRoot = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null; if ($currentRoot === $root && $left >= $first) { $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta); $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $delta); } $right = $meta->getReflectionProperty($config['right'])->getValue($node); if ($currentRoot === $root && $right >= $first) { $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta); $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $delta); } } } }
Shift tree left and right values by delta @param string $class @param int $first @param int $delta @param int|string $root @phpstan-param class-string $class @return void
shiftRL
php
doctrine-extensions/DoctrineExtensions
src/Tree/Strategy/ORM/Nested.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Strategy/ORM/Nested.php
MIT
public function shiftRangeRL(EntityManagerInterface $em, $class, $first, $last, $delta, $root = null, $destRoot = null, $levelDelta = null) { // @todo: Remove the following condition and assignment in the next major release and use 0 as default value for // the `$levelDelta` parameter. if (null === $levelDelta && func_num_args() >= 8) { Deprecation::trigger( 'gedmo/doctrine-extensions', 'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2495', 'Passing a type different than "int" as argument 8 to "%s()" is deprecated since gedmo/doctrine-extensions'. ' 3.9 and will throw a "%s" error in version 4.0.', __METHOD__, \TypeError::class ); } $levelDelta ??= 0; $meta = $em->getClassMetadata($class); $config = $this->listener->getConfiguration($em, $class); $sign = ($delta >= 0) ? ' + ' : ' - '; $absDelta = abs($delta); $levelSign = ($levelDelta >= 0) ? ' + ' : ' - '; $absLevelDelta = abs($levelDelta); $qb = $em->createQueryBuilder(); $qb->update($config['useObjectClass'], 'node') ->set('node.'.$config['left'], "node.{$config['left']} {$sign} {$absDelta}") ->set('node.'.$config['right'], "node.{$config['right']} {$sign} {$absDelta}") ->where($qb->expr()->gte('node.'.$config['left'], $first)) ->andWhere($qb->expr()->lte('node.'.$config['right'], $last)); if (isset($config['root'])) { $qb->set('node.'.$config['root'], ':drid'); $qb->setParameter('drid', $destRoot); $qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid')); $qb->setParameter('rid', $root); } if (isset($config['level'])) { $qb->set('node.'.$config['level'], "node.{$config['level']} {$levelSign} {$absLevelDelta}"); } $qb->getQuery()->getSingleScalarResult(); // update in memory nodes increases performance, saves some IO foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) { // for inheritance mapped classes, only root is always in the identity map if ($className !== $meta->rootEntityName) { continue; } foreach ($nodes as $node) { if ($node instanceof Proxy && !$node->__isInitialized()) { continue; } assert(null !== $node); $nodeMeta = $em->getClassMetadata(get_class($node)); if (property_exists($nodeMeta, 'propertyAccessors')) { // ORM 3.4+ /** @phpstan-ignore-next-line method.NotFound Method introduced in ORM 3.4 */ if (!array_key_exists($config['left'], $nodeMeta->getPropertyAccessors())) { continue; } } else { // ORM 3.3- if (!array_key_exists($config['left'], $nodeMeta->getReflectionProperties())) { continue; } } $left = $meta->getReflectionProperty($config['left'])->getValue($node); $right = $meta->getReflectionProperty($config['right'])->getValue($node); $currentRoot = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null; if ($currentRoot === $root && $left >= $first && $right <= $last) { $oid = spl_object_id($node); $uow = $em->getUnitOfWork(); $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta); $uow->setOriginalEntityProperty($oid, $config['left'], $left + $delta); $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta); $uow->setOriginalEntityProperty($oid, $config['right'], $right + $delta); if (isset($config['root'])) { $meta->getReflectionProperty($config['root'])->setValue($node, $destRoot); $uow->setOriginalEntityProperty($oid, $config['root'], $destRoot); } if (isset($config['level'])) { $level = $meta->getReflectionProperty($config['level'])->getValue($node); $meta->getReflectionProperty($config['level'])->setValue($node, $level + $levelDelta); $uow->setOriginalEntityProperty($oid, $config['level'], $level + $levelDelta); } } } } }
Shift range of right and left values on tree depending on tree level difference also @param string $class @param int $first @param int $last @param int $delta @param int|string $root @param int|string $destRoot @param int $levelDelta @phpstan-param class-string $class @return void
shiftRangeRL
php
doctrine-extensions/DoctrineExtensions
src/Tree/Strategy/ORM/Nested.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Strategy/ORM/Nested.php
MIT
public function getPathQuery($node) { $meta = $this->getClassMetadata(); if (!is_a($node, $meta->getName())) { throw new InvalidArgumentException('Node is not related to this repository'); } if (!$this->getEntityManager()->getUnitOfWork()->isInIdentityMap($node)) { throw new InvalidArgumentException('Node is not managed by UnitOfWork'); } $config = $this->listener->getConfiguration($this->getEntityManager(), $meta->getName()); $closureMeta = $this->getEntityManager()->getClassMetadata($config['closure']); $dql = "SELECT c, node FROM {$closureMeta->getName()} c"; $dql .= ' INNER JOIN c.ancestor node'; $dql .= ' WHERE c.descendant = :node'; $dql .= ' ORDER BY c.depth DESC'; $q = $this->getEntityManager()->createQuery($dql); $q->setParameter('node', $node); return $q; }
Get the Tree path query by given $node @param object $node @throws InvalidArgumentException if input is not valid @return Query
getPathQuery
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/ClosureTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/ClosureTreeRepository.php
MIT
public function getPath($node) { return array_map(static fn (AbstractClosure $closure) => $closure->getAncestor(), $this->getPathQuery($node)->getResult()); }
Get the Tree path of Nodes by given $node @param object $node @return array<int, object|null> list of Nodes in path
getPath
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/ClosureTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/ClosureTreeRepository.php
MIT
public function getPathQueryBuilder($node) { $meta = $this->getClassMetadata(); $config = $this->listener->getConfiguration($this->getEntityManager(), $meta->getName()); $alias = 'materialized_path_entity'; $qb = $this->getQueryBuilder() ->select($alias) ->from($config['useObjectClass'], $alias); $node = new EntityWrapper($node, $this->getEntityManager()); $nodePath = $node->getPropertyValue($config['path']); $paths = []; $nodePathLength = strlen($nodePath); $separatorMatchOffset = 0; while ($separatorMatchOffset < $nodePathLength) { $separatorPos = strpos($nodePath, $config['path_separator'], $separatorMatchOffset); if (false === $separatorPos || $separatorPos === $nodePathLength - 1) { // last node, done $paths[] = $nodePath; $separatorMatchOffset = $nodePathLength; } elseif (0 === $separatorPos) { // path starts with separator, continue $separatorMatchOffset = 1; } else { // add node $paths[] = substr($nodePath, 0, $config['path_ends_with_separator'] ? $separatorPos + 1 : $separatorPos); $separatorMatchOffset = $separatorPos + 1; } } $qb->where($qb->expr()->in( $alias.'.'.$config['path'], $paths )); $qb->orderBy($alias.'.'.$config['level'], 'ASC'); return $qb; }
Get the Tree path query builder by given $node @param object $node @return QueryBuilder
getPathQueryBuilder
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/MaterializedPathRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/MaterializedPathRepository.php
MIT
public function getPathQuery($node) { return $this->getPathQueryBuilder($node)->getQuery(); }
Get the Tree path query by given $node @param object $node @return Query
getPathQuery
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/MaterializedPathRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/MaterializedPathRepository.php
MIT
public function getPath($node) { return $this->getPathQuery($node)->getResult(); }
Get the Tree path of Nodes by given $node @param object $node @return array<int, object> list of Nodes in path
getPath
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/MaterializedPathRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/MaterializedPathRepository.php
MIT
public function getPathQueryBuilder($node/* , array $options = [] */) // @phpstan-ignore-line { $options = func_get_args()[1] ?? []; if (!\is_array($options)) { throw new \TypeError('Argument 2 MUST be an array.'); } $defaultOptions = [ 'includeNode' => true, ]; $options += $defaultOptions; $meta = $this->getClassMetadata(); if (!is_a($node, $meta->getName())) { throw new InvalidArgumentException('Node is not related to this repository'); } $config = $this->listener->getConfiguration($this->getEntityManager(), $meta->getName()); $wrapped = new EntityWrapper($node, $this->getEntityManager()); if (!$wrapped->hasValidIdentifier()) { throw new InvalidArgumentException('Node is not managed by UnitOfWork'); } $left = $wrapped->getPropertyValue($config['left']); $right = $wrapped->getPropertyValue($config['right']); $qb = $this->getQueryBuilder(); $qb->select('node') ->from($config['useObjectClass'], 'node') ->orderBy('node.'.$config['left'], 'ASC') ; if ($options['includeNode']) { $qb->where($qb->expr()->lte('node.'.$config['left'], $left)) ->andWhere($qb->expr()->gte('node.'.$config['right'], $right)); } else { $qb->where($qb->expr()->lt('node.'.$config['left'], $left)) ->andWhere($qb->expr()->gt('node.'.$config['right'], $right)); } if (isset($config['root'])) { $rootId = $wrapped->getPropertyValue($config['root']); $qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid')); $qb->setParameter('rid', $rootId); } return $qb; }
Get the Tree path query builder by given $node @param object $node @phpstan-param array{includeNode?: bool} $options options: - includeNode: (bool) Whether to include the node itself. Defaults to true. @throws InvalidArgumentException if input is not valid @return QueryBuilder
getPathQueryBuilder
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getPathQuery($node/* , array $options = [] */) // @phpstan-ignore-line { $options = func_get_args()[1] ?? []; if (!\is_array($options)) { throw new \TypeError('Argument 2 MUST be an array.'); } return $this->getPathQueryBuilder($node, $options)->getQuery(); }
Get the Tree path query by given $node @param object $node @phpstan-param array{includeNode?: bool} $options options: - includeNode: (bool) Whether to include the node itself. Defaults to true. @return Query
getPathQuery
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getPath($node/* , array $options = [] */) // @phpstan-ignore-line { $options = func_get_args()[1] ?? []; if (!\is_array($options)) { throw new \TypeError('Argument 2 MUST be an array.'); } return $this->getPathQuery($node, $options)->getResult(); }
Get the Tree path of Nodes by given $node @param object $node @phpstan-param array{includeNode?: bool} $options options: - includeNode: (bool) Whether to include the node itself. Defaults to true. @return array list of Nodes in path
getPath
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getLeafs($root = null, $sortByField = null, $direction = 'ASC') { return $this->getLeafsQuery($root, $sortByField, $direction)->getResult(); }
Get list of leaf nodes of the tree @param object $root root node in case of root tree is required @param string $sortByField field name to sort by @param string $direction sort direction : "ASC" or "DESC" @return array<int, object> @phpstan-param 'asc'|'desc'|'ASC'|'DESC' $direction
getLeafs
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getNextSiblingsQuery($node, $includeSelf = false) { return $this->getNextSiblingsQueryBuilder($node, $includeSelf)->getQuery(); }
Get the query for next siblings of the given $node @param object $node @param bool $includeSelf include the node itself @return Query
getNextSiblingsQuery
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getNextSiblings($node, $includeSelf = false) { return $this->getNextSiblingsQuery($node, $includeSelf)->getResult(); }
Find the next siblings of the given $node @param object $node @param bool $includeSelf include the node itself @return array<int, object>
getNextSiblings
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getPrevSiblingsQuery($node, $includeSelf = false) { return $this->getPrevSiblingsQueryBuilder($node, $includeSelf)->getQuery(); }
Get query for previous siblings of the given $node @param object $node @param bool $includeSelf include the node itself @throws InvalidArgumentException if input is invalid @return Query
getPrevSiblingsQuery
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function getPrevSiblings($node, $includeSelf = false) { return $this->getPrevSiblingsQuery($node, $includeSelf)->getResult(); }
Find the previous siblings of the given $node @param object $node @param bool $includeSelf include the node itself @return array<int, object>
getPrevSiblings
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function moveDown($node, $number = 1) { $result = false; $meta = $this->getClassMetadata(); if (is_a($node, $meta->getName())) { $nextSiblings = $this->getNextSiblings($node); if ($numSiblings = count($nextSiblings)) { $result = true; if (true === $number) { $number = $numSiblings; } elseif ($number > $numSiblings) { $number = $numSiblings; } $this->listener ->getStrategy($this->getEntityManager(), $meta->getName()) ->updateNode($this->getEntityManager(), $node, $nextSiblings[$number - 1], Nested::NEXT_SIBLING); } } else { throw new InvalidArgumentException('Node is not related to this repository'); } return $result; }
Move the node down in the same level @param object $node @param int|bool $number integer - number of positions to shift boolean - if "true" - shift till last position @throws \RuntimeException if something fails in transaction @return bool true if shifted
moveDown
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function moveUp($node, $number = 1) { $result = false; $meta = $this->getClassMetadata(); if (is_a($node, $meta->getName())) { $prevSiblings = array_reverse($this->getPrevSiblings($node)); if ($numSiblings = count($prevSiblings)) { $result = true; if (true === $number) { $number = $numSiblings; } elseif ($number > $numSiblings) { $number = $numSiblings; } $this->listener ->getStrategy($this->getEntityManager(), $meta->getName()) ->updateNode($this->getEntityManager(), $node, $prevSiblings[$number - 1], Nested::PREV_SIBLING); } } else { throw new InvalidArgumentException('Node is not related to this repository'); } return $result; }
Move the node up in the same level @param object $node @param int|bool $number integer - number of positions to shift boolean - true shift till first position @throws \RuntimeException if something fails in transaction @return bool true if shifted
moveUp
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function reorderAll($sortByField = null, $direction = 'ASC', $verify = true) { $this->reorder(null, $sortByField, $direction, $verify); }
Reorders all nodes in the tree according to the $sortByField and $direction specified. @param string $sortByField field name to sort by @param string $direction sort direction : "ASC" or "DESC" @param bool $verify true to verify tree first @return void
reorderAll
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
protected function doCallWithCompat($method, $args) { if ('persistAs' === substr($method, 0, 9)) { if (!isset($args[0])) { throw new InvalidArgumentException('Node to persist must be available as first argument.'); } $node = $args[0]; $wrapped = new EntityWrapper($node, $this->getEntityManager()); $meta = $this->getClassMetadata(); $config = $this->listener->getConfiguration($this->getEntityManager(), $meta->getName()); $position = substr($method, 9); if ('Of' === substr($method, -2)) { if (!isset($args[1])) { throw new InvalidArgumentException('If "Of" is specified you must provide parent or sibling as the second argument.'); } $parentOrSibling = $args[1]; if (strstr($method, 'Sibling')) { $wrappedParentOrSibling = new EntityWrapper($parentOrSibling, $this->getEntityManager()); $newParent = $wrappedParentOrSibling->getPropertyValue($config['parent']); if (null === $newParent && isset($config['root'])) { throw new UnexpectedValueException('Cannot persist sibling for a root node, tree operation is not possible'); } if (!$node instanceof Node) { Deprecation::trigger( 'gedmo/doctrine-extensions', 'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2547', 'Not implementing the "%s" interface from node "%s" is deprecated since gedmo/doctrine-extensions' .' 3.13 and will throw a "%s" error in version 4.0.', Node::class, \get_class($node), \TypeError::class ); } // @todo: In the next major release, remove the previous condition and uncomment the following one. // if (!$node instanceof Node) { // throw new \TypeError(\sprintf( // 'Node MUST implement "%s" interface.', // Node::class // )); // } // @todo: In the next major release, remove the `method_exists()` condition and left the `else` branch. if (!method_exists($node, 'setSibling')) { $node->sibling = $parentOrSibling; } else { $node->setSibling($parentOrSibling); } $parentOrSibling = $newParent; } $wrapped->setPropertyValue($config['parent'], $parentOrSibling); $position = substr($position, 0, -2); } $wrapped->setPropertyValue($config['left'], 0); // simulate changeset $oid = spl_object_id($node); $this->listener ->getStrategy($this->getEntityManager(), $meta->getName()) ->setNodePosition($oid, $position) ; $this->getEntityManager()->persist($node); return $this; } return parent::__call($method, $args); }
Allows the following 'virtual' methods: - persistAsFirstChild($node) - persistAsFirstChildOf($node, $parent) - persistAsLastChild($node) - persistAsLastChildOf($node, $parent) - persistAsNextSibling($node) - persistAsNextSiblingOf($node, $sibling) - persistAsPrevSibling($node) - persistAsPrevSiblingOf($node, $sibling) Inherited virtual methods: - find* @param string $method @param array $args @phpstan-param list<mixed> $args @throws \BadMethodCallException If the method called is an invalid find* or persistAs* method or no find* either persistAs* method at all and therefore an invalid method call @throws InvalidArgumentException If arguments are invalid @return mixed TreeNestedRepository if persistAs* is called @see \Doctrine\ORM\EntityRepository
doCallWithCompat
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/NestedTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/NestedTreeRepository.php
MIT
public function setRepoUtils(RepositoryUtilsInterface $repoUtils) { $this->repoUtils = $repoUtils; return $this; }
Sets the RepositoryUtilsInterface instance @return static
setRepoUtils
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/AbstractTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/AbstractTreeRepository.php
MIT
public function getRepoUtils() { return $this->repoUtils; }
Returns the RepositoryUtilsInterface instance @return RepositoryUtilsInterface|null
getRepoUtils
php
doctrine-extensions/DoctrineExtensions
src/Tree/Entity/Repository/AbstractTreeRepository.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Entity/Repository/AbstractTreeRepository.php
MIT
protected function doHydrateAllData() { $data = parent::hydrateAllData(); if ([] === $data) { return $data; } $listener = $this->getTreeListener($this->getEntityManager()); $entityClass = $this->getEntityClassFromHydratedData($data); $this->config = $listener->getConfiguration($this->getEntityManager(), $entityClass); $this->idField = $this->getIdField($entityClass); $this->parentField = $this->getParentField(); $this->childrenField = $this->getChildrenField($entityClass); $childrenHashmap = $this->buildChildrenHashmap($data); $this->populateChildrenArray($data, $childrenHashmap); // Only return root elements or elements who's parents haven't been fetched // The sub-nodes will be accessible via the `children` property return $this->getRootNodes($data); }
We hook into the `hydrateAllData` to map the children collection of the entity @return array<int, object>
doHydrateAllData
php
doctrine-extensions/DoctrineExtensions
src/Tree/Hydrator/ORM/TreeObjectHydrator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Hydrator/ORM/TreeObjectHydrator.php
MIT
public function isValidFieldForPath($meta, $field) { $mapping = $meta->getFieldMapping($field); return $mapping && in_array($this->getMappingType($mapping), $this->validPathTypes, true); }
Checks if $field type is valid for Path field @param ClassMetadata<object> $meta @param string $field @return bool
isValidFieldForPath
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function isValidFieldForPathSource($meta, $field) { $mapping = $meta->getFieldMapping($field); return $mapping && in_array($this->getMappingType($mapping), $this->validPathSourceTypes, true); }
Checks if $field type is valid for PathSource field @param ClassMetadata<object> $meta @param string $field @return bool
isValidFieldForPathSource
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function isValidFieldForPathHash($meta, $field) { $mapping = $meta->getFieldMapping($field); return $mapping && in_array($this->getMappingType($mapping), $this->validPathHashTypes, true); }
Checks if $field type is valid for PathHash field @param ClassMetadata<object> $meta @param string $field @return bool
isValidFieldForPathHash
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function isValidFieldForLockTime($meta, $field) { $mapping = $meta->getFieldMapping($field); return $mapping && ('date' === $this->getMappingType($mapping) || 'datetime' === $this->getMappingType($mapping) || 'timestamp' === $this->getMappingType($mapping)); }
Checks if $field type is valid for LockTime field @param ClassMetadata<object> $meta @param string $field @return bool
isValidFieldForLockTime
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function isValidFieldForRoot($meta, $field) { $mapping = $meta->getFieldMapping($field); return $mapping && in_array($this->getMappingType($mapping), $this->validRootTypes, true); }
Checks if $field type is valid for Root field @param ClassMetadata<object> $meta @param string $field @return bool
isValidFieldForRoot
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function validateNestedTreeMetadata($meta, array $config) { $missingFields = []; if (!isset($config['parent'])) { $missingFields[] = 'ancestor'; } if (!isset($config['left'])) { $missingFields[] = 'left'; } if (!isset($config['right'])) { $missingFields[] = 'right'; } if ($missingFields) { throw new InvalidMappingException('Missing properties: '.implode(', ', $missingFields)." in class - {$meta->getName()}"); } }
Validates metadata for nested type tree @param ClassMetadata<object> $meta @param array<string, mixed> $config @throws InvalidMappingException @return void
validateNestedTreeMetadata
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function validateClosureTreeMetadata($meta, array $config) { $missingFields = []; if (!isset($config['parent'])) { $missingFields[] = 'ancestor'; } if (!isset($config['closure'])) { $missingFields[] = 'closure class'; } if ($missingFields) { throw new InvalidMappingException('Missing properties: '.implode(', ', $missingFields)." in class - {$meta->getName()}"); } }
Validates metadata for closure type tree @param ClassMetadata<object> $meta @param array<string, mixed> $config @throws InvalidMappingException @return void
validateClosureTreeMetadata
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function validateMaterializedPathTreeMetadata($meta, array $config) { $missingFields = []; if (!isset($config['parent'])) { $missingFields[] = 'ancestor'; } if (!isset($config['path'])) { $missingFields[] = 'path'; } if (!isset($config['path_source'])) { $missingFields[] = 'path_source'; } if ($missingFields) { throw new InvalidMappingException('Missing properties: '.implode(', ', $missingFields)." in class - {$meta->getName()}"); } }
Validates metadata for materialized path type tree @param ClassMetadata<object> $meta @param array<string, mixed> $config @throws InvalidMappingException @return void
validateMaterializedPathTreeMetadata
php
doctrine-extensions/DoctrineExtensions
src/Tree/Mapping/Validator.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tree/Mapping/Validator.php
MIT
public function setTransliterator($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('Invalid transliterator callable parameter given'); } $this->transliterator = $callable; }
Set the transliteration callable method to transliterate slugs @param callable $callable @phpstan-param callable(string $text, string $separator, object $object): string $callable @throws InvalidArgumentException @return void
setTransliterator
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function setUrlizer($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('Invalid urlizer callable parameter given'); } $this->urlizer = $callable; }
Set the urlization callable method to urlize slugs @param callable $callable @phpstan-param callable(string $text, string $separator, object $object): string $callable @throws InvalidArgumentException @return void
setUrlizer
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function getTransliterator() { return $this->transliterator; }
Get currently used transliterator callable @return callable @phpstan-return callable(string $text, string $separator, object $object): string
getTransliterator
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function getUrlizer() { return $this->urlizer; }
Get currently used urlizer callable @return callable @phpstan-return callable(string $text, string $separator, object $object): string
getUrlizer
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function removeManagedFilter($name) { unset($this->managedFilters[$name]); }
Removes a filter from the managed set @param string $name @return void
removeManagedFilter
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function prePersist(EventArgs $args) { $ea = $this->getEventAdapter($args); $om = $ea->getObjectManager(); $object = $ea->getObject(); $meta = $om->getClassMetadata(get_class($object)); if ($config = $this->getConfiguration($om, $meta->getName())) { foreach ($config['slugs'] as $slugField => $options) { if ($meta->isIdentifier($slugField)) { $meta->getReflectionProperty($slugField)->setValue($object, uniqid('__sluggable_placeholder__')); } } } }
Allows identifier fields to be slugged as usual @param LifecycleEventArgs $args @phpstan-param LifecycleEventArgs<ObjectManager> $args @return void
prePersist
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
private function getFilterCollectionFromObjectManager(ObjectManager $om) { if (is_callable([$om, 'getFilters'])) { return $om->getFilters(); } if (is_callable([$om, 'getFilterCollection'])) { return $om->getFilterCollection(); } throw new InvalidArgumentException('ObjectManager does not support filters'); }
Retrieves a FilterCollection instance from the given ObjectManager. @throws InvalidArgumentException @return mixed
getFilterCollectionFromObjectManager
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/SluggableListener.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/SluggableListener.php
MIT
public function transliterate($text, $separator, $object) { $slug = $text.$this->suffix; if (strlen($this->parentSlug)) { $slug = $this->parentSlug.$this->usedPathSeparator.$slug; } else { // if no parentSlug, apply our prefix $slug = $this->prefix.$slug; } return $slug; }
Transliterates the slug and prefixes the slug by collection of parent slugs @param string $text @param string $separator @param object $object @return string
transliterate
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/Handler/TreeSlugHandler.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/Handler/TreeSlugHandler.php
MIT
public function transliterate($text, $separator, $object) { $result = call_user_func_array( $this->originalTransliterator, [$text, $separator, $object] ); $wrapped = AbstractWrapper::wrap($object, $this->om); $relation = $wrapped->getPropertyValue($this->usedOptions['relationField']); if ($relation) { $wrappedRelation = AbstractWrapper::wrap($relation, $this->om); $slug = $wrappedRelation->getPropertyValue($this->usedOptions['relationSlugField']); if (isset($this->usedOptions['urilize']) && $this->usedOptions['urilize']) { $slug = call_user_func_array( $this->originalTransliterator, [$slug, $separator, $object] ); } $result = $slug.$this->usedOptions['separator'].$result; } $this->sluggable->setTransliterator($this->originalTransliterator); return $result; }
Transliterates the slug and prefixes the slug by relative one @param string $text @param string $separator @param object $object @return string
transliterate
php
doctrine-extensions/DoctrineExtensions
src/Sluggable/Handler/RelativeSlugHandler.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sluggable/Handler/RelativeSlugHandler.php
MIT
public function addPropertyChangedListener(PropertyChangedListener $listener) { $this->_propertyChangedListeners[] = $listener; }
Adds a listener that wants to be notified about property changes. @see \Doctrine\Common\NotifyPropertyChanged::addPropertyChangedListener() @return void
addPropertyChangedListener
php
doctrine-extensions/DoctrineExtensions
tests/Gedmo/Sortable/Fixture/NotifyNode.php
https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/tests/Gedmo/Sortable/Fixture/NotifyNode.php
MIT
public function __call(string $method, array $params) { $result = $this->detect(); // Reflect a method. if (method_exists($result, $method)) { /* @phpstan-ignore-next-line */ return call_user_func_array([$result, $method], $params); } throw new BadMethodCallException( sprintf('%s method does not exists on the %s object.', $method, ResultInterface::class) ); }
Reflect calls to the result object. @throws \hisorange\BrowserDetect\Exceptions\BadMethodCallException @param string $method @param array $params @return mixed
__call
php
hisorange/browser-detect
src/Parser.php
https://github.com/hisorange/browser-detect/blob/master/src/Parser.php
MIT
public static function __callStatic(string $method, array $params) { if (!static::$instance) { static::$instance = new static(); } /* @phpstan-ignore-next-line */ return call_user_func_array([static::$instance, $method], $params); }
Acts as a facade, but proxies all the call to a singleton. @param string $method @param array $params @return mixed
__callStatic
php
hisorange/browser-detect
src/Parser.php
https://github.com/hisorange/browser-detect/blob/master/src/Parser.php
MIT
public static function provideAgents() { return [ ['NotGoingToMatch', false], ['GoogleBot', true], ['Yahoo Crawler', true], ]; }
Simple agents to test the crawler stage. @return array
provideAgents
php
hisorange/browser-detect
tests/Stages/CrawlerDetectTest.php
https://github.com/hisorange/browser-detect/blob/master/tests/Stages/CrawlerDetectTest.php
MIT
public static function provideAgent() { return [ [ 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.', [ 'deviceFamily' => 'iPad', ], ], [ 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36', [ 'browserFamily' => 'Chrome', 'browserVersionMajor' => 41, 'browserVersionMinor' => 0, 'browserVersionPatch' => 2224, ], ], [ 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', [ 'browserFamily' => 'Firefox', 'browserVersionMajor' => 40, 'browserVersionMinor' => 1, 'browserVersionPatch' => 0, ], ], [ 'TestUserAgentString', [ 'browserFamily' => null, 'browserVersionMajor' => null, 'browserVersionMinor' => null, 'browserVersionPatch' => null, ], ], ]; }
Common agents to test the crawler stage. @return array
provideAgent
php
hisorange/browser-detect
tests/Stages/UAParserTest.php
https://github.com/hisorange/browser-detect/blob/master/tests/Stages/UAParserTest.php
MIT
public function actionApp($app, $repo = null) { // root of the dev repo $base = \dirname(\dirname(__DIR__)); $appDir = "$base/apps/$app"; if (!file_exists($appDir)) { if (empty($repo)) { if (isset($this->apps[$app])) { $repo = $this->apps[$app]; if ($this->useHttp) { $repo = str_replace('[email protected]:', 'https://github.com/', $repo); } } else { $this->stderr("Repo argument is required for app '$app'.\n", Console::FG_RED); return 1; } } $this->stdout("cloning application repo '$app' from '$repo'...\n", Console::BOLD); passthru('git clone ' . escapeshellarg($repo) . ' ' . $appDir, $returnVar); if ($returnVar !== 0) { $this->stdout("Error occurred while cloning repository.\n", Console::BOLD, Console::FG_RED); return 1; } $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); } // cleanup $this->stdout("cleaning up application '$app' vendor directory...\n", Console::BOLD); $this->cleanupVendorDir($appDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // composer update $this->stdout("updating composer for app '$app'...\n", Console::BOLD); chdir($appDir); $command = 'composer update --prefer-dist'; if ($this->composerNoProgress) { $command .= ' --no-progress'; } passthru($command); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // link directories $this->stdout("linking framework and extensions to '$app' app vendor dir...\n", Console::BOLD); $this->linkFrameworkAndExtensions($appDir, $base); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); return 0; }
This command installs a project template in the `apps` directory and links the framework and extensions. It basically runs the following commands in the dev repo root: - Run `composer update` - `rm -rf apps/basic/vendor/yiisoft/yii2` - `rm -rf apps/basic/vendor/yiisoft/yii2-*` And replaces them with symbolic links to the extensions and framework path in the dev repo. Extensions required by the application are automatically installed using the `ext` action. @param string $app the application name e.g. `basic` or `advanced`. @param string $repo url of the git repo to clone if it does not already exist. @return int return code
actionApp
php
yiisoft/yii2
build/controllers/DevController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/DevController.php
BSD-3-Clause
public function actionExt($extension, $repo = null) { // root of the dev repo $base = \dirname(\dirname(__DIR__)); $extensionDir = "$base/extensions/$extension"; if (!file_exists($extensionDir)) { if (empty($repo)) { if (isset($this->extensions[$extension])) { $repo = $this->extensions[$extension]; if ($this->useHttp) { $repo = str_replace('[email protected]:', 'https://github.com/', $repo); } } else { $this->stderr("Repo argument is required for extension '$extension'.\n", Console::FG_RED); return 1; } } $this->stdout("cloning extension repo '$extension' from '$repo'...\n", Console::BOLD); passthru('git clone ' . escapeshellarg($repo) . ' ' . $extensionDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); } // cleanup $this->stdout("cleaning up extension '$extension' vendor directory...\n", Console::BOLD); $this->cleanupVendorDir($extensionDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // composer update $this->stdout("updating composer for extension '$extension'...\n", Console::BOLD); chdir($extensionDir); $command = 'composer update --prefer-dist'; if ($this->composerNoProgress) { $command .= ' --no-progress'; } passthru($command); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // link directories $this->stdout("linking framework and extensions to '$extension' vendor dir...\n", Console::BOLD); $this->linkFrameworkAndExtensions($extensionDir, $base); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); return 0; }
This command installs an extension in the `extensions` directory and links the framework and other extensions. @param string $extension the application name e.g. `basic` or `advanced`. @param string $repo url of the git repo to clone if it does not already exist. @return int
actionExt
php
yiisoft/yii2
build/controllers/DevController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/DevController.php
BSD-3-Clause
protected function cleanupVendorDir($dir) { if (is_link($link = "$dir/vendor/yiisoft/yii2")) { $this->stdout("Removing symlink $link.\n"); FileHelper::unlink($link); } $extensions = $this->findDirs("$dir/vendor/yiisoft"); foreach ($extensions as $ext) { if (is_link($link = "$dir/vendor/yiisoft/yii2-$ext")) { $this->stdout("Removing symlink $link.\n"); FileHelper::unlink($link); } } }
Remove all symlinks in the vendor subdirectory of the directory specified. @param string $dir base directory
cleanupVendorDir
php
yiisoft/yii2
build/controllers/DevController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/DevController.php
BSD-3-Clause
protected function linkFrameworkAndExtensions($dir, $base) { if (is_dir($link = "$dir/vendor/yiisoft/yii2")) { $this->stdout("Removing dir $link.\n"); FileHelper::removeDirectory($link); $this->stdout("Creating symlink for $link.\n"); symlink("$base/framework", $link); } $extensions = $this->findDirs("$dir/vendor/yiisoft"); foreach ($extensions as $ext) { if (is_dir($link = "$dir/vendor/yiisoft/yii2-$ext")) { $this->stdout("Removing dir $link.\n"); FileHelper::removeDirectory($link); $this->stdout("Creating symlink for $link.\n"); if (!file_exists("$base/extensions/$ext")) { $ret = $this->actionExt($ext); if ($ret !== 0) { return $ret; } } symlink("$base/extensions/$ext", $link); } } }
Creates symlinks to framework and extension sources for the application. @param string $dir application directory @param string $base Yii sources base directory @return int
linkFrameworkAndExtensions
php
yiisoft/yii2
build/controllers/DevController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/DevController.php
BSD-3-Clause
protected function listSubDirs($dir) { $list = []; $handle = opendir($dir); if ($handle === false) { throw new InvalidParamException("Unable to open directory: $dir"); } while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { continue; } // ignore hidden directories if (strpos($file, '.') === 0) { continue; } if (is_dir("$dir/$file")) { $list[] = "$dir/$file"; } } closedir($handle); return $list; }
Get a list of subdirectories for directory specified. @param string $dir directory to read @return array list of subdirectories
listSubDirs
php
yiisoft/yii2
build/controllers/DevController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/DevController.php
BSD-3-Clause
public function actionSortChangelog(array $what) { if (\count($what) > 1) { $this->stdout("Currently only one simultaneous release is supported.\n"); return 1; } $this->validateWhat($what, ['framework', 'ext'], false); $version = $this->version ?: array_values($this->getNextVersions($this->getCurrentVersions($what), self::PATCH))[0]; $this->stdout('sorting CHANGELOG of '); $this->stdout(reset($what), Console::BOLD); $this->stdout(' for version '); $this->stdout($version, Console::BOLD); $this->stdout('...'); $this->resortChangelogs($what, $version); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); }
Sorts CHANGELOG for framework or extension. @param array $what what do you want to resort changelog for? this can either be: - an extension name such as `redis` or `bootstrap`, - or `framework` if you want to release a new version of the framework itself.
actionSortChangelog
php
yiisoft/yii2
build/controllers/ReleaseController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/ReleaseController.php
BSD-3-Clause
protected function splitChangelog($file, $version) { $lines = explode("\n", file_get_contents($file)); // split the file into relevant parts $start = []; $changelog = []; $end = []; $state = 'start'; foreach ($lines as $l => $line) { // starting from the changelogs headline if (isset($lines[$l - 2]) && strpos($lines[$l - 2], $version) !== false && isset($lines[$l - 1]) && strncmp($lines[$l - 1], '---', 3) === 0) { $state = 'changelog'; } if ($state === 'changelog' && isset($lines[$l + 1]) && strncmp($lines[$l + 1], '---', 3) === 0) { $state = 'end'; } // add continued lines to the last item to keep them together if (!empty(${$state}) && trim($line) !== '' && strncmp($line, '- ', 2) !== 0) { end(${$state}); ${$state}[key(${$state})] .= "\n" . $line; } else { ${$state}[] = $line; } } return [$start, $changelog, $end]; }
Extract changelog content for a specific version. @param string $file @param string $version @return array
splitChangelog
php
yiisoft/yii2
build/controllers/ReleaseController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/ReleaseController.php
BSD-3-Clause
public function actionReport($sourcePath, $translationPath, $title = 'Translation report') { $sourcePath = trim($sourcePath, '/\\'); $translationPath = trim($translationPath, '/\\'); $results = []; $dir = new DirectoryIterator($sourcePath); foreach ($dir as $fileinfo) { /* @var $fileinfo DirectoryIterator */ if (!$fileinfo->isDot() && !$fileinfo->isDir()) { $translatedFilePath = $translationPath . '/' . $fileinfo->getFilename(); $sourceFilePath = $sourcePath . '/' . $fileinfo->getFilename(); $errors = $this->checkFiles($translatedFilePath); $diff = empty($errors) ? $this->getDiff($translatedFilePath, $sourceFilePath) : ''; if (!empty($diff)) { $errors[] = 'Translation outdated.'; } $result = [ 'errors' => $errors, 'diff' => $diff, ]; $results[$fileinfo->getFilename()] = $result; } } // checking if there are obsolete translation files $dir = new DirectoryIterator($translationPath); foreach ($dir as $fileinfo) { /* @var $fileinfo \DirectoryIterator */ if (!$fileinfo->isDot() && !$fileinfo->isDir()) { $translatedFilePath = $translationPath . '/' . $fileinfo->getFilename(); $errors = $this->checkFiles(null, $translatedFilePath); if (!empty($errors)) { $results[$fileinfo->getFilename()]['errors'] = $errors; } } } echo $this->renderFile(__DIR__ . '/views/translation/report_html.php', [ 'results' => $results, 'sourcePath' => $sourcePath, 'translationPath' => $translationPath, 'title' => $title, ]); }
Creates a report about documentation updates since last update of same named translations. @param string $sourcePath the directory where the original documentation files are @param string $translationPath the directory where the translated documentation files are @param string $title custom title to use for report
actionReport
php
yiisoft/yii2
build/controllers/TranslationController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/TranslationController.php
BSD-3-Clause
protected function cleanDocComment($doc) { $lines = explode("\n", $doc); $n = \count($lines); for ($i = 0; $i < $n; $i++) { $lines[$i] = rtrim($lines[$i]); if (trim($lines[$i]) == '*' && trim($lines[$i + 1]) == '*') { unset($lines[$i]); } } return implode("\n", $lines); }
remove multi empty lines and trim trailing whitespace. @param $doc @return string
cleanDocComment
php
yiisoft/yii2
build/controllers/PhpDocController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/PhpDocController.php
BSD-3-Clause
private function hash($string) { if (!function_exists('hash')) { return sha1($string); } return hash('sha256', $string); }
Generate a hash value (message digest) @param string $string message to be hashed. @return string calculated message digest.
hash
php
yiisoft/yii2
build/controllers/PhpDocController.php
https://github.com/yiisoft/yii2/blob/master/build/controllers/PhpDocController.php
BSD-3-Clause
public function __construct($url, $statusCode = 302, $scheme = false, $message = null, $code = 0, $previous = null) { $this->url = $url; $this->scheme = $scheme; $this->statusCode = $statusCode; parent::__construct((string)$message, $code, $previous); }
@param array|string $url the parameter to be used to generate a valid URL for redirection. This will be used as first parameter for [[\yii\helpers\Url::to()]] @param int $statusCode HTTP status code used for redirection @param bool|string $scheme the URI scheme to use in the generated URL for redirection. This will be used as second parameter for [[\yii\helpers\Url::to()]] @param string|null $message the error message @param int $code the error code @param \Throwable|null $previous the previous exception used for the exception chaining
__construct
php
yiisoft/yii2
framework/web/UrlNormalizerRedirectException.php
https://github.com/yiisoft/yii2/blob/master/framework/web/UrlNormalizerRedirectException.php
BSD-3-Clause
private function setCookieParamsInternal() { $data = $this->getCookieParams(); if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) { if (PHP_VERSION_ID >= 70300) { session_set_cookie_params($data); } else { if (!empty($data['samesite'])) { $data['path'] .= '; samesite=' . $data['samesite']; } session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']); } } else { throw new InvalidArgumentException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.'); } }
Sets the session cookie parameters. This method is called by [[open()]] when it is about to open the session. @throws InvalidArgumentException if the parameters are incomplete. @see https://www.php.net/manual/en/function.session-set-cookie-params.php
setCookieParamsInternal
php
yiisoft/yii2
framework/web/Session.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php
BSD-3-Clause
public function gcSession($maxLifetime) { return 0; }
Session GC (garbage collection) handler. This method should be overridden if [[useCustomStorage]] returns true. @internal Do not call this method directly. @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. @return int|false the number of deleted sessions on success, or false on failure
gcSession
php
yiisoft/yii2
framework/web/Session.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php
BSD-3-Clause
public function getAssetUrl($bundle, $asset, $appendTimestamp = null) { $assetUrl = $this->getActualAssetUrl($bundle, $asset); $assetPath = $this->getAssetPath($bundle, $asset); $withTimestamp = $this->appendTimestamp; if ($appendTimestamp !== null) { $withTimestamp = $appendTimestamp; } if ($withTimestamp && $assetPath && ($timestamp = @filemtime($assetPath)) > 0) { return "$assetUrl?v=$timestamp"; } return $assetUrl; }
Returns the actual URL for the specified asset. The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path. @param AssetBundle $bundle the asset bundle which the asset file belongs to @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]]. @param bool|null $appendTimestamp Whether to append timestamp to the URL. @return string the actual URL for the specified asset.
getAssetUrl
php
yiisoft/yii2
framework/web/AssetManager.php
https://github.com/yiisoft/yii2/blob/master/framework/web/AssetManager.php
BSD-3-Clause
public function publish($path, $options = []) { $path = Yii::getAlias($path); if (isset($this->_published[$path])) { return $this->_published[$path]; } if (!is_string($path) || ($src = realpath($path)) === false) { throw new InvalidArgumentException("The file or directory to be published does not exist: $path"); } if (!is_readable($path)) { throw new InvalidArgumentException("The file or directory to be published is not readable: $path"); } if (is_file($src)) { return $this->_published[$path] = $this->publishFile($src); } return $this->_published[$path] = $this->publishDirectory($src, $options); }
Publishes a file or a directory. This method will copy the specified file or directory to [[basePath]] so that it can be accessed via the Web server. If the asset is a file, its file modification time will be checked to avoid unnecessary file copying. If the asset is a directory, all files and subdirectories under it will be published recursively. Note, in case $forceCopy is false the method only checks the existence of the target directory to avoid repetitive copying (which is very expensive). By default, when publishing a directory, subdirectories and files whose name starts with a dot "." will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option as explained in the `$options` parameter. Note: On rare scenario, a race condition can develop that will lead to a one-time-manifestation of a non-critical problem in the creation of the directory that holds the published assets. This problem can be avoided altogether by 'requesting' in advance all the resources that are supposed to trigger a 'publish()' call, and doing that in the application deployment phase, before system goes live. See more in the following discussion: https://code.google.com/archive/p/yii/issues/2579 @param string $path the asset (file or directory) to be published @param array $options the options to be applied when publishing a directory. The following options are supported: - only: array, list of patterns that the file paths should match if they want to be copied. - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied. - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true. - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. This overrides [[beforeCopy]] if set. - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied. This overrides [[afterCopy]] if set. - forceCopy: boolean, whether the directory being published should be copied even if it is found in the target directory. This option is used only when publishing a directory. This overrides [[forceCopy]] if set. @return array the path (directory or file path) and the URL that the asset is published as. @throws InvalidArgumentException if the asset to be published does not exist. @throws InvalidConfigException if the target directory [[basePath]] is not writeable.
publish
php
yiisoft/yii2
framework/web/AssetManager.php
https://github.com/yiisoft/yii2/blob/master/framework/web/AssetManager.php
BSD-3-Clause
public function getServerPort() { foreach ($this->portHeaders as $portHeader) { if ($this->headers->has($portHeader)) { $port = $this->headers->get($portHeader); if ($port !== null) { return $port; } } } return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null; }
Returns the server port number. If a port is specified via a forwarding header (e.g. 'X-Forwarded-Port') and the remote host is a "trusted host" the that port will be used (see [[portHeaders]]), otherwise the default server port will be returned. @return int|null server port number, null if not available @see portHeaders
getServerPort
php
yiisoft/yii2
framework/web/Request.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php
BSD-3-Clause
protected function getUserIpFromIpHeaders() { $ip = $this->getSecureForwardedHeaderTrustedPart('for'); if ( $ip !== null && preg_match( '/^\[?(?P<ip>(?:(?:(?:[0-9a-f]{1,4}:){1,6}(?:[0-9a-f]{1,4})?(?:(?::[0-9a-f]{1,4}){1,6}))|(?:\d{1,3}\.){3}\d{1,3}))\]?(?::(?P<port>\d+))?$/', $ip, $matches ) ) { $ip = $this->getUserIpFromIpHeader($matches['ip']); if ($ip !== null) { return $ip; } } foreach ($this->ipHeaders as $ipHeader) { if ($this->headers->has($ipHeader)) { $ip = $this->getUserIpFromIpHeader($this->headers->get($ipHeader)); if ($ip !== null) { return $ip; } } } return null; }
Returns the user IP address from [[ipHeaders]]. @return string|null user IP address, null if not available @see ipHeaders @since 2.0.28
getUserIpFromIpHeaders
php
yiisoft/yii2
framework/web/Request.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php
BSD-3-Clause
public function getContentType() { if (isset($_SERVER['CONTENT_TYPE'])) { return $_SERVER['CONTENT_TYPE']; } //fix bug https://bugs.php.net/bug.php?id=66606 return $this->headers->get('Content-Type') ?: ''; }
Returns request content-type The Content-Type header field indicates the MIME type of the data contained in [[getRawBody()]] or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. For the MIME-types the user expects in response, see [[acceptableContentTypes]]. @return string request content-type. Empty string is returned if this information is not available. @link https://tools.ietf.org/html/rfc2616#section-14.17 HTTP 1.1 header field definitions
getContentType
php
yiisoft/yii2
framework/web/Request.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php
BSD-3-Clause
public function getCsrfToken($regenerate = false) { if ($this->validateCsrfHeaderOnly) { return null; } if ($this->_csrfToken === null || $regenerate) { $token = $this->loadCsrfToken(); if ($regenerate || empty($token)) { $token = $this->generateCsrfToken(); } $this->_csrfToken = Yii::$app->security->maskToken($token); } return $this->_csrfToken; }
Returns the token used to perform CSRF validation. This token is generated in a way to prevent [BREACH attacks](https://en.wikipedia.org/wiki/BREACH). It may be passed along via a hidden field of an HTML form or an HTTP header value to support CSRF validation. @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time this method is called, a new CSRF token will be generated and persisted (in session or cookie). @return null|string the token used to perform CSRF validation. Null is returned if the [[validateCsrfHeaderOnly]] is true.
getCsrfToken
php
yiisoft/yii2
framework/web/Request.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php
BSD-3-Clause
public function validateCsrfToken($clientSuppliedToken = null) { $method = $this->getMethod(); if ($this->validateCsrfHeaderOnly) { return in_array($method, $this->csrfHeaderUnsafeMethods, true) ? $this->headers->has($this->csrfHeader) : true; } if (!$this->enableCsrfValidation || in_array($method, $this->csrfTokenSafeMethods, true)) { return true; } $trueToken = $this->getCsrfToken(); if ($clientSuppliedToken !== null) { return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken); } return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken) || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken); }
Performs the CSRF validation. This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session. This method is mainly called in [[Controller::beforeAction()]]. Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method is among GET, HEAD or OPTIONS. @param string|null $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from the [[csrfParam]] POST field or HTTP header. This parameter is available since version 2.0.4. @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
validateCsrfToken
php
yiisoft/yii2
framework/web/Request.php
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php
BSD-3-Clause
private function preparePattern() { $this->pattern = $this->trimSlashes($this->pattern); $this->route = trim($this->route, '/'); if ($this->host !== null) { $this->host = rtrim($this->host, '/'); $this->pattern = rtrim($this->host . '/' . $this->pattern, '/'); } elseif ($this->pattern === '') { $this->_template = ''; $this->pattern = '#^$#u'; return; } elseif (($pos = strpos($this->pattern, '://')) !== false) { if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) { $this->host = substr($this->pattern, 0, $pos2); } else { $this->host = $this->pattern; } } elseif (strncmp($this->pattern, '//', 2) === 0) { if (($pos2 = strpos($this->pattern, '/', 2)) !== false) { $this->host = substr($this->pattern, 0, $pos2); } else { $this->host = $this->pattern; } } else { $this->pattern = '/' . $this->pattern . '/'; } if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) { foreach ($matches[1] as $name) { $this->_routeParams[$name] = "<$name>"; } } $this->translatePattern(true); }
Process [[$pattern]] on rule initialization.
preparePattern
php
yiisoft/yii2
framework/web/UrlRule.php
https://github.com/yiisoft/yii2/blob/master/framework/web/UrlRule.php
BSD-3-Clause
protected function isValidXmlName($name) { try { return $this->dom->createElement($name) !== false; } catch (DOMException $e) { return false; } }
Checks if name is valid to be used in XML. @param mixed $name the name to test @return bool @see https://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943 @since 2.0.12
isValidXmlName
php
yiisoft/yii2
framework/web/XmlResponseFormatter.php
https://github.com/yiisoft/yii2/blob/master/framework/web/XmlResponseFormatter.php
BSD-3-Clause
protected function formatJson($response) { if ($response->data !== null) { $options = $this->encodeOptions; if ($this->prettyPrint) { $options |= JSON_PRETTY_PRINT; } $default = Json::$keepObjectType; if ($this->keepObjectType !== null) { Json::$keepObjectType = $this->keepObjectType; } $response->content = Json::encode($response->data, $options); // Restore default value to avoid any unexpected behaviour Json::$keepObjectType = $default; } elseif ($response->content === null) { $response->content = 'null'; } }
Formats response data in JSON format. @param Response $response
formatJson
php
yiisoft/yii2
framework/web/JsonResponseFormatter.php
https://github.com/yiisoft/yii2/blob/master/framework/web/JsonResponseFormatter.php
BSD-3-Clause
public function gcSession($maxLifetime) { return $this->db->createCommand() ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()]) ->execute(); }
Session GC (garbage collection) handler. @internal Do not call this method directly. @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. @return int|false the number of deleted sessions on success, or false on failure
gcSession
php
yiisoft/yii2
framework/web/DbSession.php
https://github.com/yiisoft/yii2/blob/master/framework/web/DbSession.php
BSD-3-Clause
public function key() { return $this->_key === false ? null : $this->_key; }
Returns the key of the current array element. This method is required by the interface [[\Iterator]]. @return string|int|null the key of the current array element
key
php
yiisoft/yii2
framework/web/SessionIterator.php
https://github.com/yiisoft/yii2/blob/master/framework/web/SessionIterator.php
BSD-3-Clause
public function getIdentity($autoRenew = true) { if ($this->_identity === false) { if ($this->enableSession && $autoRenew) { try { $this->_identity = null; $this->renewAuthStatus(); } catch (\Exception $e) { $this->_identity = false; throw $e; } catch (\Throwable $e) { $this->_identity = false; throw $e; } } else { return null; } } return $this->_identity; }
Returns the identity object associated with the currently logged-in user. When [[enableSession]] is true, this method may attempt to read the user's authentication data stored in session and reconstruct the corresponding identity object, if it has not done so before. @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before. This is only useful when [[enableSession]] is true. @return IdentityInterface|null the identity object associated with the currently logged-in user. `null` is returned if the user is not logged in (not authenticated). @see login() @see logout()
getIdentity
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function setIdentity($identity) { if ($identity instanceof IdentityInterface) { $this->_identity = $identity; } elseif ($identity === null) { $this->_identity = null; } else { throw new InvalidValueException('The identity object must implement IdentityInterface.'); } $this->_access = []; }
Sets the user identity object. Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]] to change the identity of the current user. @param IdentityInterface|null $identity the identity object associated with the currently logged user. If null, it means the current user will be a guest without any associated identity. @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
setIdentity
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function login(IdentityInterface $identity, $duration = 0) { if ($this->beforeLogin($identity, false, $duration)) { $this->switchIdentity($identity, $duration); $id = $identity->getId(); $ip = Yii::$app->getRequest()->getUserIP(); if ($this->enableSession) { $log = "User '$id' logged in from $ip with duration $duration."; } else { $log = "User '$id' logged in from $ip. Session not enabled."; } $this->regenerateCsrfToken(); Yii::info($log, __METHOD__); $this->afterLogin($identity, false, $duration); } return !$this->getIsGuest(); }
Logs in a user. After logging in a user: - the user's identity information is obtainable from the [[identity]] property If [[enableSession]] is `true`: - the identity information will be stored in session and be available in the next requests - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser - in case of `$duration > 0`: as long as the session remains active or as long as the cookie remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`. If [[enableSession]] is `false`: - the `$duration` parameter will be ignored @param IdentityInterface $identity the user identity (which should already be authenticated) @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0` @return bool whether the user is logged in
login
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function loginByAccessToken($token, $type = null) { /* @var $class IdentityInterface */ $class = $this->identityClass; $identity = $class::findIdentityByAccessToken($token, $type); if ($identity && $this->login($identity)) { return $identity; } return null; }
Logs in a user by the given access token. This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]] with the provided access token. If successful, it will call [[login()]] to log in the authenticated user. If authentication fails or [[login()]] is unsuccessful, it will return null. @param string $token the access token @param mixed $type the type of the token. The value of this parameter depends on the implementation. For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`. @return IdentityInterface|null the identity associated with the given access token. Null is returned if the access token is invalid or [[login()]] is unsuccessful.
loginByAccessToken
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
protected function loginByCookie() { $data = $this->getIdentityAndDurationFromCookie(); if (isset($data['identity'], $data['duration'])) { $identity = $data['identity']; $duration = $data['duration']; if ($this->beforeLogin($identity, true, $duration)) { $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0); $id = $identity->getId(); $ip = Yii::$app->getRequest()->getUserIP(); Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__); $this->afterLogin($identity, true, $duration); } } }
Logs in a user by cookie. This method attempts to log in a user using the ID and authKey information provided by the [[identityCookie|identity cookie]].
loginByCookie
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function logout($destroySession = true) { $identity = $this->getIdentity(); if ($identity !== null && $this->beforeLogout($identity)) { $this->switchIdentity(null); $id = $identity->getId(); $ip = Yii::$app->getRequest()->getUserIP(); Yii::info("User '$id' logged out from $ip.", __METHOD__); if ($destroySession && $this->enableSession) { Yii::$app->getSession()->destroy(); } $this->afterLogout($identity); } return $this->getIsGuest(); }
Logs out the current user. This will remove authentication-related session data. If `$destroySession` is true, all session data will be removed. @param bool $destroySession whether to destroy the whole session. Defaults to true. This parameter is ignored if [[enableSession]] is false. @return bool whether the user is logged out
logout
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function getIsGuest() { return $this->getIdentity() === null; }
Returns a value indicating whether the user is a guest (not authenticated). @return bool whether the current user is a guest. @see getIdentity()
getIsGuest
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function getId() { $identity = $this->getIdentity(); return $identity !== null ? $identity->getId() : null; }
Returns a value that uniquely represents the user. @return string|int|null the unique identifier for the user. If `null`, it means the user is a guest. @see getIdentity()
getId
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause
public function getReturnUrl($defaultUrl = null) { $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl); if (is_array($url)) { if (isset($url[0])) { return Yii::$app->getUrlManager()->createUrl($url); } $url = null; } return $url === null ? Yii::$app->getHomeUrl() : $url; }
Returns the URL that the browser should be redirected to after successful login. This method reads the return URL from the session. It is usually used by the login action which may call this method to redirect the browser to where it goes after successful authentication. @param string|array|null $defaultUrl the default return URL in case it was not set previously. If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to. Please refer to [[setReturnUrl()]] on accepted format of the URL. @return string the URL that the user should be redirected to after login. @see loginRequired()
getReturnUrl
php
yiisoft/yii2
framework/web/User.php
https://github.com/yiisoft/yii2/blob/master/framework/web/User.php
BSD-3-Clause