idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
47,900
private function validateFieldName ( $ field ) { $ fieldName = $ field -> getName ( ) ; if ( ! $ fieldName || $ this -> fieldNameExists ( $ fieldName ) ) { throw new FieldNameCollisionException ( "Field Name: `{$fieldName}` already exists." ) ; } return true ; }
Validates that a field s name doesn t already exist
47,901
public function build ( ) { $ config = parent :: build ( ) ; if ( array_key_exists ( 'collapsed' , $ config ) ) { $ fieldKey = $ this -> fieldsBuilder -> getField ( $ config [ 'collapsed' ] ) -> getKey ( ) ; $ fieldKey = preg_replace ( '/^field_/' , '' , $ fieldKey ) ; $ config [ 'collapsed' ] = $ this -> getName ( ) . '_' . $ fieldKey ; } return $ config ; }
Return a repeater field configuration array
47,902
public function andCondition ( $ name , $ operator , $ value ) { $ orCondition = $ this -> popOrCondition ( ) ; $ orCondition [ ] = $ this -> createCondition ( $ name , $ operator , $ value ) ; $ this -> pushOrCondition ( $ orCondition ) ; return $ this ; }
Creates an AND condition
47,903
public function orCondition ( $ name , $ operator , $ value ) { $ condition = $ this -> createCondition ( $ name , $ operator , $ value ) ; $ this -> pushOrCondition ( [ $ condition ] ) ; return $ this ; }
Creates an OR condition
47,904
public function loadFromSession ( ) { $ this -> session = Instance :: ensure ( $ this -> session , Session :: className ( ) ) ; if ( isset ( $ this -> session [ $ this -> cartId ] ) ) $ this -> setSerialized ( $ this -> session [ $ this -> cartId ] ) ; }
Loads cart from session
47,905
public function saveToSession ( ) { $ this -> session = Instance :: ensure ( $ this -> session , Session :: className ( ) ) ; $ this -> session [ $ this -> cartId ] = $ this -> getSerialized ( ) ; }
Saves cart to the session
47,906
public function removeById ( $ id ) { $ this -> trigger ( self :: EVENT_BEFORE_POSITION_REMOVE , new CartActionEvent ( [ 'action' => CartActionEvent :: ACTION_BEFORE_REMOVE , 'position' => $ this -> _positions [ $ id ] , ] ) ) ; $ this -> trigger ( self :: EVENT_CART_CHANGE , new CartActionEvent ( [ 'action' => CartActionEvent :: ACTION_BEFORE_REMOVE , 'position' => $ this -> _positions [ $ id ] , ] ) ) ; unset ( $ this -> _positions [ $ id ] ) ; if ( $ this -> storeInSession ) $ this -> saveToSession ( ) ; }
Removes position from the cart by ID
47,907
public function removeAll ( ) { $ this -> _positions = [ ] ; $ this -> trigger ( self :: EVENT_CART_CHANGE , new CartActionEvent ( [ 'action' => CartActionEvent :: ACTION_REMOVE_ALL , ] ) ) ; if ( $ this -> storeInSession ) $ this -> saveToSession ( ) ; }
Remove all positions
47,908
public function getCost ( $ withDiscount = false ) { $ cost = 0 ; foreach ( $ this -> _positions as $ position ) { $ cost += $ position -> getCost ( $ withDiscount ) ; } $ costEvent = new CostCalculationEvent ( [ 'baseCost' => $ cost , ] ) ; $ this -> trigger ( self :: EVENT_COST_CALCULATION , $ costEvent ) ; if ( $ withDiscount ) $ cost = max ( 0 , $ cost - $ costEvent -> discountValue ) ; return $ cost ; }
Return full cart cost as a sum of the individual positions costs
47,909
protected function encodeHeaders ( $ headers = [ ] ) { $ data = '' ; foreach ( $ headers as $ name => $ values ) { $ temp = [ ] ; $ data .= $ name . ": " ; $ values = ( array ) $ values ; foreach ( $ values as $ value ) { $ temp [ ] = $ this -> encodeHeader ( $ value ) ; } $ data .= implode ( ", " , $ temp ) ; $ data .= "\r\n" ; } return $ data ; }
Encode headers .
47,910
protected function createContainer ( ) { $ this -> container = new ContainerModel ( ) ; $ this -> reflector = new ContainerReflection ( ) ; $ this -> container -> delegate ( $ this -> reflector ) ; }
Prepare Container internals .
47,911
public function log ( $ level , $ message , array $ context = array ( ) ) { try { return $ this -> logger -> log ( $ level , $ message , $ context ) ; } catch ( Error $ ex ) { } catch ( Exception $ ex ) { } throw new WriteException ( "Record with undefined level could not be logged." , 0 , $ ex ) ; }
Add a log record at an arbitrary level .
47,912
public function emergency ( $ message , array $ context = array ( ) ) { try { return $ this -> logger -> emergency ( $ message , $ context ) ; } catch ( Error $ ex ) { } catch ( Exception $ ex ) { } throw new WriteException ( "Record with debug level could not be logged." , 0 , $ ex ) ; }
Add a log record at the EMERGENCY level .
47,913
public function sortProviders ( $ providers ) { foreach ( $ providers as $ provider ) { $ providerName = get_class ( $ provider ) ; $ this -> reqs [ $ providerName ] = $ provider -> getRequires ( ) ; $ this -> pvds [ $ providerName ] = $ provider -> getProvides ( ) ; $ this -> instances [ $ providerName ] = $ provider ; foreach ( $ provider -> getProvides ( ) as $ resource ) { $ this -> obtainableIn [ $ resource ] = $ providerName ; } } $ newOrder = [ ] ; foreach ( $ providers as $ provider ) { $ orderedProviders = $ this -> orderProvider ( $ provider ) ; foreach ( $ orderedProviders as $ orderedProvider ) { $ newOrder [ ] = $ this -> instances [ $ orderedProvider ] ; } } return $ newOrder ; }
Analyze required and provided dependencies of providers and sort the list to ensure right order while resolving dependency tree .
47,914
protected function param ( $ local , $ name ) { return isset ( $ local [ $ name ] ) ? $ local [ $ name ] : ( isset ( $ this -> defaults [ $ name ] ) ? $ this -> defaults [ $ name ] : null ) ; }
Return param saved under specified key in local settings or fallbacks to global settings .
47,915
protected function solver ( $ ex , $ params = [ ] ) { $ promise = Promise :: doResolve ( ) ; foreach ( $ this -> handlers as $ handler ) { $ current = $ handler ; $ promise = $ promise -> then ( function ( ) use ( $ ex , $ params , $ current ) { return Promise :: doResolve ( $ current -> solve ( $ ex , $ params ) ) ; } ) ; } return $ promise ; }
Handler to be called when solver is requested .
47,916
protected function resolveHandler ( $ solverOrName ) { if ( ! is_string ( $ solverOrName ) ) { return $ solverOrName ; } $ ex = null ; $ handler = null ; try { $ handler = $ this -> factory -> create ( $ solverOrName ) ; } catch ( Error $ ex ) { } catch ( Exception $ ex ) { } if ( $ ex !== null ) { throw new IllegalCallException ( "Tried to invoke [$solverOrName] which is undefined." ) ; } return $ handler ; }
Resolve handler .
47,917
protected function registerCommand ( $ alias , $ class ) { $ this -> define ( $ alias , function ( $ channel , $ receiver ) use ( $ class ) { return new $ class ( $ channel , $ receiver ) ; } ) -> define ( $ class , function ( $ channel , $ receiver ) use ( $ class ) { return new $ class ( $ channel , $ receiver ) ; } ) ; }
Register command under class and alias .
47,918
public function createHandler ( $ classOrName , $ args = [ ] ) { $ classes = [ $ classOrName , '\\Monolog\\Handler\\' . $ classOrName ] ; foreach ( $ classes as $ class ) { if ( class_exists ( $ class ) ) { $ object = ( new ReflectionClass ( $ class ) ) -> newInstanceArgs ( $ args ) ; return new Handler ( $ object ) ; } } throw new InvalidArgumentException ( "Monolog handler [$classOrName] does not exist." ) ; }
Create one of Monolog handlers by specifying it name or full class .
47,919
public function createFormatter ( $ classOrName , $ args = [ ] ) { $ classes = [ $ classOrName , '\\Monolog\\Formatter\\' . $ classOrName ] ; foreach ( $ classes as $ class ) { if ( class_exists ( $ class ) ) { $ object = ( new ReflectionClass ( $ class ) ) -> newInstanceArgs ( $ args ) ; return new Formatter ( $ object ) ; } } throw new InvalidArgumentException ( "Monolog formatter [$classOrName] does not exist." ) ; }
Create one of Monolog formatters by specyfing it name of full class .
47,920
public function createProcessor ( $ classOrName , $ args = [ ] ) { $ classes = [ $ classOrName , '\\Monolog\\Processor\\' . $ classOrName ] ; foreach ( $ classes as $ class ) { if ( class_exists ( $ class ) ) { return ( new ReflectionClass ( $ class ) ) -> newInstanceArgs ( $ args ) ; } } throw new InvalidArgumentException ( "Monolog processor [$classOrName] does not exist." ) ; }
Create one of Monolog processors by specyfing it name of full class .
47,921
public function handleConnect ( $ server , $ socket ) { $ socket -> conn = new NetworkConnection ( $ socket ) ; try { $ this -> component -> handleConnect ( $ socket -> conn ) ; $ socket -> on ( 'data' , [ $ this , 'handleData' ] ) ; $ socket -> on ( 'error' , [ $ this , 'handleError' ] ) ; $ socket -> on ( 'close' , [ $ this , 'handleDisconnect' ] ) ; } catch ( Error $ ex ) { $ this -> close ( $ socket ) ; } catch ( Exception $ ex ) { $ this -> close ( $ socket ) ; } }
Handler triggered when a new connection is received from SocketListener .
47,922
public function handleDisconnect ( $ socket ) { try { $ this -> component -> handleDisconnect ( $ socket -> conn ) ; } catch ( Error $ ex ) { $ this -> handleError ( $ socket , $ ex ) ; } catch ( Exception $ ex ) { $ this -> handleError ( $ socket , $ ex ) ; } unset ( $ socket -> conn ) ; }
Handler triggered when an existing connection is being closed .
47,923
public function handleData ( $ socket , $ data ) { try { $ this -> component -> handleMessage ( $ socket -> conn , new NetworkMessage ( $ data ) ) ; } catch ( Error $ ex ) { $ this -> handleError ( $ socket , $ ex ) ; } catch ( Exception $ ex ) { $ this -> handleError ( $ socket , $ ex ) ; } }
Handler triggered when a new data is received from existing connection .
47,924
public function remove ( $ alias ) { unset ( $ this -> definitions [ $ alias ] ) ; unset ( $ this -> sharedDefinitions [ $ alias ] ) ; unset ( $ this -> shared [ $ alias ] ) ; }
Remove existing definitions .
47,925
protected function overwrite ( $ current , $ new , $ handler = null ) { if ( $ handler === null ) { $ handler = $ this -> overwriteHandler ; } return $ handler ( $ current , $ new ) ; }
Overwrites current config using known method .
47,926
protected function setOptions ( $ options ) { $ all = [ 'auto_start' , 'cache_limiter' , 'cookie_domain' , 'cookie_httponly' , 'cookie_lifetime' , 'cookie_path' , 'cookie_secure' , 'entropy_file' , 'entropy_length' , 'gc_divisor' , 'gc_maxlifetime' , 'gc_probability' , 'hash_bits_per_character' , 'hash_function' , 'name' , 'referer_check' , 'serialize_handler' , 'use_cookies' , 'use_only_cookies' , 'use_trans_sid' , 'upload_progress.enabled' , 'upload_progress.cleanup' , 'upload_progress.prefix' , 'upload_progress.name' , 'upload_progress.freq' , 'upload_progress.min-freq' , 'url_rewriter.tags' ] ; foreach ( $ all as $ key ) { if ( ! array_key_exists ( $ key , $ options ) ) { $ options [ $ key ] = ini_get ( "session.{$key}" ) ; } else { ini_set ( "session.{$key}" , $ options [ $ key ] ) ; } } return $ options ; }
Set all the php session . ini options .
47,927
public function allocateProject ( $ alias , $ name , $ pid ) { try { $ record = [ 'pid' => $ pid , 'alias' => $ alias , 'name' => $ name ] ; $ this -> updateStorage ( $ record ) ; $ this -> data = array_merge ( $ this -> data , $ record ) ; } catch ( Error $ ex ) { return false ; } catch ( Exception $ ex ) { return false ; } return true ; }
Allocate project data .
47,928
public function freeProject ( ) { try { $ this -> data = $ this -> getEmptyStorage ( ) ; $ this -> updateStorage ( ) ; } catch ( Error $ ex ) { return false ; } catch ( Exception $ ex ) { return false ; } return true ; }
Flush project data .
47,929
private function updateStorage ( $ with = [ ] ) { $ data = array_merge ( $ this -> data , $ with ) ; $ this -> fs -> create ( $ this -> fsPath , json_encode ( $ data ) ) ; }
Copy temporary project data to persistent storage .
47,930
public function allocateProcess ( $ alias , $ name , $ pid ) { try { $ record = [ 'pid' => $ pid , 'name' => $ name , 'verified' => true ] ; $ this -> updateStorage ( [ $ alias => $ record ] ) ; $ this -> processes [ $ alias ] = $ record ; } catch ( Error $ ex ) { return false ; } catch ( Exception $ ex ) { return false ; } return true ; }
Allocate process .
47,931
public function freeProcess ( $ alias ) { try { unset ( $ this -> processes [ $ alias ] ) ; $ this -> updateStorage ( ) ; } catch ( Error $ ex ) { return false ; } catch ( Exception $ ex ) { return false ; } return true ; }
Free process .
47,932
private function updateStorage ( $ with = [ ] ) { $ data = [ ] ; foreach ( $ this -> processes as $ processAlias => $ process ) { $ data [ $ processAlias ] = $ process ; } $ data = array_merge ( $ data , $ with ) ; $ this -> fs -> create ( $ this -> fsPath , json_encode ( $ data ) ) ; }
Copy temporary process allocation data to persistent storage .
47,933
private function ensuredEraseDir ( $ dirname ) { try { $ listing = $ this -> fs -> listContents ( $ dirname , false ) ; foreach ( $ listing as $ item ) { if ( $ item [ 'type' ] === 'dir' ) { $ this -> fs -> deleteDir ( $ item [ 'path' ] ) ; } else { $ this -> fs -> delete ( $ item [ 'path' ] ) ; } } return ; } catch ( Error $ ex ) { } catch ( Exception $ ex ) { } throw new WriteException ( "Directory $dirname could not be erased." , 0 , $ ex ) ; }
Erase a directory .
47,934
public function size ( ) { $ size = 0 ; if ( ! is_null ( $ this -> key_ ) ) { $ l = strlen ( $ this -> key_ ) ; $ size += 1 + Protobuf :: size_varint ( $ l ) + $ l ; } if ( ! is_null ( $ this -> value_ ) ) { $ l = strlen ( $ this -> value_ ) ; $ size += 1 + Protobuf :: size_varint ( $ l ) + $ l ; } return $ size ; }
required string key = 1 ;
47,935
public function putLogs ( PutLogsRequest $ request ) { if ( count ( $ request -> getLogItems ( ) ) > 4096 ) { throw new Exception ( "[InvalidLogSize] logItem's length exceeds maximum limitation: 4096 lines." ) ; } $ logGroup = new LogGroup ( ) ; $ logGroup -> setTopic ( $ request -> getTopic ( ) ? : '' ) ; $ source = $ request -> getSource ( ) ; if ( ! $ source ) { $ source = $ this -> source ; } $ logGroup -> setSource ( $ source ) ; $ logItems = $ request -> getLogItems ( ) ; foreach ( $ logItems as $ logItem ) { $ log = new Log ( ) ; $ log -> setTime ( $ logItem -> getTime ( ) ) ; $ content = $ logItem -> getData ( ) ; foreach ( $ content as $ key => $ value ) { $ content = new LogContent ( ) ; $ content -> setKey ( $ key ) ; $ content -> setValue ( $ value ) ; $ log -> addContent ( $ content ) ; } $ logGroup -> addLogs ( $ log ) ; } $ body = Util :: toBytes ( $ logGroup ) ; unset ( $ logGroup ) ; $ bodySize = strlen ( $ body ) ; if ( $ bodySize > 3 * 1024 * 1024 ) { throw new Exception ( "[InvalidLogSize] logItem's size exceeds maximum limitation: 3 MB." ) ; } $ params = array ( ) ; $ headers = array ( ) ; $ headers [ "x-log-bodyrawsize" ] = $ bodySize ; $ headers [ 'x-log-compresstype' ] = 'deflate' ; $ headers [ 'Content-Type' ] = 'application/x-protobuf' ; $ body = gzcompress ( $ body , 6 ) ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ project = $ request -> getProject ( ) ? : '' ; $ resource = "/logstores/" . $ logStore ; list ( $ resp , $ header ) = $ this -> send ( "POST" , $ project , $ body , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ this -> parseToJson ( $ resp , $ requestId ) ; return new PutLogsResponse ( $ header ) ; }
Put logs to Log Service . Unsuccessful operation will cause an Exception .
47,936
protected function parseToJson ( $ resBody , $ requestId ) { if ( ! $ resBody ) { return null ; } $ result = json_decode ( $ resBody , true ) ; if ( is_null ( $ result ) ) { throw new Exception ( "[BadResponse] Bad format,not json: $resBody" , 0 , $ requestId ) ; } return $ result ; }
Decodes a JSON string to a JSON Object . Unsuccessful decode will cause an Exception .
47,937
public function createLogStore ( CreateLogStoreRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; $ resource = '/logstores' ; $ project = $ request -> getProject ( ) !== null ? $ request -> getProject ( ) : '' ; $ headers [ "x-log-bodyrawsize" ] = 0 ; $ headers [ "Content-Type" ] = "application/json" ; $ body = array ( "logStoreName" => $ request -> getLogStore ( ) , "ttl" => ( int ) ( $ request -> getTtl ( ) ) , "shardCount" => ( int ) ( $ request -> getShardCount ( ) ) ) ; $ body_str = json_encode ( $ body ) ; list ( $ resp , $ header ) = $ this -> send ( "POST" , $ project , $ body_str , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new CreateLogStoreResponse ( $ resp , $ header ) ; }
create logStore Unsuccessful operation will cause an Exception .
47,938
public function updateLogStore ( UpdateLogStoreRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; $ project = $ request -> getProject ( ) !== null ? $ request -> getProject ( ) : '' ; $ headers [ "x-log-bodyrawsize" ] = 0 ; $ headers [ "Content-Type" ] = "application/json" ; $ body = array ( "logStoreName" => $ request -> getLogStore ( ) , "ttl" => ( int ) ( $ request -> getTtl ( ) ) , "shardCount" => ( int ) ( $ request -> getShardCount ( ) ) ) ; $ resource = '/logstores/' . $ request -> getLogStore ( ) ; $ body_str = json_encode ( $ body ) ; list ( $ resp , $ header ) = $ this -> send ( "PUT" , $ project , $ body_str , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new UpdateLogStoreResponse ( $ resp , $ header ) ; }
update logStore Unsuccessful operation will cause an Exception .
47,939
public function listLogStores ( ListLogStoresRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; $ resource = '/logstores' ; $ project = $ request -> getProject ( ) !== null ? $ request -> getProject ( ) : '' ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new ListLogStoresResponse ( $ resp , $ header ) ; }
List all logStores of requested project . Unsuccessful operation will cause an Exception .
47,940
public function deleteLogStore ( DeleteLogStoreRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ resource = "/logstores/$logStore" ; list ( $ resp , $ header ) = $ this -> send ( "DELETE" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new DeleteLogStoreResponse ( $ resp , $ header ) ; }
Delete logStore Unsuccessful operation will cause an Exception .
47,941
public function listTopics ( ListTopicsRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; if ( $ request -> getToken ( ) !== null ) { $ params [ 'token' ] = $ request -> getToken ( ) ; } if ( $ request -> getLine ( ) !== null ) { $ params [ 'line' ] = $ request -> getLine ( ) ; } $ params [ 'type' ] = 'topic' ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ resource = "/logstores/$logStore" ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new ListTopicsResponse ( $ resp , $ header ) ; }
List all topics in a logStore . Unsuccessful operation will cause an Exception .
47,942
public function getHistograms ( GetHistogramsRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; if ( $ request -> getTopic ( ) !== null ) { $ params [ 'topic' ] = $ request -> getTopic ( ) ; } if ( $ request -> getFrom ( ) !== null ) { $ params [ 'from' ] = $ request -> getFrom ( ) ; } if ( $ request -> getTo ( ) !== null ) { $ params [ 'to' ] = $ request -> getTo ( ) ; } if ( $ request -> getQuery ( ) !== null ) { $ params [ 'query' ] = $ request -> getQuery ( ) ; } $ params [ 'type' ] = 'histogram' ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ resource = "/logstores/$logStore" ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new GetHistogramsResponse ( $ resp , $ header ) ; }
Get histograms of requested query from log service . Unsuccessful operation will cause an Exception .
47,943
public function getLogs ( GetLogsRequest $ request ) { $ headers = array ( ) ; $ params = array ( ) ; if ( $ request -> getTopic ( ) !== null ) { $ params [ 'topic' ] = $ request -> getTopic ( ) ; } if ( $ request -> getFrom ( ) !== null ) { $ params [ 'from' ] = $ request -> getFrom ( ) ; } if ( $ request -> getTo ( ) !== null ) { $ params [ 'to' ] = $ request -> getTo ( ) ; } if ( $ request -> getQuery ( ) !== null ) { $ params [ 'query' ] = $ request -> getQuery ( ) ; } $ params [ 'type' ] = 'log' ; if ( $ request -> getLine ( ) !== null ) { $ params [ 'line' ] = $ request -> getLine ( ) ; } if ( $ request -> getOffset ( ) !== null ) { $ params [ 'offset' ] = $ request -> getOffset ( ) ; } if ( $ request -> getOffset ( ) !== null ) { $ params [ 'reverse' ] = $ request -> getReverse ( ) ? 'true' : 'false' ; } $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ resource = "/logstores/$logStore" ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new GetLogsResponse ( $ resp , $ header ) ; }
Get logs from Log service . Unsuccessful operation will cause an Exception .
47,944
public function batchGetLogs ( BatchGetLogsRequest $ request ) { $ params = array ( ) ; $ headers = array ( ) ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ shardId = ! is_null ( $ request -> getShardId ( ) ) ? $ request -> getShardId ( ) : '' ; if ( ! is_null ( $ request -> getCount ( ) ) ) { $ params [ 'count' ] = $ request -> getCount ( ) ; } if ( ! is_null ( $ request -> getCursor ( ) ) ) { $ params [ 'cursor' ] = $ request -> getCursor ( ) ; } $ params [ 'type' ] = 'log' ; $ headers [ 'Accept-Encoding' ] = 'gzip' ; $ headers [ 'accept' ] = 'application/x-protobuf' ; $ resource = "/logstores/$logStore/shards/$shardId" ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ resp = gzuncompress ( $ resp ) ; if ( $ resp === false ) { $ resp = new LogGroupList ( ) ; } else { $ resp = new LogGroupList ( $ resp ) ; } return new BatchGetLogsResponse ( $ resp , $ header ) ; }
Get logs from Log service with shardid conditions . Unsuccessful operation will cause an Exception .
47,945
public function listShards ( ListShardsRequest $ request ) { $ params = array ( ) ; $ headers = array ( ) ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ resource = '/logstores/' . $ logStore . '/shards' ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new ListShardsResponse ( $ resp , $ header ) ; }
List Shards from Log service with Project and logStore conditions . Unsuccessful operation will cause an Exception .
47,946
public function getCursor ( GetCursorRequest $ request ) { $ params = array ( ) ; $ headers = array ( ) ; $ project = $ request -> getProject ( ) ? : '' ; $ logStore = $ request -> getLogStore ( ) ? : '' ; $ shardId = is_null ( $ request -> getShardId ( ) ) ? '' : $ request -> getShardId ( ) ; $ mode = $ request -> getMode ( ) ? : '' ; $ fromTime = $ request -> getFromTime ( ) ? : - 1 ; if ( ( empty ( $ mode ) xor $ fromTime == - 1 ) == false ) { if ( ! empty ( $ mode ) ) { throw new Exception ( "[RequestError] Request is failed. Mode and fromTime can not be not empty simultaneously" ) ; } else { throw new Exception ( "[RequestError] Request is failed. Mode and fromTime can not be empty simultaneously" ) ; } } if ( ! empty ( $ mode ) && strcmp ( $ mode , 'begin' ) !== 0 && strcmp ( $ mode , 'end' ) !== 0 ) { throw new Exception ( "[RequestError] Request is failed. Mode value invalid:$mode" ) ; } if ( $ fromTime !== - 1 && ( is_integer ( $ fromTime ) == false || $ fromTime < 0 ) ) { throw new Exception ( "[RequestError] Request is failed. FromTime value invalid:$fromTime" ) ; } $ params [ 'type' ] = 'cursor' ; if ( $ fromTime !== - 1 ) { $ params [ 'from' ] = $ fromTime ; } else { $ params [ 'mode' ] = $ mode ; } $ resource = '/logstores/' . $ logStore . '/shards/' . $ shardId ; list ( $ resp , $ header ) = $ this -> send ( "GET" , $ project , null , $ resource , $ params , $ headers ) ; $ requestId = isset ( $ header [ 'x-log-requestid' ] ) ? $ header [ 'x-log-requestid' ] : '' ; $ resp = $ this -> parseToJson ( $ resp , $ requestId ) ; return new GetCursorResponse ( $ resp , $ header ) ; }
Get cursor from Log service . Unsuccessful operation will cause an Exception .
47,947
public function size ( ) { $ size = 0 ; if ( ! is_null ( $ this -> time ) ) { $ size += 1 + Protobuf :: size_varint ( $ this -> time ) ; } if ( ! is_null ( $ this -> contents ) ) { foreach ( $ this -> contents as $ v ) { $ l = $ v -> size ( ) ; $ size += 1 + Protobuf :: size_varint ( $ l ) + $ l ; } } return $ size ; }
required uint32 time = 1 ;
47,948
public function set_write_file ( $ location ) { $ this -> write_file = $ location ; $ write_file_handle = fopen ( $ location , 'w' ) ; return $ this -> set_write_stream ( $ write_file_handle ) ; }
Sets the file to write to while streaming down .
47,949
public static function skip_field ( $ fp , $ wire_type ) { switch ( $ wire_type ) { case 0 : return Protobuf :: skip_varint ( $ fp ) ; case 1 : if ( fseek ( $ fp , 8 , SEEK_CUR ) === - 1 ) { throw new Exception ( 'skip(' . Protobuf :: get_wiretype ( 1 ) . '): Error seeking' ) ; } return 8 ; case 2 : $ varlen = 0 ; $ len = Protobuf :: read_varint ( $ fp , $ varlen ) ; if ( fseek ( $ fp , $ len , SEEK_CUR ) === - 1 ) { throw new Exception ( 'skip(' . Protobuf :: get_wiretype ( 2 ) . '): Error seeking' ) ; } return $ len - $ varlen ; case 5 : if ( fseek ( $ fp , 4 , SEEK_CUR ) === - 1 ) { throw new Exception ( 'skip(' . Protobuf :: get_wiretype ( 5 ) . '): Error seeking' ) ; } return 4 ; default : throw new Exception ( 'skip(' . Protobuf :: get_wiretype ( $ wire_type ) . '): Unsupported wire_type' ) ; } }
Seek past the current field
47,950
public static function skip_varint ( $ fp ) { $ len = 0 ; do { $ b = fread ( $ fp , 1 ) ; if ( $ b === false ) { throw new Exception ( "skip(varint): Error reading byte" ) ; } $ len ++ ; } while ( $ b >= "\x80" ) ; return $ len ; }
Seek past a varint
47,951
public function size ( ) { $ size = 0 ; if ( ! is_null ( $ this -> data_ ) ) { $ l = strlen ( $ this -> data_ ) ; $ size += 1 + Protobuf :: size_varint ( $ l ) + $ l ; } if ( ! is_null ( $ this -> uncompressSize_ ) ) { $ size += 1 + Protobuf :: size_varint ( $ this -> uncompressSize_ ) ; } return $ size ; }
required bytes data = 1 ;
47,952
public function actionIndex ( ) { $ searchModel = $ this -> module -> model ( "UserSearch" ) ; $ dataProvider = $ searchModel -> search ( Yii :: $ app -> request -> getQueryParams ( ) ) ; return $ this -> render ( 'index' , compact ( 'searchModel' , 'dataProvider' ) ) ; }
List all User models
47,953
public function actionCreate ( ) { $ user = $ this -> module -> model ( "User" ) ; $ user -> setScenario ( "admin" ) ; $ profile = $ this -> module -> model ( "Profile" ) ; $ post = Yii :: $ app -> request -> post ( ) ; $ userLoaded = $ user -> load ( $ post ) ; $ profile -> load ( $ post ) ; if ( Yii :: $ app -> request -> isAjax ) { Yii :: $ app -> response -> format = Response :: FORMAT_JSON ; return ActiveForm :: validate ( $ user , $ profile ) ; } if ( $ userLoaded && $ user -> validate ( ) && $ profile -> validate ( ) ) { $ user -> save ( false ) ; $ profile -> setUser ( $ user -> id ) -> save ( false ) ; return $ this -> redirect ( [ 'view' , 'id' => $ user -> id ] ) ; } return $ this -> render ( 'create' , compact ( 'user' , 'profile' ) ) ; }
Create a new User model . If creation is successful the browser will be redirected to the view page .
47,954
public function actionDelete ( $ id ) { $ user = $ this -> findModel ( $ id ) ; $ profile = $ user -> profile ; $ userToken = $ this -> module -> model ( "UserToken" ) ; $ userAuth = $ this -> module -> model ( "UserAuth" ) ; $ userToken :: deleteAll ( [ 'user_id' => $ user -> id ] ) ; $ userAuth :: deleteAll ( [ 'user_id' => $ user -> id ] ) ; $ profile -> delete ( ) ; $ user -> delete ( ) ; return $ this -> redirect ( [ 'index' ] ) ; }
Delete an existing User model . If deletion is successful the browser will be redirected to the index page .
47,955
protected function findModel ( $ id ) { $ user = $ this -> module -> model ( "User" ) ; $ user = $ user :: findOne ( $ id ) ; if ( $ user ) { return $ user ; } throw new NotFoundHttpException ( 'The requested page does not exist.' ) ; }
Find the User model based on its primary key value . If the model is not found a 404 HTTP exception will be thrown .
47,956
public static function dropdown ( ) { static $ dropdown ; if ( $ dropdown === null ) { $ models = static :: find ( ) -> all ( ) ; foreach ( $ models as $ model ) { $ dropdown [ $ model -> id ] = $ model -> name ; } } return $ dropdown ; }
Get list of roles for creating dropdowns
47,957
public function setRegisterAttributes ( $ roleId , $ status = null ) { $ attributes = [ "role_id" => $ roleId , "created_ip" => Yii :: $ app -> request -> userIP , "auth_key" => Yii :: $ app -> security -> generateRandomString ( ) , "access_token" => Yii :: $ app -> security -> generateRandomString ( ) , "status" => static :: STATUS_ACTIVE , ] ; $ emailConfirmation = $ this -> module -> emailConfirmation ; $ requireEmail = $ this -> module -> requireEmail ; $ useEmail = $ this -> module -> useEmail ; if ( $ status ) { $ attributes [ "status" ] = $ status ; } elseif ( $ emailConfirmation && $ requireEmail ) { $ attributes [ "status" ] = static :: STATUS_INACTIVE ; } elseif ( $ emailConfirmation && $ useEmail && $ this -> email ) { $ attributes [ "status" ] = static :: STATUS_UNCONFIRMED_EMAIL ; } $ this -> setAttributes ( $ attributes , false ) ; return $ this ; }
Set attributes for registration
47,958
public function checkEmailChange ( ) { if ( $ this -> email == $ this -> getOldAttribute ( "email" ) ) { return false ; } if ( ! $ this -> module -> emailChangeConfirmation ) { return false ; } if ( ! $ this -> email ) { return false ; } $ newEmail = $ this -> email ; $ this -> status = static :: STATUS_UNCONFIRMED_EMAIL ; $ this -> email = $ this -> getOldAttribute ( "email" ) ; return $ newEmail ; }
Check for email change
47,959
public function confirm ( $ newEmail ) { $ this -> status = static :: STATUS_ACTIVE ; $ success = true ; if ( $ newEmail ) { $ checkUser = static :: findOne ( [ "email" => $ newEmail ] ) ; if ( $ checkUser ) { $ success = false ; } else { $ this -> email = $ newEmail ; } } $ this -> save ( false , [ "email" , "status" ] ) ; return $ success ; }
Confirm user email
47,960
public function sendEmailConfirmation ( $ userToken ) { $ mailer = Yii :: $ app -> mailer ; $ oldViewPath = $ mailer -> viewPath ; $ mailer -> viewPath = $ this -> module -> emailViewPath ; $ user = $ this ; $ profile = $ user -> profile ; $ email = $ userToken -> data ? : $ user -> email ; $ subject = Yii :: $ app -> id . " - " . Yii :: t ( "user" , "Email Confirmation" ) ; $ result = $ mailer -> compose ( 'confirmEmail' , compact ( "subject" , "user" , "profile" , "userToken" ) ) -> setTo ( $ email ) -> setSubject ( $ subject ) -> send ( ) ; $ mailer -> viewPath = $ oldViewPath ; return $ result ; }
Send email confirmation to user
47,961
public static function statusDropdown ( ) { static $ dropdown ; $ constPrefix = "STATUS_" ; if ( $ dropdown === null ) { $ reflClass = new ReflectionClass ( get_called_class ( ) ) ; $ constants = $ reflClass -> getConstants ( ) ; foreach ( $ constants as $ constantName => $ constantValue ) { if ( strpos ( $ constantName , $ constPrefix ) === 0 ) { $ prettyName = str_replace ( $ constPrefix , "" , $ constantName ) ; $ prettyName = Inflector :: humanize ( strtolower ( $ prettyName ) ) ; $ dropdown [ $ constantValue ] = $ prettyName ; } } } return $ dropdown ; }
Get list of statuses for creating dropdowns
47,962
public function model ( $ name , $ config = [ ] ) { $ config [ "class" ] = $ this -> modelClasses [ ucfirst ( $ name ) ] ; return Yii :: createObject ( $ config ) ; }
Get object instance of model
47,963
public function actionIndex ( ) { if ( defined ( 'YII_DEBUG' ) && YII_DEBUG ) { $ actions = $ this -> module -> getActions ( ) ; return $ this -> render ( 'index' , [ "actions" => $ actions ] ) ; } elseif ( Yii :: $ app -> user -> isGuest ) { return $ this -> redirect ( [ "/user/login" ] ) ; } else { return $ this -> redirect ( [ "/user/account" ] ) ; } }
Display index - debug page login page or account page
47,964
public function actionLogin ( ) { $ model = $ this -> module -> model ( "LoginForm" ) ; $ post = Yii :: $ app -> request -> post ( ) ; if ( $ model -> load ( $ post ) && $ model -> validate ( ) ) { $ returnUrl = $ this -> performLogin ( $ model -> getUser ( ) , $ model -> rememberMe ) ; return $ this -> redirect ( $ returnUrl ) ; } return $ this -> render ( 'login' , compact ( "model" ) ) ; }
Display login page
47,965
protected function performLogin ( $ user , $ rememberMe = true ) { $ loginDuration = $ rememberMe ? $ this -> module -> loginDuration : 0 ; Yii :: $ app -> user -> login ( $ user , $ loginDuration ) ; $ loginRedirect = $ this -> module -> loginRedirect ; $ returnUrl = Yii :: $ app -> user -> getReturnUrl ( $ loginRedirect ) ; if ( strpos ( $ returnUrl , "user/login" ) !== false || strpos ( $ returnUrl , "user/logout" ) !== false ) { $ returnUrl = null ; } return $ returnUrl ; }
Perform the login
47,966
public function actionLogout ( ) { Yii :: $ app -> user -> logout ( ) ; $ logoutRedirect = $ this -> module -> logoutRedirect ; if ( $ logoutRedirect ) { return $ this -> redirect ( $ logoutRedirect ) ; } return $ this -> goHome ( ) ; }
Log user out and redirect
47,967
public function actionRegister ( ) { $ user = $ this -> module -> model ( "User" , [ "scenario" => "register" ] ) ; $ profile = $ this -> module -> model ( "Profile" ) ; $ post = Yii :: $ app -> request -> post ( ) ; if ( $ user -> load ( $ post ) ) { $ profile -> load ( $ post ) ; if ( Yii :: $ app -> request -> isAjax ) { Yii :: $ app -> response -> format = Response :: FORMAT_JSON ; return ActiveForm :: validate ( $ user , $ profile ) ; } if ( $ user -> validate ( ) && $ profile -> validate ( ) ) { $ role = $ this -> module -> model ( "Role" ) ; $ user -> setRegisterAttributes ( $ role :: ROLE_USER ) -> save ( ) ; $ profile -> setUser ( $ user -> id ) -> save ( ) ; $ this -> afterRegister ( $ user ) ; $ successText = Yii :: t ( "user" , "Successfully registered [ {displayName} ]" , [ "displayName" => $ user -> getDisplayName ( ) ] ) ; $ guestText = "" ; if ( Yii :: $ app -> user -> isGuest ) { $ guestText = Yii :: t ( "user" , " - Please check your email to confirm your account" ) ; } Yii :: $ app -> session -> setFlash ( "Register-success" , $ successText . $ guestText ) ; } } return $ this -> render ( "register" , compact ( "user" , "profile" ) ) ; }
Display registration page
47,968
protected function afterRegister ( $ user ) { $ userToken = $ this -> module -> model ( "UserToken" ) ; $ userTokenType = null ; if ( $ user -> status == $ user :: STATUS_INACTIVE ) { $ userTokenType = $ userToken :: TYPE_EMAIL_ACTIVATE ; } elseif ( $ user -> status == $ user :: STATUS_UNCONFIRMED_EMAIL ) { $ userTokenType = $ userToken :: TYPE_EMAIL_CHANGE ; } if ( $ userTokenType ) { $ userToken = $ userToken :: generate ( $ user -> id , $ userTokenType ) ; if ( ! $ numSent = $ user -> sendEmailConfirmation ( $ userToken ) ) { } } else { Yii :: $ app -> user -> login ( $ user , $ this -> module -> loginDuration ) ; } }
Process data after registration
47,969
public function actionResend ( ) { $ model = $ this -> module -> model ( "ResendForm" ) ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> sendEmail ( ) ) { Yii :: $ app -> session -> setFlash ( "Resend-success" , Yii :: t ( "user" , "Confirmation email resent" ) ) ; return $ this -> refresh ( ) ; } return $ this -> render ( "resend" , compact ( "model" ) ) ; }
Resend email confirmation
47,970
public function actionResendChange ( ) { $ user = Yii :: $ app -> user -> identity ; $ userToken = $ this -> module -> model ( "UserToken" ) ; $ userToken = $ userToken :: findByUser ( $ user -> id , $ userToken :: TYPE_EMAIL_CHANGE ) ; if ( $ userToken ) { $ user -> sendEmailConfirmation ( $ userToken ) ; Yii :: $ app -> session -> setFlash ( "Resend-success" , Yii :: t ( "user" , "Confirmation email resent" ) ) ; } return $ this -> redirect ( [ "/user/account" ] ) ; }
Resend email change confirmation
47,971
public function actionCancel ( ) { $ user = Yii :: $ app -> user -> identity ; $ userToken = $ this -> module -> model ( "UserToken" ) ; $ userToken = $ userToken :: findByUser ( $ user -> id , $ userToken :: TYPE_EMAIL_CHANGE ) ; if ( $ userToken ) { $ userToken -> delete ( ) ; Yii :: $ app -> session -> setFlash ( "Cancel-success" , Yii :: t ( "user" , "Email change cancelled" ) ) ; } return $ this -> redirect ( [ "/user/account" ] ) ; }
Cancel email change
47,972
protected function defaultReturnUrl ( ) { $ params = $ _GET ; if ( ! empty ( $ params [ 'state' ] ) && $ params [ 'state' ] !== $ this -> state ) { throw new Exception ( "State does not match" ) ; } unset ( $ params [ 'code' ] ) ; unset ( $ params [ 'state' ] ) ; $ params [ 0 ] = Yii :: $ app -> controller -> getRoute ( ) ; return Yii :: $ app -> getUrlManager ( ) -> createAbsoluteUrl ( $ params ) ; }
Check matching state and remove from params so that return uri will match the one set in the Reddit app
47,973
public static function nocache ( ) : bool { if ( ! headers_sent ( ) ) { header ( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' ) ; header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s' ) . ' GMT' ) ; header ( 'Cache-Control: no-cache, must-revalidate, max-age=0' ) ; header ( 'Pragma: no-cache' ) ; return true ; } return false ; }
Sets the headers to prevent caching for the different browsers . Different browsers support different nocache headers so several headers must be sent so that all of them get the point that no caching should occur
47,974
public static function getHeaders ( ) : array { $ headers = [ ] ; $ contentHeaders = [ 'CONTENT_LENGTH' => true , 'CONTENT_MD5' => true , 'CONTENT_TYPE' => true ] ; foreach ( $ _SERVER as $ key => $ value ) { if ( 0 === strpos ( $ key , 'HTTP_' ) ) { $ headers [ substr ( $ key , 5 ) ] = $ value ; } elseif ( isset ( $ contentHeaders [ $ key ] ) ) { $ headers [ $ key ] = $ value ; } } if ( isset ( $ _SERVER [ 'PHP_AUTH_USER' ] ) ) { $ headers [ 'PHP_AUTH_USER' ] = $ _SERVER [ 'PHP_AUTH_USER' ] ; $ headers [ 'PHP_AUTH_PW' ] = $ _SERVER [ 'PHP_AUTH_PW' ] ?? '' ; } else { $ authorizationHeader = null ; if ( isset ( $ _SERVER [ 'HTTP_AUTHORIZATION' ] ) ) { $ authorizationHeader = $ _SERVER [ 'HTTP_AUTHORIZATION' ] ; } elseif ( isset ( $ _SERVER [ 'REDIRECT_HTTP_AUTHORIZATION' ] ) ) { $ authorizationHeader = $ _SERVER [ 'REDIRECT_HTTP_AUTHORIZATION' ] ; } if ( null !== $ authorizationHeader ) { if ( 0 === stripos ( $ authorizationHeader , 'basic ' ) ) { $ exploded = explode ( ':' , base64_decode ( substr ( $ authorizationHeader , 6 ) ) , 2 ) ; if ( count ( $ exploded ) === 2 ) { list ( $ headers [ 'PHP_AUTH_USER' ] , $ headers [ 'PHP_AUTH_PW' ] ) = $ exploded ; } } elseif ( empty ( $ _SERVER [ 'PHP_AUTH_DIGEST' ] ) && ( 0 === stripos ( $ authorizationHeader , 'digest ' ) ) ) { $ headers [ 'PHP_AUTH_DIGEST' ] = $ authorizationHeader ; $ _SERVER [ 'PHP_AUTH_DIGEST' ] = $ authorizationHeader ; } elseif ( 0 === stripos ( $ authorizationHeader , 'bearer ' ) ) { $ headers [ 'AUTHORIZATION' ] = $ authorizationHeader ; } } } if ( isset ( $ headers [ 'AUTHORIZATION' ] ) ) { return $ headers ; } if ( isset ( $ headers [ 'PHP_AUTH_USER' ] ) ) { $ authorization = 'Basic ' . base64_encode ( $ headers [ 'PHP_AUTH_USER' ] . ':' . $ headers [ 'PHP_AUTH_PW' ] ) ; $ headers [ 'AUTHORIZATION' ] = $ authorization ; } elseif ( isset ( $ headers [ 'PHP_AUTH_DIGEST' ] ) ) { $ headers [ 'AUTHORIZATION' ] = $ headers [ 'PHP_AUTH_DIGEST' ] ; } return $ headers ; }
Get all HTTP headers
47,975
public static function removeAccents ( $ string , $ language = '' ) : string { if ( ! preg_match ( '/[\x80-\xff]/' , $ string ) ) { return $ string ; } return self :: downCode ( $ string , $ language ) ; }
Converts all accent characters to ASCII characters . If there are no accent characters then the string given is just returned .
47,976
public static function path ( ) { $ url = '' ; if ( ! Arr :: key ( 'REQUEST_URI' , $ _SERVER ) ) { if ( $ queryString = Arr :: key ( 'QUERY_STRING' , $ _SERVER , true ) ) { $ url .= '?' . $ queryString ; } } else { $ url .= $ _SERVER [ 'REQUEST_URI' ] ; } return $ url ? : null ; }
Return the current path
47,977
public static function root ( $ addAuth = false ) { $ url = '' ; $ isHttps = self :: isHttps ( ) ; if ( $ addAuth ) { $ url .= self :: getAuth ( ) ; } $ serverData = data ( $ _SERVER ) ; $ host = $ serverData -> get ( 'HTTP_HOST' ) ; $ port = ( int ) $ serverData -> get ( 'SERVER_PORT' ) ; $ url .= str_replace ( ':' . $ port , '' , $ host ) ; if ( $ isHttps && $ port !== self :: PORT_HTTPS ) { $ url .= $ port ? ":{$port}" : '' ; } elseif ( ! $ isHttps && $ port !== self :: PORT_HTTP ) { $ url .= $ port ? ":{$port}" : '' ; } if ( $ url ) { if ( $ isHttps ) { return 'https://' . $ url ; } return 'http://' . $ url ; } return null ; }
Return current root URL
47,978
public static function getAuth ( ) { $ result = null ; if ( $ user = Arr :: key ( 'PHP_AUTH_USER' , $ _SERVER , true ) ) { $ result .= $ user ; if ( $ password = Arr :: key ( 'PHP_AUTH_PW' , $ _SERVER , true ) ) { $ result .= ':' . $ password ; } $ result .= '@' ; } return $ result ; }
Get current auth info
47,979
public static function pathToRel ( $ path ) : string { $ root = FS :: clean ( Vars :: get ( $ _SERVER [ 'DOCUMENT_ROOT' ] ) ) ; $ path = FS :: clean ( $ path ) ; $ normRoot = str_replace ( DIRECTORY_SEPARATOR , '/' , $ root ) ; $ normPath = str_replace ( DIRECTORY_SEPARATOR , '/' , $ path ) ; $ regExp = '/^' . preg_quote ( $ normRoot , '/' ) . '/i' ; $ relative = preg_replace ( $ regExp , '' , $ normPath ) ; $ relative = ltrim ( $ relative , '/' ) ; return $ relative ; }
Convert file path to relative URL
47,980
public static function iniSet ( $ varName , $ newValue ) { if ( self :: isFunc ( 'ini_set' ) ) { return Filter :: bool ( ini_set ( $ varName , $ newValue ) ) ; } return null ; }
Alias fo ini_set function
47,981
public static function getMemory ( $ isPeak = true ) : string { if ( $ isPeak ) { $ memory = memory_get_peak_usage ( false ) ; } else { $ memory = memory_get_usage ( false ) ; } return FS :: format ( $ memory ) ; }
Get usage memory
47,982
public static function getDocRoot ( ) : string { $ result = '.' ; $ root = Arr :: key ( 'DOCUMENT_ROOT' , $ _SERVER , true ) ; if ( $ root ) { $ result = $ root ; } $ result = FS :: clean ( $ result ) ; $ result = FS :: real ( $ result ) ; if ( ! $ result ) { $ result = FS :: real ( '.' ) ; } return $ result ; }
Return document root
47,983
public static function out ( $ message , $ addEol = true ) { if ( $ addEol ) { $ message .= PHP_EOL ; } if ( \ defined ( 'STDOUT' ) ) { fwrite ( STDOUT , $ message ) ; } else { echo $ message ; } }
Print line to std out
47,984
public static function err ( $ message , $ addEol = true ) { if ( $ addEol ) { $ message .= PHP_EOL ; } if ( \ defined ( 'STDERR' ) ) { fwrite ( STDERR , $ message ) ; } else { echo $ message ; } }
Print line to std error
47,985
public static function exec ( $ command , array $ args = [ ] , $ cwd = null , $ verbose = false ) : string { if ( ! class_exists ( Process :: class ) ) { throw new Exception ( 'Symfony/Process package required for Cli::exec() method' ) ; } $ cmd = self :: build ( $ command , $ args ) ; $ cwd = $ cwd ? realpath ( $ cwd ) : null ; if ( $ verbose ) { if ( \ function_exists ( '\JBZoo\PHPUnit\cliMessage' ) ) { cliMessage ( 'Process: ' . $ cmd ) ; cliMessage ( 'CWD: ' . $ cwd ) ; } else { self :: out ( 'Process: ' . $ cmd ) ; self :: out ( 'CWD: ' . $ cwd ) ; } } try { if ( method_exists ( Process :: class , 'fromShellCommandline' ) ) { $ process = Process :: fromShellCommandline ( $ cmd , $ cwd , null , null , 3600 ) ; } else { $ process = new Process ( $ cmd , $ cwd , null , null , 3600 ) ; } $ process -> inheritEnvironmentVariables ( true ) ; $ process -> run ( ) ; } catch ( \ Exception $ exception ) { throw new Exception ( $ exception , ( int ) $ exception -> getCode ( ) , $ exception ) ; } if ( ! $ process -> isSuccessful ( ) ) { throw new ProcessFailedException ( $ process ) ; } return $ process -> getOutput ( ) ; }
Execute cli commands
47,986
public static function build ( $ command , array $ args = [ ] ) : string { $ stringArgs = [ ] ; $ realCommand = $ command ; if ( count ( $ args ) > 0 ) { foreach ( $ args as $ key => $ value ) { $ value = trim ( $ value ) ; $ key = trim ( $ key ) ; if ( strpos ( $ key , '-' ) !== 0 ) { $ key = strlen ( $ key ) === 1 ? '-' . $ key : '--' . $ key ; } if ( strlen ( $ value ) > 0 ) { $ stringArgs [ ] = $ key . '="' . addcslashes ( $ value , '"' ) . '"' ; } else { $ stringArgs [ ] = $ key ; } } } if ( count ( $ stringArgs ) ) { $ realCommand = $ command . ' ' . implode ( ' ' , $ stringArgs ) ; } return $ realCommand ; }
Build params for cli options
47,987
public static function hasColorSupport ( ) : bool { if ( DIRECTORY_SEPARATOR === '\\' ) { $ winColor = Env :: get ( 'ANSICON' , Env :: VAR_BOOL ) || 'ON' === Env :: get ( 'ConEmuANSI' ) || 'xterm' === Env :: get ( 'TERM' ) ; return $ winColor ; } if ( ! defined ( 'STDOUT' ) ) { return false ; } return self :: isInteractive ( STDOUT ) ; }
Returns true if STDOUT supports colorization .
47,988
public static function getNumberOfColumns ( ) : int { if ( DIRECTORY_SEPARATOR === '\\' ) { $ columns = 80 ; if ( preg_match ( '/^(\d+)x\d+ \(\d+x(\d+)\)$/' , trim ( getenv ( 'ANSICON' ) ) , $ matches ) ) { $ columns = $ matches [ 1 ] ; } elseif ( function_exists ( 'proc_open' ) ) { $ process = proc_open ( 'mode CON' , [ 1 => [ 'pipe' , 'w' ] , 2 => [ 'pipe' , 'w' ] , ] , $ pipes , null , null , [ 'suppress_errors' => true ] ) ; if ( is_resource ( $ process ) ) { $ info = stream_get_contents ( $ pipes [ 1 ] ) ; fclose ( $ pipes [ 1 ] ) ; fclose ( $ pipes [ 2 ] ) ; proc_close ( $ process ) ; if ( preg_match ( '/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/' , $ info , $ matches ) ) { $ columns = $ matches [ 2 ] ; } } } return $ columns - 1 ; } if ( ! self :: isInteractive ( self :: STDIN ) ) { return 80 ; } if ( preg_match ( '#\d+ (\d+)#' , shell_exec ( 'stty size' ) , $ match ) === 1 ) { if ( ( int ) $ match [ 1 ] > 0 ) { return ( int ) $ match [ 1 ] ; } } if ( preg_match ( '#columns = (\d+);#' , shell_exec ( 'stty' ) , $ match ) === 1 ) { if ( ( int ) $ match [ 1 ] > 0 ) { return ( int ) $ match [ 1 ] ; } } return 80 ; }
Returns the number of columns of the terminal .
47,989
public static function toStamp ( $ time = null , $ currentIsDefault = true ) : int { if ( $ time instanceof DateTime ) { return $ time -> format ( 'U' ) ; } if ( null !== $ time ) { $ time = is_numeric ( $ time ) ? ( int ) $ time : strtotime ( $ time ) ; } if ( ! $ time ) { $ time = $ currentIsDefault ? time ( ) : 0 ; } return $ time ; }
Convert to timestamp
47,990
public static function timezone ( $ timezone = null ) : \ DateTimeZone { if ( $ timezone instanceof DateTimeZone ) { return $ timezone ; } $ timezone = $ timezone ? : date_default_timezone_get ( ) ; return new DateTimeZone ( $ timezone ) ; }
Return a DateTimeZone object based on the current timezone .
47,991
public static function sql ( $ time = null ) : string { return self :: factory ( $ time ) -> format ( self :: SQL_FORMAT ) ; }
Convert time for sql format
47,992
public static function isThisWeek ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'W-Y' ) === self :: factory ( ) -> format ( 'W-Y' ) ) ; }
Returns true if date passed is within this week .
47,993
public static function isThisMonth ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'm-Y' ) === self :: factory ( ) -> format ( 'm-Y' ) ) ; }
Returns true if date passed is within this month .
47,994
public static function isThisYear ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'Y' ) === self :: factory ( ) -> format ( 'Y' ) ) ; }
Returns true if date passed is within this year .
47,995
public static function isTomorrow ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'Y-m-d' ) === self :: factory ( 'tomorrow' ) -> format ( 'Y-m-d' ) ) ; }
Returns true if date passed is tomorrow .
47,996
public static function isToday ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'Y-m-d' ) === self :: factory ( ) -> format ( 'Y-m-d' ) ) ; }
Returns true if date passed is today .
47,997
public static function isYesterday ( $ time ) : bool { return ( self :: factory ( $ time ) -> format ( 'Y-m-d' ) === self :: factory ( 'yesterday' ) -> format ( 'Y-m-d' ) ) ; }
Returns true if date passed was yesterday .
47,998
protected static function checkBasic ( $ data , $ length ) : bool { return $ length < 4 || $ data [ 1 ] !== ':' || ( $ data [ $ length - 1 ] !== ';' && $ data [ $ length - 1 ] !== '}' ) ; }
Check some basic requirements of all serialized strings
47,999
public static function openFile ( $ filepath ) { $ contents = null ; if ( $ realPath = realpath ( $ filepath ) ) { $ handle = fopen ( $ realPath , 'rb' ) ; $ contents = fread ( $ handle , filesize ( $ realPath ) ) ; fclose ( $ handle ) ; } return $ contents ; }
Binary safe to open file