idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
800
public function item ( $ item , $ transformer , $ parameters = [ ] , Closure $ after = null ) { $ class = get_class ( $ item ) ; if ( $ parameters instanceof \ Closure ) { $ after = $ parameters ; $ parameters = [ ] ; } $ binding = $ this -> transformer -> register ( $ class , $ transformer , $ parameters , $ after ) ; return new Response ( $ item , 200 , [ ] , $ binding ) ; }
Bind an item to a transformer and start building a response .
801
public function resolveTransformer ( ) { if ( is_string ( $ this -> resolver ) ) { return $ this -> container -> make ( $ this -> resolver ) ; } elseif ( is_callable ( $ this -> resolver ) ) { return call_user_func ( $ this -> resolver , $ this -> container ) ; } elseif ( is_object ( $ this -> resolver ) ) { return $ this -> resolver ; } throw new RuntimeException ( 'Unable to resolve transformer binding.' ) ; }
Resolve a transformer binding instance .
802
protected function addLookups ( Route $ route ) { $ action = $ route -> getAction ( ) ; if ( isset ( $ action [ 'as' ] ) ) { $ this -> names [ $ action [ 'as' ] ] = $ route ; } if ( isset ( $ action [ 'controller' ] ) ) { $ this -> actions [ $ action [ 'controller' ] ] = $ route ; } }
Add route lookups .
803
public function getByName ( $ name ) { return isset ( $ this -> names [ $ name ] ) ? $ this -> names [ $ name ] : null ; }
Get a route by name .
804
public function getByAction ( $ action ) { return isset ( $ this -> actions [ $ action ] ) ? $ this -> actions [ $ action ] : null ; }
Get a route by action .
805
protected function routeRateLimit ( $ route ) { list ( $ limit , $ expires ) = [ $ route -> getRateLimit ( ) , $ route -> getRateLimitExpiration ( ) ] ; if ( $ limit && $ expires ) { return sprintf ( '%s req/s' , round ( $ limit / ( $ expires * 60 ) , 2 ) ) ; } }
Display the routes rate limiting requests per second . This takes the limit and divides it by the expiration time in seconds to give you a rough idea of how many requests you d be able to fire off per second on the route .
806
protected function filterByVersions ( array $ route ) { foreach ( $ this -> option ( 'versions' ) as $ version ) { if ( Str :: contains ( $ route [ 'versions' ] , $ version ) ) { return true ; } } return false ; }
Filter the route by its versions .
807
protected function filterByScopes ( array $ route ) { foreach ( $ this -> option ( 'scopes' ) as $ scope ) { if ( Str :: contains ( $ route [ 'scopes' ] , $ scope ) ) { return true ; } } return false ; }
Filter the route by its scopes .
808
public function register ( $ class , $ resolver , array $ parameters = [ ] , Closure $ after = null ) { return $ this -> bindings [ $ class ] = $ this -> createBinding ( $ resolver , $ parameters , $ after ) ; }
Register a transformer binding resolver for a class .
809
public function transform ( $ response ) { $ binding = $ this -> getBinding ( $ response ) ; return $ this -> adapter -> transform ( $ response , $ binding -> resolveTransformer ( ) , $ binding , $ this -> getRequest ( ) ) ; }
Transform a response .
810
protected function getBinding ( $ class ) { if ( $ this -> isCollection ( $ class ) && ! $ class -> isEmpty ( ) ) { return $ this -> getBindingFromCollection ( $ class ) ; } $ class = is_object ( $ class ) ? get_class ( $ class ) : $ class ; if ( ! $ this -> hasBinding ( $ class ) ) { throw new RuntimeException ( 'Unable to find bound transformer for "' . $ class . '" class.' ) ; } return $ this -> bindings [ $ class ] ; }
Get a registered transformer binding .
811
protected function createBinding ( $ resolver , array $ parameters = [ ] , Closure $ callback = null ) { return new Binding ( $ this -> container , $ resolver , $ parameters , $ callback ) ; }
Create a new binding instance .
812
protected function hasBinding ( $ class ) { if ( $ this -> isCollection ( $ class ) && ! $ class -> isEmpty ( ) ) { $ class = $ class -> first ( ) ; } $ class = is_object ( $ class ) ? get_class ( $ class ) : $ class ; return isset ( $ this -> bindings [ $ class ] ) ; }
Determine if a class has a transformer binding .
813
public function getRequest ( ) { $ request = $ this -> container [ 'request' ] ; if ( $ request instanceof IlluminateRequest && ! $ request instanceof Request ) { $ request = ( new Request ( ) ) -> createFromIlluminate ( $ request ) ; } return $ request ; }
Get the request from the container .
814
protected function normalizeRequestUri ( Request $ request ) { $ query = $ request -> server -> get ( 'QUERY_STRING' ) ; $ uri = '/' . trim ( str_replace ( '?' . $ query , '' , $ request -> server -> get ( 'REQUEST_URI' ) ) , '/' ) . ( $ query ? '?' . $ query : '' ) ; $ request -> server -> set ( 'REQUEST_URI' , $ uri ) ; }
Normalize the request URI so that Lumen can properly dispatch it .
815
protected function breakUriSegments ( $ uri ) { if ( ! Str :: contains ( $ uri , '?}' ) ) { return ( array ) $ uri ; } $ segments = preg_split ( '/\/(\{.*?\})/' , preg_replace ( '/\{(.*?)\?\}/' , '{$1}' , $ uri ) , - 1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ) ; $ uris = [ ] ; while ( $ segments ) { $ uris [ ] = implode ( '/' , $ segments ) ; array_pop ( $ segments ) ; } return $ uris ; }
Break a URI that has optional segments into individual URIs .
816
protected function removeMiddlewareFromApp ( ) { if ( $ this -> middlewareRemoved ) { return ; } $ this -> middlewareRemoved = true ; $ reflection = new ReflectionClass ( $ this -> app ) ; $ property = $ reflection -> getProperty ( 'middleware' ) ; $ property -> setAccessible ( true ) ; $ oldMiddlewares = $ property -> getValue ( $ this -> app ) ; $ newMiddlewares = [ ] ; foreach ( $ oldMiddlewares as $ middle ) { if ( ( new ReflectionClass ( $ middle ) ) -> hasMethod ( 'terminate' ) && $ middle != 'Dingo\Api\Http\Middleware\Request' ) { $ newMiddlewares = array_merge ( $ newMiddlewares , [ $ middle ] ) ; } } $ property -> setValue ( $ this -> app , $ newMiddlewares ) ; $ property -> setAccessible ( false ) ; }
Remove the global application middleware as it s run from this packages Request middleware . Lumen runs middleware later in its life cycle which results in some middleware being executed twice .
817
public function getIterableRoutes ( $ version = null ) { $ iterable = [ ] ; foreach ( $ this -> getRoutes ( $ version ) as $ version => $ collector ) { $ routeData = $ collector -> getData ( ) ; foreach ( $ this -> normalizeStaticRoutes ( $ routeData [ 0 ] ) as $ method => $ routes ) { if ( $ method === 'HEAD' ) { continue ; } foreach ( $ routes as $ route ) { $ route [ 'methods' ] = $ this -> setRouteMethods ( $ route , $ method ) ; $ iterable [ $ version ] [ ] = $ route ; } } foreach ( $ routeData [ 1 ] as $ method => $ routes ) { if ( $ method === 'HEAD' ) { continue ; } foreach ( $ routes as $ data ) { foreach ( $ data [ 'routeMap' ] as list ( $ route , $ parameters ) ) { $ route [ 'methods' ] = $ this -> setRouteMethods ( $ route , $ method ) ; $ iterable [ $ version ] [ ] = $ route ; } } } } return new ArrayIterator ( $ iterable ) ; }
Get routes in an iterable form .
818
public function terminate ( $ request , $ response ) { if ( ! ( $ request = $ this -> app [ 'request' ] ) instanceof HttpRequest ) { return ; } $ middlewares = $ this -> gatherRouteMiddlewares ( $ request ) ; if ( class_exists ( Application :: class , false ) ) { $ middlewares = array_merge ( $ middlewares , $ this -> middleware ) ; } foreach ( $ middlewares as $ middleware ) { if ( $ middleware instanceof Closure ) { continue ; } list ( $ name , $ parameters ) = $ this -> parseMiddleware ( $ middleware ) ; $ instance = $ this -> app -> make ( $ name ) ; if ( method_exists ( $ instance , 'terminate' ) ) { $ instance -> terminate ( $ request , $ response ) ; } } }
Call the terminate method on middlewares .
819
protected function setupRouteProperties ( Request $ request , $ route ) { list ( $ this -> uri , $ this -> methods , $ this -> action ) = $ this -> adapter -> getRouteProperties ( $ route , $ request ) ; $ this -> versions = Arr :: pull ( $ this -> action , 'version' ) ; $ this -> conditionalRequest = Arr :: pull ( $ this -> action , 'conditionalRequest' , true ) ; $ this -> middleware = ( array ) Arr :: pull ( $ this -> action , 'middleware' , [ ] ) ; $ this -> throttle = Arr :: pull ( $ this -> action , 'throttle' ) ; $ this -> scopes = Arr :: pull ( $ this -> action , 'scopes' , [ ] ) ; $ this -> authenticationProviders = Arr :: pull ( $ this -> action , 'providers' , [ ] ) ; $ this -> rateLimit = Arr :: pull ( $ this -> action , 'limit' , 0 ) ; $ this -> rateExpiration = Arr :: pull ( $ this -> action , 'expires' , 0 ) ; $ this -> mergeControllerProperties ( ) ; if ( is_string ( $ this -> throttle ) ) { $ this -> throttle = $ this -> container -> make ( $ this -> throttle ) ; } }
Setup the route properties .
820
protected function mergeControllerProperties ( ) { if ( isset ( $ this -> action [ 'uses' ] ) && is_string ( $ this -> action [ 'uses' ] ) && Str :: contains ( $ this -> action [ 'uses' ] , '@' ) ) { $ this -> action [ 'controller' ] = $ this -> action [ 'uses' ] ; $ this -> makeControllerInstance ( ) ; } if ( ! $ this -> controllerUsesHelpersTrait ( ) ) { return ; } $ controller = $ this -> getControllerInstance ( ) ; $ controllerMiddleware = [ ] ; if ( method_exists ( $ controller , 'getMiddleware' ) ) { $ controllerMiddleware = $ controller -> getMiddleware ( ) ; } elseif ( method_exists ( $ controller , 'getMiddlewareForMethod' ) ) { $ controllerMiddleware = $ controller -> getMiddlewareForMethod ( $ this -> controllerMethod ) ; } $ this -> middleware = array_merge ( $ this -> middleware , $ controllerMiddleware ) ; if ( $ property = $ this -> findControllerPropertyOptions ( 'throttles' ) ) { $ this -> throttle = $ property [ 'class' ] ; } if ( $ property = $ this -> findControllerPropertyOptions ( 'scopes' ) ) { $ this -> scopes = array_merge ( $ this -> scopes , $ property [ 'scopes' ] ) ; } if ( $ property = $ this -> findControllerPropertyOptions ( 'authenticationProviders' ) ) { $ this -> authenticationProviders = array_merge ( $ this -> authenticationProviders , $ property [ 'providers' ] ) ; } if ( $ property = $ this -> findControllerPropertyOptions ( 'rateLimit' ) ) { $ this -> rateLimit = $ property [ 'limit' ] ; $ this -> rateExpiration = $ property [ 'expires' ] ; } }
Merge the controller properties onto the route properties .
821
protected function findControllerPropertyOptions ( $ name ) { $ properties = [ ] ; foreach ( $ this -> getControllerInstance ( ) -> { 'get' . ucfirst ( $ name ) } ( ) as $ property ) { if ( isset ( $ property [ 'options' ] ) && ! $ this -> optionsApplyToControllerMethod ( $ property [ 'options' ] ) ) { continue ; } unset ( $ property [ 'options' ] ) ; $ properties = array_merge_recursive ( $ properties , $ property ) ; } return $ properties ; }
Find the controller options and whether or not it will apply to this routes controller method .
822
protected function optionsApplyToControllerMethod ( array $ options ) { if ( empty ( $ options ) ) { return true ; } elseif ( isset ( $ options [ 'only' ] ) && in_array ( $ this -> controllerMethod , $ this -> explodeOnPipes ( $ options [ 'only' ] ) ) ) { return true ; } elseif ( isset ( $ options [ 'except' ] ) ) { return ! in_array ( $ this -> controllerMethod , $ this -> explodeOnPipes ( $ options [ 'except' ] ) ) ; } elseif ( in_array ( $ this -> controllerMethod , $ this -> explodeOnPipes ( $ options ) ) ) { return true ; } return false ; }
Determine if a controller method is in an array of options .
823
protected function controllerUsesHelpersTrait ( ) { if ( ! $ controller = $ this -> getControllerInstance ( ) ) { return false ; } $ traits = [ ] ; do { $ traits = array_merge ( class_uses ( $ controller , false ) , $ traits ) ; } while ( $ controller = get_parent_class ( $ controller ) ) ; foreach ( $ traits as $ trait => $ same ) { $ traits = array_merge ( class_uses ( $ trait , false ) , $ traits ) ; } return isset ( $ traits [ Helpers :: class ] ) ; }
Determine if the controller instance uses the helpers trait .
824
protected function makeControllerInstance ( ) { list ( $ this -> controllerClass , $ this -> controllerMethod ) = explode ( '@' , $ this -> action [ 'uses' ] ) ; $ this -> container -> instance ( $ this -> controllerClass , $ this -> controller = $ this -> container -> make ( $ this -> controllerClass ) ) ; return $ this -> controller ; }
Make a new controller instance through the container .
825
public function isProtected ( ) { if ( isset ( $ this -> middleware [ 'api.auth' ] ) || in_array ( 'api.auth' , $ this -> middleware ) ) { if ( $ this -> controller && isset ( $ this -> middleware [ 'api.auth' ] ) ) { return $ this -> optionsApplyToControllerMethod ( $ this -> middleware [ 'api.auth' ] ) ; } return true ; } return false ; }
Determine if the route is protected .
826
protected function getToken ( Request $ request ) { try { $ this -> validateAuthorizationHeader ( $ request ) ; $ token = $ this -> parseAuthorizationHeader ( $ request ) ; } catch ( Exception $ exception ) { if ( ! $ token = $ request -> query ( 'token' , false ) ) { throw $ exception ; } } return $ token ; }
Get the JWT from the request .
827
protected function isCustomIndentStyleRequired ( ) { return $ this -> isJsonPrettyPrintEnabled ( ) && isset ( $ this -> options [ 'indent_style' ] ) && in_array ( $ this -> options [ 'indent_style' ] , $ this -> indentStyles ) ; }
Determine if JSON custom indent style is set .
828
protected function performJsonEncoding ( $ content , array $ jsonEncodeOptions = [ ] ) { $ jsonEncodeOptions = $ this -> filterJsonEncodeOptions ( $ jsonEncodeOptions ) ; $ optionsBitmask = $ this -> calucateJsonEncodeOptionsBitmask ( $ jsonEncodeOptions ) ; if ( ( $ encodedString = json_encode ( $ content , $ optionsBitmask ) ) === false ) { throw new \ ErrorException ( 'Error encoding data in JSON format: ' . json_last_error ( ) ) ; } return $ encodedString ; }
Perform JSON encode .
829
protected function indentPrettyPrintedJson ( $ jsonString , $ indentStyle , $ defaultIndentSize = 2 ) { $ indentChar = $ this -> getIndentCharForIndentStyle ( $ indentStyle ) ; $ indentSize = $ this -> getPrettyPrintIndentSize ( ) ? : $ defaultIndentSize ; if ( $ this -> hasVariousIndentSize ( $ indentStyle ) ) { return $ this -> peformIndentation ( $ jsonString , $ indentChar , $ indentSize ) ; } return $ this -> peformIndentation ( $ jsonString , $ indentChar ) ; }
Indent pretty printed JSON string using given indent style .
830
protected function peformIndentation ( $ jsonString , $ indentChar = "\t" , $ indentSize = 1 , $ defaultSpaces = 4 ) { $ pattern = '/(^|\G) {' . $ defaultSpaces . '}/m' ; $ replacement = str_repeat ( $ indentChar , $ indentSize ) . '$1' ; return preg_replace ( $ pattern , $ replacement , $ jsonString ) ; }
Perform indentation for pretty printed JSON string with a given indent char repeated N times as determined by indent size .
831
protected function config ( $ item , $ instantiate = true ) { $ value = $ this -> app [ 'config' ] -> get ( 'api.' . $ item ) ; if ( is_array ( $ value ) ) { return $ instantiate ? $ this -> instantiateConfigValues ( $ item , $ value ) : $ value ; } return $ instantiate ? $ this -> instantiateConfigValue ( $ item , $ value ) : $ value ; }
Retrieve and instantiate a config value if it exists and is a class .
832
protected function instantiateConfigValues ( $ item , array $ values ) { foreach ( $ values as $ key => $ value ) { $ values [ $ key ] = $ this -> instantiateConfigValue ( $ item , $ value ) ; } return $ values ; }
Instantiate an array of instantiable configuration values .
833
public function validate ( Request $ request ) { try { $ this -> accept -> parse ( $ request , $ this -> strict ) ; } catch ( BadRequestHttpException $ exception ) { if ( $ request -> getMethod ( ) === 'OPTIONS' ) { return true ; } throw $ exception ; } }
Validate the accept header on the request . If this fails it will throw an HTTP exception that will be caught by the middleware . This validator should always be run last and must not return a success boolean .
834
protected function updateRouterBindings ( ) { foreach ( $ this -> getRouterBindings ( ) as $ key => $ binding ) { $ this -> app [ 'api.router.adapter' ] -> getRouter ( ) -> bind ( $ key , $ binding ) ; } }
Grab the bindings from the Laravel router and set them on the adapters router .
835
public function version ( $ version , $ second , $ third = null ) { if ( func_num_args ( ) == 2 ) { list ( $ version , $ callback , $ attributes ) = array_merge ( func_get_args ( ) , [ [ ] ] ) ; } else { list ( $ version , $ attributes , $ callback ) = func_get_args ( ) ; } $ attributes = array_merge ( $ attributes , [ 'version' => $ version ] ) ; $ this -> group ( $ attributes , $ callback ) ; }
An alias for calling the group method allows a more fluent API for registering a new API version group with optional attributes and a required callback .
836
public function resource ( $ name , $ controller , array $ options = [ ] ) { if ( $ this -> container -> bound ( ResourceRegistrar :: class ) ) { $ registrar = $ this -> container -> make ( ResourceRegistrar :: class ) ; } else { $ registrar = new ResourceRegistrar ( $ this ) ; } $ registrar -> register ( $ name , $ controller , $ options ) ; }
Register a resource controller .
837
protected function mergeLastGroupAttributes ( array $ attributes ) { if ( empty ( $ this -> groupStack ) ) { return $ this -> mergeGroup ( $ attributes , [ ] ) ; } return $ this -> mergeGroup ( $ attributes , end ( $ this -> groupStack ) ) ; }
Merge the last groups attributes .
838
public function dispatch ( Request $ request ) { $ this -> currentRoute = null ; $ this -> container -> instance ( Request :: class , $ request ) ; $ this -> routesDispatched ++ ; try { $ response = $ this -> adapter -> dispatch ( $ request , $ request -> version ( ) ) ; } catch ( Exception $ exception ) { if ( $ request instanceof InternalRequest ) { throw $ exception ; } $ this -> exception -> report ( $ exception ) ; $ response = $ this -> exception -> handle ( $ exception ) ; } return $ this -> prepareResponse ( $ response , $ request , $ request -> format ( ) ) ; }
Dispatch a request via the adapter .
839
public function createRoute ( $ route ) { return new Route ( $ this -> adapter , $ this -> container , $ this -> container [ 'request' ] , $ route ) ; }
Create a new route instance from an adapter route .
840
public function getRoutes ( $ version = null ) { $ routes = $ this -> adapter -> getIterableRoutes ( $ version ) ; if ( ! is_null ( $ version ) ) { $ routes = [ $ version => $ routes ] ; } $ collections = [ ] ; foreach ( $ routes as $ key => $ value ) { $ collections [ $ key ] = new RouteCollection ( $ this -> container [ 'request' ] ) ; foreach ( $ value as $ route ) { $ route = $ this -> createRoute ( $ route ) ; $ collections [ $ key ] -> add ( $ route ) ; } } return is_null ( $ version ) ? $ collections : $ collections [ $ version ] ; }
Get all routes registered on the adapter .
841
public function setAdapterRoutes ( array $ routes ) { $ this -> adapter -> setRoutes ( $ routes ) ; $ this -> container -> instance ( 'api.routes' , $ this -> getRoutes ( ) ) ; }
Set the raw adapter routes .
842
protected function filterProviders ( array $ providers ) { if ( empty ( $ providers ) ) { return $ this -> providers ; } return array_intersect_key ( $ this -> providers , array_flip ( $ providers ) ) ; }
Filter the requested providers from the available providers .
843
public function extend ( $ key , $ provider ) { if ( is_callable ( $ provider ) ) { $ provider = call_user_func ( $ provider , $ this -> container ) ; } $ this -> providers [ $ key ] = $ provider ; }
Extend the authentication layer with a custom provider .
844
public function handle ( $ request , Closure $ next ) { if ( $ request instanceof InternalRequest ) { return $ next ( $ request ) ; } $ route = $ this -> router -> getCurrentRoute ( ) ; if ( $ route -> hasThrottle ( ) ) { $ this -> handler -> setThrottle ( $ route -> getThrottle ( ) ) ; } $ this -> handler -> rateLimitRequest ( $ request , $ route -> getRateLimit ( ) , $ route -> getRateLimitExpiration ( ) ) ; if ( $ this -> handler -> exceededRateLimit ( ) ) { throw new RateLimitExceededException ( 'You have exceeded your rate limit.' , null , $ this -> getHeaders ( ) ) ; } $ response = $ next ( $ request ) ; if ( $ this -> handler -> requestWasRateLimited ( ) ) { return $ this -> responseWithHeaders ( $ response ) ; } return $ response ; }
Perform rate limiting before a request is executed .
845
protected function responseWithHeaders ( $ response ) { foreach ( $ this -> getHeaders ( ) as $ key => $ value ) { $ response -> headers -> set ( $ key , $ value ) ; } return $ response ; }
Send the response with the rate limit headers .
846
protected function getHeaders ( ) { return [ 'X-RateLimit-Limit' => $ this -> handler -> getThrottleLimit ( ) , 'X-RateLimit-Remaining' => $ this -> handler -> getRemainingLimit ( ) , 'X-RateLimit-Reset' => $ this -> handler -> getRateLimitReset ( ) , ] ; }
Get the headers for the response .
847
protected function getDocName ( ) { $ name = $ this -> option ( 'name' ) ? : $ this -> name ; if ( ! $ name ) { $ this -> comment ( 'A name for the documentation was not supplied. Use the --name option or set a default in the configuration.' ) ; exit ; } return $ name ; }
Get the documentation name .
848
protected function getVersion ( ) { $ version = $ this -> option ( 'use-version' ) ? : $ this -> version ; if ( ! $ version ) { $ this -> comment ( 'A version for the documentation was not supplied. Use the --use-version option or set a default in the configuration.' ) ; exit ; } return $ version ; }
Get the documentation version .
849
protected function getControllers ( ) { $ controllers = new Collection ; if ( $ controller = $ this -> option ( 'use-controller' ) ) { $ this -> addControllerIfNotExists ( $ controllers , app ( $ controller ) ) ; return $ controllers ; } foreach ( $ this -> router -> getRoutes ( ) as $ collections ) { foreach ( $ collections as $ route ) { if ( $ controller = $ route -> getControllerInstance ( ) ) { $ this -> addControllerIfNotExists ( $ controllers , $ controller ) ; } } } return $ controllers ; }
Get all the controller instances .
850
protected function addControllerIfNotExists ( Collection $ controllers , $ controller ) { $ class = get_class ( $ controller ) ; if ( $ controllers -> has ( $ class ) ) { return ; } $ reflection = new ReflectionClass ( $ controller ) ; $ interface = Arr :: first ( $ reflection -> getInterfaces ( ) , function ( $ key , $ value ) { return ends_with ( $ key , 'Docs' ) ; } ) ; if ( $ interface ) { $ controller = $ interface ; } $ controllers -> put ( $ class , $ controller ) ; }
Add a controller to the collection if it does not exist . If the controller implements an interface suffixed with Docs it will be used instead of the controller .
851
public function attach ( array $ files ) { foreach ( $ files as $ key => $ file ) { if ( is_array ( $ file ) ) { $ file = new UploadedFile ( $ file [ 'path' ] , basename ( $ file [ 'path' ] ) , $ file [ 'mime' ] , $ file [ 'size' ] ) ; } elseif ( is_string ( $ file ) ) { $ finfo = finfo_open ( FILEINFO_MIME_TYPE ) ; $ file = new UploadedFile ( $ file , basename ( $ file ) , finfo_file ( $ finfo , $ file ) , $ this -> files -> size ( $ file ) ) ; } elseif ( ! $ file instanceof UploadedFile ) { continue ; } $ this -> uploads [ $ key ] = $ file ; } return $ this ; }
Attach files to be uploaded .
852
public function json ( $ content ) { if ( is_array ( $ content ) ) { $ content = json_encode ( $ content ) ; } $ this -> content = $ content ; return $ this -> header ( 'Content-Type' , 'application/json' ) ; }
Send a JSON payload in the request body .
853
public function with ( $ parameters ) { $ this -> parameters = array_merge ( $ this -> parameters , is_array ( $ parameters ) ? $ parameters : func_get_args ( ) ) ; return $ this ; }
Set the parameters to be sent on the next API request .
854
protected function queueRequest ( $ verb , $ uri , $ parameters , $ content = '' ) { if ( ! empty ( $ content ) ) { $ this -> content = $ content ; } if ( end ( $ this -> requestStack ) != $ this -> container [ 'request' ] ) { $ this -> requestStack [ ] = $ this -> container [ 'request' ] ; } $ this -> requestStack [ ] = $ request = $ this -> createRequest ( $ verb , $ uri , $ parameters ) ; return $ this -> dispatch ( $ request ) ; }
Queue up and dispatch a new request .
855
protected function dispatch ( InternalRequest $ request ) { $ this -> routeStack [ ] = $ this -> router -> getCurrentRoute ( ) ; $ this -> clearCachedFacadeInstance ( ) ; try { $ this -> container -> instance ( 'request' , $ request ) ; $ response = $ this -> router -> dispatch ( $ request ) ; if ( ! $ response -> isSuccessful ( ) && ! $ response -> isRedirection ( ) ) { throw new InternalHttpException ( $ response ) ; } if ( ! $ this -> raw ) { $ response = $ response -> getOriginalContent ( ) ; } } catch ( HttpExceptionInterface $ exception ) { $ this -> refreshRequestStack ( ) ; throw $ exception ; } $ this -> refreshRequestStack ( ) ; return $ response ; }
Attempt to dispatch an internal request .
856
public function formatEloquentModel ( $ model ) { $ key = Str :: singular ( $ model -> getTable ( ) ) ; if ( ! $ model :: $ snakeAttributes ) { $ key = Str :: camel ( $ key ) ; } return $ this -> encode ( [ $ key => $ model -> toArray ( ) ] ) ; }
Format an Eloquent model .
857
public function formatEloquentCollection ( $ collection ) { if ( $ collection -> isEmpty ( ) ) { return $ this -> encode ( [ ] ) ; } $ model = $ collection -> first ( ) ; $ key = Str :: plural ( $ model -> getTable ( ) ) ; if ( ! $ model :: $ snakeAttributes ) { $ key = Str :: camel ( $ key ) ; } return $ this -> encode ( [ $ key => $ collection -> toArray ( ) ] ) ; }
Format an Eloquent collection .
858
protected function encode ( $ content ) { $ jsonEncodeOptions = [ ] ; if ( $ this -> isJsonPrettyPrintEnabled ( ) ) { $ jsonEncodeOptions [ ] = JSON_PRETTY_PRINT ; } $ encodedString = $ this -> performJsonEncoding ( $ content , $ jsonEncodeOptions ) ; if ( $ this -> isCustomIndentStyleRequired ( ) ) { $ encodedString = $ this -> indentPrettyPrintedJson ( $ encodedString , $ this -> options [ 'indent_style' ] ) ; } return $ encodedString ; }
Encode the content to its JSON representation .
859
public function rateLimitRequest ( Request $ request , $ limit = 0 , $ expires = 0 ) { $ this -> request = $ request ; if ( $ this -> throttle instanceof Throttle ) { } elseif ( $ limit > 0 || $ expires > 0 ) { $ this -> throttle = new Route ( [ 'limit' => $ limit , 'expires' => $ expires ] ) ; $ this -> keyPrefix = sha1 ( $ request -> path ( ) ) ; } else { $ this -> throttle = $ this -> getMatchingThrottles ( ) -> sort ( function ( $ a , $ b ) { return $ a -> getLimit ( ) < $ b -> getLimit ( ) ; } ) -> first ( ) ; } if ( is_null ( $ this -> throttle ) ) { return ; } if ( $ this -> throttle instanceof HasRateLimiter ) { $ this -> setRateLimiter ( [ $ this -> throttle , 'getRateLimiter' ] ) ; } $ this -> prepareCacheStore ( ) ; $ this -> cache ( 'requests' , 0 , $ this -> throttle -> getExpires ( ) ) ; $ this -> cache ( 'expires' , $ this -> throttle -> getExpires ( ) , $ this -> throttle -> getExpires ( ) ) ; $ this -> cache ( 'reset' , time ( ) + ( $ this -> throttle -> getExpires ( ) * 60 ) , $ this -> throttle -> getExpires ( ) ) ; $ this -> increment ( 'requests' ) ; }
Execute the rate limiting for the given request .
860
protected function prepareCacheStore ( ) { if ( $ this -> retrieve ( 'expires' ) != $ this -> throttle -> getExpires ( ) ) { $ this -> forget ( 'requests' ) ; $ this -> forget ( 'expires' ) ; $ this -> forget ( 'reset' ) ; } }
Prepare the cache store .
861
protected function cache ( $ key , $ value , $ minutes ) { $ this -> cache -> add ( $ this -> key ( $ key ) , $ value , Carbon :: now ( ) -> addMinutes ( $ minutes ) ) ; }
Cache a value under a given key for a certain amount of minutes .
862
public function extend ( $ throttle ) { if ( is_callable ( $ throttle ) ) { $ throttle = call_user_func ( $ throttle , $ this -> container ) ; } $ this -> throttles -> push ( $ throttle ) ; }
Extend the rate limiter by adding a new throttle .
863
public function loadPlugins ( ) { $ this -> checkCache ( ) ; $ this -> validatePlugins ( ) ; $ this -> countPlugins ( ) ; array_map ( static function ( ) { include_once WPMU_PLUGIN_DIR . '/' . func_get_args ( ) [ 0 ] ; } , array_keys ( self :: $ cache [ 'plugins' ] ) ) ; $ this -> pluginHooks ( ) ; }
Run some checks then autoload our plugins .
864
private function checkCache ( ) { $ cache = get_site_option ( 'bedrock_autoloader' ) ; if ( $ cache === false || ( isset ( $ cache [ 'plugins' ] , $ cache [ 'count' ] ) && count ( $ cache [ 'plugins' ] ) !== $ cache [ 'count' ] ) ) { $ this -> updateCache ( ) ; return ; } self :: $ cache = $ cache ; }
This sets the cache or calls for an update
865
private function validatePlugins ( ) { foreach ( self :: $ cache [ 'plugins' ] as $ plugin_file => $ plugin_info ) { if ( ! file_exists ( WPMU_PLUGIN_DIR . '/' . $ plugin_file ) ) { $ this -> updateCache ( ) ; break ; } } }
Check that the plugin file exists if it doesn t update the cache .
866
private function countPlugins ( ) { if ( isset ( self :: $ count ) ) { return self :: $ count ; } $ count = count ( glob ( WPMU_PLUGIN_DIR . '/*/' , GLOB_ONLYDIR | GLOB_NOSORT ) ) ; if ( ! isset ( self :: $ cache [ 'count' ] ) || $ count !== self :: $ cache [ 'count' ] ) { self :: $ count = $ count ; $ this -> updateCache ( ) ; } return self :: $ count ; }
Count the number of autoloaded plugins .
867
public static function serialize ( $ filename , $ instance , $ force = false ) { if ( $ filename == '' ) { throw new \ danog \ MadelineProto \ Exception ( 'Empty filename' ) ; } if ( $ instance -> API -> asyncInitPromise ) { return $ instance -> call ( static function ( ) use ( $ filename , $ instance , $ force ) { yield $ instance -> API -> asyncInitPromise ; $ instance -> API -> asyncInitPromise = null ; return self :: serialize ( $ filename , $ instance , $ force ) ; } ) ; } if ( isset ( $ instance -> API -> setdem ) && $ instance -> API -> setdem ) { $ instance -> API -> setdem = false ; $ instance -> API -> __construct ( $ instance -> API -> settings ) ; } if ( $ instance -> API === null && ! $ instance -> getting_api_id ) { return false ; } $ instance -> serialized = time ( ) ; $ realpaths = self :: realpaths ( $ filename ) ; if ( ! file_exists ( $ realpaths [ 'lockfile' ] ) ) { touch ( $ realpaths [ 'lockfile' ] ) ; clearstatcache ( ) ; } $ realpaths [ 'lockfile' ] = fopen ( $ realpaths [ 'lockfile' ] , 'w' ) ; \ danog \ MadelineProto \ Logger :: log ( 'Waiting for exclusive lock of serialization lockfile...' ) ; flock ( $ realpaths [ 'lockfile' ] , LOCK_EX ) ; \ danog \ MadelineProto \ Logger :: log ( 'Lock acquired, serializing' ) ; try { if ( ! $ instance -> getting_api_id ) { $ update_closure = $ instance -> API -> settings [ 'updates' ] [ 'callback' ] ; if ( $ instance -> API -> settings [ 'updates' ] [ 'callback' ] instanceof \ Closure ) { $ instance -> API -> settings [ 'updates' ] [ 'callback' ] = [ $ instance -> API , 'noop' ] ; } $ logger_closure = $ instance -> API -> settings [ 'logger' ] [ 'logger_param' ] ; if ( $ instance -> API -> settings [ 'logger' ] [ 'logger_param' ] instanceof \ Closure ) { $ instance -> API -> settings [ 'logger' ] [ 'logger_param' ] = [ $ instance -> API , 'noop' ] ; } } $ wrote = file_put_contents ( $ realpaths [ 'tempfile' ] , serialize ( $ instance ) ) ; rename ( $ realpaths [ 'tempfile' ] , $ realpaths [ 'file' ] ) ; } finally { if ( ! $ instance -> getting_api_id ) { $ instance -> API -> settings [ 'updates' ] [ 'callback' ] = $ update_closure ; $ instance -> API -> settings [ 'logger' ] [ 'logger_param' ] = $ logger_closure ; } flock ( $ realpaths [ 'lockfile' ] , LOCK_UN ) ; fclose ( $ realpaths [ 'lockfile' ] ) ; } return $ wrote ; }
Serialize API class .
868
public function bufferReadAsync ( int $ length ) : \ Generator { return @ $ this -> decrypt -> encrypt ( yield $ this -> read_buffer -> bufferRead ( $ length ) ) ; }
Decrypts read data asynchronously .
869
public function setExtra ( $ extra ) { if ( isset ( $ extra [ 'secret' ] ) && strlen ( $ extra [ 'secret' ] ) > 17 ) { $ extra [ 'secret' ] = hex2bin ( $ extra [ 'secret' ] ) ; } if ( isset ( $ extra [ 'secret' ] ) && strlen ( $ extra [ 'secret' ] ) == 17 ) { $ extra [ 'secret' ] = substr ( $ extra [ 'secret' ] , 0 , 16 ) ; } $ this -> extra = $ extra ; }
Does nothing .
870
public function read ( ) : Promise { return $ this -> stream ? $ this -> stream -> read ( ) : new \ Amp \ Success ( null ) ; }
Async chunked read .
871
public function setExtra ( $ extra ) { if ( isset ( $ extra [ 'user' ] ) && isset ( $ extra [ 'password' ] ) ) { $ this -> header = \ base64_encode ( $ extra [ 'user' ] . ':' . $ extra [ 'password' ] ) . "\r\n" ; } }
Set proxy data .
872
private function get_headers ( $ httpType , $ cookies ) { $ headers = [ ] ; $ headers [ ] = 'Dnt: 1' ; $ headers [ ] = 'Connection: keep-alive' ; $ headers [ ] = 'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4' ; $ headers [ ] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' ; switch ( $ httpType ) { case 'origin' : $ headers [ ] = 'Origin: ' . self :: MY_TELEGRAM_URL ; $ headers [ ] = 'Accept-Encoding: gzip, deflate, br' ; $ headers [ ] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' ; $ headers [ ] = 'Accept: application/json, text/javascript, */*; q=0.01' ; $ headers [ ] = 'Referer: ' . self :: MY_TELEGRAM_URL . '/auth' ; $ headers [ ] = 'X-Requested-With: XMLHttpRequest' ; break ; case 'refer' : $ headers [ ] = 'Accept-Encoding: gzip, deflate, sdch, br' ; $ headers [ ] = 'Upgrade-Insecure-Requests: 1' ; $ headers [ ] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' ; $ headers [ ] = 'Referer: ' . self :: MY_TELEGRAM_URL ; $ headers [ ] = 'Cache-Control: max-age=0' ; break ; case 'app' : $ headers [ ] = 'Origin: ' . self :: MY_TELEGRAM_URL ; $ headers [ ] = 'Accept-Encoding: gzip, deflate, br' ; $ headers [ ] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' ; $ headers [ ] = 'Accept: */*' ; $ headers [ ] = 'Referer: ' . self :: MY_TELEGRAM_URL . '/apps' ; $ headers [ ] = 'X-Requested-With: XMLHttpRequest' ; break ; } foreach ( $ cookies as $ cookie ) { $ headers [ ] = 'Cookie: ' . $ cookie ; } return $ headers ; }
Function for generating curl request headers .
873
public function setUri ( $ uri ) : self { $ this -> uri = $ uri instanceof Uri ? $ uri : new Uri ( $ uri ) ; return $ this ; }
Set the connection URI .
874
public function getIntDc ( ) { $ dc = intval ( $ this -> dc ) ; if ( $ this -> test ) { $ dc += 10000 ; } if ( strpos ( $ this -> dc , '_media' ) ) { $ dc = - $ dc ; } return $ dc ; }
Get the int DC ID .
875
public function addStream ( string $ streamName , $ extra = null ) : self { $ this -> nextStreams [ ] = [ $ streamName , $ extra ] ; $ this -> key = count ( $ this -> nextStreams ) - 1 ; return $ this ; }
Add a stream to the stream chain .
876
public function getStreamAsync ( string $ buffer = '' ) : \ Generator { list ( $ clazz , $ extra ) = $ this -> nextStreams [ $ this -> key -- ] ; $ obj = new $ clazz ( ) ; if ( $ obj instanceof ProxyStreamInterface ) { $ obj -> setExtra ( $ extra ) ; } yield $ obj -> connect ( $ this , $ buffer ) ; return $ obj ; }
Get a stream from the stream chain .
877
public function getName ( ) : string { $ string = $ this -> getStringUri ( ) ; if ( $ this -> isSecure ( ) ) { $ string .= ' (TLS)' ; } $ string .= ' DC ' ; $ string .= $ this -> getDc ( ) ; $ string .= ', via ' ; $ string .= $ this -> getIpv6 ( ) ? 'ipv6' : 'ipv4' ; $ string .= ' using ' ; foreach ( array_reverse ( $ this -> nextStreams ) as $ k => $ stream ) { if ( $ k ) { $ string .= ' => ' ; } $ string .= preg_replace ( '/.*\\\\/' , '' , $ stream [ 0 ] ) ; if ( $ stream [ 1 ] ) { $ string .= ' (' . json_encode ( $ stream [ 1 ] ) . ')' ; } } return $ string ; }
Get a description name of the context .
878
private function setProperties ( ) { \ danog \ MadelineProto \ Logger :: log ( 'Generating properties...' , \ danog \ MadelineProto \ Logger :: NOTICE ) ; $ fixture = DocBlockFactory :: createInstance ( ) ; $ class = new \ ReflectionClass ( APIFactory :: class ) ; $ content = file_get_contents ( $ filename = $ class -> getFileName ( ) ) ; foreach ( $ class -> getProperties ( ) as $ property ) { if ( $ raw_docblock = $ property -> getDocComment ( ) ) { $ docblock = $ fixture -> create ( $ raw_docblock ) ; if ( $ docblock -> hasTag ( 'internal' ) ) { $ content = str_replace ( "\n " . $ raw_docblock . "\n public \$" . $ property -> getName ( ) . ';' , '' , $ content ) ; } } } foreach ( $ this -> get_method_namespaces ( ) as $ namespace ) { $ content = preg_replace ( '/(class( \\w+[,]?){0,}\\n{\\n)/' , '${1}' . " /**\n" . " * @internal this is a internal property generated by build_docs.php, don't change manually\n" . " *\n" . " * @var {$namespace}\n" . " */\n" . " public \${$namespace};\n" , $ content ) ; } file_put_contents ( $ filename , $ content ) ; }
Open file of class APIFactory Insert properties save the file with new content .
879
public function getReadHash ( ) : string { $ hash = hash_final ( $ this -> read_hash , true ) ; if ( $ this -> rev ) { $ hash = strrev ( $ hash ) ; } $ this -> read_hash = null ; $ this -> read_check_after = 0 ; $ this -> read_check_pos = 0 ; return $ hash ; }
Stop read hashing and get final hash .
880
public function getWriteHash ( ) : string { $ hash = hash_final ( $ this -> write_hash , true ) ; if ( $ this -> rev ) { $ hash = strrev ( $ hash ) ; } $ this -> write_hash = null ; $ this -> write_check_after = 0 ; $ this -> write_check_pos = 0 ; return $ hash ; }
Stop write hashing and get final hash .
881
public function bufferReadAsync ( int $ length ) : \ Generator { if ( $ this -> read_check_after && $ length + $ this -> read_check_pos >= $ this -> read_check_after ) { if ( $ length + $ this -> read_check_pos > $ this -> read_check_after ) { throw new \ danog \ MadelineProto \ Exception ( 'Tried to read too much out of frame data' ) ; } $ data = yield $ this -> read_buffer -> bufferRead ( $ length ) ; hash_update ( $ this -> read_hash , $ data ) ; $ hash = $ this -> getReadHash ( ) ; if ( $ hash !== yield $ this -> read_buffer -> bufferRead ( strlen ( $ hash ) ) ) { throw new \ danog \ MadelineProto \ Exception ( 'Hash mismatch' ) ; } return $ data ; } $ data = yield $ this -> read_buffer -> bufferRead ( $ length ) ; hash_update ( $ this -> read_hash , $ data ) ; if ( $ this -> read_check_after ) { $ this -> read_check_pos += $ length ; } return $ data ; }
Hashes read data asynchronously .
882
public function setExtra ( $ hash ) { $ rev = strpos ( $ hash , '_rev' ) ; $ this -> rev = false ; if ( $ rev !== false ) { $ hash = substr ( $ hash , 0 , $ rev ) ; $ this -> rev = true ; } $ this -> hash_name = $ hash ; }
Set the hash algorithm .
883
public function connect ( ConnectionContext $ ctx , string $ header = '' ) : Promise { $ this -> in_seq_no = - 1 ; $ this -> out_seq_no = - 1 ; $ this -> stream = new HashedBufferedStream ( ) ; $ this -> stream -> setExtra ( 'crc32b_rev' ) ; return $ this -> stream -> connect ( $ ctx , $ header ) ; }
Stream to use as data source .
884
public function bufferWrite ( string $ data ) : Promise { if ( $ this -> append_after ) { $ this -> append_after -= strlen ( $ data ) ; if ( $ this -> append_after === 0 ) { $ data .= $ this -> append ; $ this -> append = '' ; } elseif ( $ this -> append_after < 0 ) { $ this -> append_after = 0 ; $ this -> append = '' ; throw new Exception ( 'Tried to send too much out of frame data, cannot append' ) ; } } return $ this -> write ( $ data ) ; }
Async write .
885
public function connectAsync ( ConnectionContext $ ctx ) : \ Generator { $ this -> API -> logger -> logger ( "Trying connection via $ctx" , \ danog \ MadelineProto \ Logger :: WARNING ) ; $ this -> ctx = $ ctx -> getCtx ( ) ; $ this -> datacenter = $ ctx -> getDc ( ) ; $ this -> stream = yield $ ctx -> getStream ( ) ; if ( isset ( $ this -> old ) ) { unset ( $ this -> old ) ; } if ( ! isset ( $ this -> writer ) ) { $ this -> writer = new WriteLoop ( $ this -> API , $ this -> datacenter ) ; } if ( ! isset ( $ this -> reader ) ) { $ this -> reader = new ReadLoop ( $ this -> API , $ this -> datacenter ) ; } if ( ! isset ( $ this -> checker ) ) { $ this -> checker = new CheckLoop ( $ this -> API , $ this -> datacenter ) ; } if ( ! isset ( $ this -> waiter ) ) { $ this -> waiter = new HttpWaitLoop ( $ this -> API , $ this -> datacenter ) ; } if ( ! isset ( $ this -> updater ) ) { $ this -> updater = new UpdateLoop ( $ this -> API , $ this -> datacenter ) ; } foreach ( $ this -> new_outgoing as $ message_id ) { if ( $ this -> outgoing_messages [ $ message_id ] [ 'unencrypted' ] ) { $ promise = $ this -> outgoing_messages [ $ message_id ] [ 'promise' ] ; \ Amp \ Loop :: defer ( function ( ) use ( $ promise ) { $ promise -> fail ( new Exception ( 'Restart' ) ) ; } ) ; unset ( $ this -> new_outgoing [ $ message_id ] ) ; unset ( $ this -> outgoing_messages [ $ message_id ] ) ; } } $ this -> http_req_count = 0 ; $ this -> http_res_count = 0 ; $ this -> writer -> start ( ) ; $ this -> reader -> start ( ) ; if ( ! $ this -> checker -> start ( ) ) { $ this -> checker -> resume ( ) ; } $ this -> waiter -> start ( ) ; if ( $ this -> datacenter === $ this -> API -> settings [ 'connection_settings' ] [ 'default_dc' ] ) { $ this -> updater -> start ( ) ; } }
Connect function .
886
public function fetchParametersAsync ( ) : \ Generator { $ refetchable = $ this -> isRefetchable ( ) ; if ( $ this -> fetched && ! $ refetchable ) { return $ this -> params ; } $ params = yield call ( [ $ this , 'getParameters' ] ) ; if ( ! $ refetchable ) { $ this -> params = $ params ; } return $ params ; }
Fetch parameters asynchronously .
887
public function connect_to_all_dcs_async ( ) : \ Generator { $ this -> datacenter -> __construct ( $ this , $ this -> settings [ 'connection' ] , $ this -> settings [ 'connection_settings' ] ) ; $ dcs = [ ] ; foreach ( $ this -> datacenter -> get_dcs ( ) as $ new_dc ) { $ dcs [ ] = $ this -> datacenter -> dc_connect_async ( $ new_dc ) ; } yield $ dcs ; yield $ this -> init_authorization_async ( ) ; $ dcs = [ ] ; foreach ( $ this -> datacenter -> get_dcs ( false ) as $ new_dc ) { $ dcs [ ] = $ this -> datacenter -> dc_connect_async ( $ new_dc ) ; } yield $ dcs ; yield $ this -> init_authorization_async ( ) ; if ( ! $ this -> phoneConfigWatcherId ) { $ this -> phoneConfigWatcherId = Loop :: repeat ( 24 * 3600 * 1000 , [ $ this , 'get_phone_config_async' ] ) ; } yield $ this -> get_phone_config_async ( ) ; $ this -> logger -> logger ( "Started phone config fetcher" ) ; }
Connects to all datacenters and if necessary creates authorization keys binds them and writes client info
888
public function repeat ( $ question = '' ) { $ conversation = $ this -> bot -> getStoredConversation ( ) ; if ( ! $ question instanceof Question && ! $ question ) { $ question = unserialize ( $ conversation [ 'question' ] ) ; } $ next = $ conversation [ 'next' ] ; $ additionalParameters = unserialize ( $ conversation [ 'additionalParameters' ] ) ; if ( is_string ( $ next ) ) { $ next = unserialize ( $ next ) -> getClosure ( ) ; } elseif ( is_array ( $ next ) ) { $ next = Collection :: make ( $ next ) -> map ( function ( $ callback ) { if ( $ this -> bot -> getDriver ( ) -> serializesCallbacks ( ) && ! $ this -> bot -> runsOnSocket ( ) ) { $ callback [ 'callback' ] = unserialize ( $ callback [ 'callback' ] ) -> getClosure ( ) ; } return $ callback ; } ) -> toArray ( ) ; } $ this -> ask ( $ question , $ next , $ additionalParameters ) ; }
Repeat the previously asked question .
889
public static function loadFromName ( $ name , array $ config , Request $ request = null ) { if ( class_exists ( $ name ) && is_subclass_of ( $ name , DriverInterface :: class ) ) { $ name = preg_replace ( '#(Driver$)#' , '' , basename ( str_replace ( '\\' , '/' , $ name ) ) ) ; } if ( class_exists ( $ name ) && is_subclass_of ( $ name , HttpDriver :: class ) ) { $ name = $ name :: DRIVER_NAME ; } if ( is_null ( $ request ) ) { $ request = Request :: createFromGlobals ( ) ; } foreach ( self :: getAvailableDrivers ( ) as $ driver ) { $ driver = new $ driver ( $ request , $ config , new Curl ( ) ) ; if ( $ driver -> getName ( ) === $ name ) { return $ driver ; } } return new NullDriver ( $ request , [ ] , new Curl ( ) ) ; }
Load a driver by using its name .
890
public static function loadDriver ( $ driver , $ explicit = false ) { array_unshift ( self :: $ drivers , $ driver ) ; if ( method_exists ( $ driver , 'loadExtension' ) ) { call_user_func ( [ $ driver , 'loadExtension' ] ) ; } if ( method_exists ( $ driver , 'additionalDrivers' ) && $ explicit === false ) { $ additionalDrivers = ( array ) call_user_func ( [ $ driver , 'additionalDrivers' ] ) ; foreach ( $ additionalDrivers as $ additionalDriver ) { self :: loadDriver ( $ additionalDriver ) ; } } self :: $ drivers = array_unique ( self :: $ drivers ) ; }
Append a driver to the list of loadable drivers .
891
public static function unloadDriver ( $ driver ) { foreach ( array_keys ( self :: $ drivers , $ driver ) as $ key ) { unset ( self :: $ drivers [ $ key ] ) ; } }
Remove a driver from the list of loadable drivers .
892
public static function verifyServices ( array $ config , Request $ request = null ) { $ request = ( isset ( $ request ) ) ? $ request : Request :: createFromGlobals ( ) ; foreach ( self :: getAvailableHttpDrivers ( ) as $ driver ) { $ driver = new $ driver ( $ request , $ config , new Curl ( ) ) ; if ( $ driver instanceof VerifiesService && ! is_null ( $ driver -> verifyRequest ( $ request ) ) ) { return true ; } } return false ; }
Verify service webhook URLs .
893
protected function getResponse ( IncomingMessage $ message ) { $ response = $ this -> http -> post ( $ this -> apiUrl , [ ] , [ 'query' => [ $ message -> getText ( ) ] , 'sessionId' => md5 ( $ message -> getConversationIdentifier ( ) ) , 'lang' => $ this -> lang , ] , [ 'Authorization: Bearer ' . $ this -> token , 'Content-Type: application/json; charset=utf-8' , ] , true ) ; $ this -> response = json_decode ( $ response -> getContent ( ) ) ; return $ this -> response ; }
Perform the API . ai API call and cache it for the message .
894
public static function createForSocket ( array $ config , LoopInterface $ loop , CacheInterface $ cache = null , StorageInterface $ storageDriver = null ) { $ port = isset ( $ config [ 'port' ] ) ? $ config [ 'port' ] : 8080 ; $ socket = new Server ( $ loop ) ; if ( empty ( $ cache ) ) { $ cache = new ArrayCache ( ) ; } if ( empty ( $ storageDriver ) ) { $ storageDriver = new FileStorage ( __DIR__ ) ; } $ driverManager = new DriverManager ( $ config , new Curl ( ) ) ; $ botman = new BotMan ( $ cache , DriverManager :: loadFromName ( 'Null' , $ config ) , $ config , $ storageDriver ) ; $ botman -> runsOnSocket ( true ) ; $ socket -> on ( 'connection' , function ( $ conn ) use ( $ botman , $ driverManager ) { $ conn -> on ( 'data' , function ( $ data ) use ( $ botman , $ driverManager ) { $ requestData = json_decode ( $ data , true ) ; $ request = new Request ( $ requestData [ 'query' ] , $ requestData [ 'request' ] , $ requestData [ 'attributes' ] , [ ] , [ ] , [ ] , $ requestData [ 'content' ] ) ; $ driver = $ driverManager -> getMatchingDriver ( $ request ) ; $ botman -> setDriver ( $ driver ) ; $ botman -> listen ( ) ; } ) ; } ) ; $ socket -> listen ( $ port ) ; return $ botman ; }
Create a new BotMan instance that listens on a socket .
895
public static function passRequestToSocket ( $ port = 8080 , Request $ request = null ) { if ( empty ( $ request ) ) { $ request = Request :: createFromGlobals ( ) ; } $ client = stream_socket_client ( 'tcp://127.0.0.1:' . $ port ) ; fwrite ( $ client , json_encode ( [ 'attributes' => $ request -> attributes -> all ( ) , 'query' => $ request -> query -> all ( ) , 'request' => $ request -> request -> all ( ) , 'content' => $ request -> getContent ( ) , ] ) ) ; fclose ( $ client ) ; }
Pass an incoming HTTP request to the socket .
896
public function getBotMessages ( ) { return Collection :: make ( $ this -> getDriver ( ) -> getMessages ( ) ) -> filter ( function ( IncomingMessage $ message ) { return $ message -> isFromBot ( ) ; } ) -> toArray ( ) ; }
Retrieve the chat message that are sent from bots .
897
public function on ( $ names , $ callback ) { if ( ! is_array ( $ names ) ) { $ names = [ $ names ] ; } $ callable = $ this -> getCallable ( $ callback ) ; foreach ( $ names as $ name ) { $ this -> events [ ] = [ 'name' => $ name , 'callback' => $ callable , ] ; } }
Listen for messaging service events .
898
public function group ( array $ attributes , Closure $ callback ) { $ previousGroupAttributes = $ this -> groupAttributes ; $ this -> groupAttributes = array_merge_recursive ( $ previousGroupAttributes , $ attributes ) ; \ call_user_func ( $ callback , $ this ) ; $ this -> groupAttributes = $ previousGroupAttributes ; }
Create a command group with shared attributes .
899
protected function fireDriverEvents ( ) { $ driverEvent = $ this -> getDriver ( ) -> hasMatchingEvent ( ) ; if ( $ driverEvent instanceof DriverEventInterface ) { $ this -> firedDriverEvents = true ; Collection :: make ( $ this -> events ) -> filter ( function ( $ event ) use ( $ driverEvent ) { return $ driverEvent -> getName ( ) === $ event [ 'name' ] ; } ) -> each ( function ( $ event ) use ( $ driverEvent ) { $ messages = $ this -> getDriver ( ) -> getMessages ( ) ; if ( isset ( $ messages [ 0 ] ) ) { $ this -> message = $ messages [ 0 ] ; } \ call_user_func_array ( $ event [ 'callback' ] , [ $ driverEvent -> getPayload ( ) , $ this ] ) ; } ) ; } }
Fire potential driver event callbacks .