idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
500
|
protected function discoverFromMaster ( NodeConnectionInterface $ connection , FactoryInterface $ connectionFactory ) { $ response = $ connection -> executeCommand ( RawCommand :: create ( 'INFO' , 'REPLICATION' ) ) ; $ replication = $ this -> handleInfoResponse ( $ response ) ; if ( $ replication [ 'role' ] !== 'master' ) { throw new ClientException ( "Role mismatch (expected master, got slave) [$connection]" ) ; } $ this -> slaves = array ( ) ; foreach ( $ replication as $ k => $ v ) { $ parameters = null ; if ( strpos ( $ k , 'slave' ) === 0 && preg_match ( '/ip=(?P<host>.*),port=(?P<port>\d+)/' , $ v , $ parameters ) ) { $ slaveConnection = $ connectionFactory -> create ( array ( 'host' => $ parameters [ 'host' ] , 'port' => $ parameters [ 'port' ] , ) ) ; $ this -> add ( $ slaveConnection ) ; } } }
|
Discovers the replication configuration by contacting the master node .
|
501
|
protected function discoverFromSlave ( NodeConnectionInterface $ connection , FactoryInterface $ connectionFactory ) { $ response = $ connection -> executeCommand ( RawCommand :: create ( 'INFO' , 'REPLICATION' ) ) ; $ replication = $ this -> handleInfoResponse ( $ response ) ; if ( $ replication [ 'role' ] !== 'slave' ) { throw new ClientException ( "Role mismatch (expected slave, got master) [$connection]" ) ; } $ masterConnection = $ connectionFactory -> create ( array ( 'host' => $ replication [ 'master_host' ] , 'port' => $ replication [ 'master_port' ] , 'alias' => 'master' , ) ) ; $ this -> add ( $ masterConnection ) ; $ this -> discoverFromMaster ( $ masterConnection , $ connectionFactory ) ; }
|
Discovers the replication configuration by contacting one of the slaves .
|
502
|
private function retryCommandOnFailure ( CommandInterface $ command , $ method ) { RETRY_COMMAND : { try { $ connection = $ this -> getConnection ( $ command ) ; $ response = $ connection -> $ method ( $ command ) ; if ( $ response instanceof ResponseErrorInterface && $ response -> getErrorType ( ) === 'LOADING' ) { throw new ConnectionException ( $ connection , "Redis is loading the dataset in memory [$connection]" ) ; } } catch ( ConnectionException $ exception ) { $ connection = $ exception -> getConnection ( ) ; $ connection -> disconnect ( ) ; if ( $ connection === $ this -> master && ! $ this -> autoDiscovery ) { throw $ exception ; } else { $ this -> remove ( $ connection ) ; } if ( ! $ this -> slaves && ! $ this -> master ) { throw $ exception ; } elseif ( $ this -> autoDiscovery ) { $ this -> discover ( ) ; } goto RETRY_COMMAND ; } catch ( MissingMasterException $ exception ) { if ( $ this -> autoDiscovery ) { $ this -> discover ( ) ; } else { throw $ exception ; } goto RETRY_COMMAND ; } } return $ response ; }
|
Retries the execution of a command upon slave failure .
|
503
|
public function subscribe ( $ channel ) { $ this -> writeRequest ( self :: SUBSCRIBE , func_get_args ( ) ) ; $ this -> statusFlags |= self :: STATUS_SUBSCRIBED ; }
|
Subscribes to the specified channels .
|
504
|
public function psubscribe ( $ pattern ) { $ this -> writeRequest ( self :: PSUBSCRIBE , func_get_args ( ) ) ; $ this -> statusFlags |= self :: STATUS_PSUBSCRIBED ; }
|
Subscribes to the specified channels using a pattern .
|
505
|
public function stop ( $ drop = false ) { if ( ! $ this -> valid ( ) ) { return false ; } if ( $ drop ) { $ this -> invalidate ( ) ; $ this -> disconnect ( ) ; } else { if ( $ this -> isFlagSet ( self :: STATUS_SUBSCRIBED ) ) { $ this -> unsubscribe ( ) ; } if ( $ this -> isFlagSet ( self :: STATUS_PSUBSCRIBED ) ) { $ this -> punsubscribe ( ) ; } } return ! $ drop ; }
|
Closes the context by unsubscribing from all the subscribed channels . The context can be forcefully closed by dropping the underlying connection .
|
506
|
public function valid ( ) { $ isValid = $ this -> isFlagSet ( self :: STATUS_VALID ) ; $ subscriptionFlags = self :: STATUS_SUBSCRIBED | self :: STATUS_PSUBSCRIBED ; $ hasSubscriptions = ( $ this -> statusFlags & $ subscriptionFlags ) > 0 ; return $ isValid && $ hasSubscriptions ; }
|
Checks if the the consumer is still in a valid state to continue .
|
507
|
public function removeById ( $ connectionID ) { if ( $ connection = $ this -> getConnectionById ( $ connectionID ) ) { return $ this -> remove ( $ connection ) ; } return false ; }
|
Removes a connection instance using its alias or index .
|
508
|
public function getConnectionByKey ( $ key ) { $ hash = $ this -> strategy -> getSlotByKey ( $ key ) ; $ node = $ this -> distributor -> getBySlot ( $ hash ) ; return $ node ; }
|
Retrieves a connection instance from the cluster using a key .
|
509
|
public function executeCommandOnNodes ( CommandInterface $ command ) { $ responses = array ( ) ; foreach ( $ this -> pool as $ connection ) { $ responses [ ] = $ connection -> executeCommand ( $ command ) ; } return $ responses ; }
|
Executes the specified Redis command on all the nodes of a cluster .
|
510
|
protected function parseRow ( $ row ) { list ( $ k , $ v ) = explode ( ':' , $ row , 2 ) ; if ( preg_match ( '/^db\d+$/' , $ k ) ) { $ v = $ this -> parseDatabaseStats ( $ v ) ; } return array ( $ k , $ v ) ; }
|
Parses a single row of the response and returns the key - value pair .
|
511
|
protected function parseDatabaseStats ( $ str ) { $ db = array ( ) ; foreach ( explode ( ',' , $ str ) as $ dbvar ) { list ( $ dbvk , $ dbvv ) = explode ( '=' , $ dbvar ) ; $ db [ trim ( $ dbvk ) ] = $ dbvv ; } return $ db ; }
|
Extracts the statistics of each logical DB from the string buffer .
|
512
|
protected function parseAllocationStats ( $ str ) { $ stats = array ( ) ; foreach ( explode ( ',' , $ str ) as $ kv ) { @ list ( $ size , $ objects , $ extra ) = explode ( '=' , $ kv ) ; if ( isset ( $ extra ) ) { $ size = ">=$objects" ; $ objects = $ extra ; } $ stats [ $ size ] = $ objects ; } return $ stats ; }
|
Parses the response and extracts the allocation statistics .
|
513
|
public static function normalizeVariadic ( array $ arguments ) { if ( count ( $ arguments ) === 2 && is_array ( $ arguments [ 1 ] ) ) { return array_merge ( array ( $ arguments [ 0 ] ) , $ arguments [ 1 ] ) ; } return $ arguments ; }
|
Normalizes the arguments array passed to a variadic Redis command .
|
514
|
public static function parse ( $ uri ) { if ( stripos ( $ uri , 'unix://' ) === 0 ) { $ uri = str_ireplace ( 'unix://' , 'unix:' , $ uri ) ; } if ( ! $ parsed = parse_url ( $ uri ) ) { throw new \ InvalidArgumentException ( "Invalid parameters URI: $uri" ) ; } if ( isset ( $ parsed [ 'host' ] ) && false !== strpos ( $ parsed [ 'host' ] , '[' ) && false !== strpos ( $ parsed [ 'host' ] , ']' ) ) { $ parsed [ 'host' ] = substr ( $ parsed [ 'host' ] , 1 , - 1 ) ; } if ( isset ( $ parsed [ 'query' ] ) ) { parse_str ( $ parsed [ 'query' ] , $ queryarray ) ; unset ( $ parsed [ 'query' ] ) ; $ parsed = array_merge ( $ parsed , $ queryarray ) ; } if ( stripos ( $ uri , 'redis' ) === 0 ) { if ( isset ( $ parsed [ 'pass' ] ) ) { $ parsed [ 'password' ] = $ parsed [ 'pass' ] ; unset ( $ parsed [ 'pass' ] ) ; } if ( isset ( $ parsed [ 'path' ] ) && preg_match ( '/^\/(\d+)(\/.*)?/' , $ parsed [ 'path' ] , $ path ) ) { $ parsed [ 'database' ] = $ path [ 1 ] ; if ( isset ( $ path [ 2 ] ) ) { $ parsed [ 'path' ] = $ path [ 2 ] ; } else { unset ( $ parsed [ 'path' ] ) ; } } } return $ parsed ; }
|
Parses an URI string returning an array of connection parameters .
|
515
|
private function emitSocketError ( ) { $ errno = socket_last_error ( ) ; $ errstr = socket_strerror ( $ errno ) ; $ this -> disconnect ( ) ; $ this -> onConnectionError ( trim ( $ errstr ) , $ errno ) ; }
|
Helper method used to throw exceptions on socket errors .
|
516
|
protected static function getAddress ( ParametersInterface $ parameters ) { if ( filter_var ( $ host = $ parameters -> host , FILTER_VALIDATE_IP ) ) { return $ host ; } if ( $ host === $ address = gethostbyname ( $ host ) ) { return false ; } return $ address ; }
|
Gets the address of an host from connection parameters .
|
517
|
private function setSocketOptions ( $ socket , ParametersInterface $ parameters ) { if ( $ parameters -> scheme !== 'unix' ) { if ( ! socket_set_option ( $ socket , SOL_TCP , TCP_NODELAY , 1 ) ) { $ this -> emitSocketError ( ) ; } if ( ! socket_set_option ( $ socket , SOL_SOCKET , SO_REUSEADDR , 1 ) ) { $ this -> emitSocketError ( ) ; } } if ( isset ( $ parameters -> read_write_timeout ) ) { $ rwtimeout = ( float ) $ parameters -> read_write_timeout ; $ timeoutSec = floor ( $ rwtimeout ) ; $ timeoutUsec = ( $ rwtimeout - $ timeoutSec ) * 1000000 ; $ timeout = array ( 'sec' => $ timeoutSec , 'usec' => $ timeoutUsec , ) ; if ( ! socket_set_option ( $ socket , SOL_SOCKET , SO_SNDTIMEO , $ timeout ) ) { $ this -> emitSocketError ( ) ; } if ( ! socket_set_option ( $ socket , SOL_SOCKET , SO_RCVTIMEO , $ timeout ) ) { $ this -> emitSocketError ( ) ; } } }
|
Sets options on the socket resource from the connection parameters .
|
518
|
private function connectWithTimeout ( $ socket , $ address , ParametersInterface $ parameters ) { socket_set_nonblock ( $ socket ) ; if ( @ socket_connect ( $ socket , $ address , ( int ) $ parameters -> port ) === false ) { $ error = socket_last_error ( ) ; if ( $ error != SOCKET_EINPROGRESS && $ error != SOCKET_EALREADY ) { $ this -> emitSocketError ( ) ; } } socket_set_block ( $ socket ) ; $ null = null ; $ selectable = array ( $ socket ) ; $ timeout = ( isset ( $ parameters -> timeout ) ? ( float ) $ parameters -> timeout : 5.0 ) ; $ timeoutSecs = floor ( $ timeout ) ; $ timeoutUSecs = ( $ timeout - $ timeoutSecs ) * 1000000 ; $ selected = socket_select ( $ selectable , $ selectable , $ null , $ timeoutSecs , $ timeoutUSecs ) ; if ( $ selected === 2 ) { $ this -> onConnectionError ( 'Connection refused.' , SOCKET_ECONNREFUSED ) ; } if ( $ selected === 0 ) { $ this -> onConnectionError ( 'Connection timed out.' , SOCKET_ETIMEDOUT ) ; } if ( $ selected === false ) { $ this -> emitSocketError ( ) ; } }
|
Opens the actual connection to the server with a timeout .
|
519
|
private function createCurl ( ) { $ parameters = $ this -> getParameters ( ) ; $ timeout = ( isset ( $ parameters -> timeout ) ? ( float ) $ parameters -> timeout : 5.0 ) * 1000 ; if ( filter_var ( $ host = $ parameters -> host , FILTER_VALIDATE_IP ) ) { $ host = "[$host]" ; } $ options = array ( CURLOPT_FAILONERROR => true , CURLOPT_CONNECTTIMEOUT_MS => $ timeout , CURLOPT_URL => "$parameters->scheme://$host:$parameters->port" , CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1 , CURLOPT_POST => true , CURLOPT_WRITEFUNCTION => array ( $ this , 'feedReader' ) , ) ; if ( isset ( $ parameters -> user , $ parameters -> pass ) ) { $ options [ CURLOPT_USERPWD ] = "{$parameters->user}:{$parameters->pass}" ; } curl_setopt_array ( $ resource = curl_init ( ) , $ options ) ; return $ resource ; }
|
Initializes cURL .
|
520
|
private function assertClient ( ClientInterface $ client ) { if ( $ client -> getConnection ( ) instanceof AggregateConnectionInterface ) { throw new NotSupportedException ( 'Cannot initialize a MULTI/EXEC transaction over aggregate connections.' ) ; } if ( ! $ client -> getProfile ( ) -> supportsCommands ( array ( 'MULTI' , 'EXEC' , 'DISCARD' ) ) ) { throw new NotSupportedException ( 'The current profile does not support MULTI, EXEC and DISCARD.' ) ; } }
|
Checks if the passed client instance satisfies the required conditions needed to initialize the transaction object .
|
521
|
protected function configure ( ClientInterface $ client , array $ options ) { if ( isset ( $ options [ 'exceptions' ] ) ) { $ this -> exceptions = ( bool ) $ options [ 'exceptions' ] ; } else { $ this -> exceptions = $ client -> getOptions ( ) -> exceptions ; } if ( isset ( $ options [ 'cas' ] ) ) { $ this -> modeCAS = ( bool ) $ options [ 'cas' ] ; } if ( isset ( $ options [ 'watch' ] ) && $ keys = $ options [ 'watch' ] ) { $ this -> watchKeys = $ keys ; } if ( isset ( $ options [ 'retry' ] ) ) { $ this -> attempts = ( int ) $ options [ 'retry' ] ; } }
|
Configures the transaction using the provided options .
|
522
|
protected function call ( $ commandID , array $ arguments = array ( ) ) { $ response = $ this -> client -> executeCommand ( $ this -> client -> createCommand ( $ commandID , $ arguments ) ) ; if ( $ response instanceof ErrorResponseInterface ) { throw new ServerException ( $ response -> getMessage ( ) ) ; } return $ response ; }
|
Executes a Redis command bypassing the transaction logic .
|
523
|
public function watch ( $ keys ) { if ( ! $ this -> client -> getProfile ( ) -> supportsCommand ( 'WATCH' ) ) { throw new NotSupportedException ( 'WATCH is not supported by the current profile.' ) ; } if ( $ this -> state -> isWatchAllowed ( ) ) { throw new ClientException ( 'Sending WATCH after MULTI is not allowed.' ) ; } $ response = $ this -> call ( 'WATCH' , is_array ( $ keys ) ? $ keys : array ( $ keys ) ) ; $ this -> state -> flag ( MultiExecState :: WATCH ) ; return $ response ; }
|
Executes WATCH against one or more keys .
|
524
|
public function multi ( ) { if ( $ this -> state -> check ( MultiExecState :: INITIALIZED | MultiExecState :: CAS ) ) { $ this -> state -> unflag ( MultiExecState :: CAS ) ; $ this -> call ( 'MULTI' ) ; } else { $ this -> initialize ( ) ; } return $ this ; }
|
Finalizes the transaction by executing MULTI on the server .
|
525
|
public function discard ( ) { if ( $ this -> state -> isInitialized ( ) ) { $ this -> call ( $ this -> state -> isCAS ( ) ? 'UNWATCH' : 'DISCARD' ) ; $ this -> reset ( ) ; $ this -> state -> flag ( MultiExecState :: DISCARDED ) ; } return $ this ; }
|
Resets the transaction by UNWATCH - ing the keys that are being WATCHed and DISCARD - ing pending commands that have been already sent to the server .
|
526
|
private function checkBeforeExecution ( $ callable ) { if ( $ this -> state -> isExecuting ( ) ) { throw new ClientException ( 'Cannot invoke "execute" or "exec" inside an active transaction context.' ) ; } if ( $ callable ) { if ( ! is_callable ( $ callable ) ) { throw new \ InvalidArgumentException ( 'The argument must be a callable object.' ) ; } if ( ! $ this -> commands -> isEmpty ( ) ) { $ this -> discard ( ) ; throw new ClientException ( 'Cannot execute a transaction block after using fluent interface.' ) ; } } elseif ( $ this -> attempts ) { $ this -> discard ( ) ; throw new ClientException ( 'Automatic retries are supported only when a callable block is provided.' ) ; } }
|
Checks the state of the transaction before execution .
|
527
|
protected function executeTransactionBlock ( $ callable ) { $ exception = null ; $ this -> state -> flag ( MultiExecState :: INSIDEBLOCK ) ; try { call_user_func ( $ callable , $ this ) ; } catch ( CommunicationException $ exception ) { } catch ( ServerException $ exception ) { } catch ( \ Exception $ exception ) { $ this -> discard ( ) ; } $ this -> state -> unflag ( MultiExecState :: INSIDEBLOCK ) ; if ( $ exception ) { throw $ exception ; } }
|
Passes the current transaction object to a callable block for execution .
|
528
|
protected function getDefaultHandlers ( ) { return array ( '+' => new Handler \ StatusResponse ( ) , '-' => new Handler \ ErrorResponse ( ) , ':' => new Handler \ IntegerResponse ( ) , '$' => new Handler \ BulkResponse ( ) , '*' => new Handler \ MultiBulkResponse ( ) , ) ; }
|
Returns the default handlers for the supported type of responses .
|
529
|
protected function checkPreconditions ( MultiBulk $ iterator ) { if ( $ iterator -> getPosition ( ) !== 0 ) { throw new \ InvalidArgumentException ( 'Cannot initialize a tuple iterator using an already initiated iterator.' ) ; } if ( ( $ size = count ( $ iterator ) ) % 2 !== 0 ) { throw new \ UnexpectedValueException ( 'Invalid response size for a tuple iterator.' ) ; } }
|
Checks for valid preconditions .
|
530
|
protected function getScanOptions ( ) { $ options = array ( ) ; if ( strlen ( $ this -> match ) > 0 ) { $ options [ 'MATCH' ] = $ this -> match ; } if ( $ this -> count > 0 ) { $ options [ 'COUNT' ] = $ this -> count ; } return $ options ; }
|
Returns an array of options for the SCAN command .
|
531
|
public static function first ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ arguments [ 0 ] = "$prefix{$arguments[0]}" ; $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix only the first argument .
|
532
|
public static function interleaved ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ length = count ( $ arguments ) ; for ( $ i = 0 ; $ i < $ length ; $ i += 2 ) { $ arguments [ $ i ] = "$prefix{$arguments[$i]}" ; } $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix only to even arguments in the list .
|
533
|
public static function sort ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ arguments [ 0 ] = "$prefix{$arguments[0]}" ; if ( ( $ count = count ( $ arguments ) ) > 1 ) { for ( $ i = 1 ; $ i < $ count ; ++ $ i ) { switch ( strtoupper ( $ arguments [ $ i ] ) ) { case 'BY' : case 'STORE' : $ arguments [ $ i ] = "$prefix{$arguments[++$i]}" ; break ; case 'GET' : $ value = $ arguments [ ++ $ i ] ; if ( $ value !== '#' ) { $ arguments [ $ i ] = "$prefix$value" ; } break ; case 'LIMIT' ; $ i += 2 ; break ; } } } $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix to the keys of a SORT command .
|
534
|
public static function evalKeys ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { for ( $ i = 2 ; $ i < $ arguments [ 1 ] + 2 ; ++ $ i ) { $ arguments [ $ i ] = "$prefix{$arguments[$i]}" ; } $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix to the keys of an EVAL - based command .
|
535
|
public static function migrate ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ arguments [ 2 ] = "$prefix{$arguments[2]}" ; $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix to the key of a MIGRATE command .
|
536
|
public static function georadius ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ arguments [ 0 ] = "$prefix{$arguments[0]}" ; $ startIndex = $ command -> getId ( ) === 'GEORADIUS' ? 5 : 4 ; if ( ( $ count = count ( $ arguments ) ) > $ startIndex ) { for ( $ i = $ startIndex ; $ i < $ count ; ++ $ i ) { switch ( strtoupper ( $ arguments [ $ i ] ) ) { case 'STORE' : case 'STOREDIST' : $ arguments [ $ i ] = "$prefix{$arguments[++$i]}" ; break ; } } } $ command -> setRawArguments ( $ arguments ) ; } }
|
Applies the specified prefix to the key of a GEORADIUS command .
|
537
|
public function add ( $ node , $ weight = null ) { $ this -> nodes [ ] = array ( 'object' => $ node , 'weight' => ( int ) $ weight ? : $ this :: DEFAULT_WEIGHT , ) ; $ this -> reset ( ) ; }
|
Adds a node to the ring with an optional weight .
|
538
|
private function initialize ( ) { if ( $ this -> isInitialized ( ) ) { return ; } if ( ! $ this -> nodes ) { throw new EmptyRingException ( 'Cannot initialize an empty hashring.' ) ; } $ this -> ring = array ( ) ; $ totalWeight = $ this -> computeTotalWeight ( ) ; $ nodesCount = count ( $ this -> nodes ) ; foreach ( $ this -> nodes as $ node ) { $ weightRatio = $ node [ 'weight' ] / $ totalWeight ; $ this -> addNodeToRing ( $ this -> ring , $ node , $ nodesCount , $ this -> replicas , $ weightRatio ) ; } ksort ( $ this -> ring , SORT_NUMERIC ) ; $ this -> ringKeys = array_keys ( $ this -> ring ) ; $ this -> ringKeysCount = count ( $ this -> ringKeys ) ; }
|
Initializes the distributor .
|
539
|
protected function addNodeToRing ( & $ ring , $ node , $ totalNodes , $ replicas , $ weightRatio ) { $ nodeObject = $ node [ 'object' ] ; $ nodeHash = $ this -> getNodeHash ( $ nodeObject ) ; $ replicas = ( int ) round ( $ weightRatio * $ totalNodes * $ replicas ) ; for ( $ i = 0 ; $ i < $ replicas ; ++ $ i ) { $ key = crc32 ( "$nodeHash:$i" ) ; $ ring [ $ key ] = $ nodeObject ; } }
|
Implements the logic needed to add a node to the hashring .
|
540
|
private function createExceptionMessage ( $ message ) { $ parameters = $ this -> parameters ; if ( $ parameters -> scheme === 'unix' ) { return "$message [$parameters->scheme:$parameters->path]" ; } if ( filter_var ( $ parameters -> host , FILTER_VALIDATE_IP , FILTER_FLAG_IPV6 ) ) { return "$message [$parameters->scheme://[$parameters->host]:$parameters->port]" ; } return "$message [$parameters->scheme://$parameters->host:$parameters->port]" ; }
|
Helper method that returns an exception message augmented with useful details from the connection parameters .
|
541
|
protected function onConnectionError ( $ message , $ code = null ) { CommunicationException :: handle ( new ConnectionException ( $ this , static :: createExceptionMessage ( $ message ) , $ code ) ) ; }
|
Helper method to handle connection errors .
|
542
|
protected function parseClientList ( $ data ) { $ clients = array ( ) ; foreach ( explode ( "\n" , $ data , - 1 ) as $ clientData ) { $ client = array ( ) ; foreach ( explode ( ' ' , $ clientData ) as $ kv ) { @ list ( $ k , $ v ) = explode ( '=' , $ kv ) ; $ client [ $ k ] = $ v ; } $ clients [ ] = $ client ; } return $ clients ; }
|
Parses the response to CLIENT LIST and returns a structured list .
|
543
|
protected function exception ( ConnectionInterface $ connection , ErrorResponseInterface $ response ) { $ connection -> disconnect ( ) ; $ message = $ response -> getMessage ( ) ; throw new ServerException ( $ message ) ; }
|
Throws an exception on - ERR responses returned by Redis .
|
544
|
protected function getConnection ( ) { $ connection = $ this -> getClient ( ) -> getConnection ( ) ; if ( $ connection instanceof ReplicationInterface ) { $ connection -> switchTo ( 'master' ) ; } return $ connection ; }
|
Returns the underlying connection to be used by the pipeline .
|
545
|
protected function executePipeline ( ConnectionInterface $ connection , \ SplQueue $ commands ) { foreach ( $ commands as $ command ) { $ connection -> writeRequest ( $ command ) ; } $ responses = array ( ) ; $ exceptions = $ this -> throwServerExceptions ( ) ; while ( ! $ commands -> isEmpty ( ) ) { $ command = $ commands -> dequeue ( ) ; $ response = $ connection -> readResponse ( $ command ) ; if ( ! $ response instanceof ResponseInterface ) { $ responses [ ] = $ command -> parseResponse ( $ response ) ; } elseif ( $ response instanceof ErrorResponseInterface && $ exceptions ) { $ this -> exception ( $ connection , $ response ) ; } else { $ responses [ ] = $ response ; } } return $ responses ; }
|
Implements the logic to flush the queued commands and read the responses from the current connection .
|
546
|
public function flushPipeline ( $ send = true ) { if ( $ send && ! $ this -> pipeline -> isEmpty ( ) ) { $ responses = $ this -> executePipeline ( $ this -> getConnection ( ) , $ this -> pipeline ) ; $ this -> responses = array_merge ( $ this -> responses , $ responses ) ; } else { $ this -> pipeline = new \ SplQueue ( ) ; } return $ this ; }
|
Flushes the buffer holding all of the commands queued so far .
|
547
|
public function execute ( $ callable = null ) { if ( $ callable && ! is_callable ( $ callable ) ) { throw new \ InvalidArgumentException ( 'The argument must be a callable object.' ) ; } $ exception = null ; $ this -> setRunning ( true ) ; try { if ( $ callable ) { call_user_func ( $ callable , $ this ) ; } $ this -> flushPipeline ( ) ; } catch ( \ Exception $ exception ) { } $ this -> setRunning ( false ) ; if ( $ exception ) { throw $ exception ; } return $ this -> responses ; }
|
Handles the actual execution of the whole pipeline .
|
548
|
public function register ( ) { if ( PHP_VERSION_ID >= 50400 ) { session_set_save_handler ( $ this , true ) ; } else { session_set_save_handler ( array ( $ this , 'open' ) , array ( $ this , 'close' ) , array ( $ this , 'read' ) , array ( $ this , 'write' ) , array ( $ this , 'destroy' ) , array ( $ this , 'gc' ) ) ; } }
|
Registers this instance as the current session handler .
|
549
|
public static function define ( $ alias , $ class ) { $ reflection = new \ ReflectionClass ( $ class ) ; if ( ! $ reflection -> isSubclassOf ( 'Predis\Profile\ProfileInterface' ) ) { throw new \ InvalidArgumentException ( "The class '$class' is not a valid profile class." ) ; } self :: $ profiles [ $ alias ] = $ class ; }
|
Registers a new server profile .
|
550
|
public static function get ( $ version ) { if ( ! isset ( self :: $ profiles [ $ version ] ) ) { throw new ClientException ( "Unknown server profile: '$version'." ) ; } $ profile = self :: $ profiles [ $ version ] ; return new $ profile ( ) ; }
|
Returns the specified server profile .
|
551
|
public static function get ( $ payload ) { switch ( $ payload ) { case 'OK' : case 'QUEUED' : if ( isset ( self :: $ $ payload ) ) { return self :: $ $ payload ; } return self :: $ $ payload = new self ( $ payload ) ; default : return new self ( $ payload ) ; } }
|
Returns an instance of a status response object .
|
552
|
protected function checkInitializer ( $ initializer ) { if ( is_callable ( $ initializer ) ) { return $ initializer ; } $ class = new \ ReflectionClass ( $ initializer ) ; if ( ! $ class -> isSubclassOf ( 'Predis\Connection\NodeConnectionInterface' ) ) { throw new \ InvalidArgumentException ( 'A connection initializer must be a valid connection class or a callable object.' ) ; } return $ initializer ; }
|
Checks if the provided argument represents a valid connection class implementing Predis \ Connection \ NodeConnectionInterface . Optionally callable objects are used for lazy initialization of connection objects .
|
553
|
protected function createParameters ( $ parameters ) { if ( is_string ( $ parameters ) ) { $ parameters = Parameters :: parse ( $ parameters ) ; } else { $ parameters = $ parameters ? : array ( ) ; } if ( $ this -> defaults ) { $ parameters += $ this -> defaults ; } return new Parameters ( $ parameters ) ; }
|
Creates a connection parameters instance from the supplied argument .
|
554
|
protected function prepareConnection ( NodeConnectionInterface $ connection ) { $ parameters = $ connection -> getParameters ( ) ; if ( isset ( $ parameters -> password ) ) { $ connection -> addConnectCommand ( new RawCommand ( array ( 'AUTH' , $ parameters -> password ) ) ) ; } if ( isset ( $ parameters -> database ) ) { $ connection -> addConnectCommand ( new RawCommand ( array ( 'SELECT' , $ parameters -> database ) ) ) ; } }
|
Prepares a connection instance after its initialization .
|
555
|
protected function assertSslSupport ( ParametersInterface $ parameters ) { if ( filter_var ( $ parameters -> persistent , FILTER_VALIDATE_BOOLEAN ) && version_compare ( PHP_VERSION , '7.0.0beta' ) < 0 ) { throw new \ InvalidArgumentException ( 'Persistent SSL connections require PHP >= 7.0.0.' ) ; } }
|
Checks needed conditions for SSL - encrypted connections .
|
556
|
protected function createStreamSocket ( ParametersInterface $ parameters , $ address , $ flags ) { $ timeout = ( isset ( $ parameters -> timeout ) ? ( float ) $ parameters -> timeout : 5.0 ) ; if ( ! $ resource = @ stream_socket_client ( $ address , $ errno , $ errstr , $ timeout , $ flags ) ) { $ this -> onConnectionError ( trim ( $ errstr ) , $ errno ) ; } if ( isset ( $ parameters -> read_write_timeout ) ) { $ rwtimeout = ( float ) $ parameters -> read_write_timeout ; $ rwtimeout = $ rwtimeout > 0 ? $ rwtimeout : - 1 ; $ timeoutSeconds = floor ( $ rwtimeout ) ; $ timeoutUSeconds = ( $ rwtimeout - $ timeoutSeconds ) * 1000000 ; stream_set_timeout ( $ resource , $ timeoutSeconds , $ timeoutUSeconds ) ; } if ( isset ( $ parameters -> tcp_nodelay ) && function_exists ( 'socket_import_stream' ) ) { $ socket = socket_import_stream ( $ resource ) ; socket_set_option ( $ socket , SOL_TCP , TCP_NODELAY , ( int ) $ parameters -> tcp_nodelay ) ; } return $ resource ; }
|
Creates a connected stream socket resource .
|
557
|
protected function tcpStreamInitializer ( ParametersInterface $ parameters ) { if ( ! filter_var ( $ parameters -> host , FILTER_VALIDATE_IP , FILTER_FLAG_IPV6 ) ) { $ address = "tcp://$parameters->host:$parameters->port" ; } else { $ address = "tcp://[$parameters->host]:$parameters->port" ; } $ flags = STREAM_CLIENT_CONNECT ; if ( isset ( $ parameters -> async_connect ) && $ parameters -> async_connect ) { $ flags |= STREAM_CLIENT_ASYNC_CONNECT ; } if ( isset ( $ parameters -> persistent ) ) { if ( false !== $ persistent = filter_var ( $ parameters -> persistent , FILTER_VALIDATE_BOOLEAN , FILTER_NULL_ON_FAILURE ) ) { $ flags |= STREAM_CLIENT_PERSISTENT ; if ( $ persistent === null ) { $ address = "{$address}/{$parameters->persistent}" ; } } } $ resource = $ this -> createStreamSocket ( $ parameters , $ address , $ flags ) ; return $ resource ; }
|
Initializes a TCP stream resource .
|
558
|
protected function unixStreamInitializer ( ParametersInterface $ parameters ) { if ( ! isset ( $ parameters -> path ) ) { throw new \ InvalidArgumentException ( 'Missing UNIX domain socket path.' ) ; } $ flags = STREAM_CLIENT_CONNECT ; if ( isset ( $ parameters -> persistent ) ) { if ( false !== $ persistent = filter_var ( $ parameters -> persistent , FILTER_VALIDATE_BOOLEAN , FILTER_NULL_ON_FAILURE ) ) { $ flags |= STREAM_CLIENT_PERSISTENT ; if ( $ persistent === null ) { throw new \ InvalidArgumentException ( 'Persistent connection IDs are not supported when using UNIX domain sockets.' ) ; } } } $ resource = $ this -> createStreamSocket ( $ parameters , "unix://{$parameters->path}" , $ flags ) ; return $ resource ; }
|
Initializes a UNIX stream resource .
|
559
|
protected function tlsStreamInitializer ( ParametersInterface $ parameters ) { $ resource = $ this -> tcpStreamInitializer ( $ parameters ) ; $ metadata = stream_get_meta_data ( $ resource ) ; if ( isset ( $ metadata [ 'crypto' ] ) ) { return $ resource ; } if ( is_array ( $ parameters -> ssl ) ) { $ options = $ parameters -> ssl ; } else { $ options = array ( ) ; } if ( ! isset ( $ options [ 'crypto_type' ] ) ) { $ options [ 'crypto_type' ] = STREAM_CRYPTO_METHOD_TLS_CLIENT ; } if ( ! stream_context_set_option ( $ resource , array ( 'ssl' => $ options ) ) ) { $ this -> onConnectionError ( 'Error while setting SSL context options' ) ; } if ( ! stream_socket_enable_crypto ( $ resource , true , $ options [ 'crypto_type' ] ) ) { $ this -> onConnectionError ( 'Error while switching to encrypted communication' ) ; } return $ resource ; }
|
Initializes a SSL - encrypted TCP stream resource .
|
560
|
protected function write ( $ buffer ) { $ socket = $ this -> getResource ( ) ; while ( ( $ length = strlen ( $ buffer ) ) > 0 ) { $ written = @ fwrite ( $ socket , $ buffer ) ; if ( $ length === $ written ) { return ; } if ( $ written === false || $ written === 0 ) { $ this -> onConnectionError ( 'Error while writing bytes to the server.' ) ; } $ buffer = substr ( $ buffer , $ written ) ; } }
|
Performs a write operation over the stream of the buffer containing a command serialized with the Redis wire protocol .
|
561
|
public function removeById ( $ connectionID ) { if ( isset ( $ this -> pool [ $ connectionID ] ) ) { unset ( $ this -> pool [ $ connectionID ] , $ this -> slotsMap ) ; return true ; } return false ; }
|
Removes a connection instance by using its identifier .
|
562
|
public function buildSlotsMap ( ) { $ this -> slotsMap = array ( ) ; foreach ( $ this -> pool as $ connectionID => $ connection ) { $ parameters = $ connection -> getParameters ( ) ; if ( ! isset ( $ parameters -> slots ) ) { continue ; } foreach ( explode ( ',' , $ parameters -> slots ) as $ slotRange ) { $ slots = explode ( '-' , $ slotRange , 2 ) ; if ( ! isset ( $ slots [ 1 ] ) ) { $ slots [ 1 ] = $ slots [ 0 ] ; } $ this -> setSlots ( $ slots [ 0 ] , $ slots [ 1 ] , $ connectionID ) ; } } return $ this -> slotsMap ; }
|
Generates the current slots map by guessing the cluster configuration out of the connection parameters of the connections in the pool .
|
563
|
private function retryCommandOnFailure ( CommandInterface $ command , $ method ) { $ failure = false ; RETRY_COMMAND : { try { $ response = $ this -> getConnection ( $ command ) -> $ method ( $ command ) ; } catch ( ConnectionException $ exception ) { $ connection = $ exception -> getConnection ( ) ; $ connection -> disconnect ( ) ; $ this -> remove ( $ connection ) ; if ( $ failure ) { throw $ exception ; } elseif ( $ this -> useClusterSlots ) { $ this -> askSlotsMap ( ) ; } $ failure = true ; goto RETRY_COMMAND ; } } return $ response ; }
|
Ensures that a command is executed one more time on connection failure .
|
564
|
public function setCommandHandler ( $ commandID , $ callback = null ) { $ commandID = strtoupper ( $ commandID ) ; if ( ! isset ( $ callback ) ) { unset ( $ this -> commands [ $ commandID ] ) ; return ; } if ( ! is_callable ( $ callback ) ) { throw new \ InvalidArgumentException ( 'The argument must be a callable object or NULL.' ) ; } $ this -> commands [ $ commandID ] = $ callback ; }
|
Sets an handler for the specified command ID .
|
565
|
protected function checkSameSlotForKeys ( array $ keys ) { if ( ! $ count = count ( $ keys ) ) { return false ; } $ currentSlot = $ this -> getSlotByKey ( $ keys [ 0 ] ) ; for ( $ i = 1 ; $ i < $ count ; ++ $ i ) { $ nextSlot = $ this -> getSlotByKey ( $ keys [ $ i ] ) ; if ( $ currentSlot !== $ nextSlot ) { return false ; } $ currentSlot = $ nextSlot ; } return true ; }
|
Checks if the specified array of keys will generate the same hash .
|
566
|
protected function createSentinelConnection ( $ parameters ) { if ( $ parameters instanceof NodeConnectionInterface ) { return $ parameters ; } if ( is_string ( $ parameters ) ) { $ parameters = Parameters :: parse ( $ parameters ) ; } if ( is_array ( $ parameters ) ) { $ parameters [ 'database' ] = null ; $ parameters [ 'password' ] = null ; if ( ! isset ( $ parameters [ 'timeout' ] ) ) { $ parameters [ 'timeout' ] = $ this -> sentinelTimeout ; } } $ connection = $ this -> connectionFactory -> create ( $ parameters ) ; return $ connection ; }
|
Creates a new connection to a sentinel server .
|
567
|
public function getSentinelConnection ( ) { if ( ! $ this -> sentinelConnection ) { if ( ! $ this -> sentinels ) { throw new \ Predis \ ClientException ( 'No sentinel server available for autodiscovery.' ) ; } $ sentinel = array_shift ( $ this -> sentinels ) ; $ this -> sentinelConnection = $ this -> createSentinelConnection ( $ sentinel ) ; } return $ this -> sentinelConnection ; }
|
Returns the current sentinel connection .
|
568
|
private function handleSentinelErrorResponse ( NodeConnectionInterface $ sentinel , ErrorResponseInterface $ error ) { if ( $ error -> getErrorType ( ) === 'IDONTKNOW' ) { throw new ConnectionException ( $ sentinel , $ error -> getMessage ( ) ) ; } else { throw new ServerException ( $ error -> getMessage ( ) ) ; } }
|
Handles error responses returned by redis - sentinel .
|
569
|
protected function querySentinelForMaster ( NodeConnectionInterface $ sentinel , $ service ) { $ payload = $ sentinel -> executeCommand ( RawCommand :: create ( 'SENTINEL' , 'get-master-addr-by-name' , $ service ) ) ; if ( $ payload === null ) { throw new ServerException ( 'ERR No such master with that name' ) ; } if ( $ payload instanceof ErrorResponseInterface ) { $ this -> handleSentinelErrorResponse ( $ sentinel , $ payload ) ; } return array ( 'host' => $ payload [ 0 ] , 'port' => $ payload [ 1 ] , 'alias' => 'master' , ) ; }
|
Fetches the details for the master server from a sentinel .
|
570
|
protected function querySentinelForSlaves ( NodeConnectionInterface $ sentinel , $ service ) { $ slaves = array ( ) ; $ payload = $ sentinel -> executeCommand ( RawCommand :: create ( 'SENTINEL' , 'slaves' , $ service ) ) ; if ( $ payload instanceof ErrorResponseInterface ) { $ this -> handleSentinelErrorResponse ( $ sentinel , $ payload ) ; } foreach ( $ payload as $ slave ) { $ flags = explode ( ',' , $ slave [ 9 ] ) ; if ( array_intersect ( $ flags , array ( 's_down' , 'o_down' , 'disconnected' ) ) ) { continue ; } $ slaves [ ] = array ( 'host' => $ slave [ 3 ] , 'port' => $ slave [ 5 ] , 'alias' => "slave-$slave[1]" , ) ; } return $ slaves ; }
|
Fetches the details for the slave servers from a sentinel .
|
571
|
private function getConnectionInternal ( CommandInterface $ command ) { if ( ! $ this -> current ) { if ( $ this -> strategy -> isReadOperation ( $ command ) && $ slave = $ this -> pickSlave ( ) ) { $ this -> current = $ slave ; } else { $ this -> current = $ this -> getMaster ( ) ; } return $ this -> current ; } if ( $ this -> current === $ this -> master ) { return $ this -> current ; } if ( ! $ this -> strategy -> isReadOperation ( $ command ) ) { $ this -> current = $ this -> getMaster ( ) ; } return $ this -> current ; }
|
Returns the connection instance in charge for the given command .
|
572
|
protected function assertConnectionRole ( NodeConnectionInterface $ connection , $ role ) { $ role = strtolower ( $ role ) ; $ actualRole = $ connection -> executeCommand ( RawCommand :: create ( 'ROLE' ) ) ; if ( $ role !== $ actualRole [ 0 ] ) { throw new RoleException ( $ connection , "Expected $role but got $actualRole[0] [$connection]" ) ; } }
|
Asserts that the specified connection matches an expected role .
|
573
|
public function drop ( $ disconnect = false ) { if ( $ disconnect ) { if ( $ this -> valid ( ) ) { $ this -> position = $ this -> size ; $ this -> connection -> disconnect ( ) ; } } else { while ( $ this -> valid ( ) ) { $ this -> next ( ) ; } } }
|
Drop queued elements that have not been read from the connection either by consuming the rest of the multibulk response or quickly by closing the underlying connection .
|
574
|
protected static function processMastersOrSlaves ( array $ servers ) { foreach ( $ servers as $ idx => $ node ) { $ processed = array ( ) ; $ count = count ( $ node ) ; for ( $ i = 0 ; $ i < $ count ; ++ $ i ) { $ processed [ $ node [ $ i ] ] = $ node [ ++ $ i ] ; } $ servers [ $ idx ] = $ processed ; } return $ servers ; }
|
Returns a processed response to SENTINEL MASTERS or SENTINEL SLAVES .
|
575
|
private function getValue ( ) { $ database = 0 ; $ client = null ; $ event = $ this -> client -> getConnection ( ) -> read ( ) ; $ callback = function ( $ matches ) use ( & $ database , & $ client ) { if ( 2 === $ count = count ( $ matches ) ) { $ database = ( int ) $ matches [ 1 ] ; } if ( 4 === $ count ) { $ database = ( int ) $ matches [ 2 ] ; $ client = $ matches [ 3 ] ; } return ' ' ; } ; $ event = preg_replace_callback ( '/ \(db (\d+)\) | \[(\d+) (.*?)\] /' , $ callback , $ event , 1 ) ; @ list ( $ timestamp , $ command , $ arguments ) = explode ( ' ' , $ event , 3 ) ; return ( object ) array ( 'timestamp' => ( float ) $ timestamp , 'database' => $ database , 'client' => $ client , 'command' => substr ( $ command , 1 , - 1 ) , 'arguments' => $ arguments , ) ; }
|
Waits for a new message from the server generated by MONITOR and returns it when available .
|
576
|
protected static function processNumsub ( array $ channels ) { $ processed = array ( ) ; $ count = count ( $ channels ) ; for ( $ i = 0 ; $ i < $ count ; ++ $ i ) { $ processed [ $ channels [ $ i ] ] = $ channels [ ++ $ i ] ; } return $ processed ; }
|
Returns the processed response to PUBSUB NUMSUB .
|
577
|
public function attachCallback ( $ channel , $ callback ) { $ callbackName = $ this -> getPrefixKeys ( ) . $ channel ; $ this -> assertCallback ( $ callback ) ; $ this -> callbacks [ $ callbackName ] = $ callback ; $ this -> pubsub -> subscribe ( $ channel ) ; }
|
Binds a callback to a channel .
|
578
|
public function detachCallback ( $ channel ) { $ callbackName = $ this -> getPrefixKeys ( ) . $ channel ; if ( isset ( $ this -> callbacks [ $ callbackName ] ) ) { unset ( $ this -> callbacks [ $ callbackName ] ) ; $ this -> pubsub -> unsubscribe ( $ channel ) ; } }
|
Stops listening to a channel and removes the associated callback .
|
579
|
public function run ( ) { foreach ( $ this -> pubsub as $ message ) { $ kind = $ message -> kind ; if ( $ kind !== Consumer :: MESSAGE && $ kind !== Consumer :: PMESSAGE ) { if ( isset ( $ this -> subscriptionCallback ) ) { $ callback = $ this -> subscriptionCallback ; call_user_func ( $ callback , $ message ) ; } continue ; } if ( isset ( $ this -> callbacks [ $ message -> channel ] ) ) { $ callback = $ this -> callbacks [ $ message -> channel ] ; call_user_func ( $ callback , $ message -> payload ) ; } elseif ( isset ( $ this -> defaultCallback ) ) { $ callback = $ this -> defaultCallback ; call_user_func ( $ callback , $ message ) ; } } }
|
Starts the dispatcher loop .
|
580
|
protected function getPrefixKeys ( ) { $ options = $ this -> pubsub -> getClient ( ) -> getOptions ( ) ; if ( isset ( $ options -> prefix ) ) { return $ options -> prefix -> getPrefix ( ) ; } return '' ; }
|
Return the prefix used for keys .
|
581
|
private function genericSubscribeInit ( $ subscribeAction ) { if ( isset ( $ this -> options [ $ subscribeAction ] ) ) { $ this -> $ subscribeAction ( $ this -> options [ $ subscribeAction ] ) ; } }
|
This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE .
|
582
|
public static function handle ( CommunicationException $ exception ) { if ( $ exception -> shouldResetConnection ( ) ) { $ connection = $ exception -> getConnection ( ) ; if ( $ connection -> isConnected ( ) ) { $ connection -> disconnect ( ) ; } } throw $ exception ; }
|
Helper method to handle exceptions generated by a connection object .
|
583
|
protected function setProcessors ( OptionsInterface $ options , ProfileInterface $ profile ) { if ( isset ( $ options -> prefix ) && $ profile instanceof RedisProfile ) { $ profile -> setProcessor ( $ options -> __get ( 'prefix' ) ) ; } }
|
Sets the commands processors that need to be applied to the profile .
|
584
|
public function getCommandClass ( $ commandID ) { if ( isset ( $ this -> commands [ $ commandID = strtoupper ( $ commandID ) ] ) ) { return $ this -> commands [ $ commandID ] ; } }
|
Returns the fully - qualified name of a class representing the specified command ID registered in the current server profile .
|
585
|
public function defineCommand ( $ commandID , $ class ) { $ reflection = new \ ReflectionClass ( $ class ) ; if ( ! $ reflection -> isSubclassOf ( 'Predis\Command\CommandInterface' ) ) { throw new \ InvalidArgumentException ( "The class '$class' is not a valid command class." ) ; } $ this -> commands [ strtoupper ( $ commandID ) ] = $ class ; }
|
Defines a new command in the server profile .
|
586
|
protected static function registerMailableTagExtractor ( ) { Mailable :: buildViewDataUsing ( function ( $ mailable ) { return [ '__telescope' => ExtractTags :: from ( $ mailable ) , '__telescope_mailable' => get_class ( $ mailable ) , '__telescope_queued' => in_array ( ShouldQueue :: class , class_implements ( $ mailable ) ) , ] ; } ) ; }
|
Register a callback to extract mailable tags .
|
587
|
public function recordQuery ( QueryExecuted $ event ) { if ( ! Telescope :: isRecording ( ) ) { return ; } $ time = $ event -> time ; $ caller = $ this -> getCallerFromStackTrace ( ) ; Telescope :: recordQuery ( IncomingEntry :: make ( [ 'connection' => $ event -> connectionName , 'bindings' => $ this -> formatBindings ( $ event ) , 'sql' => $ event -> sql , 'time' => number_format ( $ time , 2 ) , 'slow' => isset ( $ this -> options [ 'slow' ] ) && $ time >= $ this -> options [ 'slow' ] , 'file' => $ caller [ 'file' ] , 'line' => $ caller [ 'line' ] , ] ) -> tags ( $ this -> tags ( $ event ) ) ) ; }
|
Record a query was executed .
|
588
|
public function toggle ( ) { if ( $ this -> cache -> get ( 'telescope:pause-recording' ) ) { $ this -> cache -> forget ( 'telescope:pause-recording' ) ; } else { $ this -> cache -> put ( 'telescope:pause-recording' , true , now ( ) -> addDays ( 30 ) ) ; } }
|
Toggle recording .
|
589
|
public function recordEvent ( $ eventName , $ payload ) { if ( ! Telescope :: isRecording ( ) || $ this -> shouldIgnore ( $ eventName ) ) { return ; } $ formattedPayload = $ this -> extractPayload ( $ eventName , $ payload ) ; Telescope :: recordEvent ( IncomingEntry :: make ( [ 'name' => $ eventName , 'payload' => empty ( $ formattedPayload ) ? null : $ formattedPayload , 'listeners' => $ this -> formatListeners ( $ eventName ) , 'broadcast' => class_exists ( $ eventName ) ? in_array ( ShouldBroadcast :: class , ( array ) class_implements ( $ eventName ) ) : false , ] ) -> tags ( class_exists ( $ eventName ) && isset ( $ payload [ 0 ] ) ? ExtractTags :: from ( $ payload [ 0 ] ) : [ ] ) ) ; }
|
Record an event was fired .
|
590
|
protected function extractPayload ( $ eventName , $ payload ) { if ( class_exists ( $ eventName ) && isset ( $ payload [ 0 ] ) && is_object ( $ payload [ 0 ] ) ) { return ExtractProperties :: from ( $ payload [ 0 ] ) ; } return collect ( $ payload ) -> map ( function ( $ value ) { return is_object ( $ value ) ? [ 'class' => get_class ( $ value ) , 'properties' => json_decode ( json_encode ( $ value ) , true ) , ] : $ value ; } ) -> toArray ( ) ; }
|
Extract the payload and tags from the event .
|
591
|
protected function formatListeners ( $ eventName ) { return collect ( app ( 'events' ) -> getListeners ( $ eventName ) ) -> map ( function ( $ listener ) { $ listener = ( new ReflectionFunction ( $ listener ) ) -> getStaticVariables ( ) [ 'listener' ] ; if ( is_string ( $ listener ) ) { return Str :: contains ( $ listener , '@' ) ? $ listener : $ listener . '@handle' ; } elseif ( is_array ( $ listener ) ) { return get_class ( $ listener [ 0 ] ) . '@' . $ listener [ 1 ] ; } return $ this -> formatClosureListener ( $ listener ) ; } ) -> reject ( function ( $ listener ) { return Str :: contains ( $ listener , 'Laravel\\Telescope' ) ; } ) -> map ( function ( $ listener ) { if ( Str :: contains ( $ listener , '@' ) ) { $ queued = in_array ( ShouldQueue :: class , class_implements ( explode ( '@' , $ listener ) [ 0 ] ) ) ; } return [ 'name' => $ listener , 'queued' => $ queued ?? false , ] ; } ) -> values ( ) -> toArray ( ) ; }
|
Format list of event listeners .
|
592
|
protected function formatClosureListener ( Closure $ listener ) { $ listener = new ReflectionFunction ( $ listener ) ; return sprintf ( 'Closure at %s[%s:%s]' , $ listener -> getFileName ( ) , $ listener -> getStartLine ( ) , $ listener -> getEndLine ( ) ) ; }
|
Format a closure - based listener .
|
593
|
public static function start ( $ app ) { if ( ! config ( 'telescope.enabled' ) ) { return ; } static :: registerWatchers ( $ app ) ; static :: registerMailableTagExtractor ( ) ; if ( static :: runningApprovedArtisanCommand ( $ app ) || static :: handlingApprovedRequest ( $ app ) ) { static :: startRecording ( ) ; } }
|
Register the Telescope watchers and start recording if necessary .
|
594
|
protected static function runningApprovedArtisanCommand ( $ app ) { return $ app -> runningInConsole ( ) && ! in_array ( $ _SERVER [ 'argv' ] [ 1 ] ?? null , array_merge ( [ 'migrate:rollback' , 'migrate:fresh' , 'migrate:reset' , 'migrate:install' , 'package:discover' , 'queue:listen' , 'queue:work' , 'horizon' , 'horizon:work' , 'horizon:supervisor' , ] , config ( 'telescope.ignoreCommands' , [ ] ) , config ( 'telescope.ignore_commands' , [ ] ) ) ) ; }
|
Determine if the application is running an approved command .
|
595
|
public static function withoutRecording ( $ callback ) { $ shouldRecord = static :: $ shouldRecord ; static :: $ shouldRecord = false ; call_user_func ( $ callback ) ; static :: $ shouldRecord = $ shouldRecord ; }
|
Execute the given callback without recording Telescope entries .
|
596
|
protected static function record ( string $ type , IncomingEntry $ entry ) { if ( ! static :: isRecording ( ) ) { return ; } $ entry -> type ( $ type ) -> tags ( static :: $ tagUsing ? call_user_func ( static :: $ tagUsing , $ entry ) : [ ] ) ; try { if ( Auth :: hasUser ( ) ) { $ entry -> user ( Auth :: user ( ) ) ; } } catch ( Throwable $ e ) { } static :: withoutRecording ( function ( ) use ( $ entry ) { if ( collect ( static :: $ filterUsing ) -> every -> __invoke ( $ entry ) ) { static :: $ entriesQueue [ ] = $ entry ; } if ( static :: $ afterRecordingHook ) { call_user_func ( static :: $ afterRecordingHook , new static ) ; } } ) ; }
|
Record the given entry .
|
597
|
public static function catch ( $ e , $ tags = [ ] ) { if ( $ e instanceof Throwable && ! $ e instanceof Exception ) { $ e = new FatalThrowableError ( $ e ) ; } event ( new MessageLogged ( 'error' , $ e -> getMessage ( ) , [ 'exception' => $ e , 'telescope' => $ tags , ] ) ) ; }
|
Record the given exception .
|
598
|
public static function store ( EntriesRepository $ storage ) { if ( empty ( static :: $ entriesQueue ) && empty ( static :: $ updatesQueue ) ) { return ; } if ( ! collect ( static :: $ filterBatchUsing ) -> every -> __invoke ( collect ( static :: $ entriesQueue ) ) ) { static :: flushEntries ( ) ; } try { $ batchId = Str :: orderedUuid ( ) -> toString ( ) ; $ storage -> store ( static :: collectEntries ( $ batchId ) ) ; $ storage -> update ( static :: collectUpdates ( $ batchId ) ) ; if ( $ storage instanceof TerminableRepository ) { $ storage -> terminate ( ) ; } } catch ( Exception $ e ) { app ( ExceptionHandler :: class ) -> report ( $ e ) ; } static :: $ entriesQueue = [ ] ; static :: $ updatesQueue = [ ] ; }
|
Store the queued entries and flush the queue .
|
599
|
protected static function collectEntries ( $ batchId ) { return collect ( static :: $ entriesQueue ) -> each ( function ( $ entry ) use ( $ batchId ) { $ entry -> batchId ( $ batchId ) ; if ( $ entry -> isDump ( ) ) { $ entry -> assignEntryPointFromBatch ( static :: $ entriesQueue ) ; } } ) ; }
|
Collect the entries for storage .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.