idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
55,900
public function markAsRead ( $ userId ) { try { $ participant = $ this -> getParticipantFromUser ( $ userId ) ; $ participant -> last_read = new Carbon ; $ participant -> save ( ) ; } catch ( ModelNotFoundException $ e ) { } }
Mark a thread as read for a user
55,901
public function isUnread ( $ userId ) { try { $ participant = $ this -> getParticipantFromUser ( $ userId ) ; if ( $ this -> updated_at > $ participant -> last_read ) { return true ; } } catch ( ModelNotFoundException $ e ) { } return false ; }
See if the current thread is unread by the user
55,902
public function participantsString ( $ userId = null , $ columns = [ 'first_name' ] ) { $ selectString = $ this -> createSelectString ( $ columns ) ; $ participantNames = $ this -> getConnection ( ) -> table ( $ this -> getUsersTable ( ) ) -> join ( 'participants' , $ this -> getUsersTable ( ) . '.id' , '=' , 'participants.user_id' ) -> where ( 'participants.thread_id' , $ this -> id ) -> select ( $ this -> getConnection ( ) -> raw ( $ selectString ) ) ; if ( $ userId !== null ) { $ participantNames -> where ( $ this -> getUsersTable ( ) . '.id' , '!=' , $ userId ) ; } $ userNames = $ participantNames -> lists ( $ this -> getUsersTable ( ) . '.name' ) ; return implode ( ', ' , $ userNames ) ; }
Generates a string of participant information
55,903
private function getUsersTable ( ) { if ( $ this -> usersTable !== null ) { return $ this -> usersTable ; } $ userModel = Config :: get ( 'chat.user_model' ) ; return $ this -> usersTable = ( new $ userModel ) -> getTable ( ) ; }
Returns the users table name to use in manual queries
55,904
public function relativeDateFilter ( $ field , $ fromUnit = self :: RELATIVE_DATE_FILTER_UNIT_MINUTES , $ fromInterval , $ toUnit = self :: RELATIVE_DATE_FILTER_UNIT_MINUTES , $ toInterval = 0 , $ dateFormat = self :: RELATIVE_DATE_FILTER_DATEFORMAT , $ isNegative = false ) { $ parameters = array ( 'fromUnit' => $ fromUnit , 'fromInterval' => $ fromInterval , 'toUnit' => $ toUnit , 'toInterval' => $ toInterval , 'dateFormat' => $ dateFormat , 'field' => $ field ) ; $ this -> addFilter ( null , self :: RELATIVE_DATE_FILTER , $ isNegative , $ parameters ) ; return $ this ; }
Add a RelativeDateFilter on request
55,905
public function negativeRelativeDateFilter ( $ field , $ fromUnit = self :: RELATIVE_DATE_FILTER_UNIT_MINUTES , $ fromInterval , $ toUnit = self :: RELATIVE_DATE_FILTER_UNIT_MINUTES , $ toInterval = 0 , $ dateFormat = self :: RELATIVE_DATE_FILTER_DATEFORMAT , $ isNegative = false ) { return $ this -> relativeDateFilter ( $ field , $ fromUnit , $ fromInterval , $ toUnit , $ toInterval , $ dateFormat , true ) ; }
Add a negative RelativeDateFilter on request
55,906
public function geoFilter ( $ shape = self :: GEO_FILTER_SQUARED , $ unit = self :: GEO_FILTER_KILOMETERS , $ distance , $ isNegative = false ) { $ parameters = array ( 'shape' => $ shape , 'unit' => $ unit , 'distance' => $ distance ) ; $ this -> addFilter ( null , self :: GEO_FILTER , $ isNegative , $ parameters ) ; return $ this ; }
Add a GeoFilter on request
55,907
public function negativeGeoFilter ( $ shape = self :: GEO_FILTER_SQUARED , $ unit = self :: GEO_FILTER_KILOMETERS , $ distance ) { return $ this -> geoFilter ( null , $ shape , $ unit , $ distance , true ) ; }
Add a negative GeoFilter on request
55,908
public function returnedFields ( $ fields ) { if ( empty ( $ this -> data [ 'returnedFields' ] ) ) { $ this -> data [ 'returnedFields' ] = array ( ) ; } $ this -> data [ 'returnedFields' ] = array_unique ( array_merge ( $ this -> data [ 'returnedFields' ] , ( array ) $ fields ) ) ; return $ this ; }
Configure fields to return
55,909
static public function fetch ( $ tagID , $ locale , $ includeDrafts = false ) { $ fetchParams = array ( 'keyword_id' => $ tagID , 'locale' => $ locale ) ; if ( ! $ includeDrafts ) $ fetchParams [ 'status' ] = self :: STATUS_PUBLISHED ; return parent :: fetchObject ( self :: definition ( ) , null , $ fetchParams ) ; }
Returns eZTagsKeyword object for given tag ID and locale
55,910
static public function fetchByTagID ( $ tagID ) { $ tagKeywordList = parent :: fetchObjectList ( self :: definition ( ) , null , array ( 'keyword_id' => $ tagID ) ) ; if ( is_array ( $ tagKeywordList ) ) return $ tagKeywordList ; return array ( ) ; }
Returns eZTagsKeyword list for given tag ID
55,911
public function languageName ( ) { $ language = eZContentLanguage :: fetchByLocale ( $ this -> attribute ( 'locale' ) ) ; if ( $ language instanceof eZContentLanguage ) return array ( 'locale' => $ language -> attribute ( 'locale' ) , 'name' => $ language -> attribute ( 'name' ) ) ; return false ; }
Returns array with language name and locale for this instance
55,912
public function searchField ( $ field , $ mode = self :: SEARCH_MODE_PATTERN , $ boost = 1 , $ phraseBoost = 1 ) { if ( empty ( $ this -> data [ 'searchFields' ] ) ) { $ this -> data [ 'searchFields' ] = array ( ) ; } $ this -> data [ 'searchFields' ] [ ] = array ( 'field' => $ field , 'mode' => $ mode , 'boost' => $ boost , 'phraseBoost' => $ phraseBoost ) ; return $ this ; }
Add a field to search into
55,913
public function getFilenames ( array $ fileOrDirectoryNames , array $ filePatterns = [ ] , FinderObserver $ observer = null ) : array { $ finder = clone $ this -> finder ; $ finder -> files ( ) ; $ observer = $ observer ? : new CallbackFinderObserver ( function ( ) { } ) ; if ( count ( $ filePatterns ) > 0 ) { $ finder -> filter ( function ( SplFileInfo $ fileInfo ) use ( $ filePatterns ) { if ( $ fileInfo -> isDir ( ) ) { return true ; } foreach ( $ filePatterns as $ pattern ) { if ( fnmatch ( $ pattern , $ fileInfo -> getFilename ( ) ) ) { return true ; } } return false ; } ) ; } $ filenames = [ ] ; foreach ( $ fileOrDirectoryNames as $ fileOrDirectoryName ) { $ subFinder = clone $ finder ; $ resolvedFileOrDirectoryName = $ fileOrDirectoryName ; if ( $ fileOrDirectoryName { 0 } !== '/' && substr ( $ fileOrDirectoryName , 0 , 6 ) !== 'vfs://' ) { $ resolvedFileOrDirectoryName = realpath ( $ fileOrDirectoryName ) ; if ( $ resolvedFileOrDirectoryName === false ) { $ observer -> onEntryNotFound ( $ fileOrDirectoryName ) ; continue ; } } if ( file_exists ( $ resolvedFileOrDirectoryName ) === false ) { $ observer -> onEntryNotFound ( $ resolvedFileOrDirectoryName ) ; continue ; } $ fileInfo = $ this -> filesystem -> openFile ( $ resolvedFileOrDirectoryName ) ; if ( $ fileInfo -> isFile ( ) ) { $ filenames [ ] = $ resolvedFileOrDirectoryName ; } else { $ subFinder -> in ( $ resolvedFileOrDirectoryName ) ; foreach ( $ subFinder as $ subFileInfo ) { $ filenames [ ] = $ subFileInfo -> getPathname ( ) ; } } } return $ filenames ; }
Generates a list of file names from a list of file and directory names .
55,914
public function getField ( $ fieldName , $ returnFirstValueOnly = true ) { if ( ! empty ( $ this -> fields [ $ fieldName ] ) && count ( $ this -> fields [ $ fieldName ] > 0 ) ) { return ( $ returnFirstValueOnly ) ? $ this -> fields [ $ fieldName ] [ 0 ] : $ this -> fields [ $ fieldName ] ; } }
Return value of a field
55,915
public function getSnippet ( $ fieldName , $ returnFirstValueOnly = true ) { if ( ! empty ( $ this -> snippets [ $ fieldName ] ) && count ( $ this -> snippets [ $ fieldName ] > 0 ) ) { return ( $ returnFirstValueOnly ) ? $ this -> snippets [ $ fieldName ] [ 0 ] : $ this -> snippets [ $ fieldName ] ; } }
Return value of a snippet
55,916
public function versionAssociation ( $ field = null , $ options = [ ] ) { $ name = $ this -> _associationName ( $ field ) ; if ( ! $ this -> _table -> associations ( ) -> has ( $ name ) ) { $ model = $ this -> _config [ 'referenceName' ] ; $ options += [ 'className' => $ this -> _config [ 'versionTable' ] , 'foreignKey' => $ this -> _config [ 'foreignKey' ] , 'strategy' => 'subquery' , 'dependent' => true ] ; if ( $ field ) { $ options += [ 'conditions' => [ $ name . '.model' => $ model , $ name . '.field' => $ field , ] , 'propertyName' => $ field . '_version' ] ; } else { $ options += [ 'conditions' => [ $ name . '.model' => $ model ] , 'propertyName' => '__version' ] ; } $ this -> _table -> hasMany ( $ name , $ options ) ; } return $ this -> _table -> getAssociation ( $ name ) ; }
Returns association object for all versions or single field version .
55,917
public function beforeSave ( Event $ event , EntityInterface $ entity , ArrayObject $ options ) { $ association = $ this -> versionAssociation ( ) ; $ name = $ association -> getName ( ) ; $ newOptions = [ $ name => [ 'validate' => false ] ] ; $ options [ 'associated' ] = $ newOptions + $ options [ 'associated' ] ; $ fields = $ this -> _fields ( ) ; $ values = $ entity -> extract ( $ fields , $ this -> _config [ 'onlyDirty' ] ) ; $ primaryKey = ( array ) $ this -> _table -> getPrimaryKey ( ) ; $ versionField = $ this -> _config [ 'versionField' ] ; if ( isset ( $ options [ 'versionId' ] ) ) { $ versionId = $ options [ 'versionId' ] ; } else { $ versionId = $ this -> getVersionId ( $ entity ) + 1 ; } $ created = new DateTime ( ) ; $ new = [ ] ; $ entityClass = TableRegistry :: get ( $ this -> _config [ 'versionTable' ] ) -> getEntityClass ( ) ; foreach ( $ values as $ field => $ content ) { if ( in_array ( $ field , $ primaryKey ) || $ field == $ versionField ) { continue ; } $ converted = $ this -> _convertFieldsToType ( [ $ field => $ content ] , 'toDatabase' ) ; $ data = [ 'version_id' => $ versionId , 'model' => $ this -> _config [ 'referenceName' ] , 'field' => $ field , 'content' => $ converted [ $ field ] , 'created' => $ created , ] + $ this -> _extractForeignKey ( $ entity ) ; $ event = new Event ( 'Model.Version.beforeSave' , $ this , $ options ) ; $ userData = EventManager :: instance ( ) -> dispatch ( $ event ) ; if ( isset ( $ userData -> result ) && is_array ( $ userData -> result ) ) { $ data = array_merge ( $ data , $ userData -> result ) ; } $ new [ $ field ] = new $ entityClass ( $ data , [ 'useSetters' => false , 'markNew' => true ] ) ; } $ entity -> set ( $ association -> getProperty ( ) , $ new ) ; if ( ! empty ( $ versionField ) && in_array ( $ versionField , $ this -> _table -> getSchema ( ) -> columns ( ) ) ) { $ entity -> set ( $ this -> _config [ 'versionField' ] , $ versionId ) ; } }
Modifies the entity before it is saved so that versioned fields are persisted in the database too .
55,918
public function getVersionId ( EntityInterface $ entity ) { $ table = TableRegistry :: get ( $ this -> _config [ 'versionTable' ] ) ; $ preexistent = $ table -> find ( ) -> select ( [ 'version_id' ] ) -> where ( [ 'model' => $ this -> _config [ 'referenceName' ] ] + $ this -> _extractForeignKey ( $ entity ) ) -> order ( [ 'id desc' ] ) -> limit ( 1 ) -> enableHydration ( false ) -> toArray ( ) ; return Hash :: get ( $ preexistent , '0.version_id' , 0 ) ; }
return the last version id
55,919
public function findVersions ( Query $ query , array $ options ) { $ association = $ this -> versionAssociation ( ) ; $ name = $ association -> getName ( ) ; return $ query -> contain ( [ $ name => function ( Query $ q ) use ( $ name , $ options , $ query ) { if ( ! empty ( $ options [ 'primaryKey' ] ) ) { $ foreignKey = ( array ) $ this -> _config [ 'foreignKey' ] ; $ aliasedFK = [ ] ; foreach ( $ foreignKey as $ field ) { $ aliasedFK [ ] = "$name.$field" ; } $ conditions = array_combine ( $ aliasedFK , ( array ) $ options [ 'primaryKey' ] ) ; $ q -> where ( $ conditions ) ; } if ( ! empty ( $ options [ 'versionId' ] ) ) { $ q -> where ( [ "$name.version_id IN" => $ options [ 'versionId' ] ] ) ; } $ q -> where ( [ "$name.field IN" => $ this -> _fields ( ) ] ) ; return $ q ; } ] ) -> formatResults ( [ $ this , 'groupVersions' ] , $ query :: PREPEND ) ; }
Custom finder method used to retrieve all versions for the found records .
55,920
public function groupVersions ( $ results ) { $ property = $ this -> versionAssociation ( ) -> getProperty ( ) ; return $ results -> map ( function ( EntityInterface $ row ) use ( $ property ) { $ versionField = $ this -> _config [ 'versionField' ] ; $ versions = ( array ) $ row -> get ( $ property ) ; $ grouped = new Collection ( $ versions ) ; $ result = [ ] ; foreach ( $ grouped -> combine ( 'field' , 'content' , 'version_id' ) as $ versionId => $ keys ) { $ entityClass = $ this -> _table -> getEntityClass ( ) ; $ versionData = [ $ versionField => $ versionId ] ; $ keys = $ this -> _convertFieldsToType ( $ keys , 'toPHP' ) ; $ versionRow = $ grouped -> match ( [ 'version_id' => $ versionId ] ) -> first ( ) ; foreach ( $ this -> _config [ 'additionalVersionFields' ] as $ mappedField => $ field ) { if ( ! is_string ( $ mappedField ) ) { $ mappedField = 'version_' . $ field ; } $ versionData [ $ mappedField ] = $ versionRow -> get ( $ field ) ; } $ version = new $ entityClass ( $ keys + $ versionData , [ 'markNew' => false , 'useSetters' => false , 'markClean' => true ] ) ; $ result [ $ versionId ] = $ version ; } $ options = [ 'setter' => false , 'guard' => false ] ; $ row -> set ( '_versions' , $ result , $ options ) ; unset ( $ row [ $ property ] ) ; $ row -> clean ( ) ; return $ row ; } ) ; }
Modifies the results from a table find in order to merge full version records into each entity under the _versions key
55,921
public function getVersions ( EntityInterface $ entity ) { $ primaryKey = ( array ) $ this -> _table -> getPrimaryKey ( ) ; $ query = $ this -> _table -> find ( 'versions' ) ; $ pkValue = $ entity -> extract ( $ primaryKey ) ; $ conditions = [ ] ; foreach ( $ pkValue as $ key => $ value ) { $ field = current ( $ query -> aliasField ( $ key ) ) ; $ conditions [ $ field ] = $ value ; } $ entities = $ query -> where ( $ conditions ) -> all ( ) ; if ( empty ( $ entities ) ) { return new Collection ( [ ] ) ; } $ entity = $ entities -> first ( ) ; return $ entity -> get ( '_versions' ) ; }
Returns the versions of a specific entity .
55,922
protected function _fields ( ) { $ schema = $ this -> _table -> getSchema ( ) ; $ fields = $ schema -> columns ( ) ; if ( $ this -> _config [ 'fields' ] !== null ) { $ fields = array_intersect ( $ fields , ( array ) $ this -> _config [ 'fields' ] ) ; } return $ fields ; }
Returns an array of fields to be versioned .
55,923
protected function _extractForeignKey ( $ entity ) { $ foreignKey = ( array ) $ this -> _config [ 'foreignKey' ] ; $ primaryKey = ( array ) $ this -> _table -> getPrimaryKey ( ) ; $ pkValue = $ entity -> extract ( $ primaryKey ) ; return array_combine ( $ foreignKey , $ pkValue ) ; }
Returns an array with foreignKey value .
55,924
protected function _associationName ( $ field = null ) { $ alias = Inflector :: singularize ( $ this -> _table -> getAlias ( ) ) ; if ( $ field ) { $ field = Inflector :: camelize ( $ field ) ; } return $ alias . $ field . 'Version' ; }
Returns default version association name .
55,925
protected function _referenceName ( ) { $ table = $ this -> _table ; $ name = namespaceSplit ( get_class ( $ table ) ) ; $ name = substr ( end ( $ name ) , 0 , - 5 ) ; if ( empty ( $ name ) ) { $ name = $ table -> getTable ( ) ? : $ table -> getAlias ( ) ; $ name = Inflector :: camelize ( $ name ) ; } return $ name ; }
Returns reference name for identifying this model s records in version table .
55,926
protected function _convertFieldsToType ( array $ fields , $ direction ) { if ( ! in_array ( $ direction , [ 'toPHP' , 'toDatabase' ] ) ) { throw new InvalidArgumentException ( sprintf ( 'Cannot convert type, Cake\Database\Type::%s does not exist' , $ direction ) ) ; } $ driver = $ this -> _table -> getConnection ( ) -> getDriver ( ) ; foreach ( $ fields as $ field => $ content ) { $ column = $ this -> _table -> getSchema ( ) -> getColumn ( $ field ) ; $ type = Type :: build ( $ column [ 'type' ] ) ; $ fields [ $ field ] = $ type -> { $ direction } ( $ content , $ driver ) ; } return $ fields ; }
Converts fields to the appropriate type to be stored in the version and to be converted from the version record to the entity
55,927
public function indexed ( $ indexed ) { if ( $ indexed === true or $ indexed === false ) { $ this -> data [ 'indexed' ] = ( $ indexed ) ? 'YES' : 'NO' ; } else { $ this -> data [ 'indexed' ] = $ indexed ; } return $ this ; }
Tell whether this field must be indexed or not
55,928
public function stored ( $ stored ) { if ( $ stored === true or $ stored === false ) { $ this -> data [ 'stored' ] = ( $ stored ) ? 'YES' : 'NO' ; } else { $ this -> data [ 'stored' ] = $ stored ; } return $ this ; }
Tell whether this field must be stored or not
55,929
protected function generateMediaLinks ( MediaInterface $ media ) { $ media_type = $ this -> entityTypeManager -> getStorage ( 'media_type' ) -> load ( $ media -> bundle ( ) ) ; $ type_configuration = $ media_type -> get ( 'source_configuration' ) ; $ links = [ ] ; $ update_route_name = 'islandora.media_source_update' ; $ update_route_params = [ 'media' => $ media -> id ( ) ] ; if ( $ this -> accessManager -> checkNamedRoute ( $ update_route_name , $ update_route_params , $ this -> account ) ) { $ edit_media_url = Url :: fromRoute ( $ update_route_name , $ update_route_params ) -> setAbsolute ( ) -> toString ( ) ; $ links [ ] = "<$edit_media_url>; rel=\"edit-media\"" ; } if ( ! isset ( $ type_configuration [ 'source_field' ] ) ) { return $ links ; } $ source_field = $ type_configuration [ 'source_field' ] ; if ( empty ( $ source_field ) || ! $ media -> hasField ( $ source_field ) ) { return $ links ; } foreach ( $ media -> get ( $ source_field ) -> referencedEntities ( ) as $ referencedEntity ) { if ( $ referencedEntity -> access ( 'view' ) ) { $ file_url = $ referencedEntity -> url ( 'canonical' , [ 'absolute' => TRUE ] ) ; $ links [ ] = "<$file_url>; rel=\"describes\"; type=\"{$referencedEntity->getMimeType()}\"" ; } } return $ links ; }
Generates link headers for the described file and source update routes .
55,930
public function evaluateContexts ( array $ provided = [ ] ) { $ this -> activeContexts = [ ] ; foreach ( $ this -> getContexts ( ) as $ context ) { if ( $ this -> evaluateContextConditions ( $ context , $ provided ) && ! $ context -> disabled ( ) ) { $ this -> activeContexts [ $ context -> id ( ) ] = $ context ; } } $ this -> contextConditionsEvaluated = TRUE ; }
Evaluate all context conditions .
55,931
public function evaluateContextConditions ( ContextInterface $ context , array $ provided = [ ] ) { $ conditions = $ context -> getConditions ( ) ; $ this -> applyContexts ( $ conditions , $ provided ) ; $ logic = $ context -> requiresAllConditions ( ) ? 'and' : 'or' ; if ( ! count ( $ conditions ) ) { $ logic = 'and' ; } return $ this -> resolveConditions ( $ conditions , $ logic ) ; }
Evaluate a contexts conditions .
55,932
protected function applyContexts ( ConditionPluginCollection & $ conditions , array $ provided = [ ] ) { foreach ( $ conditions as $ condition ) { if ( $ condition instanceof ContextAwarePluginInterface ) { try { if ( empty ( $ provided ) ) { $ contexts = $ this -> contextRepository -> getRuntimeContexts ( array_values ( $ condition -> getContextMapping ( ) ) ) ; } else { $ contexts = $ provided ; } $ this -> contextHandler -> applyContextMapping ( $ condition , $ contexts ) ; } catch ( ContextException $ e ) { return FALSE ; } } } return TRUE ; }
Apply context to all the context aware conditions in the collection .
55,933
protected function getObject ( Response $ response , $ object_type ) { if ( $ object_type != 'node' && $ object_type != 'media' ) { return FALSE ; } if ( $ response -> headers -> get ( 'X-Drupal-Dynamic-Cache' ) == 'HIT' ) { return FALSE ; } if ( ! $ response -> isOk ( ) ) { return FALSE ; } $ route_object = $ this -> routeMatch -> getRouteObject ( ) ; if ( ! $ route_object ) { return FALSE ; } $ methods = $ route_object -> getMethods ( ) ; $ is_get = in_array ( 'GET' , $ methods ) ; $ is_head = in_array ( 'HEAD' , $ methods ) ; if ( ! ( $ is_get || $ is_head ) ) { return FALSE ; } $ route_contexts = $ route_object -> getOption ( 'parameters' ) ; if ( ! $ route_contexts ) { return FALSE ; } if ( ! isset ( $ route_contexts [ $ object_type ] ) ) { return FALSE ; } $ object = $ this -> routeMatch -> getParameter ( $ object_type ) ; if ( ! $ object ) { return FALSE ; } return $ object ; }
Get the Node | Media | File .
55,934
protected function generateEntityReferenceLinks ( EntityInterface $ entity ) { $ entity_type = $ entity -> getEntityType ( ) -> id ( ) ; $ bundle = $ entity -> bundle ( ) ; $ fields = $ this -> entityFieldManager -> getFieldDefinitions ( $ entity_type , $ bundle ) ; $ entity_reference_fields = array_filter ( $ fields , function ( $ field ) { return $ field -> getFieldStorageDefinition ( ) -> isBaseField ( ) == FALSE && $ field -> getType ( ) == "entity_reference" ; } ) ; $ links = [ ] ; foreach ( $ entity_reference_fields as $ field_name => $ field_definition ) { foreach ( $ entity -> get ( $ field_name ) -> referencedEntities ( ) as $ referencedEntity ) { if ( $ referencedEntity -> access ( 'view' ) ) { if ( $ referencedEntity -> getEntityTypeId ( ) == 'taxonomy_term' ) { $ rel = "tag" ; $ entity_url = $ referencedEntity -> url ( 'canonical' , [ 'absolute' => TRUE ] ) ; if ( $ referencedEntity -> hasField ( 'field_external_uri' ) ) { $ external_uri = $ referencedEntity -> get ( 'field_external_uri' ) -> getValue ( ) ; if ( ! empty ( $ external_uri ) && isset ( $ external_uri [ 0 ] [ 'uri' ] ) ) { $ entity_url = $ external_uri [ 0 ] [ 'uri' ] ; } } $ title = $ referencedEntity -> label ( ) ; } else { $ rel = "related" ; $ entity_url = $ referencedEntity -> url ( 'canonical' , [ 'absolute' => TRUE ] ) ; $ title = $ field_definition -> label ( ) ; } $ links [ ] = "<$entity_url>; rel=\"$rel\"; title=\"$title\"" ; } } } return $ links ; }
Generates link headers for each referenced entity .
55,935
protected function generateRestLinks ( EntityInterface $ entity ) { $ rest_resource_config_storage = $ this -> entityTypeManager -> getStorage ( 'rest_resource_config' ) ; $ entity_type = $ entity -> getEntityType ( ) -> id ( ) ; $ rest_resource_config = $ rest_resource_config_storage -> load ( "entity.$entity_type" ) ; $ current_format = $ this -> requestStack -> getCurrentRequest ( ) -> query -> get ( '_format' ) ; $ links = [ ] ; $ route_name = $ this -> routeMatch -> getRouteName ( ) ; if ( $ rest_resource_config ) { $ formats = $ rest_resource_config -> getFormats ( "GET" ) ; foreach ( $ formats as $ format ) { if ( $ format == $ current_format ) { continue ; } switch ( $ format ) { case 'json' : $ mime = 'application/json' ; break ; case 'jsonld' : $ mime = 'application/ld+json' ; break ; case 'hal_json' : $ mime = 'application/hal+json' ; break ; case 'xml' : $ mime = 'application/xml' ; break ; default : continue ; } $ meta_route_name = "rest.entity.$entity_type.GET" ; $ route_params = [ $ entity_type => $ entity -> id ( ) ] ; if ( ! $ this -> accessManager -> checkNamedRoute ( $ meta_route_name , $ route_params , $ this -> account ) ) { continue ; } $ meta_url = Url :: fromRoute ( $ meta_route_name , $ route_params ) -> setAbsolute ( ) -> toString ( ) ; $ links [ ] = "<$meta_url?_format=$format>; rel=\"alternate\"; type=\"$mime\"" ; } } return $ links ; }
Generates link headers for REST endpoints .
55,936
public function threadsWithNewMessages ( ) { $ threadsWithNewMessages = [ ] ; $ participants = Participant :: where ( 'user_id' , $ this -> id ) -> lists ( 'last_read' , 'thread_id' ) ; if ( getenv ( 'APP_ENV' ) == 'testing' || ! str_contains ( \ Illuminate \ Foundation \ Application :: VERSION , '5.0' ) ) { $ participants = $ participants -> all ( ) ; } if ( $ participants ) { $ threads = Thread :: whereIn ( 'id' , array_keys ( $ participants ) ) -> get ( ) ; foreach ( $ threads as $ thread ) { if ( $ thread -> updated_at > $ participants [ $ thread -> id ] ) { $ threadsWithNewMessages [ ] = $ thread -> id ; } } } return $ threadsWithNewMessages ; }
Returns all threads with new messages
55,937
private function buildFacetsArray ( $ facetsJson ) { foreach ( $ facetsJson as $ facetObj ) { $ terms = array ( ) ; foreach ( $ facetObj -> terms as $ termObj ) { $ terms [ $ termObj -> term ] = $ termObj -> count ; } $ this -> facets [ $ facetObj -> fieldName ] = $ terms ; } }
Build array of facets based on JSON results
55,938
public function validateUser ( CommandData $ commandData ) { $ userid = $ commandData -> input ( ) -> getOption ( 'userid' ) ; if ( $ userid ) { $ account = User :: load ( $ userid ) ; if ( ! $ account ) { throw new \ Exception ( "User ID does not match an existing user." ) ; } } }
Validate the provided userid .
55,939
public function preImport ( CommandData $ commandData ) { $ userid = $ commandData -> input ( ) -> getOption ( 'userid' ) ; if ( $ userid ) { $ account = User :: load ( $ userid ) ; $ accountSwitcher = \ Drupal :: service ( 'account_switcher' ) ; $ userSession = new UserSession ( [ 'uid' => $ account -> id ( ) , 'name' => $ account -> getUsername ( ) , 'roles' => $ account -> getRoles ( ) , ] ) ; $ accountSwitcher -> switchTo ( $ userSession ) ; $ this -> logger ( ) -> notice ( dt ( 'Now acting as user ID @id' , [ '@id' => \ Drupal :: currentUser ( ) -> id ( ) ] ) ) ; } }
Switch the active user account to perform the import .
55,940
public function postImport ( $ result , CommandData $ commandData ) { if ( $ commandData -> input ( ) -> getOption ( 'userid' ) ) { $ accountSwitcher = \ Drupal :: service ( 'account_switcher' ) ; $ this -> logger ( ) -> notice ( dt ( 'Switching back from user @uid.' , [ '@uid' => \ Drupal :: currentUser ( ) -> id ( ) ] ) ) ; $ accountSwitcher -> switchBack ( ) ; } }
Switch the user back once the migration is complete .
55,941
protected function getEntropyOffsets ( \ Imagick $ original , $ targetWidth , $ targetHeight ) { $ measureImage = clone ( $ original ) ; $ measureImage -> edgeimage ( 1 ) ; $ measureImage -> modulateImage ( 100 , 0 , 100 ) ; $ measureImage -> blackThresholdImage ( "#070707" ) ; return $ this -> getOffsetFromEntropy ( $ measureImage , $ targetWidth , $ targetHeight ) ; }
Get the topleftX and topleftY that will can be passed to a cropping method .
55,942
protected function getOffsetFromEntropy ( \ Imagick $ originalImage , $ targetWidth , $ targetHeight ) { $ image = clone $ originalImage ; $ image -> blurImage ( 3 , 2 ) ; $ size = $ image -> getImageGeometry ( ) ; $ originalWidth = $ size [ 'width' ] ; $ originalHeight = $ size [ 'height' ] ; $ leftX = $ this -> slice ( $ image , $ originalWidth , $ targetWidth , 'h' ) ; $ topY = $ this -> slice ( $ image , $ originalHeight , $ targetHeight , 'v' ) ; return array ( 'x' => $ leftX , 'y' => $ topY ) ; }
Get the offset of where the crop should start
55,943
protected function grayscaleEntropy ( \ Imagick $ image ) { $ histogram = $ image -> getImageHistogram ( ) ; return $ this -> getEntropy ( $ histogram , $ this -> area ( $ image ) ) ; }
Calculate the entropy for this image .
55,944
protected function colorEntropy ( \ Imagick $ image ) { $ histogram = $ image -> getImageHistogram ( ) ; $ newHistogram = array ( ) ; $ colors = count ( $ histogram ) ; for ( $ idx = 0 ; $ idx < $ colors ; $ idx ++ ) { $ colors = $ histogram [ $ idx ] -> getColor ( ) ; $ grey = $ this -> rgb2bw ( $ colors [ 'r' ] , $ colors [ 'g' ] , $ colors [ 'b' ] ) ; if ( ! isset ( $ newHistogram [ $ grey ] ) ) { $ newHistogram [ $ grey ] = $ histogram [ $ idx ] -> getColorCount ( ) ; } else { $ newHistogram [ $ grey ] += $ histogram [ $ idx ] -> getColorCount ( ) ; } } return $ this -> getEntropy ( $ newHistogram , $ this -> area ( $ image ) ) ; }
Find out the entropy for a color image
55,945
public static function createFromParseError ( ParseError $ parseError ) : self { return new self ( $ parseError -> getSourceLine ( ) , 0 , "Parse error: " . $ parseError -> getMessage ( ) , self :: SEVERITY_ERROR , get_class ( $ parseError ) ) ; }
Creates a new warning from a parse error .
55,946
public static function createFromTokenizerError ( TokenizerException $ tokenizerException ) : self { return new self ( $ tokenizerException -> getSourceLine ( ) , 0 , "Tokenization error: " . $ tokenizerException -> getMessage ( ) , self :: SEVERITY_ERROR , get_class ( $ tokenizerException ) ) ; }
Creates a new warning from a tokenizer error .
55,947
public function getConfig ( ) { $ config = [ ] ; foreach ( $ this -> providers as $ key => $ provider ) { $ config [ $ key ] = $ provider -> getConfig ( ) ; } return $ config ; }
Aggregates the config from the providers and returns a hash with the namespace as the key and the config as the value .
55,948
public function createCommand ( $ name ) { $ startTimestamp = time ( ) ; $ basePath = $ this -> getStashEntryPath ( $ name ) ; $ databaseDestination = $ basePath . '/database.sql' ; $ persistentDestination = $ basePath . '/persistent/' ; FileUtils :: createDirectoryRecursively ( $ basePath ) ; $ this -> checkConfiguration ( ) ; $ this -> addSecret ( $ this -> databaseConfiguration [ 'user' ] ) ; $ this -> addSecret ( $ this -> databaseConfiguration [ 'password' ] ) ; $ this -> renderHeadLine ( 'Write Manifest' ) ; $ presetName = $ this -> configurationService -> getCurrentPreset ( ) ; $ presetConfiguration = $ this -> configurationService -> getCurrentConfiguration ( ) ; $ cloneTimestamp = $ this -> configurationService -> getMostRecentCloneTimeStamp ( ) ; $ stashTimestamp = time ( ) ; $ this -> writeStashEntryManifest ( $ name , [ 'preset' => [ 'name' => $ presetName , 'configuration' => $ presetConfiguration ] , 'cloned_at' => $ cloneTimestamp , 'stashed_at' => $ stashTimestamp ] ) ; $ this -> renderHeadLine ( 'Backup Database' ) ; $ this -> executeLocalShellCommand ( 'mysqldump --single-transaction --add-drop-table --host="%s" --user="%s" --password="%s" %s > %s' , [ $ this -> databaseConfiguration [ 'host' ] , $ this -> databaseConfiguration [ 'user' ] , $ this -> databaseConfiguration [ 'password' ] , $ this -> databaseConfiguration [ 'dbname' ] , $ databaseDestination ] ) ; $ this -> renderHeadLine ( 'Backup Persistent Resources' ) ; $ this -> executeLocalShellCommand ( 'cp -al %s %s' , [ FLOW_PATH_ROOT . 'Data/Persistent' , $ persistentDestination ] ) ; $ endTimestamp = time ( ) ; $ duration = $ endTimestamp - $ startTimestamp ; $ this -> renderHeadLine ( 'Done' ) ; $ this -> renderLine ( 'Successfuly stashed %s in %s seconds' , [ $ name , $ duration ] ) ; }
Creates a new stash entry with the given name .
55,949
public function listCommand ( ) { $ head = [ 'Name' , 'Stashed At' , 'From Preset' , 'Cloned At' ] ; $ rows = [ ] ; $ basePath = sprintf ( FLOW_PATH_ROOT . 'Data/MagicWandStash' ) ; if ( ! is_dir ( $ basePath ) ) { $ this -> renderLine ( 'Stash is empty.' ) ; $ this -> quit ( 1 ) ; } $ baseDir = new \ DirectoryIterator ( $ basePath ) ; $ anyEntry = false ; foreach ( $ baseDir as $ entry ) { if ( ! in_array ( $ entry , [ '.' , '..' ] ) ) { $ stashEntryName = $ entry -> getFilename ( ) ; $ manifest = $ this -> readStashEntryManifest ( $ stashEntryName ) ? : [ ] ; $ rows [ ] = [ $ stashEntryName , $ manifest [ 'stashed_at' ] ? date ( 'Y-m-d H:i:s' , $ manifest [ 'stashed_at' ] ) : 'N/A' , isset ( $ manifest [ 'preset' ] [ 'name' ] ) ? $ manifest [ 'preset' ] [ 'name' ] : 'N/A' , $ manifest [ 'cloned_at' ] ? date ( 'Y-m-d H:i:s' , $ manifest [ 'cloned_at' ] ) : 'N/A' , ] ; $ anyEntry = true ; } } if ( ! $ anyEntry ) { $ this -> renderLine ( 'Stash is empty.' ) ; $ this -> quit ( 1 ) ; } $ this -> output -> outputTable ( $ rows , $ head ) ; }
Lists all entries
55,950
public function clearCommand ( ) { $ startTimestamp = time ( ) ; $ path = FLOW_PATH_ROOT . 'Data/MagicWandStash' ; FileUtils :: removeDirectoryRecursively ( $ path ) ; $ endTimestamp = time ( ) ; $ duration = $ endTimestamp - $ startTimestamp ; $ this -> renderHeadLine ( 'Done' ) ; $ this -> renderLine ( 'Cleanup successful in %s seconds' , [ $ duration ] ) ; }
Clear the whole stash
55,951
public function restoreCommand ( $ name , $ yes = false , $ keepDb = false ) { $ basePath = $ this -> getStashEntryPath ( $ name ) ; $ this -> restoreStashEntry ( $ basePath , $ name , $ yes , true , $ keepDb ) ; }
Restores stash entries
55,952
public function removeCommand ( $ name , $ yes = false ) { $ directory = FLOW_PATH_ROOT . 'Data/MagicWandStash/' . $ name ; if ( ! is_dir ( $ directory ) ) { $ this -> renderLine ( '<error>%s does not exist</error>' , [ $ name ] ) ; $ this -> quit ( 1 ) ; } if ( ! $ yes ) { $ this -> renderLine ( "Are you sure you want to do this? Type 'yes' to continue: " ) ; $ handle = fopen ( "php://stdin" , "r" ) ; $ line = fgets ( $ handle ) ; if ( trim ( $ line ) != 'yes' ) { $ this -> renderLine ( 'exit' ) ; $ this -> quit ( 1 ) ; } else { $ this -> renderLine ( ) ; $ this -> renderLine ( ) ; } } $ startTimestamp = time ( ) ; FileUtils :: removeDirectoryRecursively ( $ directory ) ; $ endTimestamp = time ( ) ; $ duration = $ endTimestamp - $ startTimestamp ; $ this -> renderHeadLine ( 'Done' ) ; $ this -> renderLine ( 'Cleanup removed stash %s in %s seconds' , [ $ name , $ duration ] ) ; }
Remove a named stash entry
55,953
public function goToContentWithPath ( $ path ) { $ this -> clickNavigationZone ( 'Content' ) ; $ this -> clickNavigationItem ( 'Content structure' ) ; $ this -> clickOnBrowsePath ( $ path ) ; $ this -> confirmSelection ( ) ; }
Opens a content in PlatformUi .
55,954
private function loadSonata ( ContainerBuilder $ container , Loader \ XmlFileLoader $ loader ) { $ bundles = $ container -> getParameter ( 'kernel.bundles' ) ; if ( ! isset ( $ bundles [ 'SonataDoctrineORMAdminBundle' ] ) ) { return ; } $ refl = new \ ReflectionMethod ( 'Sonata\\DoctrineORMAdminBundle\\Filter\\StringFilter' , 'filter' ) ; if ( method_exists ( $ refl , 'getReturnType' ) ) { if ( $ returnType = $ refl -> getReturnType ( ) ) { return ; } } $ loader -> load ( 'sonata.xml' ) ; }
Load the Sonata configuration if the versions is supported
55,955
protected function notify ( $ message , array $ params = [ ] , $ domain = null , $ status = Notification :: STATE_DONE ) { $ this -> notificationPool -> addNotification ( new TranslatableNotificationMessage ( [ 'message' => $ message , 'translationParams' => $ params , 'domain' => $ domain , ] ) , $ status ) ; }
Registers a translatable notification .
55,956
protected function notifyError ( $ message , array $ params = [ ] , $ domain = null ) { $ this -> notify ( $ message , $ params , $ domain , Notification :: STATE_ERROR ) ; }
Registers a translatable error notification .
55,957
private function foundErrors ( ) { $ page = $ this -> getSession ( ) -> getPage ( ) ; $ element = $ page -> find ( 'css' , '.is-error' ) ; return $ element != null ; }
Helper function returns true if errors are found in the page false otherwise .
55,958
public function onMessage ( Mf4phpMessage $ message ) : void { Preconditions :: checkArgument ( $ message instanceof ObjectMessage , "Message must be an instance of ObjectMessage" ) ; $ object = $ message -> getObject ( ) ; if ( $ object instanceof MessageWrapper ) { $ object = $ object -> getMessage ( ) ; } parent :: dispatch ( $ object , self :: emptyCallback ( ) ) ; }
Forward incoming message to handlers .
55,959
protected function findObjectMessageFactory ( $ message ) : ObjectMessageFactory { $ messageClass = get_class ( $ message ) ; foreach ( $ this -> objectMessageFactories as $ class => $ factory ) { if ( $ class === $ messageClass ) { return $ factory ; } } return $ this -> defaultObjectMessageFactory ; }
Finds the appropriate message factory for the given message .
55,960
protected function dispatch ( $ message , MessageCallback $ callback ) : void { $ sendable = $ message ; if ( ! ( $ message instanceof Serializable ) ) { $ sendable = new MessageWrapper ( $ message ) ; } $ mf4phpMessage = $ this -> findObjectMessageFactory ( $ message ) -> createMessage ( $ sendable ) ; $ this -> dispatcher -> send ( $ this -> queue , $ mf4phpMessage ) ; }
Send the message to the message queue .
55,961
public function listCommand ( ) { if ( $ this -> clonePresets ) { foreach ( $ this -> clonePresets as $ presetName => $ presetConfiguration ) { $ this -> renderHeadLine ( $ presetName ) ; $ presetConfigurationAsYaml = Yaml :: dump ( $ presetConfiguration ) ; $ lines = explode ( PHP_EOL , $ presetConfigurationAsYaml ) ; foreach ( $ lines as $ line ) { $ this -> renderLine ( $ line ) ; } } } }
Show the list of predefined clone configurations
55,962
public function defaultCommand ( bool $ yes = false , bool $ keepDb = false ) : void { if ( $ this -> defaultPreset === null || $ this -> defaultPreset === '' ) { $ this -> renderLine ( 'There is no default preset configured!' ) ; $ this -> quit ( 1 ) ; } $ this -> presetCommand ( $ this -> defaultPreset , $ yes , $ keepDb ) ; }
Clones the default preset
55,963
public function push ( $ class , $ args = [ ] , $ retry = true , $ queue = self :: QUEUE ) { $ jobId = $ this -> idGenerator -> generate ( ) ; $ this -> atomicPush ( $ jobId , $ class , $ args , $ queue , $ retry ) ; return $ jobId ; }
Push a job
55,964
public function schedule ( $ doAt , $ class , $ args = [ ] , $ retry = true , $ queue = self :: QUEUE ) { $ jobId = $ this -> idGenerator -> generate ( ) ; $ this -> atomicPush ( $ jobId , $ class , $ args , $ queue , $ retry , $ doAt ) ; return $ jobId ; }
Schedule a job at a certain time
55,965
public function pushBulk ( $ jobs = [ ] , $ queue = self :: QUEUE ) { $ ids = [ ] ; foreach ( $ jobs as $ job ) { if ( ! isset ( $ job [ 'class' ] ) ) { throw new Exception ( 'pushBulk: each job needs a job class' ) ; } if ( ! isset ( $ job [ 'args' ] ) || ! is_array ( $ job [ 'args' ] ) ) { throw new Exception ( 'pushBulk: each job needs args' ) ; } $ retry = isset ( $ job [ 'retry' ] ) ? $ job [ 'retry' ] : true ; $ doAt = isset ( $ job [ 'at' ] ) ? $ job [ 'at' ] : null ; $ jobId = $ this -> idGenerator -> generate ( ) ; array_push ( $ ids , $ jobId ) ; $ this -> atomicPush ( $ jobId , $ job [ 'class' ] , $ job [ 'args' ] , $ queue , $ retry , $ doAt ) ; } return $ ids ; }
Push multiple jobs to queue
55,966
private function atomicPush ( $ jobId , $ class , $ args = [ ] , $ queue = self :: QUEUE , $ retry = true , $ doAt = null ) { if ( array_values ( $ args ) !== $ args ) { throw new Exception ( 'Associative arrays in job args are not allowed' ) ; } if ( ! is_null ( $ doAt ) && ! is_float ( $ doAt ) && is_string ( $ doAt ) ) { throw new Exception ( 'at argument needs to be in a unix epoch format. Use microtime(true).' ) ; } $ job = $ this -> serializer -> serialize ( $ jobId , $ class , $ args , $ retry , $ queue ) ; if ( $ doAt === null ) { $ this -> redis -> sadd ( $ this -> name ( 'queues' ) , $ queue ) ; $ this -> redis -> lpush ( $ this -> name ( 'queue' , $ queue ) , $ job ) ; } else { $ this -> redis -> zadd ( $ this -> name ( 'schedule' ) , $ doAt , $ job ) ; } }
Push job to redis
55,967
public function wrapTemplateAction ( $ module ) { if ( $ this -> getModuleSetting ( $ module , 'type' ) !== 'template' ) { throw new BadRequestHttpException ( $ module . ' is not declared as a template' ) ; } $ path = $ this -> getModuleSetting ( $ module , 'path' ) ; $ response = new Response ( ) ; return $ this -> render ( 'eZPlatformUIBundle:Template:wraptemplate.js.twig' , [ 'path' => $ path , 'module' => $ module , 'templateCode' => file_get_contents ( $ path ) , ] , $ response ) ; }
Wraps the template file content in a YUI module . The generated module also registers the template under the same name of the module .
55,968
final public function loadFromHistory ( Iterator $ events ) : void { $ bus = self :: createInnerEventBus ( $ this ) ; foreach ( $ events as $ event ) { $ this -> handleEventInAggregate ( $ event , $ bus ) ; } }
Useful in case of Event Sourcing .
55,969
final protected function apply ( DomainEvent $ event ) : void { $ this -> handleEventInAggregate ( $ event ) ; parent :: raise ( $ event ) ; }
Fire a domain event from a handler method .
55,970
protected function defineCss ( NodeBuilder $ saNode ) { $ saNode -> arrayNode ( 'css' ) -> children ( ) -> arrayNode ( 'files' ) -> prototype ( 'scalar' ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) ; }
Defines the expected configuration for the CSS .
55,971
protected function defineJavaScript ( NodeBuilder $ saNode ) { $ saNode -> arrayNode ( 'javascript' ) -> children ( ) -> arrayNode ( 'files' ) -> prototype ( 'scalar' ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) ; }
Defines the expected configuration for the JavaScript .
55,972
protected function defineYui ( NodeBuilder $ saNode ) { $ saNode -> arrayNode ( 'yui' ) -> children ( ) -> enumNode ( 'filter' ) -> values ( [ 'raw' , 'min' , 'debug' ] ) -> info ( "Filter to apply to module urls. This filter will modify the default path for all modules.\nPossible values are 'raw', 'min' or 'debug''" ) -> end ( ) -> booleanNode ( 'combine' ) -> defaultTrue ( ) -> info ( 'If true, YUI combo loader will be used.' ) -> end ( ) -> arrayNode ( 'modules' ) -> useAttributeAsKey ( 'yui_module_name' ) -> normalizeKeys ( false ) -> prototype ( 'array' ) -> info ( 'YUI module definitions' ) -> children ( ) -> scalarNode ( 'path' ) -> info ( "Path to the module's JS file, relative to web/ directory." ) -> example ( 'bundles/acmedemo/js/my_yui_module.js' ) -> end ( ) -> arrayNode ( 'requires' ) -> info ( "Module's dependencies. Use modules' name to reference them." ) -> example ( [ 'ez-capi' , 'parallel' ] ) -> prototype ( 'scalar' ) -> end ( ) -> end ( ) -> arrayNode ( 'dependencyOf' ) -> info ( "Reverse dependencies.\nWhen loading modules referenced here, current module will be considered as a dependency." ) -> example ( [ 'ez-capi' , 'parallel' ] ) -> prototype ( 'scalar' ) -> end ( ) -> end ( ) -> enumNode ( 'type' ) -> values ( [ 'js' , 'template' ] ) -> defaultValue ( 'js' ) -> info ( "Type of module, either 'js' or 'template'" ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) ; }
Defines the expected configuration for the YUI modules .
55,973
private function hasJoin ( ProxyQueryInterface $ queryBuilder , $ alias ) { $ joins = $ queryBuilder -> getDQLPart ( 'join' ) ; if ( ! isset ( $ joins [ $ alias ] ) ) { return false ; } foreach ( $ joins [ $ alias ] as $ join ) { if ( 'trans' === $ join -> getAlias ( ) ) { return true ; } } return false ; }
Does the query builder have a translation join
55,974
function it_should_be_unique ( ) { $ ids = [ ] ; $ iterations = 100 ; for ( $ i = 0 ; $ i < $ iterations ; $ i ++ ) { $ ids [ ] = $ this -> getWrappedObject ( ) -> generate ( ) ; } return ( count ( array_values ( $ ids ) ) === $ iterations ) ; }
Naive way of testing uniqueness I know
55,975
public function load ( AggregateId $ aggregateId ) : AggregateRoot { $ aggregateRootClass = ObjectClass :: forName ( $ aggregateId -> aggregateClass ( ) ) ; $ aggregate = null ; $ stateHash = null ; if ( $ this -> eventStore instanceof SnapshotEventStore ) { $ aggregate = $ this -> eventStore -> loadSnapshot ( $ aggregateId ) ; $ stateHash = $ aggregate === null ? null : $ aggregate -> stateHash ( ) ; } $ events = $ this -> eventStore -> getEventsFor ( $ aggregateId , $ stateHash ) ; if ( $ aggregate === null ) { Preconditions :: checkArgument ( $ events -> valid ( ) , 'Aggregate with ID [%s] does not exist' , $ aggregateId ) ; $ aggregate = $ aggregateRootClass -> newInstanceWithoutConstructor ( ) ; } $ aggregateRootClass -> cast ( $ aggregate ) ; $ aggregate -> loadFromHistory ( $ events ) ; return $ aggregate ; }
Initializes the stored aggregate with its events persisted in event store .
55,976
public function build ( ContainerBuilder $ container ) { parent :: build ( $ container ) ; $ container -> addCompilerPass ( new ApplicationConfigProviderPass ( ) ) ; $ container -> addCompilerPass ( new TranslationDomainsExtensionsPass ( ) ) ; $ container -> addCompilerPass ( new ValueObjectVisitorPass ( ) ) ; }
Builds the bundle . It is only ever called once when the cache is empty . This method can be overridden to register compilation passes other extensions ...
55,977
public function disableValidation ( $ once = false ) { $ this -> skipValidation = ( $ once ) ? Observer :: SKIP_ONCE : Observer :: SKIP_ALWAYS ; return $ this ; }
Disable validation for this instance .
55,978
public function getValidator ( ) { if ( ! $ this -> validator ) { $ this -> validator = static :: $ validatorFactory -> make ( [ ] , static :: getCreateRules ( ) , static :: getValidationMessages ( ) , static :: getValidationAttributes ( ) ) ; } return $ this -> validator ; }
Get the validator instance .
55,979
protected static function gatherRules ( ) { $ keys = static :: getValidatedFields ( ) ; $ result = array_fill_keys ( $ keys , [ ] ) ; foreach ( $ keys as $ key ) { foreach ( static :: getRulesGroups ( ) as $ groupName ) { $ group = static :: getRulesGroup ( $ groupName ) ; if ( isset ( $ group [ $ key ] ) ) { $ rules = is_array ( $ group [ $ key ] ) ? $ group [ $ key ] : explode ( '|' , $ group [ $ key ] ) ; foreach ( $ rules as & $ rule ) { if ( $ rule === 'unique' ) { $ table = ( new static ) -> getTable ( ) ; $ rule .= ":{$table}" ; } } unset ( $ rule ) ; $ result [ $ key ] = array_unique ( array_merge ( $ result [ $ key ] , $ rules ) ) ; } } } return $ result ; }
Gather all the rules for the model and store it for easier use .
55,980
public static function getValidatedFields ( ) { $ fields = [ ] ; foreach ( static :: getRulesGroups ( ) as $ groupName ) { $ fields = array_merge ( $ fields , array_keys ( static :: getRulesGroup ( $ groupName ) ) ) ; } return array_values ( array_unique ( $ fields ) ) ; }
Get array of attributes that have validation rules defined .
55,981
protected static function getRulesGroups ( ) { $ groups = [ ] ; foreach ( get_class_vars ( get_called_class ( ) ) as $ property => $ val ) { if ( preg_match ( '/^.*rules$/i' , $ property ) ) { $ groups [ ] = $ property ; } } return $ groups ; }
Get all the rules groups defined on this model .
55,982
public function spin ( $ lambda ) { $ e = null ; $ timeLimit = time ( ) + self :: SPIN_TIMEOUT ; do { try { $ return = $ lambda ( $ this ) ; if ( $ return ) { return $ return ; } } catch ( \ Exception $ e ) { } $ this -> sleep ( ) ; } while ( $ timeLimit > time ( ) ) ; throw new \ Exception ( 'Timeout while retreaving DOM element' . ( $ e !== null ? '. Last exception: ' . $ e -> getMessage ( ) : '' ) ) ; }
Behat spin function Execute a provided function and return it s result if valid if an exception is thrown or the result is false wait and retry until a max timeout is reached .
55,983
public function findWithWait ( $ selector , $ baseElement = null , $ checkVisibility = true ) { if ( ! $ baseElement ) { $ baseElement = $ this -> getSession ( ) -> getPage ( ) ; } $ element = $ this -> spin ( function ( ) use ( $ selector , $ baseElement , $ checkVisibility ) { $ element = $ baseElement -> find ( 'css' , $ selector ) ; if ( ! $ element ) { throw new \ Exception ( "Element with selector '$selector' was not found" ) ; } $ element -> getValue ( ) ; if ( $ checkVisibility && ! $ element -> isVisible ( ) ) { throw new \ Exception ( "Element with selector '$selector' is not visible" ) ; } return $ element ; } ) ; return $ element ; }
Adpted Mink find function combined with a spin function to find one element that might still be loading .
55,984
public function getElementByText ( $ text , $ selector , $ textSelector = null , $ baseElement = null ) { if ( $ baseElement == null ) { $ baseElement = $ this -> getSession ( ) -> getPage ( ) ; } $ elements = $ this -> findAllWithWait ( $ selector , $ baseElement ) ; foreach ( $ elements as $ element ) { if ( $ textSelector != null ) { try { $ elementText = $ this -> findWithWait ( $ textSelector , $ element ) -> getText ( ) ; } catch ( \ Exception $ e ) { continue ; } } else { $ elementText = $ element -> getText ( ) ; } if ( $ elementText == $ text ) { return $ element ; } } return false ; }
Finds an HTML element by class and the text value and returns it .
55,985
public function clickElementByText ( $ text , $ selector , $ textSelector = null , $ baseElement = null ) { $ element = $ this -> getElementByText ( $ text , $ selector , $ textSelector , $ baseElement ) ; if ( $ element && $ element -> isVisible ( ) ) { $ element -> click ( ) ; } elseif ( $ element ) { throw new \ Exception ( "Can't click '$text' element: not visible" ) ; } else { throw new \ Exception ( "Can't click '$text' element: not Found" ) ; } }
Finds an HTML element by class and the text value and clicks it .
55,986
protected function openFinderExplorerNode ( $ text , $ parentNode ) { $ this -> waitWhileLoading ( '.ez-ud-finder-explorerlevel-loading' ) ; $ parentNode = $ this -> findWithWait ( '.ez-view-universaldiscoveryfinderexplorerlevelview:last-child' , $ parentNode ) ; $ element = $ this -> getElementByText ( $ text , '.ez-explorer-level-list-item' , '.ez-explorer-level-item' , $ parentNode ) ; if ( ! $ element ) { throw new \ Exception ( "The browser node '$text' was not found" ) ; } $ element -> click ( ) ; }
Clicks a content browser node based on the root of the browser or a given node .
55,987
public function openFinderExplorerPath ( $ path , $ node ) { $ path = explode ( '/' , $ path ) ; foreach ( $ path as $ nodeName ) { $ this -> openFinderExplorerNode ( $ nodeName , $ node ) ; } }
Explores the content browser expanding it .
55,988
public function clickOnBrowsePath ( $ path ) { $ this -> clickDiscoveryBar ( 'Content browse' ) ; $ this -> waitWhileLoading ( '.is-universaldiscovery-hidden' ) ; $ node = $ this -> findWithWait ( '.ez-view-universaldiscoveryview' ) ; $ node = $ this -> findWithWait ( '.ez-view-universaldiscoveryfinderview .ez-ud-finder-explorerlevel' , $ node ) ; $ this -> openFinderExplorerPath ( $ path , $ node ) ; }
Explores the UDW expanding it and click on the desired element .
55,989
public function dontSeeBrowsePath ( $ path ) { $ found = true ; try { $ this -> clickOnBrowsePath ( $ path ) ; } catch ( \ Exception $ e ) { $ found = false ; } if ( $ found ) { throw new \ Exception ( "Browse path '$path' was found" ) ; } return true ; }
Explores the UDW to find the desired element .
55,990
protected function closeConfirmBox ( ) { try { $ elem = $ this -> getSession ( ) -> getPage ( ) -> find ( 'css' , '.ez-view-confirmboxview' ) ; if ( $ elem && $ elem -> isVisible ( ) ) { $ elem -> find ( 'css' , '.ez-confirmbox-close-icon' ) -> click ( ) ; $ this -> sleep ( ) ; } } catch ( \ Exception $ e ) { } }
Close the Confirm modal dialog if it is visible .
55,991
protected function closeEditView ( ) { try { $ elem = $ this -> getSession ( ) -> getPage ( ) -> find ( 'css' , '.ez-main-content' ) ; if ( $ elem && $ elem -> isVisible ( ) ) { $ elem -> find ( 'css' , '.ez-view-close' ) -> click ( ) ; $ this -> waitWhileLoading ( ) ; } } catch ( \ Exception $ e ) { } }
Close the Edit view if it is open .
55,992
protected function attachFile ( $ fileName , $ selector ) { if ( $ this -> getMinkParameter ( 'files_path' ) ) { $ fullPath = rtrim ( realpath ( $ this -> getMinkParameter ( 'files_path' ) ) , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . $ fileName ; if ( is_file ( $ fullPath ) ) { $ fileInput = 'input[type="file"]' . $ selector ; $ field = $ this -> getSession ( ) -> getPage ( ) -> find ( 'css' , $ fileInput ) ; if ( null === $ field ) { throw new Exception ( "File input $selector is not found" ) ; } $ field -> attachFile ( $ fullPath ) ; } } else { throw new Exception ( "File $fileName is not found at the given location: $fullPath" ) ; } }
Attaches a file to a input field on the HTML .
55,993
public static function create ( array $ properties , Direction $ direction = null ) : Sort { if ( $ direction === null ) { $ direction = Direction :: $ ASC ; } $ orders = [ ] ; foreach ( $ properties as $ property ) { $ orders [ ] = new Order ( $ direction , $ property ) ; } return new self ( $ orders ) ; }
Factory method to order by several properties with the same direction .
55,994
public function andSort ( Sort $ sort = null ) : Sort { if ( $ sort === null ) { return $ this ; } $ orders = $ this -> orders ; foreach ( $ sort as $ order ) { $ orders [ ] = $ order ; } return new Sort ( $ orders ) ; }
Does not modifies the object itself will return a new instance instead .
55,995
public function getOrderFor ( string $ property ) : ? Order { foreach ( $ this as $ order ) { if ( $ order -> getProperty ( ) == $ property ) { return $ order ; } } return null ; }
Returns the direction defined to the given property .
55,996
private function loadFile ( $ file , $ ext ) { $ filename = $ this -> fixFilename ( $ file , $ ext ) ; if ( ! is_readable ( $ filename ) ) { throw new NotFoundException ( 'file' , $ file ) ; } return file_get_contents ( $ filename ) ; }
Reads file from disk .
55,997
public function userInfo ( string $ username ) : Lastfm { $ this -> query = array_merge ( $ this -> query , [ 'method' => 'user.getInfo' , 'user' => $ username , ] ) ; $ this -> pluck = 'user' ; return $ this ; }
Get an array with user information .
55,998
public function userTopAlbums ( string $ username ) : Lastfm { $ this -> query = array_merge ( $ this -> query , [ 'method' => 'user.getTopAlbums' , 'user' => $ username , ] ) ; $ this -> pluck = 'topalbums.album' ; return $ this ; }
Get an array of top albums .
55,999
public function userTopArtists ( string $ username ) : Lastfm { $ this -> query = array_merge ( $ this -> query , [ 'method' => 'user.getTopArtists' , 'user' => $ username , ] ) ; $ this -> pluck = 'topartists.artist' ; return $ this ; }
Get an array of top artists .