idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
45,000
private function parameterBuilder ( $ parameters ) { foreach ( get_object_vars ( $ this ) as $ variable => $ value ) { if ( ! in_array ( $ variable , $ this -> exceptions ) ) { if ( $ value !== null ) { if ( is_bool ( $ value ) ) { $ value = $ value ? 'true' : 'false' ; } switch ( $ variable ) { case 'location' : if ( is_array ( $ value ) ) { $ value = array_values ( $ value ) ; $ value = $ value [ 0 ] . ',' . $ value [ 1 ] ; } break ; case 'rankby' : $ value = strtolower ( $ value ) ; if ( ! in_array ( $ value , array ( 'prominence' , 'distance' ) ) ) { throw new \ Exception ( 'Invalid rank by value, please specify either "prominence" or "distance".' ) ; } break ; case 'types' : if ( is_array ( $ value ) ) { $ value = implode ( '|' , $ value ) ; } break ; } $ parameters [ $ variable ] = $ value ; } } } return $ parameters ; }
Loops through all of our variables to make a parameter list
45,001
private function methodChecker ( $ parameters , $ method ) { if ( ! isset ( $ parameters [ 'pagetoken' ] ) ) { switch ( $ method ) { case 'nearbysearch' : if ( ! isset ( $ parameters [ 'location' ] ) ) { throw new \ Exception ( 'You must specify a location before calling nearbysearch().' ) ; } elseif ( isset ( $ parameters [ 'rankby' ] ) ) { switch ( $ parameters [ 'rankby' ] ) { case 'distance' : if ( ! isset ( $ parameters [ 'keyword' ] ) && ! isset ( $ parameters [ 'name' ] ) && ! isset ( $ parameters [ 'types' ] ) ) { throw new \ Exception ( 'You much specify at least one of the following: "keyword", "name", "types".' ) ; } if ( isset ( $ parameters [ 'radius' ] ) ) { unset ( $ this -> radius , $ parameters [ 'radius' ] ) ; } break ; case 'prominence' : if ( ! isset ( $ parameters [ 'radius' ] ) ) { throw new \ Exception ( 'You must specify a radius.' ) ; } break ; } } break ; case 'radarsearch' : if ( ! isset ( $ parameters [ 'location' ] ) ) { throw new \ Exception ( 'You must specify a location before calling radarsearch().' ) ; } elseif ( ! isset ( $ parameters [ 'radius' ] ) ) { throw new \ Exception ( 'You must specify a radius.' ) ; } elseif ( empty ( $ parameters [ 'keyword' ] ) && empty ( $ parameters [ 'name' ] ) && empty ( $ parameters [ 'types' ] ) ) { throw new \ Exception ( 'You much specify at least one of the following: "keyword", "name", "types".' ) ; } if ( isset ( $ parameters [ 'rankby' ] ) ) { unset ( $ this -> rankby , $ parameters [ 'rankby' ] ) ; } break ; case 'details' : if ( ! ( isset ( $ parameters [ 'reference' ] ) ^ isset ( $ parameters [ 'placeid' ] ) ) ) { throw new \ Exception ( 'You must specify either a "placeid" or a "reference" (but not both) before calling details().' ) ; } if ( isset ( $ parameters [ 'rankby' ] ) ) { unset ( $ this -> rankby , $ parameters [ 'rankby' ] ) ; } break ; } } return $ parameters ; }
takes the parameters and method to throw exceptions or modify parameters as needed
45,002
private function queryGoogle ( $ url , $ parameters ) { if ( $ this -> pagetoken !== null ) { $ parameters [ 'pagetoken' ] = $ this -> pagetoken ; sleep ( $ this -> sleep ) ; } $ querystring = '' ; foreach ( $ parameters as $ variable => $ value ) { if ( $ querystring != '' ) { $ querystring .= '&' ; } $ querystring .= $ variable . '=' . $ value ; } $ response = $ this -> client -> get ( $ url . '?' . $ querystring ) ; if ( $ this -> output == 'json' ) { $ response = json_decode ( $ response , true ) ; if ( $ response === null ) { throw new \ Exception ( 'The returned JSON was malformed or nonexistent.' ) ; } } else { throw new \ Exception ( 'XML is terrible, don\'t use it, ever.' ) ; } $ this -> response = $ response ; return $ this -> response ; }
Submits request via curl sets the response then returns the response
45,003
private function subdivide ( $ url , $ parameters ) { if ( $ this -> subradius < 200 ) { throw new \ Exception ( 'Subradius should be at least 200 meters.' ) ; } $ quotient = $ parameters [ 'radius' ] / $ this -> subradius ; if ( $ parameters [ 'radius' ] % $ this -> subradius || $ quotient % 2 ) { throw new \ Exception ( 'Subradius should divide evenly into radius.' ) ; } $ center = explode ( ',' , $ parameters [ 'location' ] ) ; $ centerlat = $ center [ 0 ] ; $ centerlng = $ center [ 1 ] ; $ count = $ quotient ; $ lati = $ this -> meters2lat ( $ this -> subradius * 2 ) ; $ this -> grid [ 'results' ] = array ( ) ; for ( $ i = $ count / 2 * - 1 ; $ i <= $ count / 2 ; $ i ++ ) { $ lat = $ centerlat + $ i * $ lati ; $ lngi = $ this -> meters2lng ( $ this -> subradius * 2 , $ lat ) ; for ( $ j = $ count / 2 * - 1 ; $ j <= $ count / 2 ; $ j ++ ) { $ lng = $ centerlng + $ j * $ lngi ; $ loc = $ lat . ',' . $ lng ; $ parameters [ 'location' ] = $ loc ; $ parameters [ 'radius' ] = $ this -> subradius ; $ pagetoken = true ; while ( $ pagetoken ) { $ this -> queryGoogle ( $ url , $ parameters ) ; $ this -> grid [ $ i ] [ $ j ] = $ this -> response ; $ this -> grid [ 'results' ] = array_merge ( $ this -> grid [ 'results' ] , $ this -> response [ 'results' ] ) ; if ( isset ( $ this -> response [ 'next_page_token' ] ) ) { $ this -> pagetoken = $ this -> response [ 'next_page_token' ] ; } else { $ this -> pagetoken = null ; $ pagetoken = false ; } } } } return $ this -> grid ; }
Returns the aggregated responses for a subdivided search
45,004
protected function readResponse ( RequestInterface $ request , $ socket ) : ResponseInterface { $ headers = [ ] ; $ reason = null ; while ( false !== ( $ line = fgets ( $ socket ) ) ) { if ( '' === rtrim ( $ line ) ) { break ; } $ headers [ ] = trim ( $ line ) ; } $ metadatas = stream_get_meta_data ( $ socket ) ; if ( array_key_exists ( 'timed_out' , $ metadatas ) && true === $ metadatas [ 'timed_out' ] ) { throw new TimeoutException ( 'Error while reading response, stream timed out' , $ request , null ) ; } $ parts = explode ( ' ' , array_shift ( $ headers ) , 3 ) ; if ( count ( $ parts ) <= 1 ) { throw new BrokenPipeException ( 'Cannot read the response' , $ request ) ; } $ protocol = substr ( $ parts [ 0 ] , - 3 ) ; $ status = $ parts [ 1 ] ; if ( isset ( $ parts [ 2 ] ) ) { $ reason = $ parts [ 2 ] ; } $ responseHeaders = [ ] ; foreach ( $ headers as $ header ) { $ headerParts = explode ( ':' , $ header , 2 ) ; if ( ! array_key_exists ( trim ( $ headerParts [ 0 ] ) , $ responseHeaders ) ) { $ responseHeaders [ trim ( $ headerParts [ 0 ] ) ] = [ ] ; } $ responseHeaders [ trim ( $ headerParts [ 0 ] ) ] [ ] = isset ( $ headerParts [ 1 ] ) ? trim ( $ headerParts [ 1 ] ) : '' ; } $ response = new Response ( $ status , $ responseHeaders , null , $ protocol , $ reason ) ; $ stream = $ this -> createStream ( $ socket , $ request , $ response ) ; return $ response -> withBody ( $ stream ) ; }
Read a response from a socket .
45,005
protected function createStream ( $ socket , RequestInterface $ request , ResponseInterface $ response ) : Stream { $ size = null ; if ( $ response -> hasHeader ( 'Content-Length' ) ) { $ size = ( int ) $ response -> getHeaderLine ( 'Content-Length' ) ; } return new Stream ( $ request , $ socket , $ size ) ; }
Create the stream .
45,006
protected function createSocket ( RequestInterface $ request , string $ remote , bool $ useSsl ) { $ errNo = null ; $ errMsg = null ; $ socket = @ stream_socket_client ( $ remote , $ errNo , $ errMsg , floor ( $ this -> config [ 'timeout' ] / 1000 ) , STREAM_CLIENT_CONNECT , $ this -> config [ 'stream_context' ] ) ; if ( false === $ socket ) { if ( 110 === $ errNo ) { throw new TimeoutException ( $ errMsg , $ request ) ; } throw new ConnectionException ( $ errMsg , $ request ) ; } stream_set_timeout ( $ socket , floor ( $ this -> config [ 'timeout' ] / 1000 ) , $ this -> config [ 'timeout' ] % 1000 ) ; if ( $ useSsl && false === @ stream_socket_enable_crypto ( $ socket , true , $ this -> config [ 'ssl_method' ] ) ) { throw new SSLConnectionException ( sprintf ( 'Cannot enable tls: %s' , error_get_last ( ) [ 'message' ] ) , $ request ) ; } return $ socket ; }
Create the socket to write request and read response on it .
45,007
protected function configure ( array $ config = [ ] ) { $ resolver = new OptionsResolver ( ) ; $ resolver -> setDefaults ( $ this -> config ) ; $ resolver -> setDefault ( 'stream_context' , function ( Options $ options ) { return stream_context_create ( $ options [ 'stream_context_options' ] , $ options [ 'stream_context_param' ] ) ; } ) ; $ resolver -> setDefault ( 'timeout' , ini_get ( 'default_socket_timeout' ) * 1000 ) ; $ resolver -> setAllowedTypes ( 'stream_context_options' , 'array' ) ; $ resolver -> setAllowedTypes ( 'stream_context_param' , 'array' ) ; $ resolver -> setAllowedTypes ( 'stream_context' , 'resource' ) ; $ resolver -> setAllowedTypes ( 'ssl' , [ 'bool' , 'null' ] ) ; return $ resolver -> resolve ( $ config ) ; }
Return configuration for the socket client .
45,008
private function determineRemoteFromRequest ( RequestInterface $ request ) { if ( ! $ request -> hasHeader ( 'Host' ) && '' === $ request -> getUri ( ) -> getHost ( ) ) { throw new InvalidRequestException ( 'Remote is not defined and we cannot determine a connection endpoint for this request (no Host header)' , $ request ) ; } $ host = $ request -> getUri ( ) -> getHost ( ) ; $ port = $ request -> getUri ( ) -> getPort ( ) ? : ( 'https' === $ request -> getUri ( ) -> getScheme ( ) ? 443 : 80 ) ; $ endpoint = sprintf ( '%s:%s' , $ host , $ port ) ; if ( empty ( $ host ) && $ request -> hasHeader ( 'Host' ) ) { $ endpoint = $ request -> getHeaderLine ( 'Host' ) ; } if ( $ this -> hasAsync ) { return sprintf ( 'async-tcp://%s' , $ endpoint ) ; } return sprintf ( 'tcp://%s' , $ endpoint ) ; }
Return remote socket from the request .
45,009
protected function writeRequest ( $ socket , RequestInterface $ request , int $ bufferSize = 8192 ) { if ( false === $ this -> fwrite ( $ socket , $ this -> transformRequestHeadersToString ( $ request ) ) ) { throw new BrokenPipeException ( 'Failed to send request, underlying socket not accessible, (BROKEN EPIPE)' , $ request ) ; } if ( $ request -> getBody ( ) -> isReadable ( ) ) { $ this -> writeBody ( $ socket , $ request , $ bufferSize ) ; } }
Write a request to a socket .
45,010
protected function writeBody ( $ socket , RequestInterface $ request , int $ bufferSize = 8192 ) { $ body = $ request -> getBody ( ) ; if ( $ body -> isSeekable ( ) ) { $ body -> rewind ( ) ; } while ( ! $ body -> eof ( ) ) { $ buffer = $ body -> read ( $ bufferSize ) ; if ( false === $ this -> fwrite ( $ socket , $ buffer ) ) { throw new BrokenPipeException ( 'An error occur when writing request to client (BROKEN EPIPE)' , $ request ) ; } } }
Write Body of the request .
45,011
protected function transformRequestHeadersToString ( RequestInterface $ request ) : string { $ message = vsprintf ( '%s %s HTTP/%s' , [ strtoupper ( $ request -> getMethod ( ) ) , $ request -> getRequestTarget ( ) , $ request -> getProtocolVersion ( ) , ] ) . "\r\n" ; foreach ( $ request -> getHeaders ( ) as $ name => $ values ) { $ message .= $ name . ': ' . implode ( ', ' , $ values ) . "\r\n" ; } $ message .= "\r\n" ; return $ message ; }
Produce the header of request as a string based on a PSR Request .
45,012
public function only ( $ keys ) { $ keys = is_array ( $ keys ) ? $ keys : func_get_args ( ) ; $ results = [ ] ; foreach ( $ keys as $ key ) { $ results = array_merge_recursive ( $ results , $ this -> buildArray ( explode ( '.' , $ key ) , $ this -> get ( $ key ) ) ) ; } return $ results ; }
Get a subset of the items from the payload data .
45,013
public function has ( $ keys ) { $ keys = is_array ( $ keys ) ? $ keys : func_get_args ( ) ; $ results = $ this -> payload ( ) ; foreach ( $ keys as $ value ) { if ( $ this -> hasValueAtKey ( $ value , $ results ) === false ) { return false ; } } return true ; }
Determine if the payload contains a non - empty value for a given key .
45,014
public function get ( $ key = null , $ default = null ) { if ( $ this -> has ( $ key ) ) { return $ this -> getValueAtKey ( $ key , $ this -> payload ( ) ) ; } return $ default ; }
Retrieve an payload item from the payload data return default item if item not found .
45,015
public function mask ( array $ mask ) { $ keys = [ ] ; foreach ( $ mask as $ key => $ value ) { $ keys [ ] = $ key . ( is_array ( $ value ) ? $ this -> processMask ( $ value ) : '' ) ; } return $ this -> only ( $ keys ) ; }
Mask input data with a given mapping .
45,016
private function processMask ( $ mask ) { foreach ( $ mask as $ key => $ value ) { return '.' . $ key . ( is_array ( $ value ) ? $ this -> processMask ( $ value ) : '' ) ; } }
Recursive processor for processing user masks .
45,017
public function getFormatClass ( $ format = '' ) { if ( ! empty ( $ format ) ) { return $ this -> processContentType ( $ format ) ; } if ( isset ( $ _SERVER [ 'CONTENT_TYPE' ] ) ) { $ type = $ this -> processContentType ( $ _SERVER [ 'CONTENT_TYPE' ] ) ; if ( $ type !== false ) { return $ type ; } } if ( isset ( $ _SERVER [ 'HTTP_CONTENT_TYPE' ] ) ) { $ type = $ this -> processContentType ( $ _SERVER [ 'HTTP_CONTENT_TYPE' ] ) ; if ( $ type !== false ) { return $ type ; } } return 'Nathanmac\Utilities\Parser\Formats\JSON' ; }
Autodetect the payload data type using content - type value .
45,018
private function processContentType ( $ contentType ) { foreach ( explode ( ';' , $ contentType ) as $ type ) { $ type = strtolower ( trim ( $ type ) ) ; if ( isset ( $ this -> supported_formats [ $ type ] ) ) { return $ this -> supported_formats [ $ type ] ; } } return false ; }
Process the content - type values
45,019
private function getValueAtKey ( $ key , $ data ) { $ keys = explode ( '.' , $ key ) ; while ( count ( $ keys ) > 1 ) { $ key = array_shift ( $ keys ) ; if ( preg_match ( $ this -> wildcards , $ key ) && is_array ( $ data ) && ! empty ( $ data ) ) { if ( preg_match ( '/^:(index|item)\[\d+\]$/' , $ key ) ) { for ( $ x = substr ( $ key , 7 , - 1 ) ; $ x >= 0 ; $ x -- ) { if ( empty ( $ data ) ) { return false ; } $ item = array_shift ( $ data ) ; } } elseif ( $ key == ':last' ) { $ item = array_pop ( $ data ) ; } else { $ item = array_shift ( $ data ) ; } $ data = & $ item ; } else { if ( ! isset ( $ data [ $ key ] ) || ! is_array ( $ data [ $ key ] ) ) { return false ; } $ data = & $ data [ $ key ] ; } } $ key = array_shift ( $ keys ) ; if ( preg_match ( $ this -> wildcards , $ key ) ) { if ( preg_match ( '/^:(index|item)\[\d+\]$/' , $ key ) ) { for ( $ x = substr ( $ key , 7 , - 1 ) ; $ x >= 0 ; $ x -- ) { if ( empty ( $ data ) ) { return false ; } $ item = array_shift ( $ data ) ; } return $ item ; } elseif ( $ key == ':last' ) { return array_pop ( $ data ) ; } return array_shift ( $ data ) ; } return ( $ data [ $ key ] ) ; }
Return a value from the array identified from the key .
45,020
private function hasValueAtKey ( $ key , $ data ) { $ keys = explode ( '.' , $ key ) ; while ( count ( $ keys ) > 0 ) { $ key = array_shift ( $ keys ) ; if ( preg_match ( $ this -> wildcards , $ key ) && is_array ( $ data ) && ! empty ( $ data ) ) { if ( preg_match ( '/^:(index|item)\[\d+\]$/' , $ key ) ) { for ( $ x = substr ( $ key , 7 , - 1 ) ; $ x >= 0 ; $ x -- ) { if ( empty ( $ data ) ) { return false ; } $ item = array_shift ( $ data ) ; } } elseif ( $ key == ':last' ) { $ item = array_pop ( $ data ) ; } else { $ item = array_shift ( $ data ) ; } $ data = & $ item ; } else { if ( ! isset ( $ data [ $ key ] ) ) { return false ; } if ( is_bool ( $ data [ $ key ] ) ) { return true ; } if ( $ data [ $ key ] === '' ) { return false ; } $ data = & $ data [ $ key ] ; } } return true ; }
Array contains a value identified from the key returns bool
45,021
private function buildArray ( $ route , $ data = null ) { $ key = array_pop ( $ route ) ; $ data = [ $ key => $ data ] ; if ( count ( $ route ) == 0 ) { return $ data ; } return $ this -> buildArray ( $ route , $ data ) ; }
Build the array structure for value .
45,022
private function removeValue ( & $ array , $ key ) { $ keys = explode ( '.' , $ key ) ; while ( count ( $ keys ) > 1 ) { $ key = array_shift ( $ keys ) ; if ( ! isset ( $ array [ $ key ] ) || ! is_array ( $ array [ $ key ] ) ) { return ; } $ array = & $ array [ $ key ] ; } unset ( $ array [ array_shift ( $ keys ) ] ) ; }
Remove a value identified from the key
45,023
protected static function ourStrlen ( $ str ) { static $ exists = null ; if ( $ exists === null ) { $ exists = \ function_exists ( '\\mb_strlen' ) ; } if ( $ exists ) { return \ mb_strlen ( $ str , '8bit' ) ; } return \ strlen ( $ str ) ; }
Multi - byte - safe string length calculation
45,024
protected static function ourSubstr ( $ str , $ start = 0 , $ length = null ) { static $ exists = null ; if ( $ exists === null ) { $ exists = \ function_exists ( '\\mb_substr' ) ; } if ( $ exists ) { return \ mb_substr ( $ str , $ start , $ length , '8bit' ) ; } elseif ( $ length !== null ) { return \ substr ( $ str , $ start , $ length ) ; } return \ substr ( $ str , $ start ) ; }
Multi - byte - safe substring calculation
45,025
public static function imageSizeFromString ( $ imagedata , & $ imageinfo = null ) { $ uri = 'data://application/octet-stream;base64,' . \ base64_encode ( $ imagedata ) ; if ( $ imageinfo !== null ) { return \ getimagesize ( $ uri , $ imageinfo ) ; } return \ getimagesize ( $ uri ) ; }
Get the size of an image from a string
45,026
public static function arrayColumn ( array $ array , $ column_key , $ index_key = null ) { $ aReturn = array ( ) ; if ( $ column_key === null ) { if ( $ index_key === null ) { return $ array ; } foreach ( $ array as $ sub ) { $ aReturn [ $ sub [ $ index_key ] ] = $ sub ; } } elseif ( empty ( $ index_key ) ) { foreach ( $ array as $ sub ) { $ aReturn [ ] = $ sub [ $ column_key ] ; } } else { foreach ( $ array as $ sub ) { $ aReturn [ $ sub [ $ index_key ] ] = $ sub [ $ column_key ] ; } } return $ aReturn ; }
Return the values from a single column in the input array
45,027
public static function hexToBin ( $ data ) { if ( self :: ourStrlen ( $ data ) % 2 !== 0 ) { \ trigger_error ( "hex2bin(): Hexadecimal input string must have an even length" , E_USER_WARNING ) ; return false ; } return \ pack ( 'H*' , $ data ) ; }
Convert a hexadecimal string into raw binary
45,028
public static function getConfigOverrides ( Event $ event ) { $ extra = $ event -> getComposer ( ) -> getPackage ( ) -> getExtra ( ) ; if ( isset ( $ extra [ "patternlab" ] ) && isset ( $ extra [ "patternlab" ] [ "config" ] ) && is_array ( $ extra [ "patternlab" ] [ "config" ] ) ) { self :: $ installerInfo [ "configOverrides" ] = $ extra [ "patternlab" ] [ "config" ] ; } }
Get any config overrides that may exist for the edition
45,029
public static function prePackageUninstall ( PackageEvent $ event ) { self :: setPackagesRemove ( ) ; $ package = $ event -> getOperation ( ) -> getPackage ( ) ; $ packageType = $ package -> getType ( ) ; $ packageInfo = array ( ) ; if ( strpos ( $ packageType , "patternlab-" ) !== false ) { $ packageInfo [ "name" ] = $ package -> getName ( ) ; $ packageInfo [ "type" ] = $ packageType ; $ packageInfo [ "pathBase" ] = $ event -> getComposer ( ) -> getInstallationManager ( ) -> getInstallPath ( $ package ) ; InstallerUtil :: packageRemove ( $ packageInfo ) ; } }
Clean - up when a package is removed
45,030
public function getScripts ( ) { $ scripts = array ( ) ; switch ( $ this -> _jsEngine ) { case self :: ENGINE_JQUERY : $ scripts [ ] = $ this -> _confs [ 'jQuery' ] [ 'path' ] . $ this -> _confs [ 'jQuery' ] [ 'name' ] ; break ; case self :: ENGINE_MOOTOOLS : $ scripts [ ] = $ this -> _confs [ 'mootools' ] [ 'path' ] . $ this -> _confs [ 'mootools' ] [ 'name' ] ; if ( $ this -> _chartType === self :: HIGHCHART ) { $ scripts [ ] = $ this -> _confs [ 'highchartsMootoolsAdapter' ] [ 'path' ] . $ this -> _confs [ 'highchartsMootoolsAdapter' ] [ 'name' ] ; } else { $ scripts [ ] = $ this -> _confs [ 'highstockMootoolsAdapter' ] [ 'path' ] . $ this -> _confs [ 'highstockMootoolsAdapter' ] [ 'name' ] ; } break ; case self :: ENGINE_PROTOTYPE : $ scripts [ ] = $ this -> _confs [ 'prototype' ] [ 'path' ] . $ this -> _confs [ 'prototype' ] [ 'name' ] ; if ( $ this -> _chartType === self :: HIGHCHART ) { $ scripts [ ] = $ this -> _confs [ 'highchartsPrototypeAdapter' ] [ 'path' ] . $ this -> _confs [ 'highchartsPrototypeAdapter' ] [ 'name' ] ; } else { $ scripts [ ] = $ this -> _confs [ 'highstockPrototypeAdapter' ] [ 'path' ] . $ this -> _confs [ 'highstockPrototypeAdapter' ] [ 'name' ] ; } break ; } switch ( $ this -> _chartType ) { case self :: HIGHCHART : $ scripts [ ] = $ this -> _confs [ 'highcharts' ] [ 'path' ] . $ this -> _confs [ 'highcharts' ] [ 'name' ] ; break ; case self :: HIGHSTOCK : $ scripts [ ] = $ this -> _confs [ 'highstock' ] [ 'path' ] . $ this -> _confs [ 'highstock' ] [ 'name' ] ; break ; case self :: HIGHMAPS : $ scripts [ ] = $ this -> _confs [ 'highmaps' ] [ 'path' ] . $ this -> _confs [ 'highmaps' ] [ 'name' ] ; break ; } if ( ! empty ( $ this -> _extraScripts ) ) { foreach ( $ this -> _extraScripts as $ key ) { $ scripts [ ] = $ this -> _confs [ 'extra' ] [ $ key ] [ 'path' ] . $ this -> _confs [ 'extra' ] [ $ key ] [ 'name' ] ; } } return $ scripts ; }
Finds the javascript files that need to be included on the page based on the chart type and js engine . Uses the conf . php file to build the files path
45,031
public function printScripts ( $ return = false ) { $ scripts = '' ; foreach ( $ this -> getScripts ( ) as $ script ) { $ scripts .= '<script type="text/javascript" src="' . $ script . '"></script>' ; } if ( $ return ) { return $ scripts ; } else { echo $ scripts ; } }
Prints javascript script tags for all scripts that need to be included on page
45,032
public function includeExtraScripts ( array $ keys = array ( ) ) { $ this -> _extraScripts = empty ( $ keys ) ? array_keys ( $ this -> _confs [ 'extra' ] ) : $ keys ; }
Signals which extra scripts are to be included given its keys
45,033
private static function _replaceJsExpr ( $ data , & $ jsExpressions ) { if ( ! is_array ( $ data ) && ! is_object ( $ data ) ) { return $ data ; } if ( is_object ( $ data ) ) { if ( $ data instanceof \ stdClass ) { return $ data ; } elseif ( ! $ data instanceof HighchartJsExpr ) { $ data = $ data -> getValue ( ) ; } } if ( $ data instanceof HighchartJsExpr ) { $ magicKey = " _" . count ( $ jsExpressions ) . "_" . count ( $ jsExpressions ) ; $ jsExpressions [ $ magicKey ] = $ data -> getExpression ( ) ; return $ magicKey ; } if ( is_array ( $ data ) ) { foreach ( $ data as $ key => $ value ) { $ data [ $ key ] = static :: _replaceJsExpr ( $ value , $ jsExpressions ) ; } } return $ data ; }
Replaces any HighchartJsExpr for an id and save the js expression on the jsExpressions array Based on Zend_Json
45,034
public function iAmAuthenticatingAs ( $ username , $ password ) { $ this -> removeHeader ( 'Authorization' ) ; $ this -> authorization = base64_encode ( $ username . ':' . $ password ) ; $ this -> addHeader ( 'Authorization' , 'Basic ' . $ this -> authorization ) ; }
Adds Basic Authentication header to next request .
45,035
public function iSendARequest ( $ method , $ url ) { $ url = $ this -> prepareUrl ( $ url ) ; if ( version_compare ( ClientInterface :: VERSION , '6.0' , '>=' ) ) { $ this -> request = new Request ( $ method , $ url , $ this -> headers ) ; } else { $ this -> request = $ this -> getClient ( ) -> createRequest ( $ method , $ url ) ; if ( ! empty ( $ this -> headers ) ) { $ this -> request -> addHeaders ( $ this -> headers ) ; } } $ this -> sendRequest ( ) ; }
Sends HTTP request to specific relative URL .
45,036
public function iSendARequestWithValues ( $ method , $ url , TableNode $ post ) { $ url = $ this -> prepareUrl ( $ url ) ; $ fields = array ( ) ; foreach ( $ post -> getRowsHash ( ) as $ key => $ val ) { $ fields [ $ key ] = $ this -> replacePlaceHolder ( $ val ) ; } $ bodyOption = array ( 'body' => json_encode ( $ fields ) , ) ; if ( version_compare ( ClientInterface :: VERSION , '6.0' , '>=' ) ) { $ this -> request = new Request ( $ method , $ url , $ this -> headers , $ bodyOption [ 'body' ] ) ; } else { $ this -> request = $ this -> getClient ( ) -> createRequest ( $ method , $ url , $ bodyOption ) ; if ( ! empty ( $ this -> headers ) ) { $ this -> request -> addHeaders ( $ this -> headers ) ; } } $ this -> sendRequest ( ) ; }
Sends HTTP request to specific URL with field values from Table .
45,037
public function iSendARequestWithFormData ( $ method , $ url , PyStringNode $ body ) { $ url = $ this -> prepareUrl ( $ url ) ; $ body = $ this -> replacePlaceHolder ( trim ( $ body ) ) ; $ fields = array ( ) ; parse_str ( implode ( '&' , explode ( "\n" , $ body ) ) , $ fields ) ; if ( version_compare ( ClientInterface :: VERSION , '6.0' , '>=' ) ) { $ this -> request = new Request ( $ method , $ url , [ 'Content-Type' => 'application/x-www-form-urlencoded' ] , http_build_query ( $ fields , null , '&' ) ) ; } else { $ this -> request = $ this -> getClient ( ) -> createRequest ( $ method , $ url ) ; $ requestBody = $ this -> request -> getBody ( ) ; foreach ( $ fields as $ key => $ value ) { $ requestBody -> setField ( $ key , $ value ) ; } } $ this -> sendRequest ( ) ; }
Sends HTTP request to specific URL with form data from PyString .
45,038
public function theResponseCodeShouldBe ( $ code ) { $ expected = intval ( $ code ) ; $ actual = intval ( $ this -> response -> getStatusCode ( ) ) ; Assertions :: assertSame ( $ expected , $ actual ) ; }
Checks that response has specific status code .
45,039
public function theResponseShouldContain ( $ text ) { $ expectedRegexp = '/' . preg_quote ( $ text ) . '/i' ; $ actual = ( string ) $ this -> response -> getBody ( ) ; Assertions :: assertRegExp ( $ expectedRegexp , $ actual ) ; }
Checks that response body contains specific text .
45,040
public function theResponseShouldNotContain ( $ text ) { $ expectedRegexp = '/' . preg_quote ( $ text ) . '/' ; $ actual = ( string ) $ this -> response -> getBody ( ) ; Assertions :: assertNotRegExp ( $ expectedRegexp , $ actual ) ; }
Checks that response body doesn t contains specific text .
45,041
public function printResponse ( ) { $ request = $ this -> request ; $ response = $ this -> response ; echo sprintf ( "%s %s => %d:\n%s" , $ request -> getMethod ( ) , ( string ) ( $ request instanceof RequestInterface ? $ request -> getUri ( ) : $ request -> getUrl ( ) ) , $ response -> getStatusCode ( ) , ( string ) $ response -> getBody ( ) ) ; }
Prints last response body .
45,042
protected function replacePlaceHolder ( $ string ) { foreach ( $ this -> placeHolders as $ key => $ val ) { $ string = str_replace ( $ key , $ val , $ string ) ; } return $ string ; }
Replaces placeholders in provided text .
45,043
public function encode ( Message $ message , int $ options = 0 ) : string { $ ctx = new Context ( $ options ) ; $ qdCount = $ anCount = $ nsCount = $ arCount = 0 ; foreach ( $ message -> getQuestionRecords ( ) as $ record ) { if ( ! $ this -> encodeQuestionRecord ( $ ctx , $ record ) ) { goto done ; } $ qdCount ++ ; } foreach ( $ message -> getAnswerRecords ( ) as $ record ) { if ( ! $ this -> encodeResourceRecord ( $ ctx , $ record ) ) { goto done ; } $ anCount ++ ; } foreach ( $ message -> getAuthorityRecords ( ) as $ record ) { if ( ! $ this -> encodeResourceRecord ( $ ctx , $ record ) ) { goto done ; } $ nsCount ++ ; } foreach ( $ message -> getAdditionalRecords ( ) as $ record ) { if ( ! $ this -> encodeResourceRecord ( $ ctx , $ record ) ) { goto done ; } $ arCount ++ ; } done : $ packet = $ this -> encodeHeader ( $ ctx , $ message , $ qdCount , $ anCount , $ nsCount , $ arCount ) . $ ctx -> data ; if ( ! ( $ options & EncodingOptions :: FORMAT_TCP ) ) { \ assert ( \ strlen ( $ packet ) <= 512 , new \ Error ( 'UDP packet exceeds 512 byte limit: got ' . \ strlen ( $ packet ) . ' bytes' ) ) ; return $ packet ; } \ assert ( \ strlen ( $ packet ) <= 65535 , new \ Error ( 'TCP packet exceeds 65535 byte limit: got ' . \ strlen ( $ packet ) . ' bytes' ) ) ; return \ pack ( 'n' , \ strlen ( $ packet ) ) . $ packet ; }
Encode a Message to raw network data
45,044
public function aliasHandler ( $ type , $ name , & $ content , & $ modified , Smarty $ smarty ) { $ file = Yii :: getAlias ( $ name ) ; return is_file ( $ file ) ? $ file : false ; }
Resolves Yii alias into file path
45,045
public function functionPath ( $ params , \ Smarty_Internal_Template $ template ) { if ( ! isset ( $ params [ 'route' ] ) ) { trigger_error ( "path: missing 'route' parameter" ) ; } array_unshift ( $ params , $ params [ 'route' ] ) ; unset ( $ params [ 'route' ] ) ; return Url :: to ( $ params ) ; }
Smarty template function to get relative URL for using in links
45,046
public function functionUrl ( $ params , \ Smarty_Internal_Template $ template ) { if ( ! isset ( $ params [ 'route' ] ) ) { trigger_error ( "path: missing 'route' parameter" ) ; } array_unshift ( $ params , $ params [ 'route' ] ) ; unset ( $ params [ 'route' ] ) ; return Url :: to ( $ params , true ) ; }
Smarty template function to get absolute URL for using in links
45,047
protected function onFulfilled ( RequestInterface $ request , array $ options ) { return function ( ResponseInterface $ response ) use ( $ request , $ options ) { return $ this -> shouldRetryHttpResponse ( $ options , $ response ) ? $ this -> doRetry ( $ request , $ options , $ response ) : $ this -> returnResponse ( $ options , $ response ) ; } ; }
No exceptions were thrown during processing
45,048
protected function onRejected ( RequestInterface $ request , array $ options ) { return function ( $ reason ) use ( $ request , $ options ) { if ( $ reason instanceof BadResponseException ) { if ( $ this -> shouldRetryHttpResponse ( $ options , $ reason -> getResponse ( ) ) ) { return $ this -> doRetry ( $ request , $ options , $ reason -> getResponse ( ) ) ; } } elseif ( $ reason instanceof ConnectException ) { if ( $ this -> shouldRetryConnectException ( $ reason , $ options ) ) { return $ this -> doRetry ( $ request , $ options ) ; } } return \ GuzzleHttp \ Promise \ rejection_for ( $ reason ) ; } ; }
An exception or error was thrown during processing
45,049
protected function shouldRetryHttpResponse ( array $ options , ResponseInterface $ response ) { $ statuses = array_map ( '\intval' , ( array ) $ options [ 'retry_on_status' ] ) ; switch ( true ) { case $ options [ 'retry_enabled' ] === false : return false ; case $ this -> countRemainingRetries ( $ options ) === 0 : return false ; case ( ! $ response -> hasHeader ( 'Retry-After' ) && $ options [ 'retry_only_if_retry_after_header' ] ) : return false ; default : return \ in_array ( $ response -> getStatusCode ( ) , $ statuses , true ) ; } }
Check to see if a request can be retried
45,050
protected function countRemainingRetries ( array $ options ) { $ retryCount = isset ( $ options [ 'retry_count' ] ) ? ( int ) $ options [ 'retry_count' ] : 0 ; $ numAllowed = isset ( $ options [ 'max_retry_attempts' ] ) ? ( int ) $ options [ 'max_retry_attempts' ] : $ this -> defaultOptions [ 'max_retry_attempts' ] ; return max ( [ $ numAllowed - $ retryCount , 0 ] ) ; }
Count the number of retries remaining . Always returns 0 or greater .
45,051
protected function doRetry ( RequestInterface $ request , array $ options , ResponseInterface $ response = null ) { ++ $ options [ 'retry_count' ] ; $ delayTimeout = $ this -> determineDelayTimeout ( $ options , $ response ) ; if ( $ options [ 'on_retry_callback' ] ) { \ call_user_func ( $ options [ 'on_retry_callback' ] , ( int ) $ options [ 'retry_count' ] , ( float ) $ delayTimeout , $ request , $ options , $ response ) ; } usleep ( $ delayTimeout * 1000000 ) ; return $ this ( $ request , $ options ) ; }
Retry the request
45,052
protected function determineDelayTimeout ( array $ options , ResponseInterface $ response = null ) { if ( \ is_callable ( $ options [ 'default_retry_multiplier' ] ) ) { $ defaultDelayTimeout = ( float ) \ call_user_func ( $ options [ 'default_retry_multiplier' ] , $ options [ 'retry_count' ] , $ response ) ; } else { $ defaultDelayTimeout = ( float ) $ options [ 'default_retry_multiplier' ] * $ options [ 'retry_count' ] ; } if ( $ response && $ response -> hasHeader ( 'Retry-After' ) ) { return $ this -> deriveTimeoutFromHeader ( $ response -> getHeader ( 'Retry-After' ) [ 0 ] ) ? : $ defaultDelayTimeout ; } return $ defaultDelayTimeout ; }
Determine the delay timeout
45,053
protected function deriveTimeoutFromHeader ( $ headerValue ) { if ( ( string ) ( int ) trim ( $ headerValue ) === $ headerValue ) { return ( int ) trim ( $ headerValue ) ; } elseif ( $ date = \ DateTime :: createFromFormat ( self :: DATE_FORMAT , trim ( $ headerValue ) ) ) { return ( int ) $ date -> format ( 'U' ) - time ( ) ; } return null ; }
Attempt to derive the timeout from the HTTP Retry - After header
45,054
public function create ( string $ className , string $ typeName ) : Type { $ type = new InputObjectType ( [ 'name' => $ typeName , 'fields' => function ( ) use ( $ className , $ typeName ) : array { $ fieldsEnum = new EnumType ( [ 'name' => $ typeName . 'Field' , 'values' => $ this -> getPossibleValues ( $ className ) , 'description' => 'Fields available for `' . $ typeName . '`' , ] ) ; $ this -> types -> registerInstance ( $ fieldsEnum ) ; return [ [ 'name' => 'field' , 'type' => Type :: nonNull ( $ fieldsEnum ) , ] , [ 'name' => 'nullAsHighest' , 'type' => Type :: boolean ( ) , 'description' => 'If true `NULL` values will be considered as the highest value, so appearing last in a `ASC` order, and first in a `DESC` order.' , 'defaultValue' => false , ] , [ 'name' => 'order' , 'type' => $ this -> types -> get ( 'SortingOrder' ) , 'defaultValue' => 'ASC' , ] , ] ; } , ] ) ; return $ type ; }
Create an InputObjectType from a Doctrine entity to sort them by their fields and custom sorter .
45,055
private function getPossibleValues ( string $ className ) : array { $ metadata = $ this -> entityManager -> getClassMetadata ( $ className ) ; $ standard = array_values ( $ metadata -> fieldNames ) ; $ custom = $ this -> getCustomSortingNames ( $ className ) ; return array_merge ( $ standard , $ custom ) ; }
Get names for all possible sorting including the custom one
45,056
private function getCustomSortingNames ( string $ className ) : array { $ this -> fillCache ( $ className ) ; return array_keys ( $ this -> customSortings [ $ className ] ) ; }
Get names for all custom sorting
45,057
public function getCustomSorting ( string $ className , string $ name ) : ? SortingInterface { $ this -> fillCache ( $ className ) ; return $ this -> customSortings [ $ className ] [ $ name ] ?? null ; }
Get instance of custom sorting for the given entity and sorting name
45,058
private function fillCache ( string $ className ) : void { if ( array_key_exists ( $ className , $ this -> customSortings ) ) { return ; } $ class = new ReflectionClass ( $ className ) ; $ this -> customSortings [ $ className ] = $ this -> getFromAnnotation ( $ class ) ; }
Fill the cache for custom sorting
45,059
private function getFromAnnotation ( ReflectionClass $ class ) : array { $ sortings = Utils :: getRecursiveClassAnnotations ( $ this -> getAnnotationReader ( ) , $ class , Sorting :: class ) ; $ result = [ ] ; foreach ( $ sortings as $ classWithAnnotation => $ sorting ) { foreach ( $ sorting -> classes as $ className ) { $ this -> throwIfInvalidAnnotation ( $ classWithAnnotation , 'Sorting' , SortingInterface :: class , $ className ) ; $ name = lcfirst ( preg_replace ( '~Type$~' , '' , Utils :: getTypeName ( $ className ) ) ) ; $ result [ $ name ] = new $ className ( ) ; } } return $ result ; }
Get all instance of custom sorting from the annotation
45,060
final protected function getDescription ( string $ className ) : ? string { $ class = new \ ReflectionClass ( $ className ) ; $ comment = $ class -> getDocComment ( ) ? : '' ; $ comment = preg_replace ( '~^\s*(/\*\*|\* ?|\*/)~m' , '' , $ comment ) ; $ comment = trim ( explode ( '@' , $ comment ) [ 0 ] ) ; if ( ! $ comment ) { $ comment = null ; } return $ comment ; }
Get the description of a class from the doc block
45,061
final protected function throwIfInvalidAnnotation ( string $ classWithAnnotation , string $ annotation , string $ expectedClassName , string $ actualClassName ) : void { if ( ! is_a ( $ actualClassName , $ expectedClassName , true ) ) { throw new Exception ( 'On class `' . $ classWithAnnotation . '` the annotation `@API\\' . $ annotation . '` expects a FQCN implementing `' . $ expectedClassName . '`, but instead got: ' . $ actualClassName ) ; } }
Throw an exception if the given type does not inherit expected type
45,062
public function has ( string $ key ) : bool { return $ this -> customTypes && $ this -> customTypes -> has ( $ key ) || array_key_exists ( $ key , $ this -> types ) ; }
Returns whether a type exists for the given key
45,063
public function get ( string $ key ) : Type { if ( $ this -> customTypes && $ this -> customTypes -> has ( $ key ) ) { $ t = $ this -> customTypes -> get ( $ key ) ; $ this -> registerInstance ( $ t ) ; return $ t ; } if ( array_key_exists ( $ key , $ this -> types ) ) { return $ this -> types [ $ key ] ; } throw new Exception ( 'No type registered with key `' . $ key . '`. Either correct the usage, or register it in your custom types container when instantiating `' . self :: class . '`.' ) ; }
Always return the same instance of Type for the given key
45,064
private function getViaFactory ( string $ className , string $ typeName , AbstractTypeFactory $ factory ) : Type { $ this -> throwIfNotEntity ( $ className ) ; if ( ! isset ( $ this -> types [ $ typeName ] ) ) { $ instance = $ factory -> create ( $ className , $ typeName ) ; $ this -> registerInstance ( $ instance ) ; } return $ this -> types [ $ typeName ] ; }
Get a type from internal registry and create it via the factory if needed
45,065
public function getOutput ( string $ className ) : ObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) , $ this -> objectTypeFactory ) ; return $ type ; }
Returns an output type for the given entity
45,066
public function getInput ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'Input' , $ this -> inputTypeFactory ) ; return $ type ; }
Returns an input type for the given entity
45,067
public function getPartialInput ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'PartialInput' , $ this -> partialInputTypeFactory ) ; return $ type ; }
Returns a partial input type for the given entity
45,068
public function getFilter ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'Filter' , $ this -> filterTypeFactory ) ; return $ type ; }
Returns a filter input type for the given entity
45,069
public function getSorting ( string $ className ) : ListOfType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'Sorting' , $ this -> sortingTypeFactory ) ; return Type :: listOf ( Type :: nonNull ( $ type ) ) ; }
Returns a sorting input type for the given entity
45,070
public function getJoinOn ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , 'JoinOn' . Utils :: getTypeName ( $ className ) , $ this -> joinOnTypeFactory ) ; return $ type ; }
Returns a joinOn input type for the given entity
45,071
public function getFilterGroupJoin ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'FilterGroupJoin' , $ this -> filterGroupJoinTypeFactory ) ; return $ type ; }
Returns a joins input type for the given entity
45,072
public function getFilterGroupCondition ( string $ className ) : InputObjectType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'FilterGroupCondition' , $ this -> filterGroupConditionTypeFactory ) ; return $ type ; }
Returns a condition input type for the given entity
45,073
public function getId ( string $ className ) : EntityIDType { $ type = $ this -> getViaFactory ( $ className , Utils :: getTypeName ( $ className ) . 'ID' , $ this -> entityIDTypeFactory ) ; return $ type ; }
Returns an special ID type for the given entity
45,074
public function getOperator ( string $ className , LeafType $ type ) : AbstractOperator { if ( ! is_a ( $ className , AbstractOperator :: class , true ) ) { throw new Exception ( 'Expects a FQCN implementing `' . AbstractOperator :: class . '`, but instead got: ' . $ className ) ; } $ key = Utils :: getOperatorTypeName ( $ className , $ type ) ; if ( ! isset ( $ this -> types [ $ key ] ) ) { $ instance = new $ className ( $ this , $ type ) ; $ this -> registerInstance ( $ instance ) ; } return $ this -> types [ $ key ] ; }
Returns an operator input type
45,075
public function isEntity ( string $ className ) : bool { return class_exists ( $ className ) && ! $ this -> entityManager -> getMetadataFactory ( ) -> isTransient ( $ className ) ; }
Checks if a className is a valid doctrine entity
45,076
private function initializeInternalTypes ( ) : void { $ phpToGraphQLMapping = [ 'id' => Type :: id ( ) , 'bool' => Type :: boolean ( ) , 'int' => Type :: int ( ) , 'float' => Type :: float ( ) , 'string' => Type :: string ( ) , 'boolean' => Type :: boolean ( ) , 'integer' => Type :: int ( ) , 'smallint' => Type :: int ( ) , 'bigint' => Type :: int ( ) , 'decimal' => Type :: string ( ) , 'text' => Type :: string ( ) , ] ; $ this -> types = $ phpToGraphQLMapping ; $ this -> registerInstance ( new LogicalOperatorType ( ) ) ; $ this -> registerInstance ( new JoinTypeType ( ) ) ; $ this -> registerInstance ( new SortingOrderType ( ) ) ; }
Initialize internal types for common needs
45,077
private function throwIfNotEntity ( string $ className ) : void { if ( ! $ this -> isEntity ( $ className ) ) { throw new \ UnexpectedValueException ( 'Given class name `' . $ className . '` is not a Doctrine entity. Either register a custom GraphQL type for `' . $ className . '` when instantiating `' . self :: class . '`, or change the usage of that class to something else.' ) ; } }
Throw an exception if the class name is not Doctrine entity
45,078
public function createFilteredQueryBuilder ( string $ className , array $ filter , array $ sorting ) : QueryBuilder { return $ this -> filteredQueryBuilderFactory -> create ( $ className , $ filter , $ sorting ) ; }
Create and return a query builder that is filtered and sorted for the given entity
45,079
public function getMethodDescription ( ) : ? string { $ description = preg_replace ( '~\*/$~' , '' , $ this -> comment ) ; $ description = preg_replace ( '~^\s*(/\*\*|\* ?|\*/)~m' , '' , $ description ) ; $ description = trim ( explode ( '@' , $ description ) [ 0 ] ) ; $ description = ucfirst ( preg_replace ( '~^(set|get|return)s? ~i' , '' , $ description ) ) ; return $ description ? : null ; }
Get the description of a method from the doc block
45,080
public function getParameterDescription ( ReflectionParameter $ param ) : ? string { $ name = preg_quote ( $ param -> getName ( ) ) ; if ( preg_match ( '~@param\h+\H+\h+\$' . $ name . '\h+(.*)~' , $ this -> comment , $ m ) ) { return ucfirst ( trim ( $ m [ 1 ] ) ) ; } return null ; }
Get the parameter description
45,081
final protected function getAnnotationReader ( ) : Reader { $ driver = $ this -> entityManager -> getConfiguration ( ) -> getMetadataDriverImpl ( ) ; if ( $ driver instanceof AnnotationDriver ) { return $ driver -> getReader ( ) ; } if ( $ driver instanceof MappingDriverChain ) { return new MappingDriverChainAdapter ( $ driver ) ; } throw new Exception ( 'graphql-doctrine requires Doctrine to be configured with a `' . AnnotationDriver :: class . '`.' ) ; }
Get annotation reader
45,082
private function applyGroups ( ClassMetadata $ metadata , InputObjectType $ type , array $ filter , string $ alias ) : void { $ typeFields = $ type -> getField ( 'groups' ) -> type -> getWrappedType ( true ) -> getField ( 'conditions' ) -> type -> getWrappedType ( true ) ; foreach ( $ filter [ 'groups' ] ?? [ ] as $ group ) { $ this -> applyJoinsAndFilters ( $ metadata , $ alias , $ typeFields , $ group [ 'joins' ] ?? [ ] , $ group [ 'conditions' ] ?? [ ] ) ; $ this -> applyCollectedDqlConditions ( $ group ) ; } }
Apply filters to the query builder
45,083
private function applyJoinsAndFilters ( ClassMetadata $ metadata , string $ alias , InputObjectType $ typeFields , array $ joins , array $ conditions ) : void { $ this -> applyJoins ( $ metadata , $ joins , $ alias ) ; $ this -> collectDqlConditions ( $ metadata , $ conditions , $ typeFields , $ alias ) ; }
Apply both joins and filters to the query builder
45,084
private function collectDqlConditions ( ClassMetadata $ metadata , array $ allConditions , InputObjectType $ typeFields , string $ alias ) : void { foreach ( $ allConditions as $ conditions ) { foreach ( $ conditions as $ field => $ operators ) { if ( $ operators === null ) { continue ; } $ typeField = $ typeFields -> getField ( $ field ) -> type ; foreach ( $ operators as $ operatorName => $ operatorArgs ) { $ operatorField = $ typeField -> getField ( $ operatorName ) ; $ operatorType = $ operatorField -> type ; $ dqlCondition = $ operatorType -> getDqlCondition ( $ this -> uniqueNameFactory , $ metadata , $ this -> queryBuilder , $ alias , $ field , $ operatorArgs ) ; if ( $ dqlCondition ) { $ this -> dqlConditions [ ] = $ dqlCondition ; } } } } }
Gather all DQL conditions for the given array of fields
45,085
private function applyJoins ( ClassMetadata $ metadata , array $ joins , string $ alias ) : void { foreach ( $ joins as $ field => $ join ) { $ joinedAlias = $ this -> createJoin ( $ alias , $ field , $ join [ 'type' ] ) ; if ( isset ( $ join [ 'joins' ] ) || isset ( $ join [ 'conditions' ] ) ) { $ targetClassName = $ metadata -> getAssociationMapping ( $ field ) [ 'targetEntity' ] ; $ targetMetadata = $ this -> entityManager -> getClassMetadata ( $ targetClassName ) ; $ type = $ this -> types -> getFilterGroupCondition ( $ targetClassName ) ; $ this -> applyJoinsAndFilters ( $ targetMetadata , $ joinedAlias , $ type , $ join [ 'joins' ] ?? [ ] , $ join [ 'conditions' ] ?? [ ] ) ; } } }
Apply joins to the query builder
45,086
private function applySorting ( ClassMetadata $ metadata , string $ className , array $ sorting , string $ alias ) : void { foreach ( $ sorting as $ sort ) { $ customSort = $ this -> sortingTypeFactory -> getCustomSorting ( $ className , $ sort [ 'field' ] ) ; if ( $ customSort ) { $ customSort ( $ this -> uniqueNameFactory , $ metadata , $ this -> queryBuilder , $ alias , $ sort [ 'order' ] ) ; } else { $ sortingField = $ alias . '.' . $ sort [ 'field' ] ; if ( $ sort [ 'nullAsHighest' ] ?? false ) { $ expression = 'CASE WHEN ' . $ sortingField . ' IS NULL THEN 1 ELSE 0 END' ; $ sortingField = $ this -> uniqueNameFactory -> createAliasName ( 'sorting' ) ; $ this -> queryBuilder -> addSelect ( $ expression . ' AS HIDDEN ' . $ sortingField ) ; } $ this -> queryBuilder -> addOrderBy ( $ sortingField , $ sort [ 'order' ] ) ; } } }
Apply sorting to the query builder
45,087
private function applyCollectedDqlConditions ( array $ group ) : void { if ( ! $ this -> dqlConditions ) { return ; } if ( $ group [ 'conditionsLogic' ] === 'AND' ) { $ fieldsDql = $ this -> queryBuilder -> expr ( ) -> andX ( ... $ this -> dqlConditions ) ; } else { $ fieldsDql = $ this -> queryBuilder -> expr ( ) -> orX ( ... $ this -> dqlConditions ) ; } if ( $ group [ 'groupLogic' ] === 'AND' ) { $ this -> queryBuilder -> andWhere ( $ fieldsDql ) ; } else { $ this -> queryBuilder -> orWhere ( $ fieldsDql ) ; } $ this -> dqlConditions = [ ] ; }
Apply collected DQL conditions on the query builder and reset them
45,088
private function createJoin ( string $ alias , string $ field , string $ joinType ) : string { $ relationship = $ alias . '.' . $ field ; $ key = $ relationship . '.' . $ joinType ; if ( ! isset ( $ this -> uniqueJoins [ $ key ] ) ) { $ joinedAlias = $ this -> uniqueNameFactory -> createAliasName ( $ field ) ; if ( $ joinType === 'innerJoin' ) { $ this -> queryBuilder -> innerJoin ( $ relationship , $ joinedAlias ) ; } else { $ this -> queryBuilder -> leftJoin ( $ relationship , $ joinedAlias ) ; } $ this -> queryBuilder -> addSelect ( $ joinedAlias ) ; $ this -> uniqueJoins [ $ key ] = $ joinedAlias ; } return $ this -> uniqueJoins [ $ key ] ; }
Create a join but only if it does not exist yet
45,089
private function findReader ( ReflectionClass $ class ) : Reader { $ className = $ class -> getName ( ) ; foreach ( $ this -> chainDriver -> getDrivers ( ) as $ namespace => $ driver ) { if ( mb_stripos ( $ className , $ namespace ) === 0 ) { if ( $ driver instanceof AnnotationDriver ) { return $ driver -> getReader ( ) ; } } } if ( $ this -> chainDriver -> getDefaultDriver ( ) instanceof AnnotationDriver ) { return $ this -> chainDriver -> getDefaultDriver ( ) -> getReader ( ) ; } throw new Exception ( 'graphql-doctrine requires ' . $ className . ' entity to be configured with a `' . AnnotationDriver :: class . '`.' ) ; }
Find the reader for the class
45,090
public function getMethodAnnotation ( \ ReflectionMethod $ method , $ annotationName ) { return $ this -> findReader ( $ method -> getDeclaringClass ( ) ) -> getMethodAnnotation ( $ method , $ annotationName ) ; }
Gets a method annotation .
45,091
public function getPropertyAnnotation ( \ ReflectionProperty $ property , $ annotationName ) { return $ this -> findReader ( $ property -> getDeclaringClass ( ) ) -> getPropertyAnnotation ( $ property , $ annotationName ) ; }
Gets a property annotation .
45,092
public function getEntity ( ) { $ entity = $ this -> entityManager -> getRepository ( $ this -> className ) -> find ( $ this -> id ) ; if ( ! $ entity ) { throw new Error ( 'Entity not found for class `' . $ this -> className . '` and ID `' . $ this -> id . '`.' ) ; } return $ entity ; }
Get the entity from DB
45,093
private function completeFieldArguments ( Field $ field , ReflectionMethod $ method , DocBlockReader $ docBlock ) : void { $ argsFromAnnotations = $ field -> args ; $ args = [ ] ; foreach ( $ method -> getParameters ( ) as $ param ) { $ arg = $ argsFromAnnotations [ $ param -> getName ( ) ] ?? new Argument ( ) ; $ args [ $ param -> getName ( ) ] = $ arg ; $ this -> completeArgumentFromTypeHint ( $ arg , $ method , $ param , $ docBlock ) ; } $ extraAnnotations = array_diff ( array_keys ( $ argsFromAnnotations ) , array_keys ( $ args ) ) ; if ( $ extraAnnotations ) { throw new Exception ( 'The following arguments were declared via `@API\Argument` annotation but do not match actual parameter names on method ' . $ this -> getMethodFullName ( $ method ) . '. Either rename or remove the annotations: ' . implode ( ', ' , $ extraAnnotations ) ) ; } $ field -> args = $ args ; }
Complete arguments configuration from existing type hints
45,094
private function completeArgumentFromTypeHint ( Argument $ arg , ReflectionMethod $ method , ReflectionParameter $ param , DocBlockReader $ docBlock ) : void { if ( ! $ arg -> getName ( ) ) { $ arg -> setName ( $ param -> getName ( ) ) ; } if ( ! $ arg -> getDescription ( ) ) { $ arg -> setDescription ( $ docBlock -> getParameterDescription ( $ param ) ) ; } if ( ! $ arg -> hasDefaultValue ( ) && $ param -> isDefaultValueAvailable ( ) ) { $ arg -> setDefaultValue ( $ param -> getDefaultValue ( ) ) ; } $ this -> completeArgumentTypeFromTypeHint ( $ arg , $ method , $ param , $ docBlock ) ; }
Complete a single argument from its type hint
45,095
private function completeArgumentTypeFromTypeHint ( Argument $ arg , ReflectionMethod $ method , ReflectionParameter $ param , DocBlockReader $ docBlock ) : void { if ( ! $ arg -> getTypeInstance ( ) ) { $ typeDeclaration = $ docBlock -> getParameterType ( $ param ) ; $ this -> throwIfArray ( $ param , $ typeDeclaration ) ; $ arg -> setTypeInstance ( $ this -> getTypeFromPhpDeclaration ( $ method , $ typeDeclaration , true ) ) ; } $ type = $ param -> getType ( ) ; if ( ! $ arg -> getTypeInstance ( ) && $ type ) { $ this -> throwIfArray ( $ param , ( string ) $ type ) ; $ arg -> setTypeInstance ( $ this -> reflectionTypeToType ( $ type , true ) ) ; } $ this -> nonNullIfHasDefault ( $ arg ) ; $ this -> throwIfNotInputType ( $ param , $ arg ) ; }
Complete a single argument type from its type hint and doc block
45,096
private function getTypeFromDocBock ( ReflectionMethod $ method , DocBlockReader $ docBlock ) : ? Type { $ typeDeclaration = $ docBlock -> getReturnType ( ) ; $ blacklist = [ 'Collection' , 'array' , ] ; if ( $ typeDeclaration && ! in_array ( $ typeDeclaration , $ blacklist , true ) ) { return $ this -> getTypeFromPhpDeclaration ( $ method , $ typeDeclaration ) ; } return null ; }
Get a GraphQL type instance from dock block return type
45,097
public function getField ( string $ className ) : array { $ joinsType = $ this -> types -> getFilterGroupJoin ( $ className ) ; $ joinsField = [ 'name' => 'joins' , 'description' => 'Optional joins to either filter the query or fetch related objects from DB in a single query' , 'type' => $ joinsType , ] ; return $ joinsField ; }
Get the field for joins
45,098
private function getJoinsFields ( string $ className ) : array { $ fields = [ ] ; $ associations = $ this -> entityManager -> getClassMetadata ( $ className ) -> associationMappings ; foreach ( $ associations as $ association ) { $ field = [ 'name' => $ association [ 'fieldName' ] , 'type' => $ this -> types -> getJoinOn ( $ association [ 'targetEntity' ] ) , ] ; $ fields [ ] = $ field ; } return $ fields ; }
Get the all the possible relations to be joined
45,099
public function canCreate ( string $ className ) : bool { return ! empty ( $ this -> entityManager -> getClassMetadata ( $ className ) -> associationMappings ) ; }
Return whether it is possible to create a valid type for join