_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q14600
HydrationCompleteHandler.hydrationComplete
train
public function hydrationComplete() { $toInvoke = $this->deferredPostLoadInvocations; $this->deferredPostLoadInvocations = []; foreach ($toInvoke as $classAndEntity) { [$class, $invoke, $entity] = $classAndEntity; $this->listenersInvoker->invoke( $class, Events::postLoad, $entity, new LifecycleEventArgs($entity, $this->em), $invoke ); } }
php
{ "resource": "" }
q14601
AbstractClassMetadataFactory.getOrCreateClassMetadataDefinition
train
private function getOrCreateClassMetadataDefinition(string $className, ?ClassMetadata $parent) : ClassMetadataDefinition { if (! isset($this->definitions[$className])) { $this->definitions[$className] = $this->definitionFactory->build($className, $parent); } return $this->definitions[$className]; }
php
{ "resource": "" }
q14602
StatisticsCacheLogger.clearRegionStats
train
public function clearRegionStats($regionName) { $this->cachePutCountMap[$regionName] = 0; $this->cacheHitCountMap[$regionName] = 0; $this->cacheMissCountMap[$regionName] = 0; }
php
{ "resource": "" }
q14603
BasicEntityPersister.getSelectColumnSQL
train
protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r') { $property = $class->getProperty($field); $columnAlias = $this->getSQLColumnAlias(); $sql = sprintf( '%s.%s', $this->getSQLTableAlias($property->getTableName(), ($alias === 'r' ? '' : $alias)), $this->platform->quoteIdentifier($property->getColumnName()) ); $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field, $class->getClassName()); return $property->getType()->convertToPHPValueSQL($sql, $this->platform) . ' AS ' . $columnAlias; }
php
{ "resource": "" }
q14604
BasicEntityPersister.getSelectConditionCriteriaSQL
train
protected function getSelectConditionCriteriaSQL(Criteria $criteria) { $expression = $criteria->getWhereExpression(); if ($expression === null) { return ''; } $visitor = new SqlExpressionVisitor($this, $this->class); return $visitor->dispatch($expression); }
php
{ "resource": "" }
q14605
BasicEntityPersister.getIndividualValue
train
private function getIndividualValue($value) { if (! is_object($value) || ! $this->em->getMetadataFactory()->hasMetadataFor(StaticClassNameConverter::getClass($value))) { return $value; } return $this->em->getUnitOfWork()->getSingleIdentifierValue($value); }
php
{ "resource": "" }
q14606
BasicEntityPersister.getJoinSQLForAssociation
train
protected function getJoinSQLForAssociation(AssociationMetadata $association) { if (! $association->isOwningSide()) { return 'LEFT JOIN'; } // if one of the join columns is nullable, return left join foreach ($association->getJoinColumns() as $joinColumn) { if (! $joinColumn->isNullable()) { continue; } return 'LEFT JOIN'; } return 'INNER JOIN'; }
php
{ "resource": "" }
q14607
SqlWalker.setSQLTableAlias
train
public function setSQLTableAlias($tableName, $alias, $dqlAlias = '') { $tableName .= $dqlAlias ? '@[' . $dqlAlias . ']' : ''; $this->tableAliasMap[$tableName] = $alias; return $alias; }
php
{ "resource": "" }
q14608
SqlWalker.walkIdentificationVariableDeclaration
train
public function walkIdentificationVariableDeclaration($identificationVariableDecl) { $sql = $this->walkRangeVariableDeclaration($identificationVariableDecl->rangeVariableDeclaration); if ($identificationVariableDecl->indexBy) { $this->walkIndexBy($identificationVariableDecl->indexBy); } foreach ($identificationVariableDecl->joins as $join) { $sql .= $this->walkJoin($join); } return $sql; }
php
{ "resource": "" }
q14609
SqlWalker.walkIndexBy
train
public function walkIndexBy($indexBy) { $pathExpression = $indexBy->simpleStateFieldPathExpression; $alias = $pathExpression->identificationVariable; $field = $pathExpression->field; if (isset($this->scalarFields[$alias][$field])) { $this->rsm->addIndexByScalar($this->scalarFields[$alias][$field]); return; } $this->rsm->addIndexBy($alias, $field); }
php
{ "resource": "" }
q14610
SqlWalker.generateRangeVariableDeclarationSQL
train
private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string { $class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName); $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable; if ($rangeVariableDeclaration->isRoot) { $this->rootAliases[] = $dqlAlias; } $tableName = $class->table->getQuotedQualifiedName($this->platform); $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); $sql = $this->platform->appendLockHint( $tableName . ' ' . $tableAlias, $this->query->getHint(Query::HINT_LOCK_MODE) ); if ($class->inheritanceType !== InheritanceType::JOINED) { return $sql; } $classTableInheritanceJoins = $this->generateClassTableInheritanceJoins($class, $dqlAlias); if (! $buildNestedJoins) { return $sql . $classTableInheritanceJoins; } return $classTableInheritanceJoins === '' ? $sql : '(' . $sql . $classTableInheritanceJoins . ')'; }
php
{ "resource": "" }
q14611
SqlWalker.walkCoalesceExpression
train
public function walkCoalesceExpression($coalesceExpression) { $sql = 'COALESCE('; $scalarExpressions = []; foreach ($coalesceExpression->scalarExpressions as $scalarExpression) { $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression); } return $sql . implode(', ', $scalarExpressions) . ')'; }
php
{ "resource": "" }
q14612
SqlWalker.walkNullIfExpression
train
public function walkNullIfExpression($nullIfExpression) { $firstExpression = is_string($nullIfExpression->firstExpression) ? $this->conn->quote($nullIfExpression->firstExpression) : $this->walkSimpleArithmeticExpression($nullIfExpression->firstExpression); $secondExpression = is_string($nullIfExpression->secondExpression) ? $this->conn->quote($nullIfExpression->secondExpression) : $this->walkSimpleArithmeticExpression($nullIfExpression->secondExpression); return 'NULLIF(' . $firstExpression . ', ' . $secondExpression . ')'; }
php
{ "resource": "" }
q14613
SqlWalker.walkGeneralCaseExpression
train
public function walkGeneralCaseExpression(AST\GeneralCaseExpression $generalCaseExpression) { $sql = 'CASE'; foreach ($generalCaseExpression->whenClauses as $whenClause) { $sql .= ' WHEN ' . $this->walkConditionalExpression($whenClause->caseConditionExpression); $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($whenClause->thenScalarExpression); } $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($generalCaseExpression->elseScalarExpression) . ' END'; return $sql; }
php
{ "resource": "" }
q14614
SqlWalker.walkSimpleCaseExpression
train
public function walkSimpleCaseExpression($simpleCaseExpression) { $sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand); foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) { $sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression); $sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression); } $sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END'; return $sql; }
php
{ "resource": "" }
q14615
SqlWalker.walkArithmeticPrimary
train
public function walkArithmeticPrimary($primary) { if ($primary instanceof AST\SimpleArithmeticExpression) { return '(' . $this->walkSimpleArithmeticExpression($primary) . ')'; } if ($primary instanceof AST\Node) { return $primary->dispatch($this); } return $this->walkEntityIdentificationVariable($primary); }
php
{ "resource": "" }
q14616
EntityRepository.resolveMagicCall
train
private function resolveMagicCall($method, $by, array $arguments) { if (! $arguments) { throw InvalidMagicMethodCall::onMissingParameter($method . $by); } $fieldName = lcfirst(Inflector::classify($by)); if ($this->class->getProperty($fieldName) === null) { throw InvalidMagicMethodCall::becauseFieldNotFoundIn( $this->entityName, $fieldName, $method . $by ); } return $this->{$method}([$fieldName => $arguments[0]], ...array_slice($arguments, 1)); }
php
{ "resource": "" }
q14617
Configuration.setAutoGenerateProxyClasses
train
public function setAutoGenerateProxyClasses($autoGenerate) : void { $proxyManagerConfig = $this->getProxyManagerConfiguration(); switch ((int) $autoGenerate) { case ProxyFactory::AUTOGENERATE_ALWAYS: case ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS: $proxyManagerConfig->setGeneratorStrategy(new FileWriterGeneratorStrategy( new FileLocator($proxyManagerConfig->getProxiesTargetDir()) )); return; case ProxyFactory::AUTOGENERATE_NEVER: case ProxyFactory::AUTOGENERATE_EVAL: default: $proxyManagerConfig->setGeneratorStrategy(new EvaluatingGeneratorStrategy()); return; } }
php
{ "resource": "" }
q14618
Configuration.newDefaultAnnotationDriver
train
public function newDefaultAnnotationDriver(array $paths = []) : AnnotationDriver { AnnotationRegistry::registerFile(__DIR__ . '/Annotation/DoctrineAnnotations.php'); $reader = new CachedReader(new AnnotationReader(), new ArrayCache()); return new AnnotationDriver($reader, $paths); }
php
{ "resource": "" }
q14619
Configuration.addCustomStringFunction
train
public function addCustomStringFunction(string $functionName, $classNameOrFactory) : void { $this->customStringFunctions[strtolower($functionName)] = $classNameOrFactory; }
php
{ "resource": "" }
q14620
Configuration.setCustomStringFunctions
train
public function setCustomStringFunctions(array $functions) : void { foreach ($functions as $name => $className) { $this->addCustomStringFunction($name, $className); } }
php
{ "resource": "" }
q14621
Configuration.setCustomNumericFunctions
train
public function setCustomNumericFunctions(array $functions) : void { foreach ($functions as $name => $className) { $this->addCustomNumericFunction($name, $className); } }
php
{ "resource": "" }
q14622
Configuration.addCustomHydrationMode
train
public function addCustomHydrationMode(string $modeName, string $hydratorClassName) : void { $this->customHydrationModes[$modeName] = $hydratorClassName; }
php
{ "resource": "" }
q14623
Configuration.addFilter
train
public function addFilter(string $filterName, string $filterClassName) : void { $this->filters[$filterName] = $filterClassName; }
php
{ "resource": "" }
q14624
Setup.createXMLMetadataConfiguration
train
public static function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, ?Cache $cache = null) { $config = self::createConfiguration($isDevMode, $proxyDir, $cache); $config->setMetadataDriverImpl(new XmlDriver($paths)); return $config; }
php
{ "resource": "" }
q14625
PersistentObject.injectEntityManager
train
public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void { if ($entityManager !== self::$entityManager) { throw new RuntimeException( 'Trying to use PersistentObject with different EntityManager instances. ' . 'Was PersistentObject::setEntityManager() called?' ); } $this->cm = $classMetadata; }
php
{ "resource": "" }
q14626
PersistentObject.set
train
private function set($field, $args) { $this->initializeDoctrine(); $property = $this->cm->getProperty($field); if (! $property) { throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'"); } switch (true) { case $property instanceof FieldMetadata && ! $property->isPrimaryKey(): $this->{$field} = $args[0]; break; case $property instanceof ToOneAssociationMetadata: $targetClassName = $property->getTargetEntity(); if ($args[0] !== null && ! ($args[0] instanceof $targetClassName)) { throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'"); } $this->{$field} = $args[0]; $this->completeOwningSide($property, $args[0]); break; } return $this; }
php
{ "resource": "" }
q14627
PersistentObject.get
train
private function get($field) { $this->initializeDoctrine(); $property = $this->cm->getProperty($field); if (! $property) { throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'"); } return $this->{$field}; }
php
{ "resource": "" }
q14628
PersistentObject.completeOwningSide
train
private function completeOwningSide(AssociationMetadata $property, $targetObject) { // add this object on the owning side as well, for obvious infinite recursion // reasons this is only done when called on the inverse side. if ($property->isOwningSide()) { return; } $mappedByField = $property->getMappedBy(); $targetMetadata = self::$entityManager->getClassMetadata($property->getTargetEntity()); $targetProperty = $targetMetadata->getProperty($mappedByField); $setterMethodName = ($targetProperty instanceof ToManyAssociationMetadata ? 'add' : 'set') . $mappedByField; $targetObject->{$setterMethodName}($this); }
php
{ "resource": "" }
q14629
PersistentObject.add
train
private function add($field, $args) { $this->initializeDoctrine(); $property = $this->cm->getProperty($field); if (! $property) { throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'"); } if (! ($property instanceof ToManyAssociationMetadata)) { throw new BadMethodCallException('There is no method add' . $field . '() on ' . $this->cm->getClassName()); } $targetClassName = $property->getTargetEntity(); if (! ($args[0] instanceof $targetClassName)) { throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'"); } if (! ($this->{$field} instanceof Collection)) { $this->{$field} = new ArrayCollection($this->{$field} ?: []); } $this->{$field}->add($args[0]); $this->completeOwningSide($property, $args[0]); return $this; }
php
{ "resource": "" }
q14630
PersistentObject.initializeDoctrine
train
private function initializeDoctrine() { if ($this->cm !== null) { return; } if (! self::$entityManager) { throw new RuntimeException('No runtime entity manager set. Call PersistentObject#setEntityManager().'); } $this->cm = self::$entityManager->getClassMetadata(static::class); }
php
{ "resource": "" }
q14631
ResultSetMapping.addEntityResult
train
public function addEntityResult($class, $alias, $resultAlias = null) { $this->aliasMap[$alias] = $class; $this->entityMappings[$alias] = $resultAlias; if ($resultAlias !== null) { $this->isMixed = true; } return $this; }
php
{ "resource": "" }
q14632
ResultSetMapping.setDiscriminatorColumn
train
public function setDiscriminatorColumn($alias, $discrColumn) { $this->discriminatorColumns[$alias] = $discrColumn; $this->columnOwnerMap[$discrColumn] = $alias; return $this; }
php
{ "resource": "" }
q14633
ResultSetMapping.addIndexBy
train
public function addIndexBy($alias, $fieldName) { $found = false; foreach (array_merge($this->metaMappings, $this->fieldMappings) as $columnName => $columnFieldName) { if (! ($columnFieldName === $fieldName && $this->columnOwnerMap[$columnName] === $alias)) { continue; } $this->addIndexByColumn($alias, $columnName); $found = true; break; } /* TODO: check if this exception can be put back, for now it's gone because of assumptions made by some ORM internals if ( ! $found) { $message = sprintf( 'Cannot add index by for DQL alias %s and field %s without calling addFieldResult() for them before.', $alias, $fieldName ); throw new \LogicException($message); } */ return $this; }
php
{ "resource": "" }
q14634
ResultSetMapping.addFieldResult
train
public function addFieldResult($alias, $columnName, $fieldName, $declaringClass = null) { // column name (in result set) => field name $this->fieldMappings[$columnName] = $fieldName; // column name => alias of owner $this->columnOwnerMap[$columnName] = $alias; // field name => class name of declaring class $this->declaringClasses[$columnName] = $declaringClass ?: $this->aliasMap[$alias]; if (! $this->isMixed && $this->scalarMappings) { $this->isMixed = true; } return $this; }
php
{ "resource": "" }
q14635
ResultSetMapping.addJoinedEntityResult
train
public function addJoinedEntityResult($class, $alias, $parentAlias, $relation) { $this->aliasMap[$alias] = $class; $this->parentAliasMap[$alias] = $parentAlias; $this->relationMap[$alias] = $relation; return $this; }
php
{ "resource": "" }
q14636
OneToManyPersister.deleteJoinedEntityCollection
train
private function deleteJoinedEntityCollection(PersistentCollection $collection) { $association = $collection->getMapping(); $targetClass = $this->em->getClassMetadata($association->getTargetEntity()); $rootClass = $this->em->getClassMetadata($targetClass->getRootClassName()); $sourcePersister = $this->uow->getEntityPersister($association->getSourceEntity()); // 1) Build temporary table DDL $tempTable = $this->platform->getTemporaryTableName($rootClass->getTemporaryIdTableName()); $idColumns = $rootClass->getIdentifierColumns($this->em); $idColumnNameList = implode(', ', array_keys($idColumns)); $columnDefinitions = []; foreach ($idColumns as $columnName => $column) { $type = $column->getType(); $columnDefinitions[$columnName] = [ 'notnull' => true, 'type' => $type, ]; } $statement = $this->platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $this->platform->getColumnDeclarationListSQL($columnDefinitions) . ')'; $this->conn->executeUpdate($statement); // 2) Build insert table records into temporary table $dql = ' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames()) . ' FROM ' . $targetClass->getClassName() . ' t0 WHERE t0.' . $association->getMappedBy() . ' = :owner'; $query = $this->em->createQuery($dql)->setParameter('owner', $collection->getOwner()); $statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ') ' . $query->getSQL(); $parameters = array_values($sourcePersister->getIdentifier($collection->getOwner())); $numDeleted = $this->conn->executeUpdate($statement, $parameters); // 3) Create statement used in DELETE ... WHERE ... IN (subselect) $deleteSQLTemplate = sprintf( 'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)', $idColumnNameList, $idColumnNameList, $tempTable ); // 4) Delete records on each table in the hierarchy $hierarchyClasses = array_merge( array_map( function ($className) { return $this->em->getClassMetadata($className); }, array_reverse($targetClass->getSubClasses()) ), [$targetClass], $targetClass->getAncestorsIterator()->getArrayCopy() ); foreach ($hierarchyClasses as $class) { $statement = sprintf($deleteSQLTemplate, $class->table->getQuotedQualifiedName($this->platform)); $this->conn->executeUpdate($statement); } // 5) Drop temporary table $statement = $this->platform->getDropTemporaryTableSQL($tempTable); $this->conn->executeUpdate($statement); return $numDeleted; }
php
{ "resource": "" }
q14637
LazyCriteriaCollection.count
train
public function count() { if ($this->isInitialized()) { return $this->collection->count(); } // Return cached result in case count query was already executed if ($this->count !== null) { return $this->count; } return $this->count = $this->entityPersister->count($this->criteria); }
php
{ "resource": "" }
q14638
LazyCriteriaCollection.contains
train
public function contains($element) { if ($this->isInitialized()) { return $this->collection->contains($element); } return $this->entityPersister->exists($element, $this->criteria); }
php
{ "resource": "" }
q14639
ResultSetMappingBuilder.isInheritanceSupported
train
private function isInheritanceSupported(ClassMetadata $metadata) { if ($metadata->inheritanceType === InheritanceType::SINGLE_TABLE && in_array($metadata->getClassName(), $metadata->discriminatorMap, true)) { return true; } return ! in_array($metadata->inheritanceType, [InheritanceType::SINGLE_TABLE, InheritanceType::JOINED], true); }
php
{ "resource": "" }
q14640
Query.processParameterMappings
train
private function processParameterMappings($paramMappings) { $sqlParams = []; $types = []; foreach ($this->parameters as $parameter) { $key = $parameter->getName(); $value = $parameter->getValue(); $rsm = $this->getResultSetMapping(); if (! isset($paramMappings[$key])) { throw QueryException::unknownParameter($key); } if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) { $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]); } if (isset($rsm->discriminatorParameters[$key]) && $value instanceof ClassMetadata) { $value = array_keys(HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($value, $this->em)); } $value = $this->processParameterValue($value); $type = $parameter->getValue() === $value ? $parameter->getType() : ParameterTypeInferer::inferType($value); foreach ($paramMappings[$key] as $position) { $types[$position] = $type; } $sqlPositions = $paramMappings[$key]; $sqlPositionsCount = count($sqlPositions); // optimized multi value sql positions away for now, // they are not allowed in DQL anyways. $value = [$value]; $countValue = count($value); for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) { $sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)]; } } if (count($sqlParams) !== count($types)) { throw QueryException::parameterTypeMismatch(); } if ($sqlParams) { ksort($sqlParams); $sqlParams = array_values($sqlParams); ksort($types); $types = array_values($types); } return [$sqlParams, $types]; }
php
{ "resource": "" }
q14641
Query.iterate
train
public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT) { $this->setHint(self::HINT_INTERNAL_ITERATION, true); return parent::iterate($parameters, $hydrationMode); }
php
{ "resource": "" }
q14642
Query.getLockMode
train
public function getLockMode() { $lockMode = $this->getHint(self::HINT_LOCK_MODE); if ($lockMode === false) { return null; } return $lockMode; }
php
{ "resource": "" }
q14643
DatabaseDriver.setTables
train
public function setTables($entityTables, $manyToManyTables) { $this->tables = $this->manyToManyTables = $this->classToTableNames = []; foreach ($entityTables as $table) { $className = $this->getClassNameForTable($table->getName()); $this->classToTableNames[$className] = $table->getName(); $this->tables[$table->getName()] = $table; } foreach ($manyToManyTables as $table) { $this->manyToManyTables[$table->getName()] = $table; } }
php
{ "resource": "" }
q14644
DatabaseDriver.buildTable
train
private function buildTable(Mapping\ClassMetadata $metadata) { $tableName = $this->classToTableNames[$metadata->getClassName()]; $indexes = $this->tables[$tableName]->getIndexes(); $tableMetadata = new Mapping\TableMetadata(); $tableMetadata->setName($this->classToTableNames[$metadata->getClassName()]); foreach ($indexes as $index) { /** @var Index $index */ if ($index->isPrimary()) { continue; } $tableMetadata->addIndex([ 'name' => $index->getName(), 'columns' => $index->getColumns(), 'unique' => $index->isUnique(), 'options' => $index->getOptions(), 'flags' => $index->getFlags(), ]); } $metadata->setTable($tableMetadata); }
php
{ "resource": "" }
q14645
DatabaseDriver.getFieldNameForColumn
train
private function getFieldNameForColumn($tableName, $columnName, $fk = false) { if (isset($this->fieldNamesForColumns[$tableName], $this->fieldNamesForColumns[$tableName][$columnName])) { return $this->fieldNamesForColumns[$tableName][$columnName]; } $columnName = strtolower($columnName); // Replace _id if it is a foreignkey column if ($fk) { $columnName = str_replace('_id', '', $columnName); } return Inflector::camelize($columnName); }
php
{ "resource": "" }
q14646
ClassMetadataGenerator.generate
train
public function generate(ClassMetadataDefinition $definition) : string { $metadata = $this->mappingDriver->loadMetadataForClass( $definition->entityClassName, $definition->parentClassMetadata ); return $this->metadataExporter->export($metadata); }
php
{ "resource": "" }
q14647
UnitOfWork.computeScheduleInsertsChangeSets
train
private function computeScheduleInsertsChangeSets() { foreach ($this->entityInsertions as $entity) { $class = $this->em->getClassMetadata(get_class($entity)); $this->computeChangeSet($class, $entity); } }
php
{ "resource": "" }
q14648
UnitOfWork.executeExtraUpdates
train
private function executeExtraUpdates() { foreach ($this->extraUpdates as $oid => $update) { [$entity, $changeset] = $update; $this->entityChangeSets[$oid] = $changeset; $this->getEntityPersister(get_class($entity))->update($entity); } $this->extraUpdates = []; }
php
{ "resource": "" }
q14649
UnitOfWork.executeUpdates
train
private function executeUpdates($class) { $className = $class->getClassName(); $persister = $this->getEntityPersister($className); $preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate); $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate); foreach ($this->entityUpdates as $oid => $entity) { if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) { continue; } if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) { $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke); $this->recomputeSingleEntityChangeSet($class, $entity); } if (! empty($this->entityChangeSets[$oid])) { $persister->update($entity); } unset($this->entityUpdates[$oid]); if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) { $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke); } } }
php
{ "resource": "" }
q14650
UnitOfWork.scheduleForInsert
train
public function scheduleForInsert($entity) { $oid = spl_object_id($entity); if (isset($this->entityUpdates[$oid])) { throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.'); } if (isset($this->entityDeletions[$oid])) { throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity); } if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) { throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity); } if (isset($this->entityInsertions[$oid])) { throw ORMInvalidArgumentException::scheduleInsertTwice($entity); } $this->entityInsertions[$oid] = $entity; if (isset($this->entityIdentifiers[$oid])) { $this->addToIdentityMap($entity); } if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); } }
php
{ "resource": "" }
q14651
UnitOfWork.scheduleForUpdate
train
public function scheduleForUpdate($entity) : void { $oid = spl_object_id($entity); if (! isset($this->entityIdentifiers[$oid])) { throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update'); } if (isset($this->entityDeletions[$oid])) { throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update'); } if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) { $this->entityUpdates[$oid] = $entity; } }
php
{ "resource": "" }
q14652
UnitOfWork.isEntityScheduled
train
public function isEntityScheduled($entity) { $oid = spl_object_id($entity); return isset($this->entityInsertions[$oid]) || isset($this->entityUpdates[$oid]) || isset($this->entityDeletions[$oid]); }
php
{ "resource": "" }
q14653
UnitOfWork.performCallbackOnCachedPersister
train
private function performCallbackOnCachedPersister(callable $callback) { if (! $this->hasCache) { return; } foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) { if ($persister instanceof CachedPersister) { $callback($persister); } } }
php
{ "resource": "" }
q14654
AnnotationDriver.convertTableAnnotationToTableMetadata
train
private function convertTableAnnotationToTableMetadata( Annotation\Table $tableAnnot, Mapping\TableMetadata $table ) : Mapping\TableMetadata { if (! empty($tableAnnot->name)) { $table->setName($tableAnnot->name); } if (! empty($tableAnnot->schema)) { $table->setSchema($tableAnnot->schema); } foreach ($tableAnnot->options as $optionName => $optionValue) { $table->addOption($optionName, $optionValue); } foreach ($tableAnnot->indexes as $indexAnnot) { $table->addIndex([ 'name' => $indexAnnot->name, 'columns' => $indexAnnot->columns, 'unique' => $indexAnnot->unique, 'options' => $indexAnnot->options, 'flags' => $indexAnnot->flags, ]); } foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { $table->addUniqueConstraint([ 'name' => $uniqueConstraintAnnot->name, 'columns' => $uniqueConstraintAnnot->columns, 'options' => $uniqueConstraintAnnot->options, 'flags' => $uniqueConstraintAnnot->flags, ]); } return $table; }
php
{ "resource": "" }
q14655
AbstractEntityPersister.getHash
train
protected function getHash($query, $criteria, ?array $orderBy = null, $limit = null, $offset = null) { [$params] = $criteria instanceof Criteria ? $this->persister->expandCriteriaParameters($criteria) : $this->persister->expandParameters($criteria); return sha1($query . serialize($params) . serialize($orderBy) . $limit . $offset); }
php
{ "resource": "" }
q14656
MappingException.missingRequiredOption
train
public static function missingRequiredOption($field, $expectedOption, $hint = '') { $message = sprintf("The mapping of field '%s' is invalid: The option '%s' is required.", $field, $expectedOption); if (! empty($hint)) { $message .= ' (Hint: ' . $hint . ')'; } return new self($message); }
php
{ "resource": "" }
q14657
Parser.match
train
public function match($token) { $lookaheadType = $this->lexer->lookahead['type']; // Short-circuit on first condition, usually types match if ($lookaheadType === $token) { $this->lexer->moveNext(); return; } // If parameter is not identifier (1-99) must be exact match if ($token < Lexer::T_IDENTIFIER) { $this->syntaxError($this->lexer->getLiteral($token)); } // If parameter is keyword (200+) must be exact match if ($token > Lexer::T_IDENTIFIER) { $this->syntaxError($this->lexer->getLiteral($token)); } // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+) if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) { $this->syntaxError($this->lexer->getLiteral($token)); } $this->lexer->moveNext(); }
php
{ "resource": "" }
q14658
Parser.free
train
public function free($deep = false, $position = 0) { // WARNING! Use this method with care. It resets the scanner! $this->lexer->resetPosition($position); // Deep = true cleans peek and also any previously defined errors if ($deep) { $this->lexer->resetPeek(); } $this->lexer->token = null; $this->lexer->lookahead = null; }
php
{ "resource": "" }
q14659
Parser.peekBeyondClosingParenthesis
train
private function peekBeyondClosingParenthesis($resetPeek = true) { $token = $this->lexer->peek(); $numUnmatched = 1; while ($numUnmatched > 0 && $token !== null) { switch ($token['type']) { case Lexer::T_OPEN_PARENTHESIS: ++$numUnmatched; break; case Lexer::T_CLOSE_PARENTHESIS: --$numUnmatched; break; default: // Do nothing } $token = $this->lexer->peek(); } if ($resetPeek) { $this->lexer->resetPeek(); } return $token; }
php
{ "resource": "" }
q14660
Parser.isMathOperator
train
private function isMathOperator($token) { return in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY], true); }
php
{ "resource": "" }
q14661
Parser.AliasIdentificationVariable
train
public function AliasIdentificationVariable() { $this->match(Lexer::T_IDENTIFIER); $aliasIdentVariable = $this->lexer->token['value']; $exists = isset($this->queryComponents[$aliasIdentVariable]); if ($exists) { $this->semanticalError(sprintf("'%s' is already defined.", $aliasIdentVariable), $this->lexer->token); } return $aliasIdentVariable; }
php
{ "resource": "" }
q14662
Parser.validateAbstractSchemaName
train
private function validateAbstractSchemaName($schemaName) : void { if (class_exists($schemaName, true) || interface_exists($schemaName, true)) { return; } try { $this->getEntityManager()->getClassMetadata($schemaName); return; } catch (MappingException $mappingException) { $this->semanticalError( sprintf('Class %s could not be mapped', $schemaName), $this->lexer->token ); } $this->semanticalError(sprintf("Class '%s' is not defined.", $schemaName), $this->lexer->token); }
php
{ "resource": "" }
q14663
HandlePreflight.handle
train
public function handle($request, Closure $next) { if ($this->cors->isPreflightRequest($request)) { return $this->cors->handlePreflightRequest($request); } return $next($request); }
php
{ "resource": "" }
q14664
AuthCodeGrant.respondToAccessTokenRequest
train
public function respondToAccessTokenRequest( ServerRequestInterface $request, ResponseTypeInterface $responseType, DateInterval $accessTokenTTL ) { // Validate request $client = $this->validateClient($request); $encryptedAuthCode = $this->getRequestParameter('code', $request, null); if ($encryptedAuthCode === null) { throw OAuthServerException::invalidRequest('code'); } try { $authCodePayload = json_decode($this->decrypt($encryptedAuthCode)); $this->validateAuthorizationCode($authCodePayload, $client, $request); $scopes = $this->scopeRepository->finalizeScopes( $this->validateScopes($authCodePayload->scopes), $this->getIdentifier(), $client, $authCodePayload->user_id ); } catch (LogicException $e) { throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e); } // Validate code challenge if ($this->enableCodeExchangeProof === true) { $codeVerifier = $this->getRequestParameter('code_verifier', $request, null); if ($codeVerifier === null) { throw OAuthServerException::invalidRequest('code_verifier'); } // Validate code_verifier according to RFC-7636 // @see: https://tools.ietf.org/html/rfc7636#section-4.1 if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) { throw OAuthServerException::invalidRequest( 'code_verifier', 'Code Verifier must follow the specifications of RFC-7636.' ); } switch ($authCodePayload->code_challenge_method) { case 'plain': if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) { throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.'); } break; case 'S256': if ( hash_equals( strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'), $authCodePayload->code_challenge ) === false ) { throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.'); } // @codeCoverageIgnoreStart break; default: throw OAuthServerException::serverError( sprintf( 'Unsupported code challenge method `%s`', $authCodePayload->code_challenge_method ) ); // @codeCoverageIgnoreEnd } } // Issue and persist new access token $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes); $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request)); $responseType->setAccessToken($accessToken); // Issue and persist new refresh token if given $refreshToken = $this->issueRefreshToken($accessToken); if ($refreshToken !== null) { $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request)); $responseType->setRefreshToken($refreshToken); } // Revoke used auth code $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id); return $responseType; }
php
{ "resource": "" }
q14665
AuthCodeGrant.validateAuthorizationCode
train
private function validateAuthorizationCode( $authCodePayload, ClientEntityInterface $client, ServerRequestInterface $request ) { if (time() > $authCodePayload->expire_time) { throw OAuthServerException::invalidRequest('code', 'Authorization code has expired'); } if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) { throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked'); } if ($authCodePayload->client_id !== $client->getIdentifier()) { throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client'); } // The redirect URI is required in this request $redirectUri = $this->getRequestParameter('redirect_uri', $request, null); if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) { throw OAuthServerException::invalidRequest('redirect_uri'); } if ($authCodePayload->redirect_uri !== $redirectUri) { throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI'); } }
php
{ "resource": "" }
q14666
AuthCodeGrant.getClientRedirectUri
train
private function getClientRedirectUri(AuthorizationRequest $authorizationRequest) { return \is_array($authorizationRequest->getClient()->getRedirectUri()) ? $authorizationRequest->getClient()->getRedirectUri()[0] : $authorizationRequest->getClient()->getRedirectUri(); }
php
{ "resource": "" }
q14667
CryptTrait.encrypt
train
protected function encrypt($unencryptedData) { try { if ($this->encryptionKey instanceof Key) { return Crypto::encrypt($unencryptedData, $this->encryptionKey); } return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey); } catch (Exception $e) { throw new LogicException($e->getMessage(), null, $e); } }
php
{ "resource": "" }
q14668
CryptTrait.decrypt
train
protected function decrypt($encryptedData) { try { if ($this->encryptionKey instanceof Key) { return Crypto::decrypt($encryptedData, $this->encryptionKey); } return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey); } catch (Exception $e) { throw new LogicException($e->getMessage(), null, $e); } }
php
{ "resource": "" }
q14669
OAuthServerException.getPayload
train
public function getPayload() { $payload = $this->payload; // The "message" property is deprecated and replaced by "error_description" // TODO: remove "message" property if (isset($payload['error_description']) && !isset($payload['message'])) { $payload['message'] = $payload['error_description']; } return $payload; }
php
{ "resource": "" }
q14670
OAuthServerException.invalidRequest
train
public static function invalidRequest($parameter, $hint = null, Throwable $previous = null) { $errorMessage = 'The request is missing a required parameter, includes an invalid parameter value, ' . 'includes a parameter more than once, or is otherwise malformed.'; $hint = ($hint === null) ? sprintf('Check the `%s` parameter', $parameter) : $hint; return new static($errorMessage, 3, 'invalid_request', 400, $hint, null, $previous); }
php
{ "resource": "" }
q14671
OAuthServerException.invalidScope
train
public static function invalidScope($scope, $redirectUri = null) { $errorMessage = 'The requested scope is invalid, unknown, or malformed'; if (empty($scope)) { $hint = 'Specify a scope in the request or set a default scope'; } else { $hint = sprintf( 'Check the `%s` scope', htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false) ); } return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri); }
php
{ "resource": "" }
q14672
OAuthServerException.accessDenied
train
public static function accessDenied($hint = null, $redirectUri = null, Throwable $previous = null) { return new static( 'The resource owner or authorization server denied the request.', 9, 'access_denied', 401, $hint, $redirectUri, $previous ); }
php
{ "resource": "" }
q14673
OAuthServerException.generateHttpResponse
train
public function generateHttpResponse(ResponseInterface $response, $useFragment = false, $jsonOptions = 0) { $headers = $this->getHttpHeaders(); $payload = $this->getPayload(); if ($this->redirectUri !== null) { if ($useFragment === true) { $this->redirectUri .= (strstr($this->redirectUri, '#') === false) ? '#' : '&'; } else { $this->redirectUri .= (strstr($this->redirectUri, '?') === false) ? '?' : '&'; } return $response->withStatus(302)->withHeader('Location', $this->redirectUri . http_build_query($payload)); } foreach ($headers as $header => $content) { $response = $response->withHeader($header, $content); } $response->getBody()->write(json_encode($payload, $jsonOptions)); return $response->withStatus($this->getHttpStatusCode()); }
php
{ "resource": "" }
q14674
OAuthServerException.getHttpHeaders
train
public function getHttpHeaders() { $headers = [ 'Content-type' => 'application/json', ]; // Add "WWW-Authenticate" header // // RFC 6749, section 5.2.: // "If the client attempted to authenticate via the 'Authorization' // request header field, the authorization server MUST // respond with an HTTP 401 (Unauthorized) status code and // include the "WWW-Authenticate" response header field // matching the authentication scheme used by the client. // @codeCoverageIgnoreStart if ($this->errorType === 'invalid_client' && array_key_exists('HTTP_AUTHORIZATION', $_SERVER) !== false) { $authScheme = strpos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer') === 0 ? 'Bearer' : 'Basic'; $headers['WWW-Authenticate'] = $authScheme . ' realm="OAuth"'; } // @codeCoverageIgnoreEnd return $headers; }
php
{ "resource": "" }
q14675
AbstractGrant.validateClient
train
protected function validateClient(ServerRequestInterface $request) { list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request); $clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser); if ($clientId === null) { throw OAuthServerException::invalidRequest('client_id'); } // If the client is confidential require the client secret $clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword); $client = $this->clientRepository->getClientEntity( $clientId, $this->getIdentifier(), $clientSecret, true ); if ($client instanceof ClientEntityInterface === false) { $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request)); throw OAuthServerException::invalidClient(); } $redirectUri = $this->getRequestParameter('redirect_uri', $request, null); if ($redirectUri !== null) { $this->validateRedirectUri($redirectUri, $client, $request); } return $client; }
php
{ "resource": "" }
q14676
AbstractGrant.validateRedirectUri
train
protected function validateRedirectUri( string $redirectUri, ClientEntityInterface $client, ServerRequestInterface $request ) { if (\is_string($client->getRedirectUri()) && (strcmp($client->getRedirectUri(), $redirectUri) !== 0) ) { $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request)); throw OAuthServerException::invalidClient(); } elseif (\is_array($client->getRedirectUri()) && \in_array($redirectUri, $client->getRedirectUri(), true) === false ) { $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request)); throw OAuthServerException::invalidClient(); } }
php
{ "resource": "" }
q14677
AbstractGrant.validateScopes
train
public function validateScopes($scopes, $redirectUri = null) { if (!\is_array($scopes)) { $scopes = $this->convertScopesQueryStringToArray($scopes); } $validScopes = []; foreach ($scopes as $scopeItem) { $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem); if ($scope instanceof ScopeEntityInterface === false) { throw OAuthServerException::invalidScope($scopeItem, $redirectUri); } $validScopes[] = $scope; } return $validScopes; }
php
{ "resource": "" }
q14678
AbstractGrant.convertScopesQueryStringToArray
train
private function convertScopesQueryStringToArray($scopes) { return array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) { return !empty($scope); }); }
php
{ "resource": "" }
q14679
AbstractGrant.getRequestParameter
train
protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null) { $requestParameters = (array) $request->getParsedBody(); return $requestParameters[$parameter] ?? $default; }
php
{ "resource": "" }
q14680
AbstractGrant.getQueryStringParameter
train
protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null) { return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default; }
php
{ "resource": "" }
q14681
AbstractGrant.getCookieParameter
train
protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null) { return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default; }
php
{ "resource": "" }
q14682
AbstractGrant.getServerParameter
train
protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null) { return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default; }
php
{ "resource": "" }
q14683
AbstractGrant.generateUniqueIdentifier
train
protected function generateUniqueIdentifier($length = 40) { try { return bin2hex(random_bytes($length)); // @codeCoverageIgnoreStart } catch (TypeError $e) { throw OAuthServerException::serverError('An unexpected error has occurred', $e); } catch (Error $e) { throw OAuthServerException::serverError('An unexpected error has occurred', $e); } catch (Exception $e) { // If you get this message, the CSPRNG failed hard. throw OAuthServerException::serverError('Could not generate a random string', $e); } // @codeCoverageIgnoreEnd }
php
{ "resource": "" }
q14684
AuthorizationServer.enableGrantType
train
public function enableGrantType(GrantTypeInterface $grantType, DateInterval $accessTokenTTL = null) { if ($accessTokenTTL instanceof DateInterval === false) { $accessTokenTTL = new DateInterval('PT1H'); } $grantType->setAccessTokenRepository($this->accessTokenRepository); $grantType->setClientRepository($this->clientRepository); $grantType->setScopeRepository($this->scopeRepository); $grantType->setDefaultScope($this->defaultScope); $grantType->setPrivateKey($this->privateKey); $grantType->setEmitter($this->getEmitter()); $grantType->setEncryptionKey($this->encryptionKey); $this->enabledGrantTypes[$grantType->getIdentifier()] = $grantType; $this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] = $accessTokenTTL; }
php
{ "resource": "" }
q14685
AuthorizationServer.validateAuthorizationRequest
train
public function validateAuthorizationRequest(ServerRequestInterface $request) { foreach ($this->enabledGrantTypes as $grantType) { if ($grantType->canRespondToAuthorizationRequest($request)) { return $grantType->validateAuthorizationRequest($request); } } throw OAuthServerException::unsupportedGrantType(); }
php
{ "resource": "" }
q14686
AuthorizationServer.completeAuthorizationRequest
train
public function completeAuthorizationRequest(AuthorizationRequest $authRequest, ResponseInterface $response) { return $this->enabledGrantTypes[$authRequest->getGrantTypeId()] ->completeAuthorizationRequest($authRequest) ->generateHttpResponse($response); }
php
{ "resource": "" }
q14687
AuthorizationServer.respondToAccessTokenRequest
train
public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response) { foreach ($this->enabledGrantTypes as $grantType) { if (!$grantType->canRespondToAccessTokenRequest($request)) { continue; } $tokenResponse = $grantType->respondToAccessTokenRequest( $request, $this->getResponseType(), $this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] ); if ($tokenResponse instanceof ResponseTypeInterface) { return $tokenResponse->generateHttpResponse($response); } } throw OAuthServerException::unsupportedGrantType(); }
php
{ "resource": "" }
q14688
LinkedInProvider.getBasicProfile
train
protected function getBasicProfile($token) { $url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))'; $response = $this->getHttpClient()->get($url, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, 'X-RestLi-Protocol-Version' => '2.0.0', ], ]); return (array) json_decode($response->getBody(), true); }
php
{ "resource": "" }
q14689
LinkedInProvider.getEmailAddress
train
protected function getEmailAddress($token) { $url = 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))'; $response = $this->getHttpClient()->get($url, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, 'X-RestLi-Protocol-Version' => '2.0.0', ], ]); return (array) Arr::get((array) json_decode($response->getBody(), true), 'elements.0.handle~'); }
php
{ "resource": "" }
q14690
AbstractUser.map
train
public function map(array $attributes) { foreach ($attributes as $key => $value) { $this->{$key} = $value; } return $this; }
php
{ "resource": "" }
q14691
AbstractProvider.userFromTokenAndSecret
train
public function userFromTokenAndSecret($token, $secret) { $tokenCredentials = new TokenCredentials(); $tokenCredentials->setIdentifier($token); $tokenCredentials->setSecret($secret); $user = $this->server->getUserDetails( $tokenCredentials, $this->shouldBypassCache($token, $secret) ); $instance = (new User)->setRaw($user->extra) ->setToken($tokenCredentials->getIdentifier(), $tokenCredentials->getSecret()); return $instance->map([ 'id' => $user->uid, 'nickname' => $user->nickname, 'name' => $user->name, 'email' => $user->email, 'avatar' => $user->imageUrl, ]); }
php
{ "resource": "" }
q14692
AbstractProvider.shouldBypassCache
train
protected function shouldBypassCache($token, $secret) { $newHash = sha1($token.'_'.$secret); if (! empty($this->userHash) && $newHash !== $this->userHash) { $this->userHash = $newHash; return true; } $this->userHash = $this->userHash ?: $newHash; return false; }
php
{ "resource": "" }
q14693
User.setToken
train
public function setToken($token, $tokenSecret) { $this->token = $token; $this->tokenSecret = $tokenSecret; return $this; }
php
{ "resource": "" }
q14694
SocialiteManager.createTwitterDriver
train
protected function createTwitterDriver() { $config = $this->app['config']['services.twitter']; return new TwitterProvider( $this->app['request'], new TwitterServer($this->formatConfig($config)) ); }
php
{ "resource": "" }
q14695
SocialiteManager.formatRedirectUrl
train
protected function formatRedirectUrl(array $config) { $redirect = value($config['redirect']); return Str::startsWith($redirect, '/') ? $this->app['url']->to($redirect) : $redirect; }
php
{ "resource": "" }
q14696
AbstractProvider.scopes
train
public function scopes($scopes) { $this->scopes = array_unique(array_merge($this->scopes, (array) $scopes)); return $this; }
php
{ "resource": "" }
q14697
BootstrapState.getValue
train
public function getValue( $key, $fallback = null ) { return array_key_exists( $key, $this->state ) ? $this->state[ $key ] : $fallback; }
php
{ "resource": "" }
q14698
FileCache.has
train
public function has( $key, $ttl = null ) { if ( ! $this->enabled ) { return false; } $filename = $this->filename( $key ); if ( ! file_exists( $filename ) ) { return false; } // use ttl param or global ttl if ( null === $ttl ) { $ttl = $this->ttl; } elseif ( $this->ttl > 0 ) { $ttl = min( (int) $ttl, $this->ttl ); } else { $ttl = (int) $ttl; } // if ( $ttl > 0 && ( filemtime( $filename ) + $ttl ) < time() ) { if ( $this->ttl > 0 && $ttl >= $this->ttl ) { unlink( $filename ); } return false; } return $filename; }
php
{ "resource": "" }
q14699
FileCache.read
train
public function read( $key, $ttl = null ) { $filename = $this->has( $key, $ttl ); if ( $filename ) { return file_get_contents( $filename ); } return false; }
php
{ "resource": "" }