idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
47,400
|
public function format ( $ format = self :: FORMAT_COMPLETE ) { if ( ! $ this -> hasValidFormat ( ) ) { return false ; } switch ( $ format ) { case static :: FORMAT_COMPLETE : return $ this -> join ( number_format ( $ this -> number , 0 , null , "." ) , $ this -> vn ) ; break ; case static :: FORMAT_WITH_DASH : return $ this -> join ( $ this -> number , $ this -> vn ) ; break ; } return $ this -> number . $ this -> vn ; }
|
Format R . U . T
|
47,401
|
public function hasValidFormat ( ) { $ is_ok = ( preg_match ( '/^[0-9]+$/' , $ this -> number ) && preg_match ( '/([K0-9])$/' , $ this -> vn ) && strlen ( $ this -> number ) > $ this -> minChars && strlen ( $ this -> number ) < $ this -> maxChars ) ; if ( ! $ is_ok && $ this -> useExceptions ) { throw new InvalidFormatException ( "R.U.T. '{$this->number}' with verification code '{$this->vn}' has an invalid format" ) ; } return $ is_ok ; }
|
Check if RUT has a valid format . If not throws an Exception
|
47,402
|
private function initWebsocketServer ( ) { $ websocketBind = $ this -> sandstoneApplication [ 'sandstone.websocket.server' ] [ 'bind' ] ; $ websocketPort = $ this -> sandstoneApplication [ 'sandstone.websocket.server' ] [ 'port' ] ; $ socket = new ReactSocketServer ( "$websocketBind:$websocketPort" , $ this -> loop ) ; new IoServer ( new HttpServer ( new WsServer ( new ServerProtocol ( new WebsocketApplication ( $ this -> sandstoneApplication ) ) ) ) , $ socket ) ; }
|
Init websocket server and push server if enabled .
|
47,403
|
private function initPushServer ( ) { $ pushBind = $ this -> sandstoneApplication [ 'sandstone.push.server' ] [ 'bind' ] ; $ pushPort = $ this -> sandstoneApplication [ 'sandstone.push.server' ] [ 'port' ] ; $ context = new Context ( $ this -> loop ) ; $ pushServer = $ context -> getSocket ( ZMQ :: SOCKET_PULL ) ; $ pushServer -> bind ( "tcp://$pushBind:$pushPort" ) ; $ pushServer -> on ( 'message' , function ( $ message ) { $ data = $ this -> sandstoneApplication [ 'sandstone.push.event_serializer' ] -> deserializeEvent ( $ message ) ; $ this -> logger -> info ( 'Push message event' , [ 'event' => $ data [ 'name' ] ] ) ; $ this -> sandstoneApplication [ 'dispatcher' ] -> dispatch ( $ data [ 'name' ] , $ data [ 'event' ] ) ; } ) ; }
|
Init push server and redispatch events from push server to application stack .
|
47,404
|
public function run ( ) { $ this -> logger -> info ( 'Initialization...' ) ; $ this -> initWebsocketServer ( ) ; if ( $ this -> sandstoneApplication -> isPushEnabled ( ) ) { $ this -> initPushServer ( ) ; } $ this -> sandstoneApplication -> boot ( ) ; $ this -> logger -> info ( 'Bind websocket server' , $ this -> sandstoneApplication [ 'sandstone.websocket.server' ] ) ; if ( $ this -> sandstoneApplication -> isPushEnabled ( ) ) { $ this -> logger -> info ( 'Bind push server' , $ this -> sandstoneApplication [ 'sandstone.push.server' ] ) ; } $ this -> loop -> run ( ) ; }
|
Run websocket server .
|
47,405
|
public function forwardEventsToPushServer ( array $ eventsNames ) { if ( ! $ this -> offsetExists ( 'sandstone.push' ) ) { throw new \ LogicException ( sprintf ( 'You must register a Push server service provider (%s) in order to use %s method.' , PushServiceProvider :: class , __METHOD__ ) ) ; } if ( $ this -> booted ) { $ this [ 'sandstone.push.event_forwarder' ] -> forwardAllEvents ( $ eventsNames ) ; } else { $ this -> events [ ] = $ eventsNames ; } return $ this ; }
|
Automatically forward rest API events to push server .
|
47,406
|
private function updateMessages ( array $ messages ) { $ this -> reset ( ) ; foreach ( $ messages as $ message ) { $ messageSize = strlen ( $ message ) ; $ this -> data [ 'messages_size' ] += $ messageSize ; $ this -> data [ 'messages_count' ] ++ ; $ this -> data [ 'messages' ] [ ] = array ( 'content' => $ message , 'size' => $ messageSize , 'decoded' => unserialize ( $ message ) , ) ; } }
|
Update data collector data with messages .
|
47,407
|
private function initServer ( ) { $ this -> setSessionStorage ( $ this -> sessionStorage ) -> setAccessTokenStorage ( $ this -> accessTokenStorage ) -> setClientStorage ( $ this -> clientStorage ) -> setScopeStorage ( $ this -> scopeStorage ) ; }
|
Init authorization server .
|
47,408
|
public function forwardEvent ( Event $ event , $ name ) { if ( ! $ this -> enabled ) { return ; } $ this -> pushServer -> send ( $ this -> eventSerializer -> serializeEvent ( $ name , $ event ) ) ; }
|
Forward an Event to Push Server .
|
47,409
|
public function forwardAllEvents ( $ eventNames ) { if ( ! $ this -> enabled ) { return $ this ; } if ( ! is_array ( $ eventNames ) ) { $ eventNames = array ( $ eventNames ) ; } foreach ( $ eventNames as $ eventName ) { $ this -> dispatcher -> addListener ( $ eventName , array ( $ this , 'forwardEvent' ) ) ; } return $ this ; }
|
Automatically forward RestApi events to push server .
|
47,410
|
public function format ( ) { $ format = $ this -> amount ( ) ; if ( $ this -> currency -> getSymbol ( ) === null ) { $ format .= ' ' . $ this -> currency -> getCode ( ) ; } elseif ( $ this -> currency -> getSymbolPlacement ( ) == 'before' ) { $ format = $ this -> currency -> getSymbol ( ) . $ format ; } else { $ format .= $ this -> currency -> getSymbol ( ) ; } return $ format ; }
|
Format amount to currency equivalent string .
|
47,411
|
public function amount ( ) { if ( $ this -> currency -> getCode ( ) == 'INR' ) { $ decimals = null ; $ amount = $ this -> amount ; if ( ( $ pos = strpos ( $ amount , "." ) ) !== false ) { $ decimals = substr ( round ( substr ( $ amount , $ pos ) , 2 ) , 1 ) ; $ amount = substr ( $ amount , 0 , $ pos ) ; } $ result = substr ( $ amount , - 3 ) ; $ amount = substr ( $ amount , 0 , - 3 ) ; while ( strlen ( $ amount ) > 0 ) { $ result = substr ( $ amount , - 2 ) . "," . $ result ; $ amount = substr ( $ amount , 0 , - 2 ) ; } return $ result . $ decimals ; } return number_format ( $ this -> amount , $ this -> currency -> getPrecision ( ) , $ this -> currency -> getDecimalSeparator ( ) , $ this -> currency -> getThousandSeparator ( ) ) ; }
|
Get amount formatted to currency .
|
47,412
|
public static function parse ( $ str , $ currency = 'USD' ) { $ currency = ( is_string ( $ currency ) ? new Currency ( $ currency ) : $ currency ) ; $ str = preg_replace ( "/&#?[a-z0-9]{2,8};/i" , '' , $ str ) ; $ str = preg_replace ( '/^[^0-9]*/' , '' , $ str ) ; if ( strlen ( $ currency -> getThousandSeparator ( ) ) ) { $ str = str_replace ( $ currency -> getThousandSeparator ( ) , '' , $ str ) ; } if ( strlen ( $ currency -> getDecimalSeparator ( ) ) ) { $ char = preg_quote ( $ currency -> getDecimalSeparator ( ) ) ; $ str = preg_replace ( '/[^' . $ char . '\d]/' , "" , $ str ) ; $ str = preg_replace ( '/' . $ char . '/' , "." , $ str ) ; } else { $ str = preg_replace ( '/[^\d]/' , "" , $ str ) ; } return new Money ( $ str , $ currency ) ; }
|
parses locale formatted money string to object of class Money
|
47,413
|
public static function gregorianToJulian ( int $ year , int $ month , int $ day ) { if ( $ month < 3 ) { $ year -= 1 ; $ month += 12 ; } $ a = floor ( $ year / 100.0 ) ; $ b = ( $ year === 1582 && ( $ month > 10 || ( $ month === 10 && $ day > 4 ) ) ? - 10 : ( $ year === 1582 && $ month === 10 ? 0 : ( $ year < 1583 ? 0 : 2 - $ a + floor ( $ a / 4.0 ) ) ) ) ; return floor ( 365.25 * ( $ year + 4716 ) ) + floor ( 30.6001 * ( $ month + 1 ) ) + $ day + $ b - 1524 ; }
|
The Julian Day for a given Gregorian date .
|
47,414
|
public static function hijriToJulian ( int $ year , int $ month , int $ day ) { return floor ( ( 11 * $ year + 3 ) / 30 ) + floor ( 354 * $ year ) + floor ( 30 * $ month ) - floor ( ( $ month - 1 ) / 2 ) + $ day + 1948440 - 386 ; }
|
The Julian Day for a given Hijri date .
|
47,415
|
public static function julianToGregorian ( float $ julianDay ) { $ b = 0 ; if ( $ julianDay > 2299160 ) { $ a = floor ( ( $ julianDay - 1867216.25 ) / 36524.25 ) ; $ b = 1 + $ a - floor ( $ a / 4.0 ) ; } $ bb = $ julianDay + $ b + 1524 ; $ cc = floor ( ( $ bb - 122.1 ) / 365.25 ) ; $ dd = floor ( 365.25 * $ cc ) ; $ ee = floor ( ( $ bb - $ dd ) / 30.6001 ) ; $ day = ( $ bb - $ dd ) - floor ( 30.6001 * $ ee ) ; $ month = $ ee - 1 ; if ( $ ee > 13 ) { $ cc += 1 ; $ month = $ ee - 13 ; } $ year = $ cc - 4716 ; return ( object ) [ 'year' => ( int ) $ year , 'month' => ( int ) $ month , 'day' => ( int ) $ day ] ; }
|
The Gregorian date Day for a given Julian
|
47,416
|
public static function julianToHijri ( float $ julianDay ) { $ y = 10631.0 / 30.0 ; $ epochAstro = 1948084 ; $ shift1 = 8.01 / 60.0 ; $ z = $ julianDay - $ epochAstro ; $ cyc = floor ( $ z / 10631.0 ) ; $ z = $ z - 10631 * $ cyc ; $ j = floor ( ( $ z - $ shift1 ) / $ y ) ; $ z = $ z - floor ( $ j * $ y + $ shift1 ) ; $ year = 30 * $ cyc + $ j ; $ month = ( int ) floor ( ( $ z + 28.5001 ) / 29.5 ) ; if ( $ month === 13 ) { $ month = 12 ; } $ day = $ z - floor ( 29.5001 * $ month - 29 ) ; return ( object ) [ 'year' => ( int ) $ year , 'month' => ( int ) $ month , 'day' => ( int ) $ day ] ; }
|
The Hijri date Day for a given Julian
|
47,417
|
public function format ( string $ format = null , int $ numbers = null ) { $ numbers = $ numbers === null ? static :: getDefaultNumbers ( ) : $ numbers ; $ format = $ format === null ? static :: getToStringFormat ( ) : $ format ; $ formatArray = str_split ( $ format ) ; $ dateString = '' ; foreach ( $ formatArray as $ key => $ value ) { if ( key_exists ( $ value , $ this -> values ) ) { $ dateString .= $ this -> values [ $ value ] ; continue ; } $ dateString .= $ value ; } if ( $ numbers === static :: INDIAN_NUMBERS ) { $ dateString = str_replace ( $ this -> arabicNumbers , $ this -> indianNumbers , $ dateString ) ; } return $ dateString ; }
|
get date string
|
47,418
|
protected function recalculate ( ) { $ adjusted = ( new Carbon ( $ this -> date ) ) -> addDays ( $ this -> adjustment ) ; $ julian = Converter :: gregorianToJulian ( $ adjusted -> year , $ adjusted -> month , $ adjusted -> day ) ; $ hijri = Converter :: julianToHijri ( $ julian ) ; $ this -> julianDay = $ julian ; $ this -> day = $ hijri -> day ; $ this -> month = $ hijri -> month ; $ this -> day = $ hijri -> day ; return $ this -> fillValuesArray ( ) ; }
|
recalculate hijri date
|
47,419
|
protected function fillValuesArray ( ) { $ this -> values [ 'j' ] = $ this -> day ; $ this -> values [ 'd' ] = str_pad ( $ this -> day , 2 , 0 , STR_PAD_LEFT ) ; $ this -> values [ 'D' ] = static :: $ translation -> getShortDays ( ) [ $ this -> date -> dayOfWeek ] ; $ this -> values [ 'l' ] = static :: $ translation -> getDays ( ) [ $ this -> date -> dayOfWeek ] ; $ this -> values [ 'n' ] = $ this -> month ; $ this -> values [ 'm' ] = str_pad ( $ this -> month , 2 , 0 , STR_PAD_LEFT ) ; $ this -> values [ 'M' ] = static :: $ translation -> getHijriMonths ( ) [ $ this -> month - 1 ] ; $ this -> values [ 'F' ] = static :: $ translation -> getHijriMonths ( ) [ $ this -> month - 1 ] ; $ this -> values [ 'o' ] = $ this -> year ; $ this -> values [ 'y' ] = substr ( $ this -> year , 0 , 2 ) ; $ this -> values [ 'Y' ] = str_pad ( $ this -> year , 4 , 0 , STR_PAD_LEFT ) ; $ this -> values [ 'a' ] = $ this -> date -> hour >= 12 ? static :: $ translation -> getPeriods ( ) [ 1 ] : static :: $ translation -> getPeriods ( ) [ 0 ] ; $ this -> values [ 'A' ] = strtoupper ( $ this -> date -> hour >= 12 ? static :: $ translation -> getPeriods ( ) [ 1 ] : static :: $ translation -> getPeriods ( ) [ 0 ] ) ; $ this -> fillCarbonValues ( ) ; return $ this ; }
|
Fill formats values
|
47,420
|
protected function fillCarbonValues ( ) { foreach ( $ this -> formats as $ format ) { $ this -> values [ $ format ] = $ this -> date -> format ( $ format ) ; } return $ this ; }
|
get format values from carbon instance
|
47,421
|
protected function comparision ( $ function , array $ arguments ) { $ args = [ ] ; foreach ( $ arguments as $ argument ) { if ( $ argument instanceof Date ) { $ args [ ] = $ argument -> gregorian ; } elseif ( $ argument instanceof Carbon ) { $ args [ ] = $ argument ; } else { throw new InvalidArgumentException ( sprintf ( "date must be instance of %s or %s" , Carbon :: class , static :: class ) ) ; } } return $ this -> date -> { $ function } ( ... $ args ) ; }
|
simulate Comparision function od Carbon class
|
47,422
|
public function publishMessage ( $ exchangeName , $ routingKey , $ message ) { $ informations = $ this -> query ( 'POST' , sprintf ( '/api/exchanges/%s/%s/publish' , $ this -> credentials [ 'vhost' ] , $ exchangeName ) , array ( 'properties' => array ( ) , 'routing_key' => $ routingKey , 'payload' => $ message , 'payload_encoding' => 'string' , ) ) ; $ decodedInformations = json_decode ( $ informations , true ) ; if ( isset ( $ decodedInformations [ 'routed' ] ) && true === $ decodedInformations [ 'routed' ] ) { return ; } throw new \ RuntimeException ( 'Unable to send that message into rabbit.' ) ; }
|
Publish a message into a specific queue related to the current vhost
|
47,423
|
public function prepare ( string $ statement , array $ bindings = [ ] ) : RawQueryBuilder { $ this -> statement = $ statement ; $ this -> bindings = $ bindings ; return $ this ; }
|
Prepares a raw statement .
|
47,424
|
public function get ( ) : array { $ pdoStatement = $ this -> provideStatement ( ) ; $ pdoStatement = $ this -> execute ( $ pdoStatement ) ; return $ pdoStatement -> fetchAll ( \ PDO :: FETCH_OBJ ) ; }
|
Executes raw statement and returns all matching rows as array of objects .
|
47,425
|
protected function bootstrapDispatcher ( ) : void { $ this -> routeDispatcher = FastRoute \ simpleDispatcher ( function ( RouteCollector $ collector ) { foreach ( $ this -> routes as $ routeName => $ route ) { $ collector -> addRoute ( $ route [ 'method' ] , $ route [ 'pattern' ] , $ route [ 'handler' ] ) ; } } ) ; }
|
Prepares the route dispatcher .
|
47,426
|
public function dispatch ( string $ httpMethod , string $ uri ) : array { $ urlPath = rawurldecode ( parse_url ( $ uri , PHP_URL_PATH ) ) ; $ routeInfo = $ this -> routeDispatcher -> dispatch ( $ httpMethod , $ urlPath ) ; return $ routeInfo ; }
|
Dispatches HTTP request and returns route information .
|
47,427
|
public function prepareRawStatement ( string $ statement , array $ bindings ) : void { $ this -> statement = $ statement ; if ( empty ( $ bindings ) ) { return ; } foreach ( $ bindings as $ key => $ value ) { $ this -> addBindingValue ( $ key , $ value ) ; } }
|
Prepares a raw statement and binds possible values .
|
47,428
|
public function found ( array $ data ) : Response { $ this -> response -> setBody ( json_encode ( [ 'data' => $ data ] ) ) ; return $ this -> response ; }
|
Respond with data .
|
47,429
|
public function makeInsert ( string $ connectionName = '' ) : InsertQueryBuilder { $ connection = $ this -> provideConnection ( $ connectionName ) ; $ statementBuilder = new InsertStatementBuilder ; return new InsertQueryBuilder ( $ connection , $ statementBuilder ) ; }
|
Creates a new InsertQueryBuilder instance .
|
47,430
|
public function makeSelect ( string $ connectionName = '' ) : SelectQueryBuilder { $ connection = $ this -> provideConnection ( $ connectionName ) ; $ statementBuilder = new SelectStatementBuilder ; return new SelectQueryBuilder ( $ connection , $ statementBuilder ) ; }
|
Creates a new SelectQueryBuilder instance .
|
47,431
|
public function makeRaw ( string $ connectionName = '' ) : RawQueryBuilder { $ connection = $ this -> provideConnection ( $ connectionName ) ; $ statementBuilder = new RawStatementBuider ; return new RawQueryBuilder ( $ connection , $ statementBuilder ) ; }
|
Creates a new raw RawQueryBuilderInstance .
|
47,432
|
public function addConnection ( string $ connectionName , \ PDO $ connection ) : void { $ this -> connections [ $ connectionName ] = $ connection ; }
|
Adds database connection to pool .
|
47,433
|
public function getConnection ( string $ connectionName ) : \ PDO { if ( ! isset ( $ this -> connections [ $ connectionName ] ) ) { throw new DatabaseException ( sprintf ( 'Connection (%s) not found in pool.' , $ connectionName ) ) ; } return $ this -> connections [ $ connectionName ] ; }
|
Retrieves a database connection .
|
47,434
|
public function addBindingValue ( string $ key , $ value ) : string { $ key = $ this -> removeTableFromKey ( $ key ) ; $ placeholder = ':' . $ key ; if ( ! isset ( $ this -> bindingValues [ $ key ] ) ) { $ this -> bindingValues [ $ key ] = $ value ; $ this -> bindingValueCounts [ $ key ] = 1 ; return $ placeholder ; } $ placeholder .= $ this -> bindingValueCounts [ $ key ] ; $ this -> bindingValueCounts [ $ key ] ++ ; $ this -> bindingValues [ $ placeholder ] = $ value ; return $ placeholder ; }
|
Adds a value which will be used to prepare the SQL statement . Returns the placeholder name to use in SQL statement .
|
47,435
|
protected function quoteName ( string $ name ) : string { $ name = str_replace ( '`' , '' , $ name ) ; if ( stripos ( $ name , ' AS ' ) === false ) { return $ this -> quoteSimpleName ( $ name ) ; } return $ this -> quoteAliasedName ( $ name ) ; }
|
Quotes a table or field name .
|
47,436
|
public function where ( string $ key , string $ operator , $ value ) : QueryBuilder { $ this -> addWhere ( $ key , $ operator , $ value , 'AND' ) ; return $ this ; }
|
Adds a where condition .
|
47,437
|
public function orWhere ( string $ key , string $ operator , $ value ) : QueryBuilder { $ this -> addWhere ( $ key , $ operator , $ value , 'OR' ) ; return $ this ; }
|
Adds a or where condition .
|
47,438
|
public function whereIn ( string $ key , array $ values ) : QueryBuilder { $ this -> addWhere ( $ key , 'IN' , $ values , 'AND' ) ; return $ this ; }
|
Adds a where in condition .
|
47,439
|
public function whereNotIn ( string $ key , array $ values ) : QueryBuilder { $ this -> addWhere ( $ key , 'NOT IN' , $ values , 'AND' ) ; return $ this ; }
|
Adds a where not in condition .
|
47,440
|
public function orWhereBetween ( string $ key , int $ min , int $ max ) : QueryBuilder { $ values = [ 'min' => $ min , 'max' => $ max ] ; $ this -> addWhere ( $ key , 'BETWEEN' , $ values , 'OR' ) ; return $ this ; }
|
Adds a or where between condition .
|
47,441
|
protected function addWhere ( string $ key , string $ operator , $ value , string $ concatenator = 'AND' ) : void { array_push ( $ this -> where , [ 'key' => $ key , 'operator' => $ operator , 'value' => $ value , 'concatenator' => $ concatenator , ] ) ; }
|
Adds where condition to pool .
|
47,442
|
protected function provideStatement ( ) : \ PDOStatement { $ sqlStatement = $ this -> buildStatement ( ) ; $ bindingValues = $ this -> statementBuilder -> getBindingValues ( ) ; return $ this -> prepareStatement ( $ sqlStatement , $ bindingValues ) ; }
|
Builds the SQL statement and converts it into an PDO prepared statement object .
|
47,443
|
protected function prepareStatement ( string $ sqlStatement , array $ bindingValues ) : \ PDOStatement { $ pdoStatement = $ this -> connection -> prepare ( $ sqlStatement ) ; if ( $ pdoStatement === false ) { $ this -> throwError ( $ this -> connection -> errorInfo ( ) ) ; } foreach ( $ bindingValues as $ key => $ value ) { if ( is_int ( $ value ) ) { $ pdoStatement -> bindValue ( $ key , $ value , \ PDO :: PARAM_INT ) ; } elseif ( is_bool ( $ value ) ) { $ pdoStatement -> bindValue ( $ key , $ value , \ PDO :: PARAM_BOOL ) ; } elseif ( is_null ( $ value ) ) { $ pdoStatement -> bindValue ( $ key , $ value , \ PDO :: PARAM_NULL ) ; } else { $ pdoStatement -> bindValue ( $ key , $ value , \ PDO :: PARAM_STR ) ; } } return $ pdoStatement ; }
|
Coverts an SQL statement into PDO statement object and binds all values .
|
47,444
|
public function execute ( \ PDOStatement $ pdoStatement ) : \ PDOStatement { $ result = $ pdoStatement -> execute ( ) ; if ( $ result === false ) { $ this -> throwError ( $ pdoStatement -> errorInfo ( ) ) ; } return $ pdoStatement ; }
|
Executes a PDO statement .
|
47,445
|
public function addFlags ( array $ flags ) : void { if ( ! empty ( $ flags [ 'distinct' ] ) ) { $ this -> statement .= ' DISTINCT' ; } if ( ! empty ( $ flags [ 'count' ] ) ) { $ this -> isCount = true ; } }
|
Adds possible flags to SQL statement .
|
47,446
|
public function addFrom ( string $ from ) : void { $ from = $ this -> quoteName ( $ from ) ; $ this -> statement .= ' FROM ' . $ from . PHP_EOL ; }
|
Adds from - table to SQL statement .
|
47,447
|
public function addJoin ( array $ joins ) : void { if ( empty ( $ joins ) ) { return ; } foreach ( $ joins as $ join ) { $ keyword = strtoupper ( $ join [ 'type' ] ) ; $ pattern = '%s JOIN %s ON %s %s %s' ; $ this -> statement .= sprintf ( $ pattern , $ keyword , $ this -> quoteName ( $ join [ 'table' ] ) , $ this -> quoteName ( $ join [ 'key' ] ) , $ join [ 'operator' ] , $ this -> quoteName ( $ join [ 'value' ] ) ) ; $ this -> statement .= PHP_EOL ; } }
|
Adds joins to SQL statement .
|
47,448
|
public function addLimitOffset ( int $ limit , int $ offset ) : void { if ( $ limit === 0 && $ offset === 0 ) { return ; } if ( $ limit === 0 && $ offset <> 0 ) { return ; } if ( $ offset === 0 ) { $ this -> statement .= ' LIMIT ' . $ limit ; } else { $ this -> statement .= sprintf ( ' LIMIT %d, %d' , $ offset , $ limit ) ; } $ this -> statement .= PHP_EOL ; }
|
Adds limit and offset to SQL statement .
|
47,449
|
public function addInto ( string $ table ) : void { $ table = $ this -> quoteName ( $ table ) ; $ this -> statement .= ' INTO ' . $ table ; $ this -> statement .= PHP_EOL ; }
|
Adds table name to insert statement .
|
47,450
|
public function addRows ( array $ rows ) : void { if ( empty ( $ rows ) ) { throw new DatabaseException ( 'Can not perform insert with empty rows.' ) ; } $ cols = array_keys ( reset ( $ rows ) ) ; foreach ( $ cols as $ i => $ col ) { $ cols [ $ i ] = $ this -> quoteName ( $ col ) ; } $ pattern = " (%s) VALUES" . PHP_EOL ; $ this -> statement .= sprintf ( $ pattern , implode ( ',' , $ cols ) ) ; $ rowValues = [ ] ; foreach ( $ rows as $ row ) { $ placeholders = $ this -> bindRowValues ( $ row ) ; array_push ( $ rowValues , sprintf ( '(%s)' , implode ( ',' , $ placeholders ) ) ) ; } $ this -> statement .= implode ( ',' , $ rowValues ) ; }
|
Adds column names and values to insert statement .
|
47,451
|
private function bindRowValues ( array $ row ) : array { $ placeholders = [ ] ; foreach ( $ row as $ key => $ value ) { $ placeholder = $ this -> addBindingValue ( $ key , $ value ) ; array_push ( $ placeholders , $ placeholder ) ; } return $ placeholders ; }
|
Binds values of single to statement and returns placeholders .
|
47,452
|
private function getMysqlTimeZoneOffset ( string $ timezone ) : string { $ tzUtc = new \ DateTimeZone ( 'UTC' ) ; $ tLocal = new \ DateTimeZone ( $ timezone ) ; $ timeUtc = new \ DateTime ( 'now' , $ tzUtc ) ; $ offsetSeconds = $ tLocal -> getOffset ( $ timeUtc ) ; $ offsetHours = $ offsetSeconds / 3600 ; $ offsetHours = ( $ offsetHours < 0 ) ? $ offsetHours * - 1 : $ offsetHours ; $ prefix = ( $ offsetSeconds < 0 ) ? '-' : '+' ; return $ prefix . sprintf ( '%02d:00' , $ offsetHours ) ; }
|
Calculates offset between given timezone and UTC in mysql compatible format .
|
47,453
|
public function setLogsDir ( string $ logsDir ) : void { if ( ! file_exists ( $ logsDir ) || ! is_writable ( $ logsDir ) ) { throw new LoggerException ( 'Logs path does not exist or is not writable.' ) ; } $ this -> logsDir = rtrim ( $ logsDir , '/' ) . '/' ; }
|
Sets path to directory containing log files .
|
47,454
|
public function log ( string $ level , string $ message , array $ context = [ ] ) : void { if ( $ this -> levelIsValid ( $ level ) === false ) { throw new \ InvalidArgumentException ( 'Invalid log-level provided.' ) ; } if ( $ this -> isHandling ( $ level ) === false ) { return ; } $ pathToLogfile = $ this -> openLogfile ( ) ; $ lineToLog = sprintf ( '[ %s ] %s: %s' , date ( 'Y-m-d H:i:s' ) , ucfirst ( $ level ) , $ message ) . PHP_EOL ; if ( ! empty ( $ context ) ) { $ lineToLog .= '--- Context ---' . PHP_EOL ; $ lineToLog .= print_r ( $ context , true ) . PHP_EOL ; } file_put_contents ( $ pathToLogfile , $ lineToLog , FILE_APPEND ) ; }
|
Logs given event to a file .
|
47,455
|
private function openLogfile ( ) : string { $ logfileName = $ this -> getLogfileName ( ) ; $ pathToLogfile = $ this -> logsDir . $ logfileName ; if ( ! file_exists ( $ pathToLogfile ) ) { $ openedMsg = sprintf ( '[ %s ] Logfile opened' , date ( 'Y-m-d H:i:s' ) ) . PHP_EOL ; file_put_contents ( $ pathToLogfile , $ openedMsg ) ; } return $ pathToLogfile ; }
|
Creates new logfile if not yet existing .
|
47,456
|
protected function buildStatement ( ) : string { $ this -> statementBuilder -> addTable ( $ this -> table ) ; $ this -> statementBuilder -> addCols ( $ this -> cols ) ; $ this -> statementBuilder -> addWhere ( $ this -> where ) ; return $ this -> statementBuilder -> getStatement ( ) ; }
|
Builds the UPDATE statement from all attributes previously set .
|
47,457
|
public function delete ( ) : int { $ pdoStatement = $ this -> provideStatement ( ) ; $ pdoStatement = $ this -> execute ( $ pdoStatement ) ; return $ pdoStatement -> rowCount ( ) ; }
|
Executes delete statement and returns affected rows .
|
47,458
|
protected function buildStatement ( ) : string { $ this -> statementBuilder -> addFrom ( $ this -> from ) ; $ this -> statementBuilder -> addWhere ( $ this -> where ) ; return $ this -> statementBuilder -> getStatement ( ) ; }
|
Builds the DELETE statement with all previously set attributes .
|
47,459
|
public function render ( string $ view , array $ templateVars = [ ] ) : string { return $ this -> renderer -> render ( $ view , $ templateVars ) ; }
|
Renders given view and returns HTML code .
|
47,460
|
public function found ( array $ data ) : Response { $ view = $ data [ 'view' ] ?? '' ; $ templateVars = $ data [ 'vars' ] ?? [ ] ; $ this -> response -> setBody ( $ this -> renderer -> render ( $ view , $ templateVars ) ) ; return $ this -> response ; }
|
Renders view defined in data array and passes it to http - responder .
|
47,461
|
public function notFound ( ) : Response { $ this -> response -> setStatus ( 404 ) ; $ this -> response -> setBody ( '<html><title>404 Not found</title>404 Not found</html>' ) ; return $ this -> response ; }
|
Respond with an not found message .
|
47,462
|
public function run ( ) : Response { try { $ response = $ this -> dispatch ( ) ; $ this -> send ( $ response ) ; } catch ( \ Error $ e ) { $ response = $ this -> exceptionHandler -> handleError ( $ e ) ; $ this -> send ( $ response ) ; } catch ( \ Exception $ e ) { $ response = $ this -> exceptionHandler -> handleException ( $ e ) ; $ this -> send ( $ response ) ; } return $ response ; }
|
Runs the application and passes all errors to exception handler .
|
47,463
|
protected function dispatch ( ) : Response { $ httpMethod = $ this -> request -> getRequestMethod ( ) ; $ uri = $ this -> request -> getRequestUri ( ) ; $ routeInfo = $ this -> router -> dispatch ( $ httpMethod , $ uri ) ; if ( ! isset ( $ routeInfo [ 0 ] ) ) { throw new BadRequestException ( 'Unable to parse request.' ) ; } switch ( $ routeInfo [ 0 ] ) { case Router :: NOT_FOUND : throw new NotFoundException ( 'Page not found.' ) ; case Router :: METHOD_NOT_ALLOWED : throw new MethodNotAllowedException ( 'Method not allowed' ) ; case Router :: FOUND : $ action = $ routeInfo [ 1 ] ; $ arguments = $ routeInfo [ 2 ] ; return $ this -> callAction ( $ action , $ arguments ) ; default : throw new BadRequestException ( 'Unable to parse request.' ) ; } }
|
Analyzes the request using the router and calls corresponding action . Throws HTTP exceptions in case request could not be assigned to an action .
|
47,464
|
public function callAction ( string $ handler , array $ arguments = [ ] ) : Response { if ( ! class_exists ( $ handler ) ) { throw new EndocoreException ( 'Action class not found.' ) ; } $ action = new $ handler ( $ this -> config , $ this -> logger , $ this -> request ) ; return $ action -> __invoke ( $ arguments ) ; }
|
Calls an action .
|
47,465
|
public function send ( Response $ response ) : void { $ httpHeader = sprintf ( 'HTTP/%s %d %s' , $ response -> getProtocolVersion ( ) , $ response -> getStatus ( ) , $ response -> getStatusMessage ( ) ) ; header ( $ httpHeader , true ) ; foreach ( $ response -> getHeaders ( ) as $ name => $ value ) { header ( sprintf ( '%s: %s' , $ name , $ value ) , true ) ; } echo $ response -> getBody ( ) ; }
|
Sends response to client .
|
47,466
|
public function setStatus ( int $ statusCode ) : void { if ( ! isset ( $ this -> statusMessages [ $ statusCode ] ) ) { throw new \ InvalidArgumentException ( 'Invalid HTTP status code.' ) ; } $ this -> statusCode = $ statusCode ; }
|
Sets HTTP status code .
|
47,467
|
public function render ( string $ view = '' , array $ variables = [ ] ) : string { if ( ! empty ( $ view ) ) { $ this -> setView ( $ view ) ; } $ this -> assign ( $ variables ) ; $ content = $ this -> renderView ( ) ; if ( empty ( $ this -> layout ) ) { return $ content ; } return $ this -> renderLayout ( $ content ) ; }
|
Renders given view and returns html code .
|
47,468
|
protected function renderLayout ( string $ content ) : string { $ content = str_replace ( '<!-- extends "' . $ this -> layout . '" , '' , $ content ) ; $ content = trim ( $ content ) ; $ this -> assign ( [ 'content' => $ content ] ) ; $ layoutFile = $ this -> pathLayouts . '/' . $ this -> layout . '.phtml' ; return $ this -> renderFile ( $ layoutFile ) ; }
|
Renders a layout file .
|
47,469
|
public function leftJoin ( string $ table , string $ key , string $ operator , string $ value ) : SelectQueryBuilder { $ this -> addJoin ( $ table , $ key , $ operator , $ value , 'left' ) ; return $ this ; }
|
Adds an left join .
|
47,470
|
public function orderBy ( string $ key , string $ direction = 'ASC' ) : SelectQueryBuilder { array_push ( $ this -> orderBy , [ 'key' => $ key , 'direction' => strtoupper ( $ direction ) , ] ) ; return $ this ; }
|
Adds an order by clause to query .
|
47,471
|
public function having ( string $ key , string $ operator , $ value ) : SelectQueryBuilder { $ this -> addHaving ( $ key , $ operator , $ value , 'AND' ) ; return $ this ; }
|
Adds a having clause .
|
47,472
|
public function orHaving ( string $ key , string $ operator , $ value ) : SelectQueryBuilder { $ this -> addHaving ( $ key , $ operator , $ value , 'OR' ) ; return $ this ; }
|
Adds a or having clause .
|
47,473
|
protected function addJoin ( string $ table , string $ key , string $ operator , string $ value , string $ type = 'inner' ) : void { array_push ( $ this -> join , [ 'table' => $ table , 'key' => $ key , 'operator' => $ operator , 'value' => $ value , 'type' => $ type , ] ) ; }
|
Adds new join to the pool .
|
47,474
|
protected function addHaving ( string $ key , string $ operator , $ value , string $ concatenator = 'AND' ) : void { array_push ( $ this -> having , [ 'key' => $ key , 'operator' => $ operator , 'value' => $ value , 'concatenator' => $ concatenator , ] ) ; }
|
Adds having clause to the pool .
|
47,475
|
public function first ( ) : ? \ stdClass { $ pdoStatement = $ this -> provideStatement ( ) ; $ pdoStatement = $ this -> execute ( $ pdoStatement ) ; $ row = $ pdoStatement -> fetch ( \ PDO :: FETCH_OBJ ) ; return ( ! empty ( $ row ) ) ? $ row : null ; }
|
Executes select query and returns first matching row .
|
47,476
|
public function pluck ( string $ column , string $ keyBy = '' ) : array { $ pdoStatement = $ this -> provideStatement ( ) ; $ pdoStatement = $ this -> execute ( $ pdoStatement ) ; $ rows = $ pdoStatement -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; if ( empty ( $ rows ) ) { return [ ] ; } if ( ! isset ( $ rows [ 0 ] [ $ column ] ) ) { throw new DatabaseException ( 'Column not found in result.' ) ; } if ( ! empty ( $ keyBy ) && ! isset ( $ rows [ 0 ] [ $ keyBy ] ) ) { throw new DatabaseException ( 'Column to use as key not found in result.' ) ; } $ indexKey = ( ! empty ( $ keyBy ) ) ? $ keyBy : null ; return array_column ( $ rows , $ column , $ indexKey ) ; }
|
Executes a select query and returns values of a single column . Optionally a custom key column can be specified .
|
47,477
|
public function count ( ) : int { $ this -> flags [ 'count' ] = true ; $ pdoStatement = $ this -> provideStatement ( ) ; $ pdoStatement = $ this -> execute ( $ pdoStatement ) ; return $ pdoStatement -> fetchColumn ( ) ; }
|
Executes select query and returns number of matching rows .
|
47,478
|
public function setMinLevel ( string $ level ) : void { if ( $ this -> levelIsValid ( $ level ) === false ) { throw new \ InvalidArgumentException ( 'Invalid log-level provided.' ) ; } $ this -> minLevel = $ this -> getLevelCode ( $ level ) ; }
|
Sets min . log - level .
|
47,479
|
public function isHandling ( string $ level ) : bool { $ levelCode = $ this -> getLevelCode ( $ level ) ; return $ levelCode >= $ this -> minLevel ; }
|
Checks if log level is handled by logger .
|
47,480
|
public function getLevelCode ( string $ level ) : int { if ( $ this -> levelIsValid ( $ level ) === false ) { throw new \ InvalidArgumentException ( 'Invalid log-level provided.' ) ; } return array_search ( $ level , $ this -> levels ) ; }
|
Returns numeric level code for given log - level .
|
47,481
|
public function row ( array $ data ) : int { array_push ( $ this -> rows , $ data ) ; $ pdoStatement = $ this -> provideStatement ( ) ; $ this -> execute ( $ pdoStatement ) ; return $ this -> getLastInsertId ( ) ; }
|
Inserts new row into database and returns insert - id .
|
47,482
|
public function rows ( array $ data ) : void { $ this -> rows = $ data ; $ pdoStatement = $ this -> provideStatement ( ) ; $ this -> execute ( $ pdoStatement ) ; }
|
Inserts multiple rows into database .
|
47,483
|
protected function addSimpleWhere ( string $ key , string $ operator , $ value ) : void { $ placeholder = $ this -> addBindingValue ( $ key , $ value ) ; $ key = $ this -> quoteName ( $ key ) ; $ this -> statement .= sprintf ( '%s %s %s' , $ key , $ operator , $ placeholder ) ; $ this -> statement .= PHP_EOL ; }
|
Adds a regular where clause to the statement .
|
47,484
|
protected function addWhereBetween ( string $ key , int $ min , int $ max ) : void { $ phMin = $ this -> addBindingValue ( $ key , $ min ) ; $ phMax = $ this -> addBindingValue ( $ key , $ max ) ; $ key = $ this -> quoteName ( $ key ) ; $ this -> statement .= sprintf ( '%s BETWEEN %s AND %s' , $ key , $ phMin , $ phMax ) ; $ this -> statement .= PHP_EOL ; }
|
Adds a where between clause to statement .
|
47,485
|
public function handleError ( \ Error $ e ) : Response { $ this -> logger -> error ( sprintf ( '%s in %s:%d' , $ e -> getMessage ( ) , $ e -> getFile ( ) , $ e -> getLine ( ) ) ) ; return $ this -> providePhpErrorResponse ( $ e ) ; }
|
Handles internal php errors .
|
47,486
|
public function handleException ( \ Exception $ e ) : Response { if ( $ e instanceof NotFoundException ) { $ this -> logger -> info ( '404 Not Found: ' . $ this -> request -> getRequestUri ( ) ) ; $ response = $ this -> provideNotFoundResponse ( ) ; } elseif ( $ e instanceof MethodNotAllowedException ) { $ this -> logger -> notice ( 'Method not allowed.' , [ 'request_uri' => $ this -> request -> getRequestUri ( ) , 'request_method' => $ this -> request -> getRequestMethod ( ) , ] ) ; $ response = $ this -> provideMethodNotAllowedResponse ( ) ; } elseif ( $ e instanceof BadRequestException ) { $ this -> logger -> notice ( 'Bad request.' , [ 'request_uri' => $ this -> request -> getRequestUri ( ) , 'request_method' => $ this -> request -> getRequestMethod ( ) , ] ) ; $ response = $ this -> provideBadRequestResponse ( ) ; } else { $ this -> logger -> error ( sprintf ( '%s in %s:%d' , $ e -> getMessage ( ) , $ e -> getFile ( ) , $ e -> getLine ( ) ) ) ; $ response = $ this -> provideGeneralErrorResponse ( $ e ) ; } return $ response ; }
|
Handles exceptions thrown by application .
|
47,487
|
protected function providePhpErrorResponse ( \ Error $ e ) : Response { $ responder = $ this -> provideResponder ( ) ; return $ responder -> error ( [ 'Message' => $ e -> getMessage ( ) , 'File' => $ e -> getFile ( ) , 'Line' => $ e -> getLine ( ) , ] ) ; }
|
Responds to client in case of a PHP error .
|
47,488
|
protected function provideResponder ( ) : ResponderInterface { $ acceptHeader = $ this -> request -> getServerParam ( 'HTTP_ACCEPT' , '' ) ; if ( strpos ( $ acceptHeader , 'application/json' ) !== false ) { return new JsonResponder ( $ this -> config ) ; } return new HtmlResponder ( $ this -> config ) ; }
|
Provides a responder according to requested content type .
|
47,489
|
private function parseIconDirEntries ( Icon $ icon , $ data , $ count ) { for ( $ i = 0 ; $ i < $ count ; ++ $ i ) { $ icoDirEntry = unpack ( 'Cwidth/Cheight/CcolorCount/Creserved/Splanes/SbitCount/LsizeInBytes/LfileOffset' , $ data ) ; $ icoDirEntry [ 'fileOffset' ] -= ( $ count * 16 ) + 6 ; if ( $ icoDirEntry [ 'colorCount' ] == 0 ) { $ icoDirEntry [ 'colorCount' ] = 256 ; } if ( $ icoDirEntry [ 'width' ] == 0 ) { $ icoDirEntry [ 'width' ] = 256 ; } if ( $ icoDirEntry [ 'height' ] == 0 ) { $ icoDirEntry [ 'height' ] = 256 ; } $ entry = new IconImage ( $ icoDirEntry ) ; $ icon [ ] = $ entry ; $ data = substr ( $ data , 16 ) ; } return $ data ; }
|
Parse the sequence of ICONDIRENTRY structures
|
47,490
|
private function parsePng ( IconImage $ entry , $ data ) { $ png = substr ( $ data , $ entry -> fileOffset , $ entry -> sizeInBytes ) ; $ entry -> setPngFile ( $ png ) ; }
|
Handle icon image which is PNG formatted
|
47,491
|
private function parseBmp ( IconImage $ entry , $ data ) { $ bitmapInfoHeader = unpack ( 'LSize/LWidth/LHeight/SPlanes/SBitCount/LCompression/LImageSize/' . 'LXpixelsPerM/LYpixelsPerM/LColorsUsed/LColorsImportant' , substr ( $ data , $ entry -> fileOffset , 40 ) ) ; $ entry -> setBitmapInfoHeader ( $ bitmapInfoHeader ) ; switch ( $ entry -> bitCount ) { case 32 : case 24 : $ this -> parseTrueColorImageData ( $ entry , $ data ) ; break ; case 8 : case 4 : case 1 : $ this -> parsePaletteImageData ( $ entry , $ data ) ; break ; } }
|
Handle icon image which is BMP formatted
|
47,492
|
private function parseTrueColorImageData ( IconImage $ entry , $ data ) { $ length = $ entry -> bmpHeaderWidth * $ entry -> bmpHeaderHeight * ( $ entry -> bitCount / 8 ) ; $ bmpData = substr ( $ data , $ entry -> fileOffset + $ entry -> bmpHeaderSize , $ length ) ; $ entry -> setBitmapData ( $ bmpData ) ; }
|
Parse an image which doesn t use a palette
|
47,493
|
private function parsePaletteImageData ( IconImage $ entry , $ data ) { $ pal = substr ( $ data , $ entry -> fileOffset + $ entry -> bmpHeaderSize , $ entry -> colorCount * 4 ) ; $ idx = 0 ; for ( $ j = 0 ; $ j < $ entry -> colorCount ; ++ $ j ) { $ entry -> addToBmpPalette ( ord ( $ pal [ $ idx + 2 ] ) , ord ( $ pal [ $ idx + 1 ] ) , ord ( $ pal [ $ idx ] ) , ord ( $ pal [ $ idx + 3 ] ) ) ; $ idx += 4 ; } $ length = $ entry -> bmpHeaderWidth * $ entry -> bmpHeaderHeight * ( 1 + $ entry -> bitCount ) / $ entry -> bitCount ; $ bmpData = substr ( $ data , $ entry -> fileOffset + $ entry -> bmpHeaderSize + $ entry -> colorCount * 4 , $ length ) ; $ entry -> setBitmapData ( $ bmpData ) ; }
|
Parse an image which uses a limited palette of colours
|
47,494
|
public function findBestForSize ( $ w , $ h ) { $ bestBitCount = 0 ; $ best = null ; foreach ( $ this -> images as $ image ) { if ( $ image -> width == $ w && $ image -> height == $ h && ( $ image -> bitCount > $ bestBitCount ) ) { $ bestBitCount = $ image -> bitCount ; $ best = $ image ; } } return $ best ; }
|
Returns best icon image with dimensions matching w h
|
47,495
|
public function findBest ( ) { $ bestBitCount = 0 ; $ bestWidth = 0 ; $ best = null ; foreach ( $ this -> images as $ image ) { if ( ( $ image -> width > $ bestWidth ) || ( ( $ image -> width == $ bestWidth ) && ( $ image -> bitCount > $ bestBitCount ) ) ) { $ bestWidth = $ image -> width ; $ bestBitCount = $ image -> bitCount ; $ best = $ image ; } } return $ best ; }
|
Finds the highest quality image in the icon
|
47,496
|
public function extractIcon ( $ dataOrFile , $ w , $ h , array $ opts = null ) { $ icon = $ this -> from ( $ dataOrFile ) ; $ image = $ icon -> findBestForSize ( $ w , $ h ) ; if ( ! $ image ) { $ image = $ icon -> findBest ( ) ; } if ( ! $ image ) { throw new \ DomainException ( 'Icon does not contain any images.' ) ; } return $ this -> renderImage ( $ image , $ w , $ h , $ opts ) ; }
|
This is a useful one - stop function for obtaining the best possible icon of a particular size from an . ico file
|
47,497
|
public function renderImage ( IconImage $ image , $ w = null , $ h = null , array $ opts = null ) { $ opts = is_array ( $ opts ) ? $ opts : [ ] ; $ opts [ 'w' ] = $ w ; $ opts [ 'h' ] = $ h ; return $ this -> renderer -> render ( $ image , $ opts ) ; }
|
Renders an IconImage at a desired width and height .
|
47,498
|
public function from ( $ dataOrFile ) { if ( $ this -> parser -> isSupportedBinaryString ( $ dataOrFile ) ) { return $ this -> parser -> parse ( $ dataOrFile ) ; } return $ this -> fromFile ( $ dataOrFile ) ; }
|
Parses a . ico file from a pathname or binary data string and return an Icon object .
|
47,499
|
public function fromFile ( $ file ) { try { $ data = file_get_contents ( $ file ) ; if ( $ data !== false ) { return $ this -> parser -> parse ( $ data ) ; } throw new \ InvalidArgumentException ( "file could not be loaded" ) ; } catch ( \ Exception $ e ) { throw new \ InvalidArgumentException ( "file could not be loaded (" . $ e -> getMessage ( ) . ")" ) ; } }
|
Loads icon from file .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.