idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
6,600
public function setTermsLookup ( string $ key , array $ termsLookup ) : self { $ this -> _key = $ key ; $ this -> _terms = $ termsLookup ; return $ this ; }
Sets key and terms lookup for the query .
6,601
public function match ( string $ field = null , $ values = null ) : Match { return new Match ( $ field , $ values ) ; }
match query .
6,602
public function common_terms ( string $ field , string $ query , float $ cutoffFrequency ) : Common { return new Common ( $ field , $ query , $ cutoffFrequency ) ; }
common terms query .
6,603
public function fuzzy ( string $ fieldName = null , string $ value = null ) : Fuzzy { return new Fuzzy ( $ fieldName , $ value ) ; }
fuzzy query .
6,604
public function regexp ( string $ key = '' , string $ value = null , float $ boost = 1.0 ) : Regexp { return new Regexp ( $ key , $ value , $ boost ) ; }
regexp query .
6,605
public function span_first ( $ match = null , int $ end = null ) : SpanFirst { return new SpanFirst ( $ match , $ end ) ; }
span first query .
6,606
public function span_near ( array $ clauses = [ ] , int $ slop = 1 , bool $ inOrder = false ) : SpanNear { return new SpanNear ( $ clauses , $ slop , $ inOrder ) ; }
span near query .
6,607
public function span_containing ( AbstractSpanQuery $ little = null , AbstractSpanQuery $ big = null ) : SpanContaining { return new SpanContaining ( $ little , $ big ) ; }
span_containing query .
6,608
public function span_within ( AbstractSpanQuery $ little = null , AbstractSpanQuery $ big = null ) : SpanWithin { return new SpanWithin ( $ little , $ big ) ; }
span_within query .
6,609
public function wildcard ( string $ key = '' , string $ value = null , float $ boost = 1.0 ) : Wildcard { return new Wildcard ( $ key , $ value , $ boost ) ; }
wildcard query .
6,610
public function geo_distance ( string $ key , $ location , string $ distance ) : GeoDistance { return new GeoDistance ( $ key , $ location , $ distance ) ; }
geo distance query .
6,611
public function generateDefaultResponse ( array $ params ) : Response { $ response = [ 'took' => 0 , 'timed_out' => false , '_shards' => [ 'total' => 0 , 'successful' => 0 , 'failed' => 0 , ] , 'hits' => [ 'total' => 0 , 'max_score' => null , 'hits' => [ ] , ] , 'params' => $ params , ] ; return new Response ( JSON :: stringify ( $ response ) ) ; }
Generate an example response object .
6,612
protected function _convertArrayable ( array $ array ) { $ arr = [ ] ; foreach ( $ array as $ key => $ value ) { if ( $ value instanceof ArrayableInterface ) { $ arr [ $ value instanceof NameableInterface ? $ value -> getName ( ) : $ key ] = $ value -> toArray ( ) ; } elseif ( \ is_array ( $ value ) ) { $ arr [ $ key ] = $ this -> _convertArrayable ( $ value ) ; } else { $ arr [ $ key ] = $ value ; } } return $ arr ; }
Cast objects to arrays .
6,613
public function getParam ( $ key ) { if ( ! $ this -> hasParam ( $ key ) ) { throw new InvalidException ( 'Param ' . $ key . ' does not exist' ) ; } return $ this -> _params [ $ key ] ; }
Returns a specific param .
6,614
public function setParam ( string $ key , $ value ) : Mapping { $ this -> _mapping [ $ key ] = $ value ; return $ this ; }
Sets raw parameters .
6,615
public function toArray ( ) : array { $ type = $ this -> getType ( ) ; if ( empty ( $ type ) ) { throw new InvalidException ( 'Type has to be set' ) ; } return [ $ type -> getName ( ) => $ this -> _mapping ] ; }
Converts the mapping to an array .
6,616
public function send ( array $ query = [ ] ) : Response { $ endpoint = new Put ( ) ; $ endpoint -> setBody ( $ this -> toArray ( ) ) ; $ endpoint -> setParams ( $ query ) ; return $ this -> getType ( ) -> requestEndpoint ( $ endpoint ) ; }
Submits the mapping and sends it to the server .
6,617
public static function create ( $ mapping ) : Mapping { if ( \ is_array ( $ mapping ) ) { $ mappingObject = new self ( ) ; $ mappingObject -> setProperties ( $ mapping ) ; return $ mappingObject ; } if ( $ mapping instanceof self ) { return $ mapping ; } throw new InvalidException ( 'Invalid object type' ) ; }
Creates a mapping object .
6,618
public function buildResultSet ( Response $ response , Query $ query ) : ResultSet { $ resultSet = $ this -> builder -> buildResultSet ( $ response , $ query ) ; $ this -> processor -> process ( $ resultSet ) ; return $ resultSet ; }
Runs any registered transformers on the ResultSet before returning it allowing the transformers to inject additional data into each Result .
6,619
public function addRange ( string $ fromValue = null , string $ toValue = null ) : self { if ( null === $ fromValue && null === $ toValue ) { throw new InvalidException ( 'Either fromValue or toValue must be set. Both cannot be null.' ) ; } $ range = [ ] ; if ( null !== $ fromValue ) { $ range [ 'from' ] = $ fromValue ; } if ( null !== $ toValue ) { $ range [ 'to' ] = $ toValue ; } return $ this -> addParam ( 'ranges' , $ range ) ; }
Add an ip range to this aggregation .
6,620
public function addAggregation ( AbstractAggregation $ aggregation ) : self { if ( $ aggregation instanceof GlobalAggregation ) { throw new InvalidException ( 'Global aggregators can only be placed as top level aggregators' ) ; } $ this -> _aggs [ ] = $ aggregation ; return $ this ; }
Add a sub - aggregation .
6,621
public function getError ( ) : string { foreach ( $ this -> getBulkResponses ( ) as $ bulkResponse ) { if ( $ bulkResponse -> hasError ( ) ) { return $ bulkResponse -> getError ( ) ; } } return '' ; }
Returns first found error .
6,622
public function addCoordinates ( string $ key , array $ coordinates ) : self { if ( ! isset ( $ coordinates [ 0 ] ) || ! isset ( $ coordinates [ 1 ] ) ) { throw new InvalidException ( 'expected $coordinates to be an array with two elements' ) ; } $ this -> setParam ( $ key , [ 'top_left' => $ coordinates [ 0 ] , 'bottom_right' => $ coordinates [ 1 ] , ] ) ; return $ this ; }
Add coordinates .
6,623
public function addDSL ( DSL $ dsl ) { $ this -> _facades [ $ dsl -> getType ( ) ] = new Facade ( $ dsl , $ this -> _version ) ; }
Adds a new DSL object .
6,624
public function updateByQuery ( $ query , AbstractScript $ script , array $ options = [ ] ) { $ query = Query :: create ( $ query ) -> getQuery ( ) ; $ endpoint = new UpdateByQuery ( ) ; $ body = [ 'query' => \ is_array ( $ query ) ? $ query : $ query -> toArray ( ) , ] ; $ body [ 'script' ] = $ script -> toArray ( ) [ 'script' ] ; $ endpoint -> setBody ( $ body ) ; $ endpoint -> setParams ( $ options ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Update entries in the db based on a query .
6,625
public function forcemerge ( $ args = [ ] ) { $ endpoint = new ForceMerge ( ) ; $ endpoint -> setParams ( $ args ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Force merges index .
6,626
public function create ( array $ args = [ ] , $ options = null ) { if ( \ is_bool ( $ options ) && $ options ) { try { $ this -> delete ( ) ; } catch ( ResponseException $ e ) { } } elseif ( \ is_array ( $ options ) ) { foreach ( $ options as $ key => $ value ) { switch ( $ key ) { case 'recreate' : try { $ this -> delete ( ) ; } catch ( ResponseException $ e ) { } break ; default : throw new InvalidException ( 'Invalid option ' . $ key ) ; break ; } } } $ endpoint = new Create ( ) ; $ endpoint -> setBody ( $ args ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Creates a new index with the given arguments .
6,627
public function addAlias ( $ name , $ replace = false ) { $ data = [ 'actions' => [ ] ] ; if ( $ replace ) { $ status = new Status ( $ this -> getClient ( ) ) ; foreach ( $ status -> getIndicesWithAlias ( $ name ) as $ index ) { $ data [ 'actions' ] [ ] = [ 'remove' => [ 'index' => $ index -> getName ( ) , 'alias' => $ name ] ] ; } } $ data [ 'actions' ] [ ] = [ 'add' => [ 'index' => $ this -> getName ( ) , 'alias' => $ name ] ] ; $ endpoint = new Update ( ) ; $ endpoint -> setBody ( $ data ) ; return $ this -> getClient ( ) -> requestEndpoint ( $ endpoint ) ; }
Adds an alias to the current index .
6,628
public function removeAlias ( $ name ) { $ endpoint = new \ Elasticsearch \ Endpoints \ Indices \ Alias \ Delete ( ) ; $ endpoint -> setName ( $ name ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Removes an alias pointing to the current index .
6,629
public function getAliases ( ) { $ endpoint = new \ Elasticsearch \ Endpoints \ Indices \ Alias \ Get ( ) ; $ endpoint -> setName ( '*' ) ; $ responseData = $ this -> requestEndpoint ( $ endpoint ) -> getData ( ) ; if ( ! isset ( $ responseData [ $ this -> getName ( ) ] ) ) { return [ ] ; } $ data = $ responseData [ $ this -> getName ( ) ] ; if ( ! empty ( $ data [ 'aliases' ] ) ) { return \ array_keys ( $ data [ 'aliases' ] ) ; } return [ ] ; }
Returns all index aliases .
6,630
public function flush ( array $ options = [ ] ) { $ endpoint = new Flush ( ) ; $ endpoint -> setParams ( $ options ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Flushes the index to storage .
6,631
public function setSettings ( array $ data ) { $ endpoint = new Put ( ) ; $ endpoint -> setBody ( $ data ) ; return $ this -> requestEndpoint ( $ endpoint ) ; }
Can be used to change settings during runtime . One example is to use it for bulk updating .
6,632
public function requestEndpoint ( AbstractEndpoint $ endpoint ) { $ cloned = clone $ endpoint ; $ cloned -> setIndex ( $ this -> getName ( ) ) ; return $ this -> getClient ( ) -> requestEndpoint ( $ cloned ) ; }
Makes calls to the elasticsearch server with usage official client Endpoint based on this index .
6,633
public function analyze ( array $ body , $ args = [ ] ) { $ endpoint = new Analyze ( ) ; $ endpoint -> setBody ( $ body ) ; $ endpoint -> setParams ( $ args ) ; $ data = $ this -> requestEndpoint ( $ endpoint ) -> getData ( ) ; if ( isset ( $ body [ 'explain' ] ) && $ body [ 'explain' ] ) { return $ data [ 'detail' ] ; } return $ data [ 'tokens' ] ; }
Analyzes a string .
6,634
public function buildResultSet ( Response $ response , Query $ query ) : ResultSet { $ results = $ this -> buildResults ( $ response ) ; $ resultSet = new ResultSet ( $ response , $ query , $ results ) ; return $ resultSet ; }
Builds a ResultSet for a given Response .
6,635
private function buildResults ( Response $ response ) : array { $ data = $ response -> getData ( ) ; $ results = [ ] ; if ( ! isset ( $ data [ 'hits' ] [ 'hits' ] ) ) { return $ results ; } foreach ( $ data [ 'hits' ] [ 'hits' ] as $ hit ) { $ results [ ] = new Result ( $ hit ) ; } return $ results ; }
Builds individual result objects .
6,636
public function setQueryParam ( string $ key , $ value ) : self { $ this -> _queryParams [ $ key ] = $ value ; return $ this ; }
Set a parameter in the body of this query .
6,637
public function setInclude ( string $ pattern , string $ flags = null ) : self { if ( null === $ flags ) { return $ this -> setParam ( 'include' , $ pattern ) ; } return $ this -> setParam ( 'include' , [ 'pattern' => $ pattern , 'flags' => $ flags , ] ) ; }
Filter documents to include based on a regular expression .
6,638
public function setExclude ( string $ pattern , string $ flags = null ) : self { if ( null === $ flags ) { return $ this -> setParam ( 'exclude' , $ pattern ) ; } return $ this -> setParam ( 'exclude' , [ 'pattern' => $ pattern , 'flags' => $ flags , ] ) ; }
Filter documents to exclude based on a regular expression .
6,639
protected function createCacheFile ( ) { $ this -> createCacheDir ( ) ; $ cacheFilePath = $ this -> getCacheFile ( ) ; if ( ! file_exists ( $ cacheFilePath ) ) { touch ( $ cacheFilePath ) ; } }
Create a cache file .
6,640
public function put ( string $ path , string $ contents ) : int { return file_put_contents ( $ path , $ contents , LOCK_EX ) ; }
Write the contents of a file with exclusive lock .
6,641
public function isValid ( string $ key ) : bool { $ key = $ this -> getActualCacheKey ( $ key ) ; $ meta = $ this -> getCacheContents ( ) [ $ key ] ?? [ ] ; if ( empty ( $ meta [ 'expires_at' ] ) ) { return false ; } return Carbon :: now ( ) < Carbon :: createFromFormat ( self :: RFC_7231 , $ meta [ 'expires_at' ] ) ; }
Check if cache is still valid .
6,642
public function getCacheContents ( ) { $ cacheFile = $ this -> getCacheFile ( ) ; if ( ! file_exists ( $ cacheFile ) ) { return false ; } return json_decode ( $ this -> sharedGet ( $ cacheFile ) , true ) ?? [ ] ; }
Get cache contents .
6,643
public function getActualCacheKey ( string $ key ) : string { $ prefix = $ this -> getPrefix ( ) ; if ( false === strpos ( $ key , $ prefix ) ) { $ key = $ prefix . $ key ; } return $ key ; }
Get actual cache key with prefix .
6,644
public function send ( $ content , int $ status = HttpResponse :: HTTP_OK , array $ headers = [ ] ) : HttpResponse { $ headers = array_merge ( $ this -> headers , $ headers ) ; if ( is_array ( $ content ) ) { $ content = json_encode ( $ content ) ; } $ response = $ this -> response -> create ( $ content , $ status , $ headers ) ; return $ this -> createOnly ? $ response : $ response -> send ( ) ; }
Create and send a response .
6,645
public function file ( string $ file , string $ name = null ) : self { $ this -> filePath = $ file ; if ( ! file_exists ( $ file ) || ! is_readable ( $ file ) ) { throw new FileException ( 'Cannot read file: ' . $ file ) ; } $ this -> fileName = $ name ?? basename ( $ this -> filePath ) ; $ this -> fileSize = filesize ( $ file ) ; return $ this ; }
Set file properties .
6,646
public function getChecksum ( ) : string { if ( empty ( $ this -> checksum ) ) { $ this -> setChecksum ( hash_file ( $ this -> getChecksumAlgorithm ( ) , $ this -> getFilePath ( ) ) ) ; } return $ this -> checksum ; }
Get checksum .
6,647
public function isExpired ( ) : bool { $ expiresAt = $ this -> getCache ( ) -> get ( $ this -> getKey ( ) ) [ 'expires_at' ] ?? null ; return empty ( $ expiresAt ) || Carbon :: parse ( $ expiresAt ) -> lt ( Carbon :: now ( ) ) ; }
Check if current upload is expired .
6,648
public function seek ( int $ offset ) : self { $ this -> partialOffset = $ offset ; $ this -> partial ( ) ; return $ this ; }
Set offset and force this to be a partial upload request .
6,649
public function create ( string $ key ) : string { $ headers = [ 'Upload-Length' => $ this -> fileSize , 'Upload-Key' => $ key , 'Upload-Checksum' => $ this -> getUploadChecksumHeader ( ) , 'Upload-Metadata' => 'filename ' . base64_encode ( $ this -> fileName ) , ] ; if ( $ this -> isPartial ( ) ) { $ headers += [ 'Upload-Concat' => 'partial' ] ; } $ response = $ this -> getClient ( ) -> post ( $ this -> apiPath , [ 'headers' => $ headers , ] ) ; $ statusCode = $ response -> getStatusCode ( ) ; if ( HttpResponse :: HTTP_CREATED !== $ statusCode ) { throw new FileException ( 'Unable to create resource.' ) ; } $ uploadLocation = current ( $ response -> getHeader ( 'location' ) ) ; $ this -> getCache ( ) -> set ( $ this -> getKey ( ) , [ 'location' => $ uploadLocation , 'expires_at' => Carbon :: now ( ) -> addSeconds ( $ this -> getCache ( ) -> getTtl ( ) ) -> format ( $ this -> getCache ( ) :: RFC_7231 ) , ] ) ; return $ uploadLocation ; }
Create resource with POST request .
6,650
public function concat ( string $ key , ... $ partials ) : string { $ response = $ this -> getClient ( ) -> post ( $ this -> apiPath , [ 'headers' => [ 'Upload-Length' => $ this -> fileSize , 'Upload-Key' => $ key , 'Upload-Checksum' => $ this -> getUploadChecksumHeader ( ) , 'Upload-Metadata' => 'filename ' . base64_encode ( $ this -> fileName ) , 'Upload-Concat' => self :: UPLOAD_TYPE_FINAL . ';' . implode ( ' ' , $ partials ) , ] , ] ) ; $ data = json_decode ( $ response -> getBody ( ) , true ) ; $ checksum = $ data [ 'data' ] [ 'checksum' ] ?? null ; $ statusCode = $ response -> getStatusCode ( ) ; if ( HttpResponse :: HTTP_CREATED !== $ statusCode || ! $ checksum ) { throw new FileException ( 'Unable to create resource.' ) ; } return $ checksum ; }
Concatenate 2 or more partial uploads .
6,651
public function delete ( ) { try { $ this -> getClient ( ) -> delete ( $ this -> getUrl ( ) ) ; } catch ( ClientException $ e ) { $ statusCode = $ e -> getResponse ( ) -> getStatusCode ( ) ; if ( HttpResponse :: HTTP_NOT_FOUND === $ statusCode || HttpResponse :: HTTP_GONE === $ statusCode ) { throw new FileException ( 'File not found.' ) ; } } }
Send DELETE request .
6,652
protected function partial ( bool $ state = true ) { $ this -> partial = $ state ; if ( ! $ this -> partial ) { return ; } $ key = $ this -> getKey ( ) ; if ( false !== strpos ( $ key , self :: PARTIAL_UPLOAD_NAME_SEPARATOR ) ) { list ( $ key , ) = explode ( self :: PARTIAL_UPLOAD_NAME_SEPARATOR , $ key ) ; } $ this -> key = $ key . uniqid ( self :: PARTIAL_UPLOAD_NAME_SEPARATOR ) ; }
Set as partial request .
6,653
protected function handleClientException ( ClientException $ e ) { $ statusCode = $ e -> getResponse ( ) -> getStatusCode ( ) ; if ( HttpResponse :: HTTP_REQUESTED_RANGE_NOT_SATISFIABLE === $ statusCode ) { return new FileException ( 'The uploaded file is corrupt.' ) ; } if ( HttpResponse :: HTTP_CONTINUE === $ statusCode ) { return new ConnectionException ( 'Connection aborted by user.' ) ; } if ( HttpResponse :: HTTP_UNSUPPORTED_MEDIA_TYPE === $ statusCode ) { return new TusException ( 'Unsupported media types.' ) ; } return new TusException ( $ e -> getResponse ( ) -> getBody ( ) , $ statusCode ) ; }
Handle client exception during patch request .
6,654
protected function getData ( int $ offset , int $ bytes ) : string { $ file = new File ; $ handle = $ file -> open ( $ this -> getFilePath ( ) , $ file :: READ_BINARY ) ; $ file -> seek ( $ handle , $ offset ) ; $ data = $ file -> read ( $ handle , $ bytes ) ; $ file -> close ( $ handle ) ; return ( string ) $ data ; }
Get X bytes of data from file .
6,655
public function setMeta ( int $ offset , int $ fileSize , string $ filePath , string $ location = null ) : self { $ this -> offset = $ offset ; $ this -> fileSize = $ fileSize ; $ this -> filePath = $ filePath ; $ this -> location = $ location ; return $ this ; }
Set file meta .
6,656
public function details ( ) : array { $ now = Carbon :: now ( ) ; return [ 'name' => $ this -> name , 'size' => $ this -> fileSize , 'offset' => $ this -> offset , 'checksum' => $ this -> checksum , 'location' => $ this -> location , 'file_path' => $ this -> filePath , 'created_at' => $ now -> format ( $ this -> cache :: RFC_7231 ) , 'expires_at' => $ now -> addSeconds ( $ this -> cache -> getTtl ( ) ) -> format ( $ this -> cache :: RFC_7231 ) , ] ; }
Get file meta .
6,657
public function upload ( int $ totalBytes ) : int { if ( $ this -> offset === $ totalBytes ) { return $ this -> offset ; } $ input = $ this -> open ( $ this -> getInputStream ( ) , self :: READ_BINARY ) ; $ output = $ this -> open ( $ this -> getFilePath ( ) , self :: APPEND_BINARY ) ; $ key = $ this -> getKey ( ) ; try { $ this -> seek ( $ output , $ this -> offset ) ; while ( ! feof ( $ input ) ) { if ( CONNECTION_NORMAL !== connection_status ( ) ) { throw new ConnectionException ( 'Connection aborted by user.' ) ; } $ data = $ this -> read ( $ input , self :: CHUNK_SIZE ) ; $ bytes = $ this -> write ( $ output , $ data , self :: CHUNK_SIZE ) ; $ this -> offset += $ bytes ; $ this -> cache -> set ( $ key , [ 'offset' => $ this -> offset ] ) ; if ( $ this -> offset > $ totalBytes ) { throw new OutOfRangeException ( 'The uploaded file is corrupt.' ) ; } if ( $ this -> offset === $ totalBytes ) { break ; } } } finally { $ this -> close ( $ input ) ; $ this -> close ( $ output ) ; } return $ this -> offset ; }
Upload file to server .
6,658
public function open ( string $ filePath , string $ mode ) { $ this -> exists ( $ filePath , $ mode ) ; $ ptr = @ fopen ( $ filePath , $ mode ) ; if ( false === $ ptr ) { throw new FileException ( "Unable to open $filePath." ) ; } return $ ptr ; }
Open file in given mode .
6,659
public function exists ( string $ filePath , string $ mode = self :: READ_BINARY ) : bool { if ( self :: INPUT_STREAM === $ filePath ) { return true ; } if ( self :: READ_BINARY === $ mode && ! file_exists ( $ filePath ) ) { throw new FileException ( 'File not found.' ) ; } return true ; }
Check if file to read exists .
6,660
public function seek ( $ handle , int $ offset , int $ whence = SEEK_SET ) : int { $ position = fseek ( $ handle , $ offset , $ whence ) ; if ( - 1 === $ position ) { throw new FileException ( 'Cannot move pointer to desired position.' ) ; } return $ position ; }
Move file pointer to given offset .
6,661
public function read ( $ handle , int $ chunkSize ) : string { $ data = fread ( $ handle , $ chunkSize ) ; if ( false === $ data ) { throw new FileException ( 'Cannot read file.' ) ; } return ( string ) $ data ; }
Read data from file .
6,662
public function write ( $ handle , string $ data , $ length = null ) : int { $ bytesWritten = is_int ( $ length ) ? fwrite ( $ handle , $ data , $ length ) : fwrite ( $ handle , $ data ) ; if ( false === $ bytesWritten ) { throw new FileException ( 'Cannot write to a file.' ) ; } return $ bytesWritten ; }
Write data to file .
6,663
public function merge ( array $ files ) : int { $ destination = $ this -> getFilePath ( ) ; $ firstFile = array_shift ( $ files ) ; $ this -> copy ( $ firstFile [ 'file_path' ] , $ destination ) ; $ this -> offset = $ firstFile [ 'offset' ] ; $ this -> fileSize = filesize ( $ firstFile [ 'file_path' ] ) ; $ handle = $ this -> open ( $ destination , self :: APPEND_BINARY ) ; foreach ( $ files as $ file ) { if ( ! file_exists ( $ file [ 'file_path' ] ) ) { throw new FileException ( 'File to be merged not found.' ) ; } $ this -> fileSize += $ this -> write ( $ handle , file_get_contents ( $ file [ 'file_path' ] ) ) ; $ this -> offset += $ file [ 'offset' ] ; } $ this -> close ( $ handle ) ; return $ this -> fileSize ; }
Merge 2 or more files .
6,664
public function copy ( string $ source , string $ destination ) : bool { $ status = @ copy ( $ source , $ destination ) ; if ( false === $ status ) { throw new FileException ( 'Cannot copy source to destination.' ) ; } return $ status ; }
Copy file from source to destination .
6,665
public function deleteFiles ( array $ files ) : bool { if ( empty ( $ files ) ) { return false ; } $ status = true ; foreach ( $ files as $ file ) { if ( file_exists ( $ file ) ) { $ status = $ status && unlink ( $ file ) ; } } return $ status ; }
Delete multiple files .
6,666
public function allowedHttpVerbs ( ) : array { return [ HttpRequest :: METHOD_GET , HttpRequest :: METHOD_POST , HttpRequest :: METHOD_PATCH , HttpRequest :: METHOD_DELETE , HttpRequest :: METHOD_HEAD , HttpRequest :: METHOD_OPTIONS , ] ; }
Supported http requests .
6,667
public function extractFromHeader ( string $ key , string $ value ) : array { $ meta = $ this -> header ( $ key ) ; if ( false !== strpos ( $ meta , $ value ) ) { $ meta = trim ( str_replace ( $ value , '' , $ meta ) ) ; return explode ( ' ' , $ meta ) ?? [ ] ; } return [ ] ; }
Extract metadata from header .
6,668
public function extractMeta ( string $ requestedKey ) : string { $ uploadMetaData = $ this -> request -> headers -> get ( 'Upload-Metadata' ) ; if ( empty ( $ uploadMetaData ) ) { return '' ; } $ uploadMetaDataChunks = explode ( ',' , $ uploadMetaData ) ; foreach ( $ uploadMetaDataChunks as $ chunk ) { list ( $ key , $ value ) = explode ( ' ' , $ chunk ) ; if ( $ key === $ requestedKey ) { return base64_decode ( $ value ) ; } } return '' ; }
Extracts the meta data from the request header .
6,669
public function deleteAll ( array $ keys ) : bool { if ( empty ( $ keys ) ) { return false ; } $ status = true ; foreach ( $ keys as $ key ) { $ status = $ status && $ this -> delete ( $ key ) ; } return $ status ; }
Delete all keys .
6,670
public function add ( ... $ middleware ) : self { foreach ( $ middleware as $ m ) { if ( $ m instanceof TusMiddleware ) { $ this -> globalMiddleware [ get_class ( $ m ) ] = $ m ; } elseif ( is_string ( $ m ) ) { $ this -> globalMiddleware [ $ m ] = new $ m ; } } return $ this ; }
Set middleware .
6,671
public function skip ( ... $ middleware ) : self { foreach ( $ middleware as $ m ) { unset ( $ this -> globalMiddleware [ $ m ] ) ; } return $ this ; }
Skip middleware .
6,672
public function getChecksumAlgorithm ( ) : ? string { $ checksumHeader = $ this -> getRequest ( ) -> header ( 'Upload-Checksum' ) ; if ( empty ( $ checksumHeader ) ) { return self :: DEFAULT_CHECKSUM_ALGORITHM ; } list ( $ checksumAlgorithm , ) = explode ( ' ' , $ checksumHeader ) ; return $ checksumAlgorithm ; }
Get checksum algorithm .
6,673
public function getUploadKey ( ) { if ( ! empty ( $ this -> uploadKey ) ) { return $ this -> uploadKey ; } $ key = $ this -> getRequest ( ) -> header ( 'Upload-Key' ) ?? Uuid :: uuid4 ( ) -> toString ( ) ; if ( empty ( $ key ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_BAD_REQUEST ) ; } $ this -> uploadKey = $ key ; return $ this -> uploadKey ; }
Get upload key from header .
6,674
public function serve ( ) { $ this -> applyMiddleware ( ) ; $ requestMethod = $ this -> getRequest ( ) -> method ( ) ; if ( ! in_array ( $ requestMethod , $ this -> getRequest ( ) -> allowedHttpVerbs ( ) ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_METHOD_NOT_ALLOWED ) ; } $ clientVersion = $ this -> getRequest ( ) -> header ( 'Tus-Resumable' ) ; if ( $ clientVersion && $ clientVersion !== self :: TUS_PROTOCOL_VERSION ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_PRECONDITION_FAILED , [ 'Tus-Version' => self :: TUS_PROTOCOL_VERSION , ] ) ; } $ method = 'handle' . ucfirst ( strtolower ( $ requestMethod ) ) ; return $ this -> { $ method } ( ) ; }
Handle all HTTP request .
6,675
protected function applyMiddleware ( ) { $ middleware = $ this -> middleware ( ) -> list ( ) ; foreach ( $ middleware as $ m ) { $ m -> handle ( $ this -> getRequest ( ) , $ this -> getResponse ( ) ) ; } }
Apply middleware .
6,676
protected function handleOptions ( ) : HttpResponse { $ headers = [ 'Allow' => implode ( ',' , $ this -> request -> allowedHttpVerbs ( ) ) , 'Tus-Version' => self :: TUS_PROTOCOL_VERSION , 'Tus-Extension' => implode ( ',' , self :: TUS_EXTENSIONS ) , 'Tus-Checksum-Algorithm' => $ this -> getSupportedHashAlgorithms ( ) , ] ; $ maxUploadSize = $ this -> getMaxUploadSize ( ) ; if ( $ maxUploadSize > 0 ) { $ headers [ 'Tus-Max-Size' ] = $ maxUploadSize ; } return $ this -> response -> send ( null , HttpResponse :: HTTP_OK , $ headers ) ; }
Handle OPTIONS request .
6,677
protected function handleHead ( ) : HttpResponse { $ key = $ this -> request -> key ( ) ; if ( ! $ fileMeta = $ this -> cache -> get ( $ key ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_NOT_FOUND ) ; } $ offset = $ fileMeta [ 'offset' ] ?? false ; if ( false === $ offset ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_GONE ) ; } return $ this -> response -> send ( null , HttpResponse :: HTTP_OK , $ this -> getHeadersForHeadRequest ( $ fileMeta ) ) ; }
Handle HEAD request .
6,678
protected function handlePost ( ) : HttpResponse { $ fileName = $ this -> getRequest ( ) -> extractFileName ( ) ; $ uploadType = self :: UPLOAD_TYPE_NORMAL ; if ( empty ( $ fileName ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_BAD_REQUEST ) ; } if ( ! $ this -> verifyUploadSize ( ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_REQUEST_ENTITY_TOO_LARGE ) ; } $ uploadKey = $ this -> getUploadKey ( ) ; $ filePath = $ this -> uploadDir . DIRECTORY_SEPARATOR . $ fileName ; if ( $ this -> getRequest ( ) -> isFinal ( ) ) { return $ this -> handleConcatenation ( $ fileName , $ filePath ) ; } if ( $ this -> getRequest ( ) -> isPartial ( ) ) { $ filePath = $ this -> getPathForPartialUpload ( $ uploadKey ) . $ fileName ; $ uploadType = self :: UPLOAD_TYPE_PARTIAL ; } $ checksum = $ this -> getClientChecksum ( ) ; $ location = $ this -> getRequest ( ) -> url ( ) . $ this -> getApiPath ( ) . '/' . $ uploadKey ; $ file = $ this -> buildFile ( [ 'name' => $ fileName , 'offset' => 0 , 'size' => $ this -> getRequest ( ) -> header ( 'Upload-Length' ) , 'file_path' => $ filePath , 'location' => $ location , ] ) -> setKey ( $ uploadKey ) -> setChecksum ( $ checksum ) ; $ this -> cache -> set ( $ uploadKey , $ file -> details ( ) + [ 'upload_type' => $ uploadType ] ) ; $ this -> event ( ) -> dispatch ( UploadCreated :: NAME , new UploadCreated ( $ file , $ this -> getRequest ( ) , $ this -> getResponse ( ) ) ) ; return $ this -> response -> send ( null , HttpResponse :: HTTP_CREATED , [ 'Location' => $ location , 'Upload-Expires' => $ this -> cache -> get ( $ uploadKey ) [ 'expires_at' ] , ] ) ; }
Handle POST request .
6,679
protected function handleConcatenation ( string $ fileName , string $ filePath ) : HttpResponse { $ partials = $ this -> getRequest ( ) -> extractPartials ( ) ; $ uploadKey = $ this -> getUploadKey ( ) ; $ files = $ this -> getPartialsMeta ( $ partials ) ; $ filePaths = array_column ( $ files , 'file_path' ) ; $ location = $ this -> getRequest ( ) -> url ( ) . $ this -> getApiPath ( ) . '/' . $ uploadKey ; $ file = $ this -> buildFile ( [ 'name' => $ fileName , 'offset' => 0 , 'size' => 0 , 'file_path' => $ filePath , 'location' => $ location , ] ) -> setFilePath ( $ filePath ) -> setKey ( $ uploadKey ) ; $ file -> setOffset ( $ file -> merge ( $ files ) ) ; $ checksum = $ this -> getServerChecksum ( $ filePath ) ; if ( $ checksum !== $ this -> getClientChecksum ( ) ) { return $ this -> response -> send ( null , self :: HTTP_CHECKSUM_MISMATCH ) ; } $ file -> setChecksum ( $ checksum ) ; $ this -> cache -> set ( $ uploadKey , $ file -> details ( ) + [ 'upload_type' => self :: UPLOAD_TYPE_FINAL ] ) ; if ( $ file -> delete ( $ filePaths , true ) ) { $ this -> cache -> deleteAll ( $ partials ) ; } $ this -> event ( ) -> dispatch ( UploadMerged :: NAME , new UploadMerged ( $ file , $ this -> getRequest ( ) , $ this -> getResponse ( ) ) ) ; return $ this -> response -> send ( [ 'data' => [ 'checksum' => $ checksum ] ] , HttpResponse :: HTTP_CREATED , [ 'Location' => $ location , ] ) ; }
Handle file concatenation .
6,680
protected function handlePatch ( ) : HttpResponse { $ uploadKey = $ this -> request -> key ( ) ; if ( ! $ meta = $ this -> cache -> get ( $ uploadKey ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_GONE ) ; } $ status = $ this -> verifyPatchRequest ( $ meta ) ; if ( HttpResponse :: HTTP_OK !== $ status ) { return $ this -> response -> send ( null , $ status ) ; } $ file = $ this -> buildFile ( $ meta ) ; $ checksum = $ meta [ 'checksum' ] ; try { $ fileSize = $ file -> getFileSize ( ) ; $ offset = $ file -> setKey ( $ uploadKey ) -> setChecksum ( $ checksum ) -> upload ( $ fileSize ) ; if ( $ offset === $ fileSize ) { if ( ! $ this -> verifyChecksum ( $ checksum , $ meta [ 'file_path' ] ) ) { return $ this -> response -> send ( null , self :: HTTP_CHECKSUM_MISMATCH ) ; } $ this -> event ( ) -> dispatch ( UploadComplete :: NAME , new UploadComplete ( $ file , $ this -> getRequest ( ) , $ this -> getResponse ( ) ) ) ; } else { $ this -> event ( ) -> dispatch ( UploadProgress :: NAME , new UploadProgress ( $ file , $ this -> getRequest ( ) , $ this -> getResponse ( ) ) ) ; } } catch ( FileException $ e ) { return $ this -> response -> send ( $ e -> getMessage ( ) , HttpResponse :: HTTP_UNPROCESSABLE_ENTITY ) ; } catch ( OutOfRangeException $ e ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_REQUESTED_RANGE_NOT_SATISFIABLE ) ; } catch ( ConnectionException $ e ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_CONTINUE ) ; } return $ this -> response -> send ( null , HttpResponse :: HTTP_NO_CONTENT , [ 'Content-Type' => self :: HEADER_CONTENT_TYPE , 'Upload-Expires' => $ this -> cache -> get ( $ uploadKey ) [ 'expires_at' ] , 'Upload-Offset' => $ offset , ] ) ; }
Handle PATCH request .
6,681
protected function verifyPatchRequest ( array $ meta ) : int { if ( self :: UPLOAD_TYPE_FINAL === $ meta [ 'upload_type' ] ) { return HttpResponse :: HTTP_FORBIDDEN ; } $ uploadOffset = $ this -> request -> header ( 'upload-offset' ) ; if ( $ uploadOffset && $ uploadOffset !== ( string ) $ meta [ 'offset' ] ) { return HttpResponse :: HTTP_CONFLICT ; } $ contentType = $ this -> request -> header ( 'Content-Type' ) ; if ( $ contentType !== self :: HEADER_CONTENT_TYPE ) { return HTTPRESPONSE :: HTTP_UNSUPPORTED_MEDIA_TYPE ; } return HttpResponse :: HTTP_OK ; }
Verify PATCH request .
6,682
protected function handleDownload ( ) { $ path = explode ( '/' , str_replace ( '/get' , '' , $ this -> request -> path ( ) ) ) ; $ key = end ( $ path ) ; if ( ! $ fileMeta = $ this -> cache -> get ( $ key ) ) { return $ this -> response -> send ( '404 upload not found.' , HttpResponse :: HTTP_NOT_FOUND ) ; } $ resource = $ fileMeta [ 'file_path' ] ?? null ; $ fileName = $ fileMeta [ 'name' ] ?? null ; if ( ! $ resource || ! file_exists ( $ resource ) ) { return $ this -> response -> send ( '404 upload not found.' , HttpResponse :: HTTP_NOT_FOUND ) ; } return $ this -> response -> download ( $ resource , $ fileName ) ; }
Handle Download request .
6,683
protected function handleDelete ( ) : HttpResponse { $ key = $ this -> request -> key ( ) ; $ fileMeta = $ this -> cache -> get ( $ key ) ; $ resource = $ fileMeta [ 'file_path' ] ?? null ; if ( ! $ resource ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_NOT_FOUND ) ; } $ isDeleted = $ this -> cache -> delete ( $ key ) ; if ( ! $ isDeleted || ! file_exists ( $ resource ) ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_GONE ) ; } unlink ( $ resource ) ; return $ this -> response -> send ( null , HttpResponse :: HTTP_NO_CONTENT , [ 'Tus-Extension' => self :: TUS_EXTENSION_TERMINATION , ] ) ; }
Handle DELETE request .
6,684
protected function getHeadersForHeadRequest ( array $ fileMeta ) : array { $ headers = [ 'Upload-Length' => ( int ) $ fileMeta [ 'size' ] , 'Upload-Offset' => ( int ) $ fileMeta [ 'offset' ] , 'Cache-Control' => 'no-store' , ] ; if ( self :: UPLOAD_TYPE_FINAL === $ fileMeta [ 'upload_type' ] && $ fileMeta [ 'size' ] !== $ fileMeta [ 'offset' ] ) { unset ( $ headers [ 'Upload-Offset' ] ) ; } if ( self :: UPLOAD_TYPE_NORMAL !== $ fileMeta [ 'upload_type' ] ) { $ headers += [ 'Upload-Concat' => $ fileMeta [ 'upload_type' ] ] ; } return $ headers ; }
Get required headers for head request .
6,685
protected function buildFile ( array $ meta ) : File { $ file = new File ( $ meta [ 'name' ] , $ this -> cache ) ; if ( array_key_exists ( 'offset' , $ meta ) ) { $ file -> setMeta ( $ meta [ 'offset' ] , $ meta [ 'size' ] , $ meta [ 'file_path' ] , $ meta [ 'location' ] ) ; } return $ file ; }
Build file object .
6,686
protected function getSupportedHashAlgorithms ( ) : string { $ supportedAlgorithms = hash_algos ( ) ; $ algorithms = [ ] ; foreach ( $ supportedAlgorithms as $ hashAlgo ) { if ( false !== strpos ( $ hashAlgo , ',' ) ) { $ algorithms [ ] = "'{$hashAlgo}'" ; } else { $ algorithms [ ] = $ hashAlgo ; } } return implode ( ',' , $ algorithms ) ; }
Get list of supported hash algorithms .
6,687
protected function getClientChecksum ( ) { $ checksumHeader = $ this -> getRequest ( ) -> header ( 'Upload-Checksum' ) ; if ( empty ( $ checksumHeader ) ) { return '' ; } list ( $ checksumAlgorithm , $ checksum ) = explode ( ' ' , $ checksumHeader ) ; $ checksum = base64_decode ( $ checksum ) ; if ( ! in_array ( $ checksumAlgorithm , hash_algos ( ) ) || false === $ checksum ) { return $ this -> response -> send ( null , HttpResponse :: HTTP_BAD_REQUEST ) ; } return $ checksum ; }
Verify and get upload checksum from header .
6,688
protected function isExpired ( $ contents ) : bool { $ isExpired = empty ( $ contents [ 'expires_at' ] ) || Carbon :: parse ( $ contents [ 'expires_at' ] ) -> lt ( Carbon :: now ( ) ) ; if ( $ isExpired && $ contents [ 'offset' ] !== $ contents [ 'size' ] ) { return true ; } return false ; }
Get expired but incomplete uploads .
6,689
protected function getPathForPartialUpload ( string $ key ) : string { list ( $ actualKey , ) = explode ( self :: PARTIAL_UPLOAD_NAME_SEPARATOR , $ key ) ; $ path = $ this -> uploadDir . DIRECTORY_SEPARATOR . $ actualKey . DIRECTORY_SEPARATOR ; if ( ! file_exists ( $ path ) ) { mkdir ( $ path ) ; } return $ path ; }
Get path for partial upload .
6,690
protected function getPartialsMeta ( array $ partials ) : array { $ files = [ ] ; foreach ( $ partials as $ partial ) { $ fileMeta = $ this -> getCache ( ) -> get ( $ partial ) ; $ files [ ] = $ fileMeta ; } return $ files ; }
Get metadata of partials .
6,691
public function handleExpiration ( ) : array { $ deleted = [ ] ; $ cacheKeys = $ this -> cache -> keys ( ) ; foreach ( $ cacheKeys as $ key ) { $ fileMeta = $ this -> cache -> get ( $ key , true ) ; if ( ! $ this -> isExpired ( $ fileMeta ) ) { continue ; } if ( ! $ this -> cache -> delete ( $ key ) ) { continue ; } if ( is_writable ( $ fileMeta [ 'file_path' ] ) ) { unlink ( $ fileMeta [ 'file_path' ] ) ; } $ deleted [ ] = $ fileMeta ; } return $ deleted ; }
Delete expired resources .
6,692
protected function verifyUploadSize ( ) : bool { $ maxUploadSize = $ this -> getMaxUploadSize ( ) ; if ( $ maxUploadSize > 0 && $ this -> getRequest ( ) -> header ( 'Upload-Length' ) > $ maxUploadSize ) { return false ; } return true ; }
Verify max upload size .
6,693
protected function verifyChecksum ( string $ checksum , string $ filePath ) : bool { if ( empty ( $ checksum ) ) { return true ; } return $ checksum === $ this -> getServerChecksum ( $ filePath ) ; }
Verify checksum if available .
6,694
public static function set ( $ config = null , bool $ force = false ) { if ( ! $ force && ! empty ( self :: $ config ) ) { return ; } if ( is_array ( $ config ) ) { self :: $ config = $ config ; } else { self :: $ config = require $ config ?? self :: DEFAULT_CONFIG_PATH ; } }
Load default application configs .
6,695
public static function get ( string $ key = null ) { self :: set ( ) ; if ( empty ( $ key ) ) { return self :: $ config ; } $ keys = explode ( '.' , $ key ) ; $ value = self :: $ config ; foreach ( $ keys as $ key ) { if ( ! isset ( $ value [ $ key ] ) ) { return null ; } $ value = $ value [ $ key ] ; } return $ value ; }
Get config .
6,696
protected function stripComments ( ) { $ minifier = $ this ; $ callback = function ( $ match ) use ( $ minifier ) { $ count = count ( $ minifier -> extracted ) ; $ placeholder = '/*' . $ count . '*/' ; $ minifier -> extracted [ $ placeholder ] = $ match [ 0 ] ; return $ placeholder ; } ; $ this -> registerPattern ( '/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s' , $ callback ) ; $ this -> registerPattern ( '/\/\*.*?\*\//s' , '' ) ; $ this -> registerPattern ( '/\/\/.*$/m' , '' ) ; }
Strip comments from source code .
6,697
protected function canImportFile ( $ path ) { $ parsed = parse_url ( $ path ) ; if ( isset ( $ parsed [ 'host' ] ) || isset ( $ parsed [ 'query' ] ) ) { return false ; } return strlen ( $ path ) < PHP_MAXPATHLEN && @ is_file ( $ path ) && is_readable ( $ path ) ; }
Check if the path is a regular file and can be read .
6,698
public function makeClassName ( ) { $ parts = array_map ( 'studly_case' , explode ( '\\' , $ this -> argument ( 'name' ) ) ) ; $ className = array_pop ( $ parts ) ; $ ns = count ( $ parts ) > 0 ? implode ( '\\' , $ parts ) . '\\' : '' ; $ fqClass = config ( 'eloquentfilter.namespace' , 'App\\ModelFilters\\' ) . $ ns . $ className ; if ( substr ( $ fqClass , - 6 , 6 ) !== 'Filter' ) { $ fqClass .= 'Filter' ; } if ( class_exists ( $ fqClass ) ) { $ this -> error ( "\n\n\t$fqClass Already Exists!\n" ) ; die ; } $ this -> setClassName ( $ fqClass ) ; return $ this ; }
Create Filter Class Name .
6,699
public function removeEmptyInput ( $ input ) { $ filterableInput = [ ] ; foreach ( $ input as $ key => $ val ) { if ( $ val !== '' && $ val !== null ) { $ filterableInput [ $ key ] = $ val ; } } return $ filterableInput ; }
Remove empty strings from the input array .