idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
50,600
|
protected function calculateColLengths ( $ columns ) { $ idx = 0 ; $ border = $ this -> strlen ( $ this -> border ) ; $ fixed = ( count ( $ columns ) - 1 ) * $ border ; $ fluid = - 1 ; foreach ( $ columns as $ idx => $ col ) { if ( ( string ) intval ( $ col ) === ( string ) $ col ) { $ fixed += $ col ; continue ; } if ( substr ( $ col , - 1 ) == '%' ) { continue ; } if ( $ col == '*' ) { if ( $ fluid < 0 ) { $ fluid = $ idx ; continue ; } else { throw new Exception ( 'Only one fluid column allowed!' ) ; } } throw new Exception ( "unknown column format $col" ) ; } $ alloc = $ fixed ; $ remain = $ this -> max - $ alloc ; foreach ( $ columns as $ idx => $ col ) { if ( substr ( $ col , - 1 ) != '%' ) { continue ; } $ perc = floatval ( $ col ) ; $ real = ( int ) floor ( ( $ perc * $ remain ) / 100 ) ; $ columns [ $ idx ] = $ real ; $ alloc += $ real ; } $ remain = $ this -> max - $ alloc ; if ( $ remain < 0 ) { throw new Exception ( "Wanted column widths exceed available space" ) ; } if ( $ fluid < 0 ) { $ columns [ $ idx ] += ( $ remain ) ; } else { $ columns [ $ fluid ] = $ remain ; } return $ columns ; }
|
Takes an array with dynamic column width and calculates the correct width
|
50,601
|
public function format ( $ columns , $ texts , $ colors = array ( ) ) { $ columns = $ this -> calculateColLengths ( $ columns ) ; $ wrapped = array ( ) ; $ maxlen = 0 ; foreach ( $ columns as $ col => $ width ) { $ wrapped [ $ col ] = explode ( "\n" , $ this -> wordwrap ( $ texts [ $ col ] , $ width , "\n" , true ) ) ; $ len = count ( $ wrapped [ $ col ] ) ; if ( $ len > $ maxlen ) { $ maxlen = $ len ; } } $ last = count ( $ columns ) - 1 ; $ out = '' ; for ( $ i = 0 ; $ i < $ maxlen ; $ i ++ ) { foreach ( $ columns as $ col => $ width ) { if ( isset ( $ wrapped [ $ col ] [ $ i ] ) ) { $ val = $ wrapped [ $ col ] [ $ i ] ; } else { $ val = '' ; } $ chunk = $ this -> pad ( $ val , $ width ) ; if ( isset ( $ colors [ $ col ] ) && $ colors [ $ col ] ) { $ chunk = $ this -> colors -> wrap ( $ chunk , $ colors [ $ col ] ) ; } $ out .= $ chunk ; if ( $ col != $ last ) { $ out .= $ this -> border ; } } $ out .= "\n" ; } return $ out ; }
|
Displays text in multiple word wrapped columns
|
50,602
|
protected function pad ( $ string , $ len ) { $ strlen = $ this -> strlen ( $ string ) ; if ( $ strlen > $ len ) return $ string ; $ pad = $ len - $ strlen ; return $ string . str_pad ( '' , $ pad , ' ' ) ; }
|
Pad the given string to the correct length
|
50,603
|
protected function strlen ( $ string ) { $ string = preg_replace ( "/\33\\[\\d+(;\\d+)?m/" , '' , $ string ) ; if ( function_exists ( 'mb_strlen' ) ) { return mb_strlen ( $ string , 'utf-8' ) ; } return strlen ( $ string ) ; }
|
Measures char length in UTF - 8 when possible
|
50,604
|
public function run ( ) { if ( 'cli' != php_sapi_name ( ) ) { throw new Exception ( 'This has to be run from the command line' ) ; } $ this -> setup ( $ this -> options ) ; $ this -> registerDefaultOptions ( ) ; $ this -> parseOptions ( ) ; $ this -> handleDefaultOptions ( ) ; $ this -> setupLogging ( ) ; $ this -> checkArgments ( ) ; $ this -> execute ( ) ; exit ( 0 ) ; }
|
Execute the CLI program
|
50,605
|
protected function registerDefaultOptions ( ) { $ this -> options -> registerOption ( 'help' , 'Display this help screen and exit immediately.' , 'h' ) ; $ this -> options -> registerOption ( 'no-colors' , 'Do not use any colors in output. Useful when piping output to other tools or files.' ) ; $ this -> options -> registerOption ( 'loglevel' , 'Minimum level of messages to display. Default is ' . $ this -> colors -> wrap ( $ this -> logdefault , Colors :: C_CYAN ) . '. ' . 'Valid levels are: debug, info, notice, success, warning, error, critical, alert, emergency.' , null , 'level' ) ; }
|
Add the default help color and log options
|
50,606
|
protected function handleDefaultOptions ( ) { if ( $ this -> options -> getOpt ( 'no-colors' ) ) { $ this -> colors -> disable ( ) ; } if ( $ this -> options -> getOpt ( 'help' ) ) { echo $ this -> options -> help ( ) ; exit ( 0 ) ; } }
|
Handle the default options
|
50,607
|
protected function setupLogging ( ) { $ level = $ this -> options -> getOpt ( 'loglevel' , $ this -> logdefault ) ; if ( ! isset ( $ this -> loglevel [ $ level ] ) ) $ this -> fatal ( 'Unknown log level' ) ; foreach ( array_keys ( $ this -> loglevel ) as $ l ) { if ( $ l == $ level ) break ; unset ( $ this -> loglevel [ $ l ] ) ; } }
|
Handle the logging options
|
50,608
|
public function fatal ( $ error , array $ context = array ( ) ) { $ code = 0 ; if ( is_object ( $ error ) && is_a ( $ error , 'Exception' ) ) { $ this -> debug ( get_class ( $ error ) . ' caught in ' . $ error -> getFile ( ) . ':' . $ error -> getLine ( ) ) ; $ this -> debug ( $ error -> getTraceAsString ( ) ) ; $ code = $ error -> getCode ( ) ; $ error = $ error -> getMessage ( ) ; } if ( ! $ code ) { $ code = Exception :: E_ANY ; } $ this -> critical ( $ error , $ context ) ; exit ( $ code ) ; }
|
Exits the program on a fatal error
|
50,609
|
public function ptln ( $ line , $ color , $ channel = STDOUT ) { $ this -> set ( $ color ) ; fwrite ( $ channel , rtrim ( $ line ) . "\n" ) ; $ this -> reset ( ) ; }
|
Convenience function to print a line in a given color
|
50,610
|
public function getColorCode ( $ color ) { if ( ! $ this -> enabled ) { return '' ; } if ( ! isset ( $ this -> colors [ $ color ] ) ) { throw new Exception ( "No such color $color" ) ; } return $ this -> colors [ $ color ] ; }
|
Gets the appropriate terminal code for the given color
|
50,611
|
public function registerArgument ( $ arg , $ help , $ required = true , $ command = '' ) { if ( ! isset ( $ this -> setup [ $ command ] ) ) { throw new Exception ( "Command $command not registered" ) ; } $ this -> setup [ $ command ] [ 'args' ] [ ] = array ( 'name' => $ arg , 'help' => $ help , 'required' => $ required ) ; }
|
Register the names of arguments for help generation and number checking
|
50,612
|
public function registerCommand ( $ command , $ help ) { if ( isset ( $ this -> setup [ $ command ] ) ) { throw new Exception ( "Command $command already registered" ) ; } $ this -> setup [ $ command ] = array ( 'opts' => array ( ) , 'args' => array ( ) , 'help' => $ help ) ; }
|
This registers a sub command
|
50,613
|
public function registerOption ( $ long , $ help , $ short = null , $ needsarg = false , $ command = '' ) { if ( ! isset ( $ this -> setup [ $ command ] ) ) { throw new Exception ( "Command $command not registered" ) ; } $ this -> setup [ $ command ] [ 'opts' ] [ $ long ] = array ( 'needsarg' => $ needsarg , 'help' => $ help , 'short' => $ short ) ; if ( $ short ) { if ( strlen ( $ short ) > 1 ) { throw new Exception ( "Short options should be exactly one ASCII character" ) ; } $ this -> setup [ $ command ] [ 'short' ] [ $ short ] = $ long ; } }
|
Register an option for option parsing and help generation
|
50,614
|
public function checkArguments ( ) { $ argc = count ( $ this -> args ) ; $ req = 0 ; foreach ( $ this -> setup [ $ this -> command ] [ 'args' ] as $ arg ) { if ( ! $ arg [ 'required' ] ) { break ; } $ req ++ ; } if ( $ req > $ argc ) { throw new Exception ( "Not enough arguments" , Exception :: E_OPT_ARG_REQUIRED ) ; } }
|
Checks the actual number of arguments against the required number
|
50,615
|
public function getOpt ( $ option = null , $ default = false ) { if ( $ option === null ) { return $ this -> options ; } if ( isset ( $ this -> options [ $ option ] ) ) { return $ this -> options [ $ option ] ; } return $ default ; }
|
Get the value of the given option
|
50,616
|
protected function main ( Options $ options ) { $ this -> debug ( 'This is a debug message' ) ; $ this -> info ( 'This is a info message' ) ; $ this -> notice ( 'This is a notice message' ) ; $ this -> success ( 'This is a success message' ) ; $ this -> warning ( 'This is a warning message' ) ; $ this -> error ( 'This is a error message' ) ; $ this -> critical ( 'This is a critical message' ) ; $ this -> alert ( 'This is a alert message' ) ; $ this -> emergency ( 'This is a emergency message' ) ; throw new \ Exception ( 'Exception will be caught, too' ) ; }
|
implement your code
|
50,617
|
protected function response ( $ respBody , $ respHeaders , $ respCode ) { if ( $ respCode > 400 ) { $ type = $ respCode > 500 ? 'Internal error' : 'Request error' ; throw new GeneralException ( 'The request to NeverBounce was unsuccessful ' . 'Try the request again, if this error persists' . ' let us know at support@neverbounce.com.' . "\n\n($type [status $respCode: $respBody])" ) ; } $ contentType = $ respHeaders [ 'content-type' ] ; if ( $ this -> acceptedType !== $ contentType ) { throw new GeneralException ( 'The request to NeverBounce was unsuccessful ' . "Expected a response type of '{$this->acceptedType}' but " . "received a response type of '{$contentType}. " . 'Try the request again, if this error persists' . ' let us know at support@neverbounce.com.' . "\n\n(Unexpected Type [status $respCode: $respBody])" ) ; } if ( $ this -> acceptedType === 'application/json' ) { return $ this -> jsonResponse ( $ respBody , $ respCode ) ; } return $ this -> decodedResponse = $ respBody ; }
|
Parses the response string and handles any errors
|
50,618
|
protected function getIndex ( ) { if ( ! $ this -> index ) { $ path = rtrim ( Config :: get ( 'search.connections.zend.path' ) , '/' ) . '/' . $ this -> name ; try { $ this -> index = \ ZendSearch \ Lucene \ Lucene :: open ( $ path ) ; } catch ( \ ZendSearch \ Exception \ ExceptionInterface $ e ) { $ this -> index = \ ZendSearch \ Lucene \ Lucene :: create ( $ path ) ; } catch ( \ ErrorException $ e ) { if ( ! file_exists ( $ path ) ) { throw new \ Exception ( "'path' directory does not exist for the 'zend' search driver: '" . rtrim ( Config :: get ( 'search.connections.zend.path' ) , '/' ) . "'" ) ; } throw $ e ; } \ ZendSearch \ Lucene \ Analysis \ Analyzer \ Analyzer :: setDefault ( new \ ZendSearch \ Lucene \ Analysis \ Analyzer \ Common \ Utf8Num \ CaseInsensitive ( ) ) ; } return $ this -> index ; }
|
Get the ZendSearch lucene index instance associated with this instance .
|
50,619
|
protected function escape ( $ str ) { $ str = str_replace ( '\\' , '\\\\' , $ str ) ; $ str = str_replace ( '+' , '\+' , $ str ) ; $ str = str_replace ( '-' , '\-' , $ str ) ; $ str = str_replace ( '&&' , '\&&' , $ str ) ; $ str = str_replace ( '||' , '\||' , $ str ) ; $ str = str_replace ( '!' , '\!' , $ str ) ; $ str = str_replace ( '(' , '\(' , $ str ) ; $ str = str_replace ( ')' , '\)' , $ str ) ; $ str = str_replace ( '{' , '\{' , $ str ) ; $ str = str_replace ( '}' , '\}' , $ str ) ; $ str = str_replace ( '[' , '\[' , $ str ) ; $ str = str_replace ( ']' , '\]' , $ str ) ; $ str = str_replace ( '^' , '\^' , $ str ) ; $ str = str_replace ( '"' , '\"' , $ str ) ; $ str = str_replace ( '~' , '\~' , $ str ) ; $ str = str_replace ( '*' , '\*' , $ str ) ; $ str = str_replace ( '?' , '\?' , $ str ) ; $ str = str_replace ( ':' , '\:' , $ str ) ; $ str = str_ireplace ( array ( ' and ' , ' or ' , ' not ' , ' to ' ) , '' , $ str ) ; return $ str ; }
|
Helper method to escape all ZendSearch special characters .
|
50,620
|
public function where ( $ field , $ value ) { $ this -> query = $ this -> index -> addConditionToQuery ( $ this -> query , array ( 'field' => $ field , 'value' => $ value , 'required' => true , 'filter' => true , ) ) ; return $ this ; }
|
Add a basic where clause to the query . A where clause filter attemtps to match the value you specify as an entire phrase . It does not guarantee an exact match of the entire field value .
|
50,621
|
public function whereLocation ( $ lat , $ long , $ distance_in_meters = 10000 ) { $ this -> query = $ this -> index -> addConditionToQuery ( $ this -> query , array ( 'lat' => $ lat , 'long' => $ long , 'distance' => $ distance_in_meters , ) ) ; return $ this ; }
|
Add a geo distance where clause to the query .
|
50,622
|
public function search ( $ field , $ value , array $ options = array ( ) ) { $ this -> query = $ this -> index -> addConditionToQuery ( $ this -> query , array ( 'field' => $ field , 'value' => $ value , 'required' => array_get ( $ options , 'required' , true ) , 'prohibited' => array_get ( $ options , 'prohibited' , false ) , 'phrase' => array_get ( $ options , 'phrase' , false ) , 'fuzzy' => array_get ( $ options , 'fuzzy' , null ) , ) ) ; return $ this ; }
|
Add a basic search clause to the query .
|
50,623
|
public function addCallback ( $ callback , $ driver = null ) { if ( ! empty ( $ driver ) ) { if ( is_array ( $ driver ) ) { if ( ! in_array ( $ this -> index -> driver , $ driver ) ) { return $ this ; } } else if ( $ driver != $ this -> index -> driver ) { return $ this ; } } $ this -> callbacks [ ] = $ callback ; return $ this ; }
|
Add a custom callback fn to be called just before the query is executed .
|
50,624
|
public function delete ( ) { $ this -> columns = null ; $ results = $ this -> get ( ) ; foreach ( $ results as $ result ) { $ this -> index -> delete ( array_get ( $ result , 'id' ) ) ; } }
|
Execute the current query and perform delete operations on each document found .
|
50,625
|
public function paginate ( $ num = 15 ) { $ page = ( int ) Input :: get ( 'page' , 1 ) ; $ this -> limit ( $ num , ( $ page - 1 ) * $ num ) ; return new LengthAwarePaginator ( $ this -> get ( ) , $ this -> count ( ) , $ num , $ page ) ; }
|
Execute the current query and return a paginator for the results .
|
50,626
|
public function get ( ) { $ options = array ( ) ; if ( $ this -> columns ) { $ options [ 'columns' ] = $ this -> columns ; } if ( $ this -> limit ) { $ options [ 'limit' ] = $ this -> limit ; $ options [ 'offset' ] = $ this -> offset ; } $ this -> executeCallbacks ( ) ; $ results = $ this -> index -> runQuery ( $ this -> query , $ options ) ; if ( $ this -> columns && ! in_array ( '*' , $ this -> columns ) ) { $ new_results = array ( ) ; foreach ( $ results as $ result ) { $ new_result = array ( ) ; foreach ( $ this -> columns as $ field ) { if ( array_key_exists ( $ field , $ result ) ) { $ new_result [ $ field ] = $ result [ $ field ] ; } } $ new_results [ ] = $ new_result ; } $ results = $ new_results ; } return $ results ; }
|
Execute the current query and return the results .
|
50,627
|
protected function executeCallbacks ( ) { if ( $ this -> callbacks_executed ) { return ; } $ this -> callbacks_executed = true ; foreach ( $ this -> callbacks as $ callback ) { if ( $ q = call_user_func ( $ callback , $ this -> query ) ) { $ this -> query = $ q ; } } }
|
Execute any callback functions . Only execute once .
|
50,628
|
public static function factory ( $ index , $ driver = null ) { if ( null === $ driver ) { $ driver = Config :: get ( 'search.default' , 'zend' ) ; } switch ( $ driver ) { case 'algolia' : return new Index \ Algolia ( $ index , 'algolia' ) ; case 'elasticsearch' : return new Index \ Elasticsearch ( $ index , 'elasticsearch' ) ; case 'zend' : default : return new Index \ Zend ( $ index , 'zend' ) ; } }
|
Return an instance of the correct index driver for the given index name .
|
50,629
|
public function whereLocation ( $ lat , $ long , $ distance_in_meters = 10000 ) { return $ this -> query ( ) -> whereLocation ( $ lat , $ long , $ distance_in_meters ) ; }
|
Initialize and return a new Query instance on this index with the requested geo distance where clause .
|
50,630
|
public function search ( $ field , $ value , array $ options = array ( ) ) { return $ this -> query ( ) -> search ( $ field , $ value , $ options ) ; }
|
Initialize and return a new Query instance on this index with the requested search condition .
|
50,631
|
public function createIndex ( array $ fields = array ( ) ) { $ properties = array ( '_geoloc' => array ( 'type' => 'geo_point' ) ) ; foreach ( $ fields as $ field ) { $ properties [ $ field ] = array ( 'type' => 'string' ) ; } $ body [ 'mappings' ] [ static :: $ default_type ] [ 'properties' ] = $ properties ; $ this -> getClient ( ) -> indices ( ) -> create ( array ( 'index' => $ this -> name , 'body' => $ body , ) ) ; return true ; }
|
Create the index .
|
50,632
|
public function index ( $ index = null ) { if ( null === $ index ) { $ index = Config :: get ( 'search.default_index' , 'default' ) ; } if ( ! isset ( $ this -> indexes [ $ index ] ) ) { $ this -> indexes [ $ index ] = Index :: factory ( $ index , $ this -> driver ) ; } return $ this -> indexes [ $ index ] ; }
|
Return the instance associated with the requested index name . Will create one if needed .
|
50,633
|
protected function getClient ( ) { if ( ! static :: $ client ) { static :: $ client = new \ AlgoliaSearch \ Client ( Config :: get ( 'search.connections.algolia.config.application_id' ) , Config :: get ( 'search.connections.algolia.config.admin_api_key' ) ) ; } return static :: $ client ; }
|
Get the Algolia client associated with this instance .
|
50,634
|
protected function getIndex ( ) { if ( ! $ this -> index ) { $ this -> index = $ this -> getClient ( ) -> initIndex ( $ this -> name ) ; } return $ this -> index ; }
|
Get the Algolia index instance associated with this instance .
|
50,635
|
public function createRequest ( string $ method , string $ uri , array $ body = [ ] ) : RequestInterface { $ request = $ this -> requestFactory -> createRequest ( $ method , $ uri ) -> withHeader ( 'Content-Type' , 'application/json' ) -> withHeader ( 'Authorization' , 'Token ' . $ this -> token ) -> withHeader ( 'X-Secret' , $ this -> secret ) ; if ( ! empty ( $ body ) ) { $ request = $ request -> withBody ( $ this -> streamFactory -> createStream ( json_encode ( $ body , JSON_UNESCAPED_UNICODE ) ) ) ; } return $ request ; }
|
Creates request with necessary headers & encoded body .
|
50,636
|
public function validateElement ( $ element ) { if ( ! is_object ( $ element ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid element of type %s passed to %s, expected: %s' , gettype ( $ element ) , get_class ( $ this ) , $ this -> getClass ( ) ) ) ; } if ( ! is_a ( $ element , $ this -> getClass ( ) ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid element (instance of %s) passed to %s, expected: %s' , get_class ( $ element ) , get_class ( $ this ) , $ this -> getClass ( ) ) ) ; } }
|
Checks if element collection constructed with has correct class .
|
50,637
|
public function getVersion ( ) { $ request = $ this -> apiRequestFactory -> createRequest ( 'GET' , $ this -> getBaseUri ( ) . '/version' ) ; $ response = $ this -> httpClient -> sendRequest ( $ request ) ; return $ this -> getResult ( $ response , Version :: class ) ; }
|
Gets directories versions .
|
50,638
|
public function getStatus ( ) { $ request = $ this -> apiRequestFactory -> createRequest ( 'GET' , $ this -> getBaseUri ( ) . '/status/CLEAN' ) ; $ response = $ this -> httpClient -> sendRequest ( $ request ) ; return $ response -> getStatusCode ( ) === 200 ; }
|
Gets clean service status . If service is OK returns true otherwise - false .
|
50,639
|
protected function bootInConsole ( ) { if ( $ this -> app instanceof LaravelApplication && $ this -> app -> runningInConsole ( ) ) { $ this -> publishes ( [ __DIR__ . '/config/saml.php' => config_path ( 'saml.php' ) , ] , 'saml_config' ) ; if ( ! file_exists ( storage_path ( ) . "/saml/idp" ) ) { mkdir ( storage_path ( ) . "/saml/idp" , 0755 , true ) ; } } $ this -> registerCommands ( ) ; }
|
Perform various commands only if within console
|
50,640
|
protected function getSamlFile ( $ configPath , $ url ) { if ( $ url ) { return Storage :: disk ( 'saml' ) -> url ( $ configPath ) ; } return Storage :: disk ( 'saml' ) -> get ( $ configPath ) ; }
|
Get either the url or the content of a given file .
|
50,641
|
public function handleSamlLoginRequest ( $ request ) { if ( ! empty ( $ request -> input ( 'RelayState' ) ) ) { session ( ) -> put ( 'RelayState' , $ request -> input ( 'RelayState' ) ) ; } if ( isset ( $ request -> SAMLRequest ) ) { $ SAML = $ request -> SAMLRequest ; $ decoded = base64_decode ( $ SAML ) ; $ xml = gzinflate ( $ decoded ) ; $ deserializationContext = new \ LightSaml \ Model \ Context \ DeserializationContext ( ) ; $ deserializationContext -> getDocument ( ) -> loadXML ( $ xml ) ; $ authnRequest = new \ LightSaml \ Model \ Protocol \ AuthnRequest ( ) ; $ authnRequest -> deserialize ( $ deserializationContext -> getDocument ( ) -> firstChild , $ deserializationContext ) ; $ this -> buildSamlResponse ( $ authnRequest , $ request ) ; } }
|
Handle an http request as saml authentication request . Note that the method should only be called in case a saml request is also included .
|
50,642
|
protected function getNameId ( $ user , $ authnRequest ) { $ nameIdAttribute = config ( 'saml.sp.' . base64_encode ( $ authnRequest -> getAssertionConsumerServiceURL ( ) ) . '.nameID' , 'email' ) ; return $ user -> { $ nameIdAttribute } ; }
|
Get the NameID attribute to be used .
|
50,643
|
public function parseFile ( $ file ) { $ str = @ \ file_get_contents ( $ file ) ; if ( false === $ str ) { throw new Exception ( 'Can\'t read file.' ) ; } return $ this -> parse ( $ str ) ; }
|
Parse m3u file
|
50,644
|
public function parse ( $ str ) { $ this -> removeBom ( $ str ) ; $ data = $ this -> createM3uData ( ) ; $ lines = \ explode ( "\n" , $ str ) ; for ( $ i = 0 , $ l = \ count ( $ lines ) ; $ i < $ l ; ++ $ i ) { $ lineStr = \ trim ( $ lines [ $ i ] ) ; if ( '' === $ lineStr || $ this -> isComment ( $ lineStr ) ) { continue ; } if ( $ this -> isExtM3u ( $ lineStr ) ) { $ tmp = \ trim ( \ substr ( $ lineStr , 7 ) ) ; if ( $ tmp ) { $ data -> initAttributes ( $ tmp ) ; } continue ; } $ data -> append ( $ this -> parseLine ( $ i , $ lines ) ) ; } return $ data ; }
|
Parse m3u string
|
50,645
|
protected function parseLine ( & $ lineNumber , array $ linesStr ) { $ entry = $ this -> createM3uEntry ( ) ; for ( $ l = \ count ( $ linesStr ) ; $ lineNumber < $ l ; ++ $ lineNumber ) { $ nextLineStr = $ linesStr [ $ lineNumber ] ; $ nextLineStr = \ trim ( $ nextLineStr ) ; if ( '' === $ nextLineStr || $ this -> isComment ( $ nextLineStr ) || $ this -> isExtM3u ( $ nextLineStr ) ) { continue ; } $ matched = false ; foreach ( $ this -> getTags ( ) as $ availableTag ) { if ( $ availableTag :: isMatch ( $ nextLineStr ) ) { $ matched = true ; $ entry -> addExtTag ( new $ availableTag ( $ nextLineStr ) ) ; break ; } } if ( ! $ matched ) { $ entry -> setPath ( $ nextLineStr ) ; break ; } } return $ entry ; }
|
Parse one line
|
50,646
|
public function renderIntoSetCookieHeader ( ResponseInterface $ response ) : ResponseInterface { $ response = $ response -> withoutHeader ( static :: SET_COOKIE_HEADER ) ; foreach ( $ this -> setCookies as $ setCookie ) { $ response = $ response -> withAddedHeader ( static :: SET_COOKIE_HEADER , ( string ) $ setCookie ) ; } return $ response ; }
|
Render SetCookies into a Response .
|
50,647
|
public static function fromSetCookieStrings ( array $ setCookieStrings ) : self { return new static ( array_map ( function ( string $ setCookieString ) : SetCookie { return SetCookie :: fromSetCookieString ( $ setCookieString ) ; } , $ setCookieStrings ) ) ; }
|
Create SetCookies from a collection of SetCookie header value strings .
|
50,648
|
public static function fromResponse ( ResponseInterface $ response ) : SetCookies { return new static ( array_map ( function ( string $ setCookieString ) : SetCookie { return SetCookie :: fromSetCookieString ( $ setCookieString ) ; } , $ response -> getHeader ( static :: SET_COOKIE_HEADER ) ) ) ; }
|
Create SetCookies from a Response .
|
50,649
|
public static function listFromCookieString ( string $ string ) : array { $ cookies = StringUtil :: splitOnAttributeDelimiter ( $ string ) ; return array_map ( function ( $ cookiePair ) { return static :: oneFromCookiePair ( $ cookiePair ) ; } , $ cookies ) ; }
|
Create a list of Cookies from a Cookie header value string .
|
50,650
|
public function renderIntoCookieHeader ( RequestInterface $ request ) : RequestInterface { $ cookieString = implode ( '; ' , $ this -> cookies ) ; $ request = $ request -> withHeader ( static :: COOKIE_HEADER , $ cookieString ) ; return $ request ; }
|
Render Cookies into a Request .
|
50,651
|
public function parseString ( $ html ) { $ html = preg_replace ( '@<sup id="fnref:([^"]+)">\s*<a href="#fn:\1" rel="footnote">\s*\d+\s*</a>\s*</sup>@Us' , '<fnref target="$1" />' , $ html ) ; $ html = preg_replace_callback ( '#<div class="footnotes">\s*<hr />\s*<ol>\s*(.+)\s*</ol>\s*</div>#Us' , [ & $ this , '_makeFootnotes' ] , $ html ) ; return parent :: parseString ( $ html ) ; }
|
parse a HTML string clean up footnotes prior
|
50,652
|
protected function _makeFootnotes ( $ matches ) { $ fns = preg_replace ( '@\s*( \s*)?<a href="#fnref:[^"]+" rev="footnote"[^>]*>↩</a>\s*@s' , '' , $ matches [ 1 ] ) ; $ fns = preg_replace ( '@<p>\s*</p>@s' , '' , $ fns ) ; $ fns = str_replace ( '<li id="fn:' , '<fn name="' , $ fns ) ; $ fns = '<footnotes>' . $ fns . '</footnotes>' ; return preg_replace ( '#</li>\s*(?=(?:<fn|</footnotes>))#s' , '</fn>$1' , $ fns ) ; }
|
replace HTML representation of footnotes with something more easily parsable
|
50,653
|
private function applyBaseUrl ( string $ url ) : string { if ( $ this -> baseUrl === null ) { return $ url ; } if ( substr ( $ url , 0 , 7 ) === "http://" ) { return $ url ; } if ( substr ( $ url , 0 , 8 ) === "https://" ) { return $ url ; } $ baseUrl = $ this -> baseUrl ; if ( substr ( $ url , 0 , 1 ) === "/" ) { $ path = parse_url ( $ baseUrl , \ PHP_URL_PATH ) ; if ( $ path !== null ) { $ baseUrl = substr ( $ baseUrl , 0 , strlen ( $ path ) * - 1 ) ; } } return "{$baseUrl}/" . ltrim ( $ url , "/" ) ; }
|
Ensure the passed url uses the current base .
|
50,654
|
public function screenshot ( string $ filename ) : Dusk { if ( substr ( $ filename , 0 , 1 ) !== "/" ) { $ filename = "/tmp/{$filename}" ; } if ( substr ( $ filename , - 4 ) !== ".png" ) { $ filename .= ".png" ; } $ this -> getDriver ( ) -> takeScreenshot ( $ filename ) ; return $ this ; }
|
Take a screenshot and store it on disk .
|
50,655
|
protected function isMarkdownable ( ) { if ( ! isset ( $ this -> isMarkdownable [ $ this -> parser -> tagName ] ) ) { return false ; } if ( $ this -> parser -> isStartTag ) { $ return = true ; if ( $ this -> keepHTML ) { $ diff = array_diff ( array_keys ( $ this -> parser -> tagAttributes ) , array_keys ( $ this -> isMarkdownable [ $ this -> parser -> tagName ] ) ) ; if ( ! empty ( $ diff ) ) { $ return = false ; } } if ( $ return ) { foreach ( $ this -> isMarkdownable [ $ this -> parser -> tagName ] as $ attr => $ type ) { if ( $ type == 'required' && ! isset ( $ this -> parser -> tagAttributes [ $ attr ] ) ) { $ return = false ; break ; } } } if ( ! $ return ) { array_push ( $ this -> notConverted , $ this -> parser -> tagName . '::' . implode ( '/' , $ this -> parser -> openTags ) ) ; } return $ return ; } else { if ( ! empty ( $ this -> notConverted ) && end ( $ this -> notConverted ) === $ this -> parser -> tagName . '::' . implode ( '/' , $ this -> parser -> openTags ) ) { array_pop ( $ this -> notConverted ) ; return false ; } return true ; } }
|
check if current tag can be converted to Markdown
|
50,656
|
protected function wordwrap ( $ str , $ width , $ break , $ cut = false ) { if ( ! $ cut ) { $ regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){1,' . $ width . '}\b#' ; } else { $ regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){' . $ width . '}#' ; } $ return = '' ; while ( preg_match ( $ regexp , $ str , $ matches ) ) { $ string = $ matches [ 0 ] ; $ str = ltrim ( substr ( $ str , strlen ( $ string ) ) ) ; if ( ! $ cut && isset ( $ str [ 0 ] ) && in_array ( $ str [ 0 ] , [ '.' , '!' , ';' , ':' , '?' , ',' ] ) ) { $ string .= $ str [ 0 ] ; $ str = ltrim ( substr ( $ str , 1 ) ) ; } $ return .= $ string . $ break ; } return $ return . ltrim ( $ str ) ; }
|
wordwrap for utf8 encoded strings
|
50,657
|
protected function fixBlockElementSpacing ( ) { if ( $ this -> parser -> isStartTag ) { $ this -> parser -> html = ltrim ( $ this -> parser -> html ) ; } }
|
Trims whitespace in block - level elements on the left side .
|
50,658
|
protected function resetState ( ) { $ this -> notConverted = [ ] ; $ this -> skipConversion = false ; $ this -> buffer = [ ] ; $ this -> indent = '' ; $ this -> stack = [ ] ; $ this -> lineBreaks = 0 ; $ this -> lastClosedTag = '' ; $ this -> lastWasBlockTag = false ; $ this -> footnotes = [ ] ; }
|
Resetting the state forces the instance to behave as a fresh instance . Ideal for running within a loop where you want to maintain a single instance .
|
50,659
|
public function start ( ) : DriverInterface { if ( ! $ this -> process ) { $ this -> process = ( new ChromeProcess ( $ this -> port ) ) -> toProcess ( ) ; $ this -> process -> start ( ) ; sleep ( 1 ) ; } return $ this ; }
|
Start the Chromedriver process .
|
50,660
|
public function stop ( ) : DriverInterface { if ( $ this -> process ) { $ this -> process -> stop ( ) ; unset ( $ this -> process ) ; } return $ this ; }
|
Ensure the driver is closed by the upstream library .
|
50,661
|
public static function convertElement ( $ element , RemoteWebDriver $ driver ) { if ( $ element instanceof RemoteWebElement ) { return new self ( $ element , $ driver ) ; } return $ element ; }
|
Convert a standard element to one of our bespoke elements .
|
50,662
|
public function elements ( string $ selector ) : array { $ elements = $ this -> resolver -> all ( $ selector ) ; array_walk ( $ elements , function ( & $ element ) { $ element = self :: convertElement ( $ element , $ this -> driver ) ; } ) ; return $ elements ; }
|
Get all of the elements matching the given selector .
|
50,663
|
public function element ( string $ selector ) : ? Element { $ element = $ this -> resolver -> find ( $ selector ) ; return self :: convertElement ( $ element , $ this -> driver ) ; }
|
Get the element matching the given selector .
|
50,664
|
public function parent ( string $ selector = "*" ) : ? Element { if ( $ selector === "*" ) { $ prefix = "parent" ; } else { $ prefix = "ancestor" ; } $ selector = preg_replace ( "/\.([a-zA-Z0-9_-]+)/" , "[contains(@class, '$1')]" , $ selector ) ; return $ this -> findElement ( WebDriverBy :: xpath ( "{$prefix}::{$selector}" ) ) ; }
|
Get one of the parents of this element .
|
50,665
|
public function getTranslations ( $ reload = false ) { if ( $ this -> translations && ! $ reload ) { return $ this -> translations ; } collect ( $ this -> disk -> allFiles ( $ this -> languageFilesPath ) ) -> filter ( function ( $ file ) { return $ this -> disk -> extension ( $ file ) == 'json' ; } ) -> each ( function ( $ file ) { $ this -> translations [ str_replace ( '.json' , '' , $ file -> getFilename ( ) ) ] = json_decode ( $ file -> getContents ( ) ) ; } ) ; return $ this -> translations ; }
|
Get all the available lines .
|
50,666
|
public function sync ( ) { $ this -> backup ( ) ; $ output = [ ] ; $ translations = $ this -> getTranslations ( ) ; $ keysFromFiles = array_collapse ( $ this -> getTranslationsFromFiles ( ) ) ; foreach ( array_unique ( $ keysFromFiles ) as $ fileName => $ key ) { foreach ( $ translations as $ lang => $ keys ) { if ( ! array_key_exists ( $ key , $ keys ) ) { $ output [ ] = $ key ; } } } return array_values ( array_unique ( $ output ) ) ; }
|
Synchronize the language keys from files .
|
50,667
|
public function saveTranslations ( $ translations ) { $ this -> backup ( ) ; foreach ( $ translations as $ lang => $ lines ) { $ filename = $ this -> languageFilesPath . DIRECTORY_SEPARATOR . "$lang.json" ; ksort ( $ lines ) ; file_put_contents ( $ filename , json_encode ( $ lines , JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ) ) ; } }
|
Save the given translations .
|
50,668
|
public function addLanguage ( $ language ) { $ this -> backup ( ) ; file_put_contents ( $ this -> languageFilesPath . DIRECTORY_SEPARATOR . "$language.json" , json_encode ( ( object ) [ ] , JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ) ) ; }
|
Add a new JSON language file .
|
50,669
|
private function backup ( ) { if ( ! $ this -> disk -> exists ( storage_path ( 'langmanGUI' ) ) ) { $ this -> disk -> makeDirectory ( storage_path ( 'langmanGUI' ) ) ; $ this -> disk -> put ( storage_path ( 'langmanGUI' . '/.gitignore' ) , "*\n!.gitignore" ) ; } $ this -> disk -> copyDirectory ( resource_path ( 'lang' ) , storage_path ( 'langmanGUI/' . time ( ) ) ) ; }
|
Backup the existing translation files
|
50,670
|
protected function registerRoutes ( ) { $ this -> app [ 'router' ] -> group ( config ( 'langmanGUI.route_group_config' ) , function ( $ router ) { $ router -> get ( '/langman' , 'LangmanController@index' ) ; $ router -> post ( '/langman/scan' , 'LangmanController@scan' ) ; $ router -> post ( '/langman/save' , 'LangmanController@save' ) ; $ router -> post ( '/langman/add-language' , 'LangmanController@addLanguage' ) ; } ) ; }
|
Register the Langman routes .
|
50,671
|
public function refund ( $ charge , array $ options = [ ] ) : StripeRefund { $ options [ 'charge' ] = $ charge ; return StripeRefund :: create ( $ options , [ 'api_key' => $ this -> getStripeKey ( ) ] ) ; }
|
Refund a customer for a charge .
|
50,672
|
public function newSubscription ( string $ subscription , string $ plan ) : SubscriptionBuilder { return new SubscriptionBuilder ( $ this , $ subscription , $ plan ) ; }
|
Begin creating a new subscription .
|
50,673
|
public function onTrial ( string $ subscription = 'default' , ? string $ plan = null ) : bool { if ( func_num_args ( ) === 0 && $ this -> onGenericTrial ( ) ) { return true ; } $ subscription = $ this -> subscription ( $ subscription ) ; if ( is_null ( $ plan ) ) { return $ subscription && $ subscription -> onTrial ( ) ; } return $ subscription && $ subscription -> onTrial ( ) && $ subscription -> stripePlan === $ plan ; }
|
Determine if the user is on trial .
|
50,674
|
public function onGenericTrial ( ) : bool { return $ this -> trial_ends_at && Carbon :: now ( ) -> lt ( Carbon :: createFromFormat ( 'Y-m-d H:i:s' , $ this -> trial_ends_at ) ) ; }
|
Determine if the user is on a generic trial at the user level .
|
50,675
|
public function upcomingInvoice ( ) : ? Invoice { try { $ stripeInvoice = StripeInvoice :: upcoming ( [ 'customer' => $ this -> stripe_id ] , [ 'api_key' => $ this -> getStripeKey ( ) ] ) ; return new Invoice ( $ this , $ stripeInvoice ) ; } catch ( InvalidRequest $ e ) { } }
|
Get the entity s upcoming invoice .
|
50,676
|
protected function fillCardDetails ( $ card ) { if ( $ card ) { $ this -> card_brand = $ card -> brand ; $ this -> card_last_four = $ card -> last4 ; } return $ this ; }
|
Fills the user s properties with the source from Stripe .
|
50,677
|
public function createAsStripeCustomer ( string $ token , array $ options = [ ] ) : Customer { $ options = array_key_exists ( 'email' , $ options ) ? $ options : array_merge ( $ options , [ 'email' => $ this -> email ] ) ; $ customer = Customer :: create ( $ options , $ this -> getStripeKey ( ) ) ; $ this -> stripe_id = $ customer -> id ; $ this -> save ( ) ; if ( ! is_null ( $ token ) ) { $ this -> updateCard ( $ token ) ; } return $ customer ; }
|
Create a Stripe customer for the given user .
|
50,678
|
public function actionHandleWebhook ( ) { $ payload = json_decode ( Yii :: $ app -> request -> getRawBody ( ) , true ) ; if ( ! $ this -> eventExistsOnStripe ( $ payload [ 'id' ] ) ) { return ; } $ method = 'handle' . Inflector :: camelize ( str_replace ( '.' , '_' , $ payload [ 'type' ] ) ) ; if ( method_exists ( $ this , $ method ) ) { return $ this -> { $ method } ( $ payload ) ; } return $ this -> missingMethod ( ) ; }
|
Processing Stripe s callback and making membership updates according to payment data
|
50,679
|
protected function getUserByStripeId ( $ stripeId ) { $ model = Yii :: $ app -> user -> identityClass ; return $ model :: findOne ( [ 'stripe_id' => $ stripeId ] ) ; }
|
Get the billable entity instance by Stripe ID .
|
50,680
|
protected function eventExistsOnStripe ( $ id ) { try { return ! is_null ( StripeEvent :: retrieve ( $ id , Yii :: $ app -> params [ 'stripe' ] [ 'apiKey' ] ) ) ; } catch ( Exception $ e ) { return false ; } }
|
Verify with Stripe that the event is genuine .
|
50,681
|
public function invoiceItemsByType ( $ type ) { $ lineItems = [ ] ; if ( isset ( $ this -> lines -> data ) ) { foreach ( $ this -> lines -> data as $ line ) { if ( $ line -> type == $ type ) { $ lineItems [ ] = new InvoiceItem ( $ this -> user , $ line ) ; } } } return $ lineItems ; }
|
Get all of the invoie items by a given type .
|
50,682
|
public function renderInvoiceHtml ( array $ data ) { $ viewPath = ArrayHelper :: getValue ( $ data , 'invoiceView' , '@vendor/yii2mod/yii2-cashier/views/invoice' ) ; return Yii :: $ app -> controller -> renderPartial ( $ viewPath , array_merge ( $ data , [ 'invoice' => $ this , 'user' => $ this -> user ] ) ) ; }
|
Return invoice html
|
50,683
|
public function onGracePeriod ( ) : bool { if ( ! is_null ( $ endAt = $ this -> ends_at ) ) { return Carbon :: now ( ) -> lt ( Carbon :: instance ( $ endAt ) ) ; } else { return false ; } }
|
Determine if the subscription is within its grace period after cancellation .
|
50,684
|
public function decrementQuantity ( int $ count = 1 ) { $ this -> updateQuantity ( max ( 1 , $ this -> quantity - $ count ) ) ; return $ this ; }
|
Decrement the quantity of the subscription .
|
50,685
|
public static function useCurrency ( string $ currency , ? string $ symbol = null ) : void { static :: $ currency = $ currency ; static :: useCurrencySymbol ( $ symbol ? : static :: guessCurrencySymbol ( $ currency ) ) ; }
|
Set the currency to be used when billing users .
|
50,686
|
protected function getTrialEndForPayload ( ) { if ( $ this -> skipTrial ) { return 'now' ; } if ( $ this -> trialDays ) { return Carbon :: now ( ) -> addDays ( $ this -> trialDays ) -> getTimestamp ( ) ; } }
|
Get the trial ending date for the Stripe payload .
|
50,687
|
public function get ( $ key , $ default = null ) { $ location = trim ( $ this -> config -> get ( 'mpesa.cache_location' ) , '/' ) . '/.mpc' ; if ( ! is_file ( $ location ) ) { return $ default ; } $ cache = unserialize ( file_get_contents ( $ location ) ) ; $ cache = $ this -> cleanCache ( $ cache , $ location ) ; if ( ! isset ( $ cache [ $ key ] ) ) { return $ default ; } return $ cache [ $ key ] [ 'v' ] ; }
|
Get the cache value .
|
50,688
|
public function setCommand ( $ command ) { if ( ! in_array ( $ command , self :: VALID_COMMANDS ) ) { throw new InvalidArgumentException ( 'Invalid command sent' ) ; } $ this -> command = $ command ; return $ this ; }
|
Set the unique command for this transaction type .
|
50,689
|
public function push ( $ amount = null , $ number = null , $ reference = null , $ command = null , $ account = null ) { $ account = $ account ? : $ this -> account ; $ configs = ( new ConfigurationRepository ) -> useAccount ( $ account ) ; if ( ! $ configs -> getAccountKey ( 'sandbox' ) ) { throw new ErrorException ( 'Cannot simulate a transaction in the live environment.' ) ; } $ shortCode = $ configs -> getAccountKey ( 'lnmo.shortcode' ) ; $ body = [ 'CommandID' => $ command ? : $ this -> command , 'Amount' => $ amount ? : $ this -> amount , 'Msisdn' => $ number ? : $ this -> number , 'ShortCode' => $ shortCode , 'BillRefNumber' => $ reference ? : $ this -> reference , ] ; try { $ response = $ this -> makeRequest ( $ body , Core :: instance ( ) -> getEndpoint ( MPESA_SIMULATE , $ account ) , $ account ) ; return json_decode ( $ response -> getBody ( ) ) ; } catch ( RequestException $ exception ) { return json_decode ( $ exception -> getResponse ( ) -> getBody ( ) ) ; } }
|
Prepare the transaction simulation request
|
50,690
|
public function submit ( $ shortCode = null , $ confirmationURL = null , $ validationURL = null , $ onTimeout = null , $ account = null ) { $ account = $ account ? : $ this -> account ; if ( $ onTimeout ) { $ this -> onTimeout ( $ onTimeout ) ; } $ body = [ 'ShortCode' => $ shortCode ? : $ this -> shortCode , 'ResponseType' => $ onTimeout ? : $ this -> onTimeout , 'ConfirmationURL' => $ confirmationURL ? : $ this -> confirmationURL , 'ValidationURL' => $ validationURL ? : $ this -> validationURL ] ; try { $ response = $ this -> makeRequest ( $ body , Core :: instance ( ) -> getEndpoint ( MPESA_REGISTER , $ account ) , $ account ) ; return \ json_decode ( $ response -> getBody ( ) ) ; } catch ( RequestException $ exception ) { $ message = $ exception -> getResponse ( ) ? $ exception -> getResponse ( ) -> getReasonPhrase ( ) : $ exception -> getMessage ( ) ; throw new Exception ( $ message ) ; } }
|
Initiate the registration process .
|
50,691
|
public function usingReference ( $ reference , $ description ) { $ this -> reference = $ reference ; $ this -> description = $ description ; return $ this ; }
|
Set the product reference number to bill the account .
|
50,692
|
public function push ( $ amount = null , $ number = null , $ reference = null , $ description = null , $ account = null ) { $ account = $ account ? : $ this -> account ; $ time = Carbon :: now ( ) -> format ( 'YmdHis' ) ; $ configs = ( new ConfigurationRepository ) -> useAccount ( $ account ) ; $ shortCode = $ configs -> getAccountKey ( 'lnmo.shortcode' ) ; $ passkey = $ configs -> getAccountKey ( 'lnmo.passkey' ) ; $ callback = $ configs -> getAccountKey ( 'lnmo.callback' ) ; $ body = [ 'BusinessShortCode' => $ shortCode , 'Password' => $ this -> getPassword ( $ shortCode , $ passkey , $ time ) , 'Timestamp' => $ time , 'TransactionType' => 'CustomerPayBillOnline' , 'Amount' => $ amount ? : $ this -> amount , 'PartyA' => $ number ? : $ this -> number , 'PartyB' => $ shortCode , 'PhoneNumber' => $ number ? : $ this -> number , 'CallBackURL' => $ callback , 'AccountReference' => $ reference ? : $ this -> reference , 'TransactionDesc' => $ description ? : $ this -> description , ] ; try { $ response = $ this -> makeRequest ( $ body , Core :: instance ( ) -> getEndpoint ( MPESA_LNMO , $ account ) , $ account ) ; return json_decode ( $ response -> getBody ( ) ) ; } catch ( RequestException $ exception ) { return json_decode ( $ exception -> getResponse ( ) -> getBody ( ) ) ; } }
|
Prepare the STK Push request
|
50,693
|
public function validate ( $ checkoutRequestID , $ account = null ) { $ account = $ account ? : $ this -> account ; $ time = Carbon :: now ( ) -> format ( 'YmdHis' ) ; $ configs = ( new ConfigurationRepository ) -> useAccount ( $ account ) ; $ shortCode = $ configs -> getAccountKey ( 'lnmo.shortcode' ) ; $ passkey = $ configs -> getAccountKey ( 'lnmo.passkey' ) ; $ body = [ 'BusinessShortCode' => $ shortCode , 'Password' => $ this -> getPassword ( $ shortCode , $ passkey , $ time ) , 'Timestamp' => $ time , 'CheckoutRequestID' => $ checkoutRequestID , ] ; try { $ response = $ this -> makeRequest ( $ body , Core :: instance ( ) -> getEndpoint ( MPESA_LNMO_VALIDATE , $ account ) , $ account ) ; return json_decode ( $ response -> getBody ( ) ) ; } catch ( RequestException $ exception ) { return json_decode ( $ exception -> getResponse ( ) -> getBody ( ) ) ; } }
|
Validate an initialized transaction .
|
50,694
|
public static function authenticate ( $ account = null ) { $ configs = ( new ConfigurationRepository ) -> useAccount ( $ account ) ; $ key = $ configs -> getAccountKey ( 'key' ) ; $ secret = $ configs -> getAccountKey ( 'secret' ) ; $ cacheKey = self :: AC_TOKEN . "{$key}{$secret}" ; if ( $ token = Core :: instance ( ) -> cache ( ) -> get ( $ cacheKey ) ) { return $ token ; } try { $ response = self :: makeRequest ( $ key , $ secret , $ account ) ; $ body = json_decode ( $ response -> getBody ( ) ) ; self :: saveCredentials ( $ cacheKey , $ body ) ; return $ body -> access_token ; } catch ( RequestException $ exception ) { $ message = $ exception -> getResponse ( ) ? $ exception -> getResponse ( ) -> getReasonPhrase ( ) : $ exception -> getMessage ( ) ; throw self :: generateException ( $ message ) ; } }
|
Get the access token required to transact .
|
50,695
|
private static function makeRequest ( $ key , $ secret , $ account ) { $ credentials = base64_encode ( $ key . ':' . $ secret ) ; $ endpoint = Core :: instance ( ) -> getEndpoint ( MPESA_AUTH , $ account ) ; return Core :: instance ( ) -> client ( ) -> request ( 'GET' , $ endpoint , [ 'headers' => [ 'Authorization' => 'Basic ' . $ credentials , 'Content-Type' => 'application/json' , ] , ] ) ; }
|
Initiate the authentication request .
|
50,696
|
private static function saveCredentials ( $ key , $ credentials ) { $ ttl = ( $ credentials -> expires_in / 60 ) - 2 ; Core :: instance ( ) -> cache ( ) -> put ( $ key , $ credentials -> access_token , $ ttl ) ; }
|
Store the credentials in the cache .
|
50,697
|
public function useAccount ( $ account = null ) { $ account = $ account ? : Core :: instance ( ) -> getConfig ( 'default' ) ; if ( ! Core :: instance ( ) -> getConfig ( "accounts.{$account}" ) ) { throw new Exception ( 'Invalid account selected' ) ; } $ this -> account = $ account ; return $ this ; }
|
Set the account to be used when resoving configs .
|
50,698
|
public function getAccountKey ( $ key , $ default = null , $ account = null ) { if ( ! $ this -> account || ( $ account && $ account !== $ this -> account ) ) { $ this -> useAccount ( $ account ) ; } return Core :: instance ( ) -> getConfig ( "accounts.{$this->account}.{$key}" , $ default ) ; }
|
Get a configuration value from the store .
|
50,699
|
public function getEndpoint ( $ endpoint , $ account = null ) { $ isSandbox = ( new ConfigurationRepository ) -> getAccountKey ( 'sandbox' , true , $ account ) ; if ( $ isSandbox ) { return $ this -> resolveUrl ( MPESA_SANDBOX , $ endpoint ) ; } return $ this -> resolveUrl ( MPESA_PRODUCTION , $ endpoint ) ; }
|
Get the endpoint relative to the current
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.