idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
1,200
|
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 ; }
|
Walks down a SimpleCaseExpression AST node and generates the corresponding SQL .
|
1,201
|
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 ) ; }
|
Walks down an ArithmeticPrimary that represents an AST node thereby generating the appropriate SQL .
|
1,202
|
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 ) ) ; }
|
Resolves a magic method call to the proper existent method at EntityRepository .
|
1,203
|
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 ; } }
|
Sets the strategy for automatically generating proxy classes .
|
1,204
|
public function newDefaultAnnotationDriver ( array $ paths = [ ] ) : AnnotationDriver { AnnotationRegistry :: registerFile ( __DIR__ . '/Annotation/DoctrineAnnotations.php' ) ; $ reader = new CachedReader ( new AnnotationReader ( ) , new ArrayCache ( ) ) ; return new AnnotationDriver ( $ reader , $ paths ) ; }
|
Adds a new default annotation driver with a correctly configured annotation reader .
|
1,205
|
public function addCustomStringFunction ( string $ functionName , $ classNameOrFactory ) : void { $ this -> customStringFunctions [ strtolower ( $ functionName ) ] = $ classNameOrFactory ; }
|
Registers a custom DQL function that produces a string value . Such a function can then be used in any DQL statement in any place where string functions are allowed .
|
1,206
|
public function setCustomStringFunctions ( array $ functions ) : void { foreach ( $ functions as $ name => $ className ) { $ this -> addCustomStringFunction ( $ name , $ className ) ; } }
|
Sets a map of custom DQL string functions .
|
1,207
|
public function setCustomNumericFunctions ( array $ functions ) : void { foreach ( $ functions as $ name => $ className ) { $ this -> addCustomNumericFunction ( $ name , $ className ) ; } }
|
Sets a map of custom DQL numeric functions .
|
1,208
|
public function addCustomHydrationMode ( string $ modeName , string $ hydratorClassName ) : void { $ this -> customHydrationModes [ $ modeName ] = $ hydratorClassName ; }
|
Adds a custom hydration mode .
|
1,209
|
public function addFilter ( string $ filterName , string $ filterClassName ) : void { $ this -> filters [ $ filterName ] = $ filterClassName ; }
|
Adds a filter to the list of possible filters .
|
1,210
|
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 ; }
|
Creates a configuration with a xml metadata driver .
|
1,211
|
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 ; }
|
Injects the Doctrine Object Manager .
|
1,212
|
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 ; }
|
Sets a persistent fields value .
|
1,213
|
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 } ; }
|
Gets a persistent field value .
|
1,214
|
private function completeOwningSide ( AssociationMetadata $ property , $ targetObject ) { 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 ) ; }
|
If this is an inverse side association completes the owning side .
|
1,215
|
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 ; }
|
Adds an object to a collection .
|
1,216
|
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 ) ; }
|
Initializes Doctrine Metadata for this class .
|
1,217
|
public function addEntityResult ( $ class , $ alias , $ resultAlias = null ) { $ this -> aliasMap [ $ alias ] = $ class ; $ this -> entityMappings [ $ alias ] = $ resultAlias ; if ( $ resultAlias !== null ) { $ this -> isMixed = true ; } return $ this ; }
|
Adds an entity result to this ResultSetMapping .
|
1,218
|
public function setDiscriminatorColumn ( $ alias , $ discrColumn ) { $ this -> discriminatorColumns [ $ alias ] = $ discrColumn ; $ this -> columnOwnerMap [ $ discrColumn ] = $ alias ; return $ this ; }
|
Sets a discriminator column for an entity result or joined entity result . The discriminator column will be used to determine the concrete class name to instantiate .
|
1,219
|
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 ; } return $ this ; }
|
Sets a field to use for indexing an entity result or joined entity result .
|
1,220
|
public function addFieldResult ( $ alias , $ columnName , $ fieldName , $ declaringClass = null ) { $ this -> fieldMappings [ $ columnName ] = $ fieldName ; $ this -> columnOwnerMap [ $ columnName ] = $ alias ; $ this -> declaringClasses [ $ columnName ] = $ declaringClass ? : $ this -> aliasMap [ $ alias ] ; if ( ! $ this -> isMixed && $ this -> scalarMappings ) { $ this -> isMixed = true ; } return $ this ; }
|
Adds a field to the result that belongs to an entity or joined entity .
|
1,221
|
public function addJoinedEntityResult ( $ class , $ alias , $ parentAlias , $ relation ) { $ this -> aliasMap [ $ alias ] = $ class ; $ this -> parentAliasMap [ $ alias ] = $ parentAlias ; $ this -> relationMap [ $ alias ] = $ relation ; return $ this ; }
|
Adds a joined entity result .
|
1,222
|
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 ( ) ) ; $ 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 ) ; $ 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 ) ; $ deleteSQLTemplate = sprintf ( 'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)' , $ idColumnNameList , $ idColumnNameList , $ tempTable ) ; $ 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 ) ; } $ statement = $ this -> platform -> getDropTemporaryTableSQL ( $ tempTable ) ; $ this -> conn -> executeUpdate ( $ statement ) ; return $ numDeleted ; }
|
Delete Class Table Inheritance entities . A temporary table is needed to keep IDs to be deleted in both parent and child class tables .
|
1,223
|
public function count ( ) { if ( $ this -> isInitialized ( ) ) { return $ this -> collection -> count ( ) ; } if ( $ this -> count !== null ) { return $ this -> count ; } return $ this -> count = $ this -> entityPersister -> count ( $ this -> criteria ) ; }
|
Do an efficient count on the collection
|
1,224
|
public function contains ( $ element ) { if ( $ this -> isInitialized ( ) ) { return $ this -> collection -> contains ( $ element ) ; } return $ this -> entityPersister -> exists ( $ element , $ this -> criteria ) ; }
|
Do an optimized search of an element
|
1,225
|
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 ) ; }
|
Checks if inheritance if supported .
|
1,226
|
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 ) ; $ 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 ] ; }
|
Processes query parameter mappings .
|
1,227
|
public function iterate ( $ parameters = null , $ hydrationMode = self :: HYDRATE_OBJECT ) { $ this -> setHint ( self :: HINT_INTERNAL_ITERATION , true ) ; return parent :: iterate ( $ parameters , $ hydrationMode ) ; }
|
Executes the query and returns an IterableResult that can be used to incrementally iterated over the result .
|
1,228
|
public function getLockMode ( ) { $ lockMode = $ this -> getHint ( self :: HINT_LOCK_MODE ) ; if ( $ lockMode === false ) { return null ; } return $ lockMode ; }
|
Get the current lock mode for this query .
|
1,229
|
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 ; } }
|
Sets tables manually instead of relying on the reverse engineering capabilities of SchemaManager .
|
1,230
|
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 ) { if ( $ index -> isPrimary ( ) ) { continue ; } $ tableMetadata -> addIndex ( [ 'name' => $ index -> getName ( ) , 'columns' => $ index -> getColumns ( ) , 'unique' => $ index -> isUnique ( ) , 'options' => $ index -> getOptions ( ) , 'flags' => $ index -> getFlags ( ) , ] ) ; } $ metadata -> setTable ( $ tableMetadata ) ; }
|
Build table from a class metadata .
|
1,231
|
private function getFieldNameForColumn ( $ tableName , $ columnName , $ fk = false ) { if ( isset ( $ this -> fieldNamesForColumns [ $ tableName ] , $ this -> fieldNamesForColumns [ $ tableName ] [ $ columnName ] ) ) { return $ this -> fieldNamesForColumns [ $ tableName ] [ $ columnName ] ; } $ columnName = strtolower ( $ columnName ) ; if ( $ fk ) { $ columnName = str_replace ( '_id' , '' , $ columnName ) ; } return Inflector :: camelize ( $ columnName ) ; }
|
Return the mapped field name for a column if it exists . Otherwise return camelized version .
|
1,232
|
public function generate ( ClassMetadataDefinition $ definition ) : string { $ metadata = $ this -> mappingDriver -> loadMetadataForClass ( $ definition -> entityClassName , $ definition -> parentClassMetadata ) ; return $ this -> metadataExporter -> export ( $ metadata ) ; }
|
Generates class metadata code .
|
1,233
|
private function computeScheduleInsertsChangeSets ( ) { foreach ( $ this -> entityInsertions as $ entity ) { $ class = $ this -> em -> getClassMetadata ( get_class ( $ entity ) ) ; $ this -> computeChangeSet ( $ class , $ entity ) ; } }
|
Computes the changesets of all entities scheduled for insertion .
|
1,234
|
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 = [ ] ; }
|
Executes any extra updates that have been scheduled .
|
1,235
|
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 ) ; } } }
|
Executes all entity updates for entities of the specified type .
|
1,236
|
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 ) ; } }
|
Schedules an entity for insertion into the database . If the entity already has an identifier it will be added to the identity map .
|
1,237
|
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 ; } }
|
Schedules an entity for being updated .
|
1,238
|
public function isEntityScheduled ( $ entity ) { $ oid = spl_object_id ( $ entity ) ; return isset ( $ this -> entityInsertions [ $ oid ] ) || isset ( $ this -> entityUpdates [ $ oid ] ) || isset ( $ this -> entityDeletions [ $ oid ] ) ; }
|
Checks whether an entity is scheduled for insertion update or deletion .
|
1,239
|
private function performCallbackOnCachedPersister ( callable $ callback ) { if ( ! $ this -> hasCache ) { return ; } foreach ( array_merge ( $ this -> entityPersisters , $ this -> collectionPersisters ) as $ persister ) { if ( $ persister instanceof CachedPersister ) { $ callback ( $ persister ) ; } } }
|
Performs an action after the transaction .
|
1,240
|
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 ; }
|
Parse the given Table as TableMetadata
|
1,241
|
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 ) ; }
|
Generates a string of currently query
|
1,242
|
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 ) ; }
|
Called if a required option was not found but is required
|
1,243
|
public function match ( $ token ) { $ lookaheadType = $ this -> lexer -> lookahead [ 'type' ] ; if ( $ lookaheadType === $ token ) { $ this -> lexer -> moveNext ( ) ; return ; } if ( $ token < Lexer :: T_IDENTIFIER ) { $ this -> syntaxError ( $ this -> lexer -> getLiteral ( $ token ) ) ; } if ( $ token > Lexer :: T_IDENTIFIER ) { $ this -> syntaxError ( $ this -> lexer -> getLiteral ( $ token ) ) ; } if ( $ token === Lexer :: T_IDENTIFIER && $ lookaheadType < Lexer :: T_IDENTIFIER ) { $ this -> syntaxError ( $ this -> lexer -> getLiteral ( $ token ) ) ; } $ this -> lexer -> moveNext ( ) ; }
|
Attempts to match the given token with the current lookahead token .
|
1,244
|
public function free ( $ deep = false , $ position = 0 ) { $ this -> lexer -> resetPosition ( $ position ) ; if ( $ deep ) { $ this -> lexer -> resetPeek ( ) ; } $ this -> lexer -> token = null ; $ this -> lexer -> lookahead = null ; }
|
Frees this parser enabling it to be reused .
|
1,245
|
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 : } $ token = $ this -> lexer -> peek ( ) ; } if ( $ resetPeek ) { $ this -> lexer -> resetPeek ( ) ; } return $ token ; }
|
Peeks beyond the matched closing parenthesis and returns the first token after that one .
|
1,246
|
private function isMathOperator ( $ token ) { return in_array ( $ token [ 'type' ] , [ Lexer :: T_PLUS , Lexer :: T_MINUS , Lexer :: T_DIVIDE , Lexer :: T_MULTIPLY ] , true ) ; }
|
Checks if the given token indicates a mathematical operator .
|
1,247
|
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 ; }
|
AliasIdentificationVariable = identifier
|
1,248
|
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 ) ; }
|
Validates an AbstractSchemaName making sure the class exists .
|
1,249
|
public function handle ( $ request , Closure $ next ) { if ( $ this -> cors -> isPreflightRequest ( $ request ) ) { return $ this -> cors -> handlePreflightRequest ( $ request ) ; } return $ next ( $ request ) ; }
|
Handle an incoming Preflight request .
|
1,250
|
public function respondToAccessTokenRequest ( ServerRequestInterface $ request , ResponseTypeInterface $ responseType , DateInterval $ accessTokenTTL ) { $ 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 ) ; } if ( $ this -> enableCodeExchangeProof === true ) { $ codeVerifier = $ this -> getRequestParameter ( 'code_verifier' , $ request , null ) ; if ( $ codeVerifier === null ) { throw OAuthServerException :: invalidRequest ( 'code_verifier' ) ; } 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`.' ) ; } break ; default : throw OAuthServerException :: serverError ( sprintf ( 'Unsupported code challenge method `%s`' , $ authCodePayload -> code_challenge_method ) ) ; } } $ accessToken = $ this -> issueAccessToken ( $ accessTokenTTL , $ client , $ authCodePayload -> user_id , $ scopes ) ; $ this -> getEmitter ( ) -> emit ( new RequestEvent ( RequestEvent :: ACCESS_TOKEN_ISSUED , $ request ) ) ; $ responseType -> setAccessToken ( $ accessToken ) ; $ refreshToken = $ this -> issueRefreshToken ( $ accessToken ) ; if ( $ refreshToken !== null ) { $ this -> getEmitter ( ) -> emit ( new RequestEvent ( RequestEvent :: REFRESH_TOKEN_ISSUED , $ request ) ) ; $ responseType -> setRefreshToken ( $ refreshToken ) ; } $ this -> authCodeRepository -> revokeAuthCode ( $ authCodePayload -> auth_code_id ) ; return $ responseType ; }
|
Respond to an access token request .
|
1,251
|
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' ) ; } $ 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' ) ; } }
|
Validate the authorization code .
|
1,252
|
private function getClientRedirectUri ( AuthorizationRequest $ authorizationRequest ) { return \ is_array ( $ authorizationRequest -> getClient ( ) -> getRedirectUri ( ) ) ? $ authorizationRequest -> getClient ( ) -> getRedirectUri ( ) [ 0 ] : $ authorizationRequest -> getClient ( ) -> getRedirectUri ( ) ; }
|
Get the client redirect URI if not set in the request .
|
1,253
|
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 ) ; } }
|
Encrypt data with encryptionKey .
|
1,254
|
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 ) ; } }
|
Decrypt data with encryptionKey .
|
1,255
|
public function getPayload ( ) { $ payload = $ this -> payload ; if ( isset ( $ payload [ 'error_description' ] ) && ! isset ( $ payload [ 'message' ] ) ) { $ payload [ 'message' ] = $ payload [ 'error_description' ] ; } return $ payload ; }
|
Returns the current payload .
|
1,256
|
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 ) ; }
|
Invalid request error .
|
1,257
|
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 ) ; }
|
Invalid scope error .
|
1,258
|
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 ) ; }
|
Access denied .
|
1,259
|
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 ( ) ) ; }
|
Generate a HTTP response .
|
1,260
|
public function getHttpHeaders ( ) { $ headers = [ 'Content-type' => 'application/json' , ] ; 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"' ; } return $ headers ; }
|
Get all headers that have to be send with the error response .
|
1,261
|
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' ) ; } $ 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 ; }
|
Validate the client .
|
1,262
|
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 ( ) ; } }
|
Validate redirectUri from the request . If a redirect URI is provided ensure it matches what is pre - registered
|
1,263
|
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 ; }
|
Validate scopes in the request .
|
1,264
|
private function convertScopesQueryStringToArray ( $ scopes ) { return array_filter ( explode ( self :: SCOPE_DELIMITER_STRING , trim ( $ scopes ) ) , function ( $ scope ) { return ! empty ( $ scope ) ; } ) ; }
|
Converts a scopes query string to an array to easily iterate for validation .
|
1,265
|
protected function getRequestParameter ( $ parameter , ServerRequestInterface $ request , $ default = null ) { $ requestParameters = ( array ) $ request -> getParsedBody ( ) ; return $ requestParameters [ $ parameter ] ?? $ default ; }
|
Retrieve request parameter .
|
1,266
|
protected function getQueryStringParameter ( $ parameter , ServerRequestInterface $ request , $ default = null ) { return isset ( $ request -> getQueryParams ( ) [ $ parameter ] ) ? $ request -> getQueryParams ( ) [ $ parameter ] : $ default ; }
|
Retrieve query string parameter .
|
1,267
|
protected function getCookieParameter ( $ parameter , ServerRequestInterface $ request , $ default = null ) { return isset ( $ request -> getCookieParams ( ) [ $ parameter ] ) ? $ request -> getCookieParams ( ) [ $ parameter ] : $ default ; }
|
Retrieve cookie parameter .
|
1,268
|
protected function getServerParameter ( $ parameter , ServerRequestInterface $ request , $ default = null ) { return isset ( $ request -> getServerParams ( ) [ $ parameter ] ) ? $ request -> getServerParams ( ) [ $ parameter ] : $ default ; }
|
Retrieve server parameter .
|
1,269
|
protected function generateUniqueIdentifier ( $ length = 40 ) { try { return bin2hex ( random_bytes ( $ length ) ) ; } 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 ) { throw OAuthServerException :: serverError ( 'Could not generate a random string' , $ e ) ; } }
|
Generate a new unique identifier .
|
1,270
|
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 ; }
|
Enable a grant type on the server .
|
1,271
|
public function validateAuthorizationRequest ( ServerRequestInterface $ request ) { foreach ( $ this -> enabledGrantTypes as $ grantType ) { if ( $ grantType -> canRespondToAuthorizationRequest ( $ request ) ) { return $ grantType -> validateAuthorizationRequest ( $ request ) ; } } throw OAuthServerException :: unsupportedGrantType ( ) ; }
|
Validate an authorization request
|
1,272
|
public function completeAuthorizationRequest ( AuthorizationRequest $ authRequest , ResponseInterface $ response ) { return $ this -> enabledGrantTypes [ $ authRequest -> getGrantTypeId ( ) ] -> completeAuthorizationRequest ( $ authRequest ) -> generateHttpResponse ( $ response ) ; }
|
Complete an authorization request
|
1,273
|
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 ( ) ; }
|
Return an access token response .
|
1,274
|
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 ) ; }
|
Get the basic profile fields for the user .
|
1,275
|
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~' ) ; }
|
Get the email address for the user .
|
1,276
|
public function map ( array $ attributes ) { foreach ( $ attributes as $ key => $ value ) { $ this -> { $ key } = $ value ; } return $ this ; }
|
Map the given array onto the user s properties .
|
1,277
|
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 , ] ) ; }
|
Get a Social User instance from a known access token and secret .
|
1,278
|
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 ; }
|
Determine if the user information cache should be bypassed .
|
1,279
|
public function setToken ( $ token , $ tokenSecret ) { $ this -> token = $ token ; $ this -> tokenSecret = $ tokenSecret ; return $ this ; }
|
Set the token on the user .
|
1,280
|
protected function createTwitterDriver ( ) { $ config = $ this -> app [ 'config' ] [ 'services.twitter' ] ; return new TwitterProvider ( $ this -> app [ 'request' ] , new TwitterServer ( $ this -> formatConfig ( $ config ) ) ) ; }
|
Create an instance of the specified driver .
|
1,281
|
protected function formatRedirectUrl ( array $ config ) { $ redirect = value ( $ config [ 'redirect' ] ) ; return Str :: startsWith ( $ redirect , '/' ) ? $ this -> app [ 'url' ] -> to ( $ redirect ) : $ redirect ; }
|
Format the callback URL resolving a relative URI if needed .
|
1,282
|
public function scopes ( $ scopes ) { $ this -> scopes = array_unique ( array_merge ( $ this -> scopes , ( array ) $ scopes ) ) ; return $ this ; }
|
Merge the scopes of the requested access .
|
1,283
|
public function getValue ( $ key , $ fallback = null ) { return array_key_exists ( $ key , $ this -> state ) ? $ this -> state [ $ key ] : $ fallback ; }
|
Get the state value for a given key .
|
1,284
|
public function has ( $ key , $ ttl = null ) { if ( ! $ this -> enabled ) { return false ; } $ filename = $ this -> filename ( $ key ) ; if ( ! file_exists ( $ filename ) ) { return false ; } 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 ; }
|
Check if a file is in cache and return its filename
|
1,285
|
public function read ( $ key , $ ttl = null ) { $ filename = $ this -> has ( $ key , $ ttl ) ; if ( $ filename ) { return file_get_contents ( $ filename ) ; } return false ; }
|
Read from cache file
|
1,286
|
public function remove ( $ key ) { if ( ! $ this -> enabled ) { return false ; } $ filename = $ this -> filename ( $ key ) ; if ( file_exists ( $ filename ) ) { return unlink ( $ filename ) ; } return false ; }
|
Remove file from cache
|
1,287
|
public function clean ( ) { if ( ! $ this -> enabled ) { return false ; } $ ttl = $ this -> ttl ; $ max_size = $ this -> max_size ; if ( $ ttl > 0 ) { try { $ expire = new \ DateTime ( ) ; } catch ( \ Exception $ e ) { \ WP_CLI :: error ( $ e -> getMessage ( ) ) ; } $ expire -> modify ( '-' . $ ttl . ' seconds' ) ; $ finder = $ this -> get_finder ( ) -> date ( 'until ' . $ expire -> format ( 'Y-m-d H:i:s' ) ) ; foreach ( $ finder as $ file ) { unlink ( $ file -> getRealPath ( ) ) ; } } if ( $ max_size > 0 ) { $ files = array_reverse ( iterator_to_array ( $ this -> get_finder ( ) -> sortByAccessedTime ( ) -> getIterator ( ) ) ) ; $ total = 0 ; foreach ( $ files as $ file ) { if ( ( $ total + $ file -> getSize ( ) ) <= $ max_size ) { $ total += $ file -> getSize ( ) ; } else { unlink ( $ file -> getRealPath ( ) ) ; } } } return true ; }
|
Clean cache based on time to live and max size
|
1,288
|
public function clear ( ) { if ( ! $ this -> enabled ) { return false ; } $ finder = $ this -> get_finder ( ) ; foreach ( $ finder as $ file ) { unlink ( $ file -> getRealPath ( ) ) ; } return true ; }
|
Remove all cached files .
|
1,289
|
public function prune ( ) { if ( ! $ this -> enabled ) { return false ; } $ finder = $ this -> get_finder ( ) -> sortByName ( ) ; $ files_to_delete = array ( ) ; foreach ( $ finder as $ file ) { $ pieces = explode ( '-' , $ file -> getBasename ( $ file -> getExtension ( ) ) ) ; $ timestamp = end ( $ pieces ) ; if ( ! is_numeric ( $ timestamp ) ) { continue ; } $ basename_without_timestamp = str_replace ( '-' . $ timestamp , '' , $ file -> getBasename ( ) ) ; if ( isset ( $ files_to_delete [ $ basename_without_timestamp ] ) ) { unlink ( $ files_to_delete [ $ basename_without_timestamp ] ) ; } $ files_to_delete [ $ basename_without_timestamp ] = $ file -> getRealPath ( ) ; } return true ; }
|
Remove all cached files except for the newest version of one .
|
1,290
|
protected function ensure_dir_exists ( $ dir ) { if ( ! is_dir ( $ dir ) ) { if ( preg_match ( '{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}' , $ dir ) ) { return false ; } if ( ! @ mkdir ( $ dir , 0777 , true ) ) { $ error = error_get_last ( ) ; \ WP_CLI :: warning ( sprintf ( "Failed to create directory '%s': %s." , $ dir , $ error [ 'message' ] ) ) ; return false ; } } return true ; }
|
Ensure directory exists
|
1,291
|
protected function prepare_write ( $ key ) { if ( ! $ this -> enabled ) { return false ; } $ filename = $ this -> filename ( $ key ) ; if ( ! $ this -> ensure_dir_exists ( dirname ( $ filename ) ) ) { return false ; } return $ filename ; }
|
Prepare cache write
|
1,292
|
protected function validate_key ( $ key ) { $ url_parts = Utils \ parse_url ( $ key , - 1 , false ) ; if ( ! empty ( $ url_parts [ 'scheme' ] ) ) { $ parts = array ( 'misc' ) ; $ parts [ ] = $ url_parts [ 'scheme' ] . '-' . $ url_parts [ 'host' ] . ( empty ( $ url_parts [ 'port' ] ) ? '' : '-' . $ url_parts [ 'port' ] ) ; $ parts [ ] = substr ( $ url_parts [ 'path' ] , 1 ) . ( empty ( $ url_parts [ 'query' ] ) ? '' : '-' . $ url_parts [ 'query' ] ) ; } else { $ key = str_replace ( '\\' , '/' , $ key ) ; $ parts = explode ( '/' , ltrim ( $ key ) ) ; } $ parts = preg_replace ( "#[^{$this->whitelist}]#i" , '-' , $ parts ) ; return implode ( '/' , $ parts ) ; }
|
Validate cache key
|
1,293
|
protected function write ( $ handle , $ str ) { switch ( $ handle ) { case STDOUT : $ this -> stdout .= $ str ; break ; case STDERR : $ this -> stderr .= $ str ; break ; } }
|
Write a string to a resource .
|
1,294
|
public static function ucwords ( $ string , $ delimiters = " \n\t\r\0\x0B-" ) { return preg_replace_callback ( '/[^' . preg_quote ( $ delimiters , '/' ) . ']+/' , function ( $ matches ) { return ucfirst ( $ matches [ 0 ] ) ; } , $ string ) ; }
|
Uppercases words with configurable delimeters between words .
|
1,295
|
public static function pluralize ( $ word ) { if ( isset ( self :: $ cache [ 'pluralize' ] [ $ word ] ) ) { return self :: $ cache [ 'pluralize' ] [ $ word ] ; } if ( ! isset ( self :: $ plural [ 'merged' ] [ 'irregular' ] ) ) { self :: $ plural [ 'merged' ] [ 'irregular' ] = self :: $ plural [ 'irregular' ] ; } if ( ! isset ( self :: $ plural [ 'merged' ] [ 'uninflected' ] ) ) { self :: $ plural [ 'merged' ] [ 'uninflected' ] = array_merge ( self :: $ plural [ 'uninflected' ] , self :: $ uninflected ) ; } if ( ! isset ( self :: $ plural [ 'cacheUninflected' ] ) || ! isset ( self :: $ plural [ 'cacheIrregular' ] ) ) { self :: $ plural [ 'cacheUninflected' ] = '(?:' . implode ( '|' , self :: $ plural [ 'merged' ] [ 'uninflected' ] ) . ')' ; self :: $ plural [ 'cacheIrregular' ] = '(?:' . implode ( '|' , array_keys ( self :: $ plural [ 'merged' ] [ 'irregular' ] ) ) . ')' ; } if ( preg_match ( '/(.*)\\b(' . self :: $ plural [ 'cacheIrregular' ] . ')$/i' , $ word , $ regs ) ) { self :: $ cache [ 'pluralize' ] [ $ word ] = $ regs [ 1 ] . substr ( $ word , 0 , 1 ) . substr ( self :: $ plural [ 'merged' ] [ 'irregular' ] [ strtolower ( $ regs [ 2 ] ) ] , 1 ) ; return self :: $ cache [ 'pluralize' ] [ $ word ] ; } if ( preg_match ( '/^(' . self :: $ plural [ 'cacheUninflected' ] . ')$/i' , $ word , $ regs ) ) { self :: $ cache [ 'pluralize' ] [ $ word ] = $ word ; return $ word ; } foreach ( self :: $ plural [ 'rules' ] as $ rule => $ replacement ) { if ( preg_match ( $ rule , $ word ) ) { self :: $ cache [ 'pluralize' ] [ $ word ] = preg_replace ( $ rule , $ replacement , $ word ) ; return self :: $ cache [ 'pluralize' ] [ $ word ] ; } } }
|
Returns a word in plural form .
|
1,296
|
public function enough_positionals ( $ args ) { $ positional = $ this -> query_spec ( array ( 'type' => 'positional' , 'optional' => false , ) ) ; return count ( $ args ) >= count ( $ positional ) ; }
|
Check whether there are enough positional arguments .
|
1,297
|
public function unknown_positionals ( $ args ) { $ positional_repeating = $ this -> query_spec ( array ( 'type' => 'positional' , 'repeating' => true , ) ) ; if ( ! empty ( $ positional_repeating ) ) { return array ( ) ; } $ positional = $ this -> query_spec ( array ( 'type' => 'positional' , 'repeating' => false , ) ) ; return array_slice ( $ args , count ( $ positional ) ) ; }
|
Check for any unknown positionals .
|
1,298
|
public function validate_assoc ( $ assoc_args ) { $ assoc_spec = $ this -> query_spec ( array ( 'type' => 'assoc' , ) ) ; $ errors = array ( 'fatal' => array ( ) , 'warning' => array ( ) , ) ; $ to_unset = array ( ) ; foreach ( $ assoc_spec as $ param ) { $ key = $ param [ 'name' ] ; if ( ! isset ( $ assoc_args [ $ key ] ) ) { if ( ! $ param [ 'optional' ] ) { $ errors [ 'fatal' ] [ $ key ] = "missing --$key parameter" ; } } else { if ( true === $ assoc_args [ $ key ] && ! $ param [ 'value' ] [ 'optional' ] ) { $ error_type = ( ! $ param [ 'optional' ] ) ? 'fatal' : 'warning' ; $ errors [ $ error_type ] [ $ key ] = "--$key parameter needs a value" ; $ to_unset [ ] = $ key ; } } } return array ( $ errors , $ to_unset ) ; }
|
Check that all required keys are present and that they have values .
|
1,299
|
public function unknown_assoc ( $ assoc_args ) { $ generic = $ this -> query_spec ( array ( 'type' => 'generic' , ) ) ; if ( count ( $ generic ) ) { return array ( ) ; } $ known_assoc = array ( ) ; foreach ( $ this -> spec as $ param ) { if ( in_array ( $ param [ 'type' ] , array ( 'assoc' , 'flag' ) , true ) ) { $ known_assoc [ ] = $ param [ 'name' ] ; } } return array_diff ( array_keys ( $ assoc_args ) , $ known_assoc ) ; }
|
Check whether there are unknown parameters supplied .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.