idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
50,100
|
public static function convertToArray ( $ mixed ) { if ( is_callable ( $ mixed ) ) { $ callable = $ mixed ; $ mixed = new self ( ) ; call_user_func ( $ callable , $ mixed ) ; } if ( $ mixed instanceof ArrayableInterface && $ mixed instanceof self ) { $ mixed = $ mixed -> toArray ( ) ; } elseif ( ! is_array ( $ mixed ) ) { throw new Exception ( sprintf ( 'Mixed must be instance of "\Sokil\Mongo\Expression", array or callable that accepts "\Sokil\Mongo\Expression", "%s" given' , gettype ( $ mixed ) === "object" ? get_class ( $ mixed ) : gettype ( $ mixed ) ) ) ; } return $ mixed ; }
|
Transform expression in different formats to canonical array form
|
50,101
|
public function setDueDate ( $ key , $ value , $ expirationTime , array $ tags = null ) { return $ this -> set ( $ key , $ value , $ expirationTime - time ( ) , $ tags ) ; }
|
Set with expiration on concrete date
|
50,102
|
public function setNeverExpired ( $ key , $ value , array $ tags = null ) { return $ this -> set ( $ key , $ value , null , $ tags ) ; }
|
Set key that never expired
|
50,103
|
public function get ( $ key , $ default = null ) { $ document = $ this -> collection -> getDocument ( $ key ) ; if ( ! $ document ) { return $ default ; } $ expiredAt = $ document -> get ( self :: FIELD_NAME_EXPIRED ) ; if ( ! empty ( $ expiredAt ) && $ expiredAt -> sec < time ( ) ) { return $ default ; } return $ document -> get ( self :: FIELD_NAME_VALUE ) ; }
|
Get value by key
|
50,104
|
public function deleteMatchingAllTags ( array $ tags ) { $ this -> collection -> batchDelete ( function ( \ Sokil \ Mongo \ Expression $ e ) use ( $ tags ) { return $ e -> whereAll ( Cache :: FIELD_NAME_TAGS , $ tags ) ; } ) ; return $ this ; }
|
Delete documents by tag Document deletes if it contains all passed tags
|
50,105
|
public function deleteMatchingNoneOfTags ( array $ tags ) { $ this -> collection -> batchDelete ( function ( \ Sokil \ Mongo \ Expression $ e ) use ( $ tags ) { return $ e -> whereNoneOf ( Cache :: FIELD_NAME_TAGS , $ tags ) ; } ) ; return $ this ; }
|
Delete documents by tag Document deletes if it not contains all passed tags
|
50,106
|
public function getObject ( $ selector , $ className = '\Sokil\Mongo\Structure' ) { $ data = $ this -> get ( $ selector ) ; if ( ! $ data ) { return null ; } if ( is_callable ( $ className ) ) { $ className = $ className ( $ data ) ; } $ structure = new $ className ( ) ; if ( ! ( $ structure instanceof Structure ) ) { throw new Exception ( 'Wrong structure class specified' ) ; } return $ structure -> merge ( $ data ) ; }
|
Get structure object from a document s value
|
50,107
|
public function getObjectList ( $ selector , $ className = '\Sokil\Mongo\Structure' ) { $ data = $ this -> get ( $ selector ) ; if ( ! $ data || ! is_array ( $ data ) ) { return array ( ) ; } if ( is_string ( $ className ) ) { $ list = array_map ( function ( $ dataItem ) use ( $ className ) { $ listItemStructure = new $ className ( ) ; if ( ! ( $ listItemStructure instanceof Structure ) ) { throw new Exception ( 'Wrong structure class specified' ) ; } $ listItemStructure -> mergeUnmodified ( $ dataItem ) ; return $ listItemStructure ; } , $ data ) ; return $ list ; } if ( is_callable ( $ className ) ) { return array_map ( function ( $ dataItem ) use ( $ className ) { $ classNameString = $ className ( $ dataItem ) ; $ listItemStructure = new $ classNameString ; if ( ! ( $ listItemStructure instanceof Structure ) ) { throw new Exception ( 'Wrong structure class specified' ) ; } return $ listItemStructure -> merge ( $ dataItem ) ; } , $ data ) ; } throw new Exception ( 'Wrong class name specified. Use string or closure' ) ; }
|
Get list of structure objects from list of values in mongo document
|
50,108
|
public function set ( $ selector , $ value ) { $ value = self :: prepareToStore ( $ value ) ; $ arraySelector = explode ( '.' , $ selector ) ; $ chunksNum = count ( $ arraySelector ) ; if ( 1 == $ chunksNum ) { if ( ! isset ( $ this -> data [ $ selector ] ) || $ this -> data [ $ selector ] !== $ value ) { $ this -> data [ $ selector ] = $ value ; $ this -> modifiedFields [ ] = $ selector ; } return $ this ; } $ section = & $ this -> data ; for ( $ i = 0 ; $ i < $ chunksNum - 1 ; $ i ++ ) { $ field = $ arraySelector [ $ i ] ; if ( ! isset ( $ section [ $ field ] ) ) { $ section [ $ field ] = array ( ) ; } elseif ( ! is_array ( $ section [ $ field ] ) ) { throw new Exception ( 'Assigning sub-document to scalar value not allowed' ) ; } $ section = & $ section [ $ field ] ; } if ( ! isset ( $ section [ $ arraySelector [ $ chunksNum - 1 ] ] ) || $ section [ $ arraySelector [ $ chunksNum - 1 ] ] !== $ value ) { $ section [ $ arraySelector [ $ chunksNum - 1 ] ] = $ value ; $ this -> modifiedFields [ ] = $ selector ; } return $ this ; }
|
Store value to specified selector in local cache
|
50,109
|
public function has ( $ selector ) { $ pointer = & $ this -> data ; foreach ( explode ( '.' , $ selector ) as $ field ) { if ( ! array_key_exists ( $ field , $ pointer ) ) { return false ; } $ pointer = & $ pointer [ $ field ] ; } return true ; }
|
Check if structure has field identified by selector
|
50,110
|
public static function prepareToStore ( $ value ) { if ( is_array ( $ value ) ) { foreach ( $ value as $ k => $ v ) { $ value [ $ k ] = self :: prepareToStore ( $ v ) ; } return $ value ; } if ( ! is_object ( $ value ) ) { return $ value ; } if ( TypeChecker :: isInternalType ( $ value ) ) { return $ value ; } if ( $ value instanceof Geometry ) { return $ value -> jsonSerialize ( ) ; } if ( $ value instanceof Structure ) { if ( ! $ value -> isValid ( ) ) { $ exception = new InvalidDocumentException ( 'Embedded document not valid' ) ; $ exception -> setDocument ( $ value ) ; throw $ exception ; } return $ value -> toArray ( ) ; } return ( array ) $ value ; }
|
Normalize variable to be able to store in database
|
50,111
|
public function append ( $ selector , $ value ) { $ oldValue = $ this -> get ( $ selector ) ; if ( $ oldValue ) { if ( ! is_array ( $ oldValue ) ) { $ oldValue = ( array ) $ oldValue ; } $ oldValue [ ] = $ value ; $ value = $ oldValue ; } $ this -> set ( $ selector , $ value ) ; return $ this ; }
|
If field not exist - set value . If field exists and is not array - convert to array and append If field - s array - append
|
50,112
|
public function isModified ( $ selector = null ) { if ( empty ( $ this -> modifiedFields ) ) { return false ; } if ( empty ( $ selector ) ) { return ( bool ) $ this -> modifiedFields ; } foreach ( $ this -> modifiedFields as $ modifiedField ) { if ( preg_match ( '/^' . $ selector . '($|.)/' , $ modifiedField ) ) { return true ; } } return false ; }
|
If selector passed return true if field is modified . If selector omitted return true if document is modified .
|
50,113
|
public function mergeUnmodified ( array $ data ) { $ this -> mergeUnmodifiedPartial ( $ this -> data , $ data ) ; $ this -> mergeUnmodifiedPartial ( $ this -> originalData , $ data ) ; return $ this ; }
|
Merge array to current structure without setting modification mark
|
50,114
|
public function addError ( $ fieldName , $ ruleName , $ message ) { $ this -> errors [ $ fieldName ] [ $ ruleName ] = $ message ; return $ this ; }
|
Add validator error from validator classes and methods . This error reset on every re - validation
|
50,115
|
public function triggerError ( $ fieldName , $ ruleName , $ message ) { $ this -> triggeredErrors [ $ fieldName ] [ $ ruleName ] = $ message ; return $ this ; }
|
Add custom error which not reset after validation
|
50,116
|
public function isValid ( ) { $ this -> errors = array ( ) ; foreach ( $ this -> rules ( ) as $ rule ) { $ fields = array_map ( 'trim' , explode ( ',' , $ rule [ 0 ] ) ) ; $ ruleName = $ rule [ 1 ] ; $ params = array_slice ( $ rule , 2 ) ; if ( ! empty ( $ rule [ 'on' ] ) ) { $ onScenarios = explode ( ',' , $ rule [ 'on' ] ) ; if ( ! in_array ( $ this -> getScenario ( ) , $ onScenarios ) ) { continue ; } } if ( ! empty ( $ rule [ 'except' ] ) ) { $ exceptScenarios = explode ( ',' , $ rule [ 'except' ] ) ; if ( in_array ( $ this -> getScenario ( ) , $ exceptScenarios ) ) { continue ; } } if ( method_exists ( $ this , $ ruleName ) ) { foreach ( $ fields as $ field ) { $ this -> { $ ruleName } ( $ field , $ params ) ; } } else { $ validatorClassName = $ this -> getValidatorClassNameByRuleName ( $ ruleName ) ; $ validator = new $ validatorClassName ; if ( ! $ validator instanceof Validator ) { throw new Exception ( 'Validator class must implement \Sokil\Mongo\Validator class' ) ; } $ validator -> validate ( $ this , $ fields , $ params ) ; } } return ! $ this -> hasErrors ( ) ; }
|
Check if filled model params is valid
|
50,117
|
public function enqueue ( $ payload , $ priority = 0 ) { $ this -> collection -> createDocument ( array ( 'payload' => $ payload , 'priority' => ( int ) $ priority , 'datetime' => new \ MongoDate , ) ) -> save ( ) ; return $ this ; }
|
Add item to queue
|
50,118
|
public function dequeuePlain ( ) { $ document = $ this -> collection -> find ( ) -> sort ( array ( 'priority' => - 1 , 'datetime' => 1 , ) ) -> findAndRemove ( ) ; if ( ! $ document ) { return null ; } return $ document -> get ( 'payload' ) ; }
|
Get item from queue as is
|
50,119
|
public function dequeue ( ) { $ value = $ this -> dequeuePlain ( ) ; if ( ! is_array ( $ value ) ) { return $ value ; } $ structure = new Structure ( ) ; $ structure -> mergeUnmodified ( $ value ) ; return $ structure ; }
|
Get item from queue as Structure if array put into queue
|
50,120
|
public function addToSet ( $ field , $ expression ) { $ this -> stage [ $ field ] [ '$addToSet' ] = Expression :: normalize ( $ expression ) ; return $ this ; }
|
Add to set accumulator
|
50,121
|
public function first ( $ field , $ expression ) { $ this -> stage [ $ field ] [ '$first' ] = Expression :: normalize ( $ expression ) ; return $ this ; }
|
Returns the value that results from applying an expression to the first document in a group of documents that share the same group by key . Only meaningful when documents are in a defined order .
|
50,122
|
public function last ( $ field , $ expression ) { $ this -> stage [ $ field ] [ '$last' ] = Expression :: normalize ( $ expression ) ; return $ this ; }
|
Returns the value that results from applying an expression to the last document in a group of documents that share the same group by a field . Only meaningful when documents are in a defined order .
|
50,123
|
public function push ( $ field , $ expression ) { $ this -> stage [ $ field ] [ '$push' ] = Expression :: normalize ( $ expression ) ; return $ this ; }
|
Returns an array of all values that result from applying an expression to each document in a group of documents that share the same group by key .
|
50,124
|
public function listen ( ) { $ revisionsCollection = $ this -> getRevisionsCollection ( ) ; $ document = $ this -> document ; $ createRevisionCallback = function ( ) use ( $ revisionsCollection , $ document ) { $ revisionsCollection -> createDocument ( ) -> setDocumentData ( $ document -> getOriginalData ( ) ) -> save ( ) ; } ; $ this -> document -> onBeforeUpdate ( $ createRevisionCallback , PHP_INT_MAX ) ; $ this -> document -> onBeforeDelete ( $ createRevisionCallback , PHP_INT_MAX ) ; }
|
Start listening for changes in document
|
50,125
|
public function reset ( ) { parent :: reset ( ) ; $ this -> clearErrors ( ) ; $ this -> clearBehaviors ( ) ; $ this -> initDelegates ( ) ; return $ this ; }
|
Reset all data passed to object in run - time like events behaviors data modifications etc . to the state just after open or save document
|
50,126
|
public function refresh ( ) { $ data = $ this -> collection -> getMongoCollection ( ) -> findOne ( array ( '_id' => $ this -> getId ( ) ) ) ; $ this -> replace ( $ data ) ; $ this -> operator -> reset ( ) ; return $ this ; }
|
Reload data from db and reset all unsaved data
|
50,127
|
private function initDelegates ( ) { $ this -> eventDispatcher = new EventDispatcher ; $ this -> operator = $ this -> getCollection ( ) -> operator ( ) ; $ this -> attachBehaviors ( $ this -> behaviors ( ) ) ; if ( $ this -> hasOption ( 'behaviors' ) ) { $ this -> attachBehaviors ( $ this -> getOption ( 'behaviors' ) ) ; } }
|
Initialise relative classes
|
50,128
|
public function setPoint ( $ field , $ longitude , $ latitude ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ Point ( array ( $ longitude , $ latitude ) ) ) ; }
|
Set point as longitude and latitude
|
50,129
|
public function setLineString ( $ field , array $ pointArray ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ LineString ( $ pointArray ) ) ; }
|
Set line string as array of points
|
50,130
|
public function setPolygon ( $ field , array $ lineRingsArray ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ Polygon ( $ lineRingsArray ) ) ; }
|
Set polygon as array of line rings .
|
50,131
|
public function setMultiPoint ( $ field , $ pointArray ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ MultiPoint ( $ pointArray ) ) ; }
|
Set multi point as array of points
|
50,132
|
public function setMultiLineString ( $ field , $ lineStringArray ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ MultiLineString ( $ lineStringArray ) ) ; }
|
Set multi line string as array of line strings
|
50,133
|
public function setMultyPolygon ( $ field , array $ polygonsArray ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ MultiPolygon ( $ polygonsArray ) ) ; }
|
Set multy polygon as array of polygons .
|
50,134
|
public function setGeometryCollection ( $ field , array $ geometryCollection ) { return $ this -> setGeometry ( $ field , new \ GeoJson \ Geometry \ GeometryCollection ( $ geometryCollection ) ) ; }
|
Set collection of different geometries
|
50,135
|
public function getRelationDefinition ( ) { $ relations = $ this -> getOption ( 'relations' ) ; if ( ! is_array ( $ relations ) ) { return $ this -> relations ( ) ; } return $ relations + $ this -> relations ( ) ; }
|
Relation definition through mapping is more prior to defined in class
|
50,136
|
public function triggerEvent ( $ eventName , Event $ event = null ) { if ( ! $ event ) { $ event = new Event ; } $ event -> setTarget ( $ this ) ; return $ this -> eventDispatcher -> dispatch ( $ eventName , $ event ) ; }
|
Manually trigger defined events
|
50,137
|
public function attachEvent ( $ event , $ handler , $ priority = 0 ) { $ this -> eventDispatcher -> addListener ( $ event , $ handler , $ priority ) ; return $ this ; }
|
Attach event handler
|
50,138
|
public function set ( $ fieldName , $ value ) { parent :: set ( $ fieldName , $ value ) ; if ( $ this -> getId ( ) ) { $ this -> operator -> set ( $ fieldName , $ value ) ; } return $ this ; }
|
Update value in local cache and in DB
|
50,139
|
public function createReference ( ) { $ documentId = $ this -> getId ( ) ; if ( null === $ documentId ) { throw new Exception ( 'Document must be stored to get DBRef' ) ; } return $ this -> getCollection ( ) -> getMongoCollection ( ) -> createDBRef ( $ documentId ) ; }
|
Get reference to document
|
50,140
|
public function append ( $ selector , $ value ) { parent :: append ( $ selector , $ value ) ; if ( $ this -> getId ( ) ) { $ this -> operator -> set ( $ selector , $ this -> get ( $ selector ) ) ; } return $ this ; }
|
If field not exist - set value . If field exists and is not array - convert to array and append If field is array - append
|
50,141
|
public function push ( $ fieldName , $ value ) { $ oldValue = $ this -> get ( $ fieldName ) ; if ( is_array ( $ oldValue ) ) { $ isSubDocument = ( array_keys ( $ oldValue ) !== range ( 0 , count ( $ oldValue ) - 1 ) ) ; if ( $ isSubDocument ) { throw new InvalidOperationException ( sprintf ( 'The field "%s" must be an array but is of type Object' , $ fieldName ) ) ; } } $ value = Structure :: prepareToStore ( $ value ) ; if ( ! $ oldValue ) { if ( $ this -> getId ( ) ) { $ this -> operator -> push ( $ fieldName , $ value ) ; } $ value = array ( $ value ) ; } elseif ( ! is_array ( $ oldValue ) ) { $ value = array_merge ( ( array ) $ oldValue , array ( $ value ) ) ; if ( $ this -> getId ( ) ) { $ this -> operator -> set ( $ fieldName , $ value ) ; } } else { if ( $ this -> getId ( ) ) { $ setValue = $ this -> operator -> get ( '$set' , $ fieldName ) ; if ( $ setValue ) { $ setValue [ ] = $ value ; $ this -> operator -> set ( $ fieldName , $ setValue ) ; } else { $ this -> operator -> push ( $ fieldName , $ value ) ; } } $ value = array_merge ( $ oldValue , array ( $ value ) ) ; } parent :: set ( $ fieldName , $ value ) ; return $ this ; }
|
Push argument as single element to field value
|
50,142
|
public function pushEach ( $ fieldName , array $ values ) { $ oldValue = $ this -> get ( $ fieldName ) ; if ( $ this -> getId ( ) ) { if ( ! $ oldValue ) { $ this -> operator -> pushEach ( $ fieldName , $ values ) ; } elseif ( ! is_array ( $ oldValue ) ) { $ values = array_merge ( ( array ) $ oldValue , $ values ) ; $ this -> operator -> set ( $ fieldName , $ values ) ; } else { $ this -> operator -> pushEach ( $ fieldName , $ values ) ; $ values = array_merge ( $ oldValue , $ values ) ; } } else { if ( $ oldValue ) { $ values = array_merge ( ( array ) $ oldValue , $ values ) ; } } parent :: set ( $ fieldName , $ values ) ; return $ this ; }
|
Push each element of argument s array as single element to field value
|
50,143
|
public function pull ( $ expression , $ value = null ) { $ this -> operator -> pull ( $ expression , $ value ) ; return $ this ; }
|
Removes from an existing array all instances of a value or values that match a specified query
|
50,144
|
private function internalInsert ( ) { if ( $ this -> triggerEvent ( self :: EVENT_NAME_BEFORE_INSERT ) -> isCancelled ( ) ) { return ; } $ document = $ this -> toArray ( ) ; try { $ this -> collection -> getMongoCollection ( ) -> insert ( $ document ) ; } catch ( \ Exception $ e ) { throw new WriteException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } $ this -> defineId ( $ document [ '_id' ] ) ; $ this -> triggerEvent ( self :: EVENT_NAME_AFTER_INSERT ) ; }
|
Internal method to insert document
|
50,145
|
private function internalUpdate ( ) { if ( $ this -> triggerEvent ( self :: EVENT_NAME_BEFORE_UPDATE ) -> isCancelled ( ) ) { return ; } $ query = array ( '_id' => $ this -> getId ( ) ) ; if ( $ this -> getOption ( 'lock' ) === Definition :: LOCK_OPTIMISTIC ) { $ query [ '__version__' ] = $ this -> get ( '__version__' ) ; $ this -> getOperator ( ) -> increment ( '__version__' ) ; } try { $ status = $ this -> collection -> getMongoCollection ( ) -> update ( $ query , $ this -> getOperator ( ) -> toArray ( ) ) ; } catch ( \ Exception $ e ) { throw new WriteException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } if ( $ status [ 'ok' ] != 1 ) { throw new WriteException ( sprintf ( 'Update error: %s: %s' , $ status [ 'err' ] , $ status [ 'errmsg' ] ) ) ; } if ( $ this -> getOption ( 'lock' ) === Definition :: LOCK_OPTIMISTIC ) { if ( $ status [ 'n' ] === 0 ) { throw new OptimisticLockFailureException ; } } if ( $ this -> getOperator ( ) -> isReloadRequired ( ) ) { $ this -> refresh ( ) ; } else { $ this -> getOperator ( ) -> reset ( ) ; } $ this -> triggerEvent ( self :: EVENT_NAME_AFTER_UPDATE ) ; }
|
Internal method to update document
|
50,146
|
public function getMongoCollection ( ) { if ( empty ( $ this -> collection ) ) { $ mongoCollectionClassName = $ this -> mongoCollectionClassName ; $ this -> collection = new $ mongoCollectionClassName ( $ this -> database -> getMongoDB ( ) , $ this -> collectionName ) ; } return $ this -> collection ; }
|
Get native collection instance of mongo driver
|
50,147
|
public function getDocumentClassName ( array $ documentData = null ) { $ documentClass = $ this -> definition -> getOption ( 'documentClass' ) ; if ( is_callable ( $ documentClass ) ) { return call_user_func ( $ documentClass , $ documentData ) ; } if ( class_exists ( $ documentClass ) ) { return $ documentClass ; } throw new Exception ( 'Property "documentClass" must be callable or valid name of class' ) ; }
|
Override to define class name of document by document data
|
50,148
|
public function createDocument ( array $ data = null ) { $ className = $ this -> getDocumentClassName ( $ data ) ; $ document = new $ className ( $ this , $ data , array ( 'stored' => false ) + $ this -> definition -> getOptions ( ) ) ; if ( $ this -> isDocumentPoolEnabled ( ) ) { $ collection = $ this ; $ document -> onAfterInsert ( function ( \ Sokil \ Mongo \ Event $ event ) use ( $ collection ) { $ collection -> addDocumentToDocumentPool ( $ event -> getTarget ( ) ) ; } ) ; } return $ document ; }
|
Factory method to get not stored Document instance from array
|
50,149
|
public function getDistinct ( $ selector , $ expression = null ) { if ( $ expression ) { return $ this -> getMongoCollection ( ) -> distinct ( $ selector , Expression :: convertToArray ( $ expression ) ) ; } return $ this -> getMongoCollection ( ) -> distinct ( $ selector ) ; }
|
Retrieve a list of distinct values for the given key across a collection .
|
50,150
|
public function find ( $ callable = null ) { $ cursor = new Cursor ( $ this , array ( 'expressionClass' => $ this -> definition -> getExpressionClass ( ) , 'batchSize' => $ this -> definition -> getOption ( 'batchSize' ) , 'clientTimeout' => $ this -> definition -> getOption ( 'cursorClientTimeout' ) , 'serverTimeout' => $ this -> definition -> getOption ( 'cursorServerTimeout' ) , ) ) ; if ( is_callable ( $ callable ) ) { $ callable ( $ cursor -> getExpression ( ) ) ; } return $ cursor ; }
|
Create document query builder
|
50,151
|
public function addDocumentToDocumentPool ( Document $ document ) { $ documentId = ( string ) $ document -> getId ( ) ; if ( ! isset ( $ this -> documentPool [ $ documentId ] ) ) { $ this -> documentPool [ $ documentId ] = $ document ; } else { $ this -> documentPool [ $ documentId ] -> mergeUnmodified ( $ document -> toArray ( ) ) ; } return $ this ; }
|
Store document to pool
|
50,152
|
public function getDocumentsFromDocumentPool ( array $ ids = null ) { if ( ! $ ids ) { return $ this -> documentPool ; } return array_intersect_key ( $ this -> documentPool , array_flip ( array_map ( 'strval' , $ ids ) ) ) ; }
|
Get documents from pool if they stored
|
50,153
|
public function isDocumentInDocumentPool ( $ document ) { if ( $ document instanceof Document ) { $ document = $ document -> getId ( ) ; } return isset ( $ this -> documentPool [ ( string ) $ document ] ) ; }
|
Check if document exists in identity map
|
50,154
|
public function hasDocument ( Document $ document ) { $ documentCollection = $ document -> getCollection ( ) ; $ documentDatabase = $ documentCollection -> getDatabase ( ) ; if ( $ documentDatabase -> getClient ( ) -> getDsn ( ) !== $ this -> getDatabase ( ) -> getClient ( ) -> getDsn ( ) ) { return false ; } if ( $ documentDatabase -> getName ( ) !== $ this -> getDatabase ( ) -> getName ( ) ) { return false ; } return $ documentCollection -> getName ( ) == $ this -> getName ( ) ; }
|
Check if document belongs to collection
|
50,155
|
public function getDocuments ( array $ idList , $ callable = null ) { $ idListToFindDirectly = $ idList ; $ documentsInDocumentPool = array ( ) ; if ( $ this -> isDocumentPoolEnabled ( ) && ! $ callable ) { $ documentsInDocumentPool = $ this -> getDocumentsFromDocumentPool ( $ idList ) ; if ( count ( $ documentsInDocumentPool ) === count ( $ idList ) ) { return $ documentsInDocumentPool ; } $ idListToFindDirectly = array_diff_key ( array_map ( 'strval' , $ idList ) , array_keys ( $ documentsInDocumentPool ) ) ; } $ cursor = $ this -> find ( ) ; if ( is_callable ( $ callable ) ) { call_user_func ( $ callable , $ cursor ) ; } $ documentsGettingDirectly = $ cursor -> byIdList ( $ idListToFindDirectly ) -> findAll ( ) ; if ( empty ( $ documentsGettingDirectly ) ) { return $ documentsInDocumentPool ? $ documentsInDocumentPool : array ( ) ; } if ( $ this -> isDocumentPoolEnabled ( ) ) { $ this -> addDocumentsToDocumentPool ( $ documentsGettingDirectly ) ; } return $ documentsGettingDirectly + $ documentsInDocumentPool ; }
|
Get documents by list of id
|
50,156
|
public function createBatchInsert ( $ writeConcern = null , $ timeout = null , $ ordered = null ) { return new BatchInsert ( $ this , $ writeConcern , $ timeout , $ ordered ) ; }
|
Creates batch insert operation handler
|
50,157
|
public function createBatchUpdate ( $ writeConcern = null , $ timeout = null , $ ordered = null ) { return new BatchUpdate ( $ this , $ writeConcern , $ timeout , $ ordered ) ; }
|
Creates batch update operation handler
|
50,158
|
public function createBatchDelete ( $ writeConcern = null , $ timeout = null , $ ordered = null ) { return new BatchDelete ( $ this , $ writeConcern , $ timeout , $ ordered ) ; }
|
Creates batch delete operation handler
|
50,159
|
public function batchDelete ( $ expression ) { $ result = $ this -> getMongoCollection ( ) -> remove ( Expression :: convertToArray ( $ expression ) ) ; if ( true !== $ result && $ result [ 'ok' ] != 1 ) { throw new Exception ( 'Error removing documents from collection: ' . $ result [ 'err' ] ) ; } return $ this ; }
|
Delete documents by expression
|
50,160
|
public function batchInsert ( $ rows , $ validate = true ) { if ( $ validate ) { $ document = $ this -> createDocument ( ) ; foreach ( $ rows as $ row ) { $ document -> merge ( $ row ) ; if ( ! $ document -> isValid ( ) ) { throw new InvalidDocumentException ( 'Document is invalid on batch insert' ) ; } $ document -> reset ( ) ; } } $ result = $ this -> getMongoCollection ( ) -> batchInsert ( $ rows ) ; if ( is_array ( $ result ) ) { if ( $ result [ 'ok' ] != 1 ) { throw new Exception ( 'Batch insert error: ' . $ result [ 'err' ] ) ; } return $ this ; } if ( ! $ result ) { throw new Exception ( 'Batch insert error' ) ; } return $ this ; }
|
Insert multiple documents defined as arrays
|
50,161
|
public function insert ( array $ document ) { $ result = $ this -> getMongoCollection ( ) -> insert ( $ document ) ; if ( is_array ( $ result ) ) { if ( $ result [ 'ok' ] != 1 ) { throw new Exception ( 'Insert error: ' . $ result [ 'err' ] . ': ' . $ result [ 'errmsg' ] ) ; } return $ this ; } if ( ! $ result ) { throw new Exception ( 'Insert error' ) ; } return $ this ; }
|
Direct insert of array to MongoDB without creating document object and validation
|
50,162
|
public function update ( $ expression , $ updateData , array $ options = array ( ) ) { $ result = $ this -> getMongoCollection ( ) -> update ( Expression :: convertToArray ( $ expression ) , Operator :: convertToArray ( $ updateData ) , $ options ) ; if ( is_array ( $ result ) ) { if ( $ result [ 'ok' ] != 1 ) { throw new Exception ( sprintf ( 'Update error: %s: %s' , $ result [ 'err' ] , $ result [ 'errmsg' ] ) ) ; } return $ this ; } if ( ! $ result ) { throw new Exception ( 'Update error' ) ; } return $ this ; }
|
Update multiple documents
|
50,163
|
private function validateAggregationOptions ( array $ options ) { $ client = $ this -> getDatabase ( ) -> getClient ( ) ; $ dbVersion = $ client -> getDbVersion ( ) ; if ( version_compare ( $ dbVersion , '2.6.0' , '<' ) ) { if ( ! empty ( $ options [ 'explain' ] ) ) { throw new FeatureNotSupportedException ( 'Explain of aggregation implemented only from 2.6.0' ) ; } if ( ! empty ( $ options [ 'allowDiskUse' ] ) ) { throw new FeatureNotSupportedException ( 'Option allowDiskUse of aggregation implemented only from 2.6.0' ) ; } if ( ! empty ( $ options [ 'cursor' ] ) ) { throw new FeatureNotSupportedException ( 'Option cursor of aggregation implemented only from 2.6.0' ) ; } } if ( version_compare ( $ dbVersion , '3.2.0' , '<' ) ) { if ( ! empty ( $ options [ 'bypassDocumentValidation' ] ) ) { throw new FeatureNotSupportedException ( 'Option bypassDocumentValidation of aggregation implemented only from 3.2.0' ) ; } if ( ! empty ( $ options [ 'readConcern' ] ) ) { throw new FeatureNotSupportedException ( 'Option readConcern of aggregation implemented only from 3.2.0' ) ; } } }
|
Check if aggragator options supported by database
|
50,164
|
public function ensureUniqueIndex ( array $ key , $ dropDups = false ) { $ this -> getMongoCollection ( ) -> createIndex ( $ key , array ( 'unique' => true , 'dropDups' => ( bool ) $ dropDups , ) ) ; return $ this ; }
|
Create unique index
|
50,165
|
public function ensureFulltextIndex ( $ field = '$**' , array $ weights = null , $ defaultLanguage = Language :: ENGLISH , $ languageOverride = null ) { if ( is_array ( $ field ) ) { $ keys = array_fill_keys ( $ field , 'text' ) ; } else { $ keys = array ( $ field => 'text' , ) ; } $ options = array ( 'default_language' => $ defaultLanguage , ) ; if ( ! empty ( $ weights ) ) { $ options [ 'weights' ] = $ weights ; } if ( ! empty ( $ languageOverride ) ) { $ options [ 'language_override' ] = $ languageOverride ; } $ this -> getMongoCollection ( ) -> createIndex ( $ keys , $ options ) ; return $ this ; }
|
Create fulltext index
|
50,166
|
public function setWriteConcern ( $ w , $ timeout = 10000 ) { if ( ! $ this -> getMongoCollection ( ) -> setWriteConcern ( $ w , ( int ) $ timeout ) ) { throw new Exception ( 'Error setting write concern' ) ; } return $ this ; }
|
Define write concern for all requests to current collection
|
50,167
|
private function replaceRenameCollection ( $ newName , $ dropTarget ) { $ adminDb = $ this -> getDatabase ( ) -> getClient ( ) -> getDatabase ( 'admin' ) ; list ( $ targetDatabaseName , $ targetCollectionName ) = $ this -> getCompleteCollectionNamespace ( $ newName ) ; $ response = $ adminDb -> executeCommand ( array ( 'renameCollection' => $ this -> getDatabase ( ) -> getName ( ) . '.' . $ this -> getName ( ) , 'to' => $ targetDatabaseName . '.' . $ targetCollectionName , 'dropTarget' => $ dropTarget , ) ) ; if ( $ response [ 'ok' ] !== 1.0 ) { throw new Exception ( 'Error: #' . $ response [ 'code' ] . ': ' . $ response [ 'errmsg' ] , $ response [ 'code' ] ) ; } $ this -> database = $ this -> getDatabase ( ) -> getClient ( ) -> getDatabase ( $ targetDatabaseName ) ; $ this -> collection = $ this -> database -> getCollection ( $ targetCollectionName ) -> getMongoCollection ( ) ; $ this -> collectionName = $ this -> collection -> getName ( ) ; return $ this ; }
|
Rename collection with optionally dropping previously created target collection
|
50,168
|
public function match ( $ expression ) { if ( is_callable ( $ expression ) ) { $ expressionConfigurator = $ expression ; $ expression = new Expression ( ) ; call_user_func ( $ expressionConfigurator , $ expression ) ; } if ( $ expression instanceof Expression ) { $ expression = $ expression -> toArray ( ) ; } elseif ( ! is_array ( $ expression ) ) { throw new Exception ( 'Must be array, callable or instance of \Sokil\Mongo\Expression' ) ; } $ this -> addStage ( '$match' , $ expression ) ; return $ this ; }
|
Filter documents by expression
|
50,169
|
public function deleteFileById ( $ id ) { if ( $ id instanceof \ MongoId ) { $ result = $ this -> getMongoCollection ( ) -> delete ( $ id ) ; } else { try { $ result = $ this -> getMongoCollection ( ) -> delete ( new \ MongoId ( $ id ) ) ; } catch ( \ MongoException $ e ) { $ result = $ this -> getMongoCollection ( ) -> delete ( $ id ) ; } } if ( $ result [ 'ok' ] !== ( double ) 1 ) { throw new Exception ( 'Error deleting file: ' . $ result [ 'err' ] . ': ' . $ result [ 'errmsg' ] ) ; } return $ this ; }
|
Delete file by id
|
50,170
|
public function setDocumentData ( array $ document ) { $ this -> set ( '__date__' , new \ MongoDate ) ; $ this -> set ( '__documentId__' , $ document [ '_id' ] ) ; unset ( $ document [ '_id' ] ) ; $ this -> merge ( $ document ) ; return $ this ; }
|
Set document data
|
50,171
|
public function getDocument ( ) { $ data = $ this -> toArray ( ) ; $ data [ '_id' ] = $ data [ '__documentId__' ] ; unset ( $ data [ '__date__' ] , $ data [ '__documentId__' ] ) ; return $ this -> baseCollection -> hydrate ( $ data ) ; }
|
Get document instance
|
50,172
|
public static function normalizeEach ( array $ expressions ) { foreach ( $ expressions as $ i => $ expression ) { $ expressions [ $ i ] = self :: normalize ( $ expression ) ; } return $ expressions ; }
|
Convert expressions specified in different formats to canonical form
|
50,173
|
public static function normalize ( $ expression ) { if ( is_callable ( $ expression ) ) { $ expressionConfigurator = $ expression ; $ expression = new Expression ; call_user_func ( $ expressionConfigurator , $ expression ) ; } if ( $ expression instanceof Expression ) { $ expression = $ expression -> toArray ( ) ; } elseif ( is_array ( $ expression ) ) { foreach ( $ expression as $ fieldName => $ value ) { $ expression [ $ fieldName ] = self :: normalize ( $ value ) ; } } return $ expression ; }
|
Convert expression specified in different formats to canonical form
|
50,174
|
protected function shouldMerge ( $ variantName ) { return ! Arr :: has ( $ this -> variants , $ variantName ) && ! Arr :: get ( $ this -> exclude , $ variantName ) ; }
|
Returns whether variant configuration should be merged in for a given variant name .
|
50,175
|
public function create ( $ storage = null ) { $ storage = $ storage ? : $ this -> getStorageDisk ( ) ; return new FileHandler ( $ this -> makeStorage ( $ storage ) , $ this -> makeProcessor ( ) ) ; }
|
Makes a file handler instance .
|
50,176
|
public function steps ( $ steps ) { if ( ! is_array ( $ steps ) ) { $ steps = [ $ steps ] ; } $ this -> steps = $ steps ; return $ this ; }
|
Sets variant processing steps .
|
50,177
|
public function extension ( $ extension ) { if ( is_string ( $ extension ) ) { $ this -> extension = ltrim ( $ extension , '.' ) ; } else { $ this -> extension = null ; } return $ this ; }
|
The filename extension to use .
|
50,178
|
protected function filename ( AttachmentDataInterface $ attachment , $ variant = '' ) { if ( $ variant ) { return $ attachment -> variantFilename ( $ variant ) ; } return $ attachment -> originalFilename ( ) ; }
|
Returns the file name .
|
50,179
|
protected function secureHash ( AttachmentDataInterface $ attachment , $ variant = '' ) { return hash ( 'sha256' , $ this -> id ( $ attachment , $ variant ) . $ attachment -> size ( ) . $ this -> filename ( $ attachment , $ variant ) ) ; }
|
Return a secure Bcrypt hash of the attachment s corresponding instance id .
|
50,180
|
protected function style ( AttachmentDataInterface $ attachment , $ variant = '' ) { if ( $ variant ) { return $ variant ; } return Arr :: get ( $ attachment -> getConfig ( ) , 'default-variant' , FileHandler :: ORIGINAL ) ; }
|
Returns the style or the default style if an empty style is supplied .
|
50,181
|
protected function getAttachmentsToProcess ( AttachableInterface $ model ) { $ attachments = $ model -> getAttachedFiles ( ) ; $ attachmentNames = $ this -> option ( 'attachments' ) ; $ availableAttachmentNames = array_map ( function ( AttachmentInterface $ attachment ) { return $ attachment -> name ( ) ; } , $ attachments ) ; if ( empty ( $ attachmentNames ) ) { return $ availableAttachmentNames ; } $ attachmentNames = explode ( ',' , str_replace ( ', ' , ',' , $ attachmentNames ) ) ; $ unavailableNames = array_diff ( $ attachmentNames , $ availableAttachmentNames ) ; if ( count ( $ unavailableNames ) ) { throw new UnexpectedValueException ( get_class ( $ model ) . ' does not have attachment(s): ' . implode ( ', ' , $ unavailableNames ) ) ; } return array_intersect ( $ availableAttachmentNames , $ attachmentNames ) ; }
|
Returns the attachment names that should be procesed for a given model .
|
50,182
|
protected function getModelInstanceQuery ( Model $ model ) { $ query = $ model -> query ( ) ; $ this -> applyOrderingToModelInstanceQuery ( $ query ) ; $ this -> applyStartAndStopLimitsToQuery ( $ query ) ; return $ query ; }
|
Returns base query for returning all model instances .
|
50,183
|
protected function generateModelInstances ( $ query , $ totalCount ) { $ chunkSize = $ this -> getChunkSize ( ) ; $ chunkCount = ceil ( $ totalCount / $ chunkSize ) ; for ( $ x = 0 ; $ x < $ chunkCount ; $ x ++ ) { $ skip = $ x * $ chunkSize ; yield $ query -> skip ( $ skip ) -> take ( $ chunkSize ) -> get ( ) ; } }
|
Sets up and returns generator for model instances .
|
50,184
|
public function defaultVariantUrl ( $ variant ) { $ defaultVariant = $ this -> getDefaultUrlVariantName ( ) ; return $ this -> getConfigValue ( "urls.{$variant}" , $ variant === $ defaultVariant ? $ this -> getDefaultUrlWithoutVariantFallback ( ) : null ) ; }
|
Returns the default URL for a variant to use when no attachment is stored .
|
50,185
|
protected function getConfigValue ( $ key , $ default = null ) { if ( Arr :: has ( $ this -> normalizedConfig , $ key ) ) { return Arr :: get ( $ this -> normalizedConfig , $ key ) ; } return $ this -> getFallbackConfigValue ( $ key , $ default ) ; }
|
Returns the config value relevant for this attachment .
|
50,186
|
protected function getFallbackConfigValue ( $ key , $ default = null ) { $ map = [ 'keep-old-files' => 'keep-old-files' , 'preserve-files' => 'preserve-files' , 'storage' => 'storage.disk' , 'path' => 'path.original' , 'variant-path' => 'path.variant' , 'attributes.size' => 'model.attributes.size' , 'attributes.content_type' => 'model.attributes.content_type' , 'attributes.updated_at' => 'model.attributes.updated_at' , 'attributes.created_at' => 'model.attributes.created_at' , 'attributes.variants' => 'model.attributes.variants' , ] ; if ( ! in_array ( $ key , array_keys ( $ map ) ) ) { return $ default ; } return config ( 'paperclip.' . $ map [ $ key ] , $ default ) ; }
|
Returns the global configuration fallback for a config value .
|
50,187
|
public function hasAttachedFile ( $ name , array $ options = [ ] ) { $ factory = app ( AttachmentFactoryInterface :: class ) ; $ attachment = $ factory -> create ( $ this , $ name , $ options ) ; $ this -> attachedFiles [ $ name ] = $ attachment ; }
|
Add a new file attachment type to the list of available attachments .
|
50,188
|
public static function bootPaperclipTrait ( ) { static :: saved ( function ( $ model ) { if ( $ model -> attachedUpdated ) { $ model -> attachedUpdated = false ; foreach ( $ model -> getAttachedFiles ( ) as $ attachedFile ) { $ attachedFile -> afterSave ( $ model ) ; } } } ) ; static :: deleting ( function ( $ model ) { foreach ( $ model -> getAttachedFiles ( ) as $ attachedFile ) { $ attachedFile -> beforeDelete ( $ model ) ; } } ) ; static :: deleted ( function ( $ model ) { foreach ( $ model -> getAttachedFiles ( ) as $ attachedFile ) { $ attachedFile -> afterDelete ( $ model ) ; } } ) ; }
|
Registers the observers .
|
50,189
|
public function getAttribute ( $ key ) { if ( array_key_exists ( $ key , $ this -> attachedFiles ) ) { return $ this -> attachedFiles [ $ key ] ; } return parent :: getAttribute ( $ key ) ; }
|
Handle the dynamic retrieval of attachment objects .
|
50,190
|
public function setAttribute ( $ key , $ value ) { if ( array_key_exists ( $ key , $ this -> attachedFiles ) ) { if ( $ value ) { $ attachedFile = $ this -> attachedFiles [ $ key ] ; if ( $ value === $ this -> getDeleteAttachmentString ( ) ) { $ attachedFile -> setToBeDeleted ( ) ; return ; } $ factory = app ( StorableFileFactoryInterface :: class ) ; $ attachedFile -> setUploadedFile ( $ factory -> makeFromAny ( $ value ) ) ; } $ this -> attachedUpdated = true ; return ; } parent :: setAttribute ( $ key , $ value ) ; }
|
Handles the setting of attachment objects .
|
50,191
|
public function getAttributes ( ) { if ( $ this -> isPerformInsertInBacktrace ( ) ) { return parent :: getAttributes ( ) ; } return array_merge ( $ this -> attachedFiles , parent :: getAttributes ( ) ) ; }
|
Get all of the current attributes and attached files on the model .
|
50,192
|
public function pathsForAttachment ( $ attachmentName ) { $ paths = [ ] ; if ( isset ( $ this -> attachedFiles [ $ attachmentName ] ) ) { $ attachment = $ this -> attachedFiles [ $ attachmentName ] ; foreach ( $ attachment -> variants ( true ) as $ variant ) { $ paths [ $ variant ] = $ attachment -> variantPath ( $ variant ) ; } } return $ paths ; }
|
Return the image paths for a given attachment .
|
50,193
|
public function urlsForAttachment ( $ attachmentName ) { $ urls = [ ] ; if ( isset ( $ this -> attachedFiles [ $ attachmentName ] ) ) { $ attachment = $ this -> attachedFiles [ $ attachmentName ] ; foreach ( $ attachment -> variants ( true ) as $ variant ) { $ urls [ $ variant ] = $ attachment -> url ( $ variant ) ; } } return $ urls ; }
|
Return the image urls for a given attachment .
|
50,194
|
public function setStorage ( $ storage ) { if ( $ this -> storage !== $ storage || ! $ this -> handler ) { $ this -> storage = $ storage ; $ this -> handler = $ this -> getFileHandlerFactory ( ) -> create ( $ storage ) ; } return $ this ; }
|
Sets the storage disk identifier .
|
50,195
|
public function setUploadedFile ( StorableFileInterface $ file ) { $ this -> instance -> markAttachmentUpdated ( ) ; if ( ! $ this -> config -> keepOldFiles ( ) ) { $ this -> clear ( ) ; } $ this -> clearTarget ( ) ; $ this -> uploadedFile = $ file ; $ this -> instanceWrite ( 'file_name' , $ this -> uploadedFile -> name ( ) ) ; $ this -> instanceWrite ( 'file_size' , $ this -> uploadedFile -> size ( ) ) ; $ this -> instanceWrite ( 'content_type' , $ this -> uploadedFile -> mimeType ( ) ) ; $ this -> instanceWrite ( 'updated_at' , Carbon :: now ( ) ) ; $ this -> performCallableHookBeforeProcessing ( ) ; $ this -> queueAllForWrite ( ) ; }
|
Sets a file to be processed and stored .
|
50,196
|
public function setToBeDeleted ( ) { $ this -> instance -> markAttachmentUpdated ( ) ; if ( ! $ this -> config -> keepOldFiles ( ) ) { $ this -> clear ( ) ; } $ this -> clearAttributes ( ) ; }
|
Sets the attachment to be deleted .
|
50,197
|
public function reprocess ( $ variants = [ '*' ] ) { if ( ! $ this -> exists ( ) ) { return ; } if ( in_array ( '*' , $ variants ) ) { $ variants = $ this -> variants ( ) ; } $ source = $ this -> getStorableFileFactory ( ) -> makeFromUrl ( $ this -> url ( ) , $ this -> originalFilename ( ) , $ this -> contentType ( ) ) ; $ variantInformation = [ ] ; foreach ( $ variants as $ variant ) { $ this -> processSingleVariant ( $ source , $ variant , $ variantInformation ) ; } if ( $ this -> shouldVariantInformationBeStored ( ) ) { $ this -> instanceWrite ( 'variants' , json_encode ( $ variantInformation ) ) ; $ this -> instance -> save ( ) ; } }
|
Reprocesses variants from the currently set original file .
|
50,198
|
public function variants ( $ withOriginal = false ) { $ variants = array_keys ( $ this -> config -> variantConfigs ( ) ) ; if ( $ withOriginal && ! in_array ( FileHandler :: ORIGINAL , $ variants ) ) { array_unshift ( $ variants , FileHandler :: ORIGINAL ) ; } return $ variants ; }
|
Returns list of keys for defined variants .
|
50,199
|
public function variantPath ( $ variant = null ) { $ variant = $ variant ? : FileHandler :: ORIGINAL ; $ target = $ this -> getOrMakeTargetInstance ( ) ; if ( $ variant == FileHandler :: ORIGINAL ) { return $ target -> original ( ) ; } return $ target -> variant ( $ variant ) ; }
|
Returns the relative storage path for a variant .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.