idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
2,900
public function success ( $ data = null ) { $ this -> _status = static :: STATUS_SUCCESS ; $ this -> _code = 200 ; $ this -> _data = ! $ data && $ data !== false ? null : $ data ; }
Turns the response into a success response . Will by default set the response code to 200 .
2,901
public function fail ( $ data = null , $ code = 200 ) { $ this -> _status = static :: STATUS_FAIL ; $ this -> _code = $ code ; $ this -> _data = ! $ data && $ data !== false ? null : $ data ; }
Turns the response into a fail response . Will by default set the response code to 200 if not provided otherwise .
2,902
public function error ( $ message , $ data = null , $ code = 404 ) { $ this -> _status = static :: STATUS_FAIL ; $ this -> _message = $ message ; $ this -> _data = ! $ data && $ data !== false ? null : $ data ; $ this -> _code = $ code ; }
Turns the response into an error response . Will by default set the response code to 404 if not provided otherwise .
2,903
public function to ( $ type ) { if ( $ type === 'array' ) { $ result = [ ] ; foreach ( [ 'status' , 'message' , 'data' , 'code' ] as $ field ) { if ( $ this -> { "_{$field}" } !== null || $ field === 'data' ) { $ result [ $ field ] = $ this -> { "_{$field}" } ; } } return $ result ; } throw new Exception ( "Cannot convert to type `{$type}`." ) ; }
Converts the response to given type . Currently just array is supported .
2,904
protected function executeAndHandleApiException ( $ command , $ params ) { try { $ manager = $ this -> getManager ( ) ; $ handler = array ( $ manager , $ command ) ; if ( is_callable ( $ handler ) ) { $ data = call_user_func_array ( $ handler , $ params ) ; } else { throw new \ BadMethodCallException ( 'The method "' . $ command . '" not exist to this manager. Message showed in mehtod "executeAndHandleApiException" of ChateaClientBundle' ) ; } } catch ( ApiException $ e ) { if ( $ e -> getCode ( ) == 404 ) { return null ; } throw $ e ; } return $ data ; }
Executes a command and returns the result . If ApiException happens and has status code 404 null is returned else the exception
2,905
protected function executeAndHydrateOrHandleApiException ( $ command , $ params ) { $ data = $ this -> executeAndHandleApiException ( $ command , $ params ) ; if ( $ data !== null ) { return $ this -> hydrate ( $ data ) ; } return null ; }
Executes a command and hydrates the result . If ApiException happens and has status code 404 null is returned else the exception
2,906
public static function getArgumentsForCall ( $ name , $ arguments ) : array { $ name = strtoupper ( $ name ) ; if ( $ name === 'ANY' ) { $ name = self :: ALLOWED_METHODS ; } else if ( ! in_array ( $ name , self :: ALLOWED_METHODS ) ) { throw new InvalidArgumentException ( 'Route::method must be one of: ' . implode ( ', ' , self :: ALLOWED_METHODS ) ) ; } array_unshift ( $ arguments , $ name ) ; return $ arguments ; }
Get the arguments for the call
2,907
protected function runApplicationWithEvents ( ) { $ this -> prepareEnvironment ( ) ; if ( static :: $ before ) { $ this -> runBeforeCallbacks ( ) ; } $ this -> readGeneralConfigs ( ) ; $ this -> registerAliases ( ) ; $ this -> resolveHelpers ( ) ; $ this -> prepareServiceProviders ( ) ; if ( static :: $ after ) { $ this -> runAfterCallbacks ( ) ; } }
run application with before and after events
2,908
private function prepareEnvironment ( ) { $ filesystem = $ this -> make ( Filesystem :: class ) ; if ( $ filesystem instanceof Filesystem ) { if ( $ filesystem -> exists ( $ path = $ this -> getEnvironmentPath ( ) ) ) { $ env = $ filesystem -> get ( $ path ) ; array_map ( function ( $ env ) { if ( $ env !== '' && $ env !== null ) { putenv ( $ env ) ; } } , explode ( "\n" , $ env ) ) ; $ this -> environments = count ( $ _ENV ) ? $ _ENV : isset ( $ _SERVER [ 'ENV' ] ) ? $ _SERVER [ 'ENV' ] : [ ] ; } } }
find and register Environment variables for application
2,909
private function registerAliases ( ) { Facade :: setApplication ( $ this ) ; $ aliases = [ 'app' => [ 'Anonym\Application\Application' , Container :: class ] , 'redirect' => [ 'Anonym\Http\Redirect' ] , 'validation' => [ 'Anonym\Support\Validation' ] , 'route' => [ 'Anonym\Route\RouteCollector' ] , 'event' => [ 'Anonym\Event\EventDispatcher' ] , 'cookie' => [ 'Anonym\Cookie\CookieInterface' ] , 'session' => [ 'Anonym\Session\StrogeInterface' ] , 'config' => [ 'Anonym\Config\Reposity' ] , 'crypt' => [ 'Anonym\Crypt\Crypter' ] , 'view' => [ 'Anonym\View\View' ] ] ; foreach ( $ aliases as $ key => $ alias ) { foreach ( ( array ) $ alias as $ abstract ) { $ this -> alias ( $ abstract , $ key ) ; } } $ this -> setAliasLoader ( new AliasLoader ( Arr :: get ( $ this -> getGeneral ( ) , 'alias' ) ) ) ; $ this -> getAliasLoader ( ) -> register ( ) ; }
register all aliases and alias loader
2,910
private function resolveHelpers ( ) { if ( count ( $ helpers = Arr :: get ( $ this -> getGeneral ( ) , 'helpers' , [ ] ) ) ) { foreach ( $ helpers as $ helper ) { if ( file_exists ( $ helper ) ) { include $ helper ; } } } }
resolve the helpers
2,911
public function assertMatchesSelector ( $ selector , DOMElement $ element , $ message = '' ) { return PHPUnit_Framework_Assert :: assertThat ( $ element , $ this -> matchesSelector ( $ selector ) , $ message ) ; }
Asserts that a dom element matches a specified selector
2,912
public function findAllByUserId ( $ userId ) { $ platform = $ this -> getDbAdapter ( ) -> getPlatform ( ) ; $ from = $ this -> getTableInSchema ( 'user_right_x_user' ) ; if ( $ from instanceof TableIdentifier ) { $ from = $ from -> getIdentifierChain ( ) ; } else { $ from = ( array ) ( string ) $ from ; } return $ this -> findAll ( array ( new Expression ( $ platform -> quoteIdentifier ( 'id' ) . ' IN ( SELECT ' . $ platform -> quoteIdentifier ( 'rightId' ) . ' FROM ' . $ platform -> quoteIdentifierChain ( $ from ) . ' WHERE ' . $ platform -> quoteIdentifier ( 'userId' ) . ' = ? )' , $ userId ) , ) ) ; }
Get permissions by userId
2,913
public function findAllByGroupId ( $ userGroupId ) { $ platform = $ this -> getDbAdapter ( ) -> getPlatform ( ) ; $ from = $ this -> getTableInSchema ( 'user_right_x_user_group' ) ; if ( $ from instanceof TableIdentifier ) { $ from = $ from -> getIdentifierChain ( ) ; } else { $ from = ( array ) ( string ) $ from ; } return $ this -> findAll ( array ( new Expression ( $ platform -> quoteIdentifier ( 'id' ) . ' IN ( SELECT ' . $ platform -> quoteIdentifier ( 'rightId' ) . ' FROM ' . $ platform -> quoteIdentifierChain ( $ from ) . ' WHERE ' . $ platform -> quoteIdentifier ( 'groupId' ) . ' = ? )' , $ userGroupId ) , ) ) ; }
Get permissions by userGroupId
2,914
public function findUserGroups ( ) { if ( null === $ this -> userGroups ) { $ this -> userGroups = array ( ) ; $ select = $ this -> sql ( 'user_group' ) -> select ( ) -> columns ( array ( 'id' , 'name' ) ) ; $ result = $ this -> sql ( ) -> prepareStatementForSqlObject ( $ select ) -> execute ( ) ; foreach ( $ result as $ row ) { $ this -> userGroups [ $ row [ 'id' ] ] = $ row [ 'name' ] ; } } return $ this -> userGroups ; }
Find all user - groups
2,915
public function validate ( string ... $ urls ) : ResultInterface { $ httpUrls = array_filter ( $ urls , function ( string $ url ) : bool { return 'https' !== wp_parse_url ( $ url , PHP_URL_SCHEME ) ; } ) ; return $ this -> report ( ... $ httpUrls ) ; }
Validates URLs are HTTPS .
2,916
public function isAuthorized ( ) { $ rbac = $ this -> getContainer ( ) -> get ( 'rbac' ) ; $ auth = $ this -> getContainer ( ) -> get ( 'auth' ) ; foreach ( $ auth -> getStorage ( ) -> read ( ) [ 'roles' ] as $ roleName ) { if ( true === $ rbac -> isGranted ( $ roleName , 'admin.panel.view' ) ) { return true ; } } return false ; }
Check user is authorized
2,917
protected static function putLogFile ( $ logFile , $ info ) { touch ( $ logFile ) ; if ( ! @ file_put_contents ( $ logFile , date ( "Y-m-d H:i:s" ) . ': ' . $ info . "\n\n" , FILE_APPEND ) || ! @ chmod ( $ logFile , 0777 ) ) { throw new \ LogicException ( "LOG_FOLDER should be writable. Could not write log-entry." ) ; } }
Writes log - entry to file and prepends date in front .
2,918
protected static function getLogFile ( $ folder , $ noAppend = false ) { if ( ! isset ( self :: $ logCache [ $ folder . date ( "mdy_h" ) ] ) || $ noAppend ) { $ logFolder = GomaENV :: getDataDirectory ( ) . LOG_FOLDER . "/" . $ folder . "/" . date ( "m-d-y" ) . "/" ; if ( ! is_dir ( $ logFolder ) ) { if ( ! mkdir ( $ logFolder , 0777 , true ) ) { throw new \ LogicException ( "LOG_FOLDER should be writable." ) ; } } $ noAppendFileName = $ noAppend ? date ( "H_i_s" ) . "_" : "" ; $ file = $ logFolder . $ noAppendFileName . "1.log" ; $ i = 1 ; while ( file_exists ( $ logFolder . $ noAppendFileName . $ i . ".log" ) && ( $ noAppend || filesize ( $ file ) > static :: $ fileSizeLimit ) ) { $ i ++ ; $ file = $ logFolder . $ noAppendFileName . $ i . ".log" ; } self :: $ logCache [ $ folder . date ( "mdy_h" ) ] = $ file ; } return self :: $ logCache [ $ folder . date ( "mdy_h" ) ] ; }
Gets latest log - file based on size of previous files .
2,919
public function apply_filters ( $ tag , $ value ) { $ args = array ( ) ; if ( isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; $ args = func_get_args ( ) ; self :: _call_all_hook ( $ args ) ; } if ( ! isset ( $ this -> filter [ $ tag ] ) ) { if ( isset ( $ this -> filter [ 'all' ] ) ) { array_pop ( $ this -> current_filter ) ; } return $ value ; } if ( ! isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; } if ( ! isset ( $ this -> merged_filters [ $ tag ] ) ) { ksort ( $ this -> filter [ $ tag ] ) ; $ this -> merged_filters [ $ tag ] = true ; } reset ( $ this -> filter [ $ tag ] ) ; if ( empty ( $ args ) ) { $ args = func_get_args ( ) ; } do { foreach ( ( array ) current ( $ this -> filter [ $ tag ] ) as $ the_ ) { if ( ! is_null ( $ the_ [ 'function' ] ) ) { $ args [ 1 ] = $ value ; $ value = call_user_func_array ( $ the_ [ 'function' ] , array_slice ( $ args , 1 , ( int ) $ the_ [ 'accepted_args' ] ) ) ; } } } while ( next ( $ this -> filter [ $ tag ] ) !== false ) ; array_pop ( $ this -> current_filter ) ; return $ value ; }
Call the functions added to a filter hook .
2,920
private function _call_all_hook ( $ args ) { reset ( $ this -> filter [ 'all' ] ) ; do { foreach ( ( array ) current ( $ this -> filter [ 'all' ] ) as $ the_ ) { if ( ! is_null ( $ the_ [ 'function' ] ) ) { call_user_func_array ( $ the_ [ 'function' ] , $ args ) ; } } } while ( next ( $ this -> filter [ 'all' ] ) !== false ) ; }
Call the all hook which will process the functions hooked into it .
2,921
public function doing_filter ( $ filter = null ) { if ( null === $ filter ) { return ! empty ( $ this -> current_filter ) ; } return in_array ( $ filter , $ this -> current_filter ) ; }
Retrieve the name of a filter currently being processed .
2,922
public function add_action ( $ tag , $ function_to_add , $ priority = 10 , $ accepted_args = 1 ) { return self :: add_filter ( $ tag , $ function_to_add , $ priority , $ accepted_args ) ; }
Hooks a function on to a specific action .
2,923
public function add_filter ( $ tag , $ function_to_add , $ priority = 10 , $ accepted_args = 1 ) { $ idx = self :: _filter_build_unique_id ( $ tag , $ function_to_add , $ priority ) ; $ this -> filter [ $ tag ] [ $ priority ] [ $ idx ] = array ( 'function' => $ function_to_add , 'accepted_args' => $ accepted_args , ) ; unset ( $ this -> merged_filters [ $ tag ] ) ; return true ; }
Hook a function or method to a specific filter action .
2,924
private function _filter_build_unique_id ( $ tag , $ function , $ priority ) { static $ filter_id_count = 0 ; if ( is_string ( $ function ) ) { return $ function ; } if ( is_object ( $ function ) ) { $ function = array ( $ function , '' ) ; } else { $ function = ( array ) $ function ; } if ( is_object ( $ function [ 0 ] ) ) { if ( function_exists ( 'spl_object_hash' ) ) { return spl_object_hash ( $ function [ 0 ] ) . $ function [ 1 ] ; } else { $ obj_idx = get_class ( $ function [ 0 ] ) . $ function [ 1 ] ; if ( ! isset ( $ function [ 0 ] -> filter_id ) ) { if ( false === $ priority ) { return false ; } $ obj_idx .= isset ( $ this -> filter [ $ tag ] [ $ priority ] ) ? count ( ( array ) $ this -> filter [ $ tag ] [ $ priority ] ) : $ filter_id_count ; $ function [ 0 ] -> filter_id = $ filter_id_count ; ++ $ filter_id_count ; } else { $ obj_idx .= $ function [ 0 ] -> filter_id ; } return $ obj_idx ; } } elseif ( is_string ( $ function [ 0 ] ) ) { return $ function [ 0 ] . '::' . $ function [ 1 ] ; } }
Build Unique ID for storage and retrieval .
2,925
public function do_action ( $ tag , $ arg = '' ) { if ( ! isset ( $ this -> actions [ $ tag ] ) ) { $ this -> actions [ $ tag ] = 1 ; } else { ++ $ this -> actions [ $ tag ] ; } if ( isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; $ all_args = func_get_args ( ) ; self :: _call_all_hook ( $ all_args ) ; } if ( ! isset ( $ this -> filter [ $ tag ] ) ) { if ( isset ( $ this -> filter [ 'all' ] ) ) { array_pop ( $ this -> current_filter ) ; } return ; } if ( ! isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; } $ args = array ( ) ; if ( is_array ( $ arg ) && 1 == count ( $ arg ) && isset ( $ arg [ 0 ] ) && is_object ( $ arg [ 0 ] ) ) { $ args [ ] = & $ arg [ 0 ] ; } else { $ args [ ] = $ arg ; } for ( $ a = 2 , $ num = func_num_args ( ) ; $ a < $ num ; $ a ++ ) { $ args [ ] = func_get_arg ( $ a ) ; } if ( ! isset ( $ this -> merged_filters [ $ tag ] ) ) { ksort ( $ this -> filter [ $ tag ] ) ; $ this -> merged_filters [ $ tag ] = true ; } reset ( $ this -> filter [ $ tag ] ) ; do { foreach ( ( array ) current ( $ this -> filter [ $ tag ] ) as $ the_ ) { if ( ! is_null ( $ the_ [ 'function' ] ) ) { call_user_func_array ( $ the_ [ 'function' ] , array_slice ( $ args , 0 , ( int ) $ the_ [ 'accepted_args' ] ) ) ; } } } while ( next ( $ this -> filter [ $ tag ] ) !== false ) ; array_pop ( $ this -> current_filter ) ; }
Execute functions hooked on a specific action hook .
2,926
public function do_action_ref_array ( $ tag , $ args ) { if ( ! isset ( $ this -> actions [ $ tag ] ) ) { $ this -> actions [ $ tag ] = 1 ; } else { ++ $ this -> actions [ $ tag ] ; } if ( isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; $ all_args = func_get_args ( ) ; self :: _call_all_hook ( $ all_args ) ; } if ( ! isset ( $ this -> filter [ $ tag ] ) ) { if ( isset ( $ this -> filter [ 'all' ] ) ) { array_pop ( $ this -> current_filter ) ; } return ; } if ( ! isset ( $ this -> filter [ 'all' ] ) ) { $ this -> current_filter [ ] = $ tag ; } if ( ! isset ( $ this -> merged_filters [ $ tag ] ) ) { ksort ( $ this -> filter [ $ tag ] ) ; $ this -> merged_filters [ $ tag ] = true ; } reset ( $ this -> filter [ $ tag ] ) ; do { foreach ( ( array ) current ( $ this -> filter [ $ tag ] ) as $ the_ ) { if ( ! is_null ( $ the_ [ 'function' ] ) ) { call_user_func_array ( $ the_ [ 'function' ] , array_slice ( $ args , 0 , ( int ) $ the_ [ 'accepted_args' ] ) ) ; } } } while ( next ( $ this -> filter [ $ tag ] ) !== false ) ; array_pop ( $ this -> current_filter ) ; }
Execute functions hooked on a specific action hook specifying arguments in an array .
2,927
public function remove_filter ( $ tag , $ function_to_remove , $ priority = 10 ) { $ function_to_remove = self :: _filter_build_unique_id ( $ tag , $ function_to_remove , $ priority ) ; $ r = isset ( $ $ this -> filter [ $ tag ] [ $ priority ] [ $ function_to_remove ] ) ; if ( true === $ r ) { unset ( $ this -> filter [ $ tag ] [ $ priority ] [ $ function_to_remove ] ) ; if ( empty ( $ this -> filter [ $ tag ] [ $ priority ] ) ) { unset ( $ this -> filter [ $ tag ] [ $ priority ] ) ; } if ( empty ( $ this -> filter [ $ tag ] ) ) { $ this -> filter [ $ tag ] = array ( ) ; } unset ( $ this -> merged_filters [ $ tag ] ) ; } return $ r ; }
Removes a function from a specified filter hook .
2,928
public function merge ( PatchCollection $ otherCollection ) { $ this -> patches = array_merge ( $ this -> patches , $ otherCollection -> getPatches ( ) ) ; return $ this ; }
Merge another patch collection into this collection .
2,929
public function containsPatchesFor ( PackageInterface $ package ) { foreach ( $ this -> getPatches ( ) as $ patch ) { if ( $ patch -> isForPackage ( $ package ) ) { return true ; } } return false ; }
Check if this collection contains patches for a package .
2,930
public function getPatchesFor ( PackageInterface $ package ) { $ patches = array ( ) ; foreach ( $ this -> getPatches ( ) as $ patch ) { if ( $ patch -> isForPackage ( $ package ) ) { $ patches [ ] = $ patch ; } } $ result = new static ( ) ; $ result -> patches = $ patches ; return $ result ; }
Get the patches to be applied to a package .
2,931
public function getHash ( ) { $ hashes = array ( ) ; foreach ( $ this -> getPatches ( ) as $ patch ) { $ hashes [ ] = $ patch -> getHash ( ) ; } sort ( $ hashes ) ; return sha1 ( implode ( ' ' , $ hashes ) ) ; }
Get the hash of all the patches .
2,932
protected function _implodeRecursive ( array $ pieces ) { $ values = array ( ) ; foreach ( $ pieces as $ item ) { if ( is_array ( $ item ) ) { $ values [ ] = $ this -> _implodeRecursive ( $ item ) ; } else { $ values [ ] = $ item ; } } return implode ( ', ' , $ values ) ; }
Joins elements of a multidimensional array
2,933
private function createServerRequest ( string $ method , UriInterface $ uri , array $ headers , StreamInterface $ inputStream , string $ protocol , array $ server , array $ cookie , array $ get , array $ post ) : ServerRequestInterface { $ serverRequest = $ this -> httpFactory -> createServerRequest ( $ method , $ uri , $ headers , $ inputStream , $ protocol , $ server ) ; foreach ( $ server as $ key => $ value ) { if ( preg_match ( '/^HTTP_(?P<header>.*)\Z/' , $ key , $ matches ) ) { if ( $ matches [ 'header' ] != 'HOST' ) { $ serverRequest = $ serverRequest -> withAddedHeader ( str_replace ( '_' , '-' , strtolower ( $ matches [ 'header' ] ) ) , $ value ) ; } } } return $ serverRequest -> withMethod ( $ method ) -> withUri ( $ uri ) -> withCookieParams ( $ cookie ) -> withQueryParams ( $ get ) -> withParsedBody ( $ post ) ; }
Construct the server request .
2,934
public function knownExtensions ( $ type = null ) { $ extensions = [ 'images' => static :: $ imageExtensions , 'audios' => static :: $ audiosExtensions , 'archives' => static :: $ archivesExtensions , 'videos' => static :: $ videosExtensions , ] ; if ( $ type ) { if ( in_array ( $ type , array_keys ( $ extensions ) ) ) { return $ extensions [ $ type ] ; } return null ; } return $ extensions ; }
Get known extensions .
2,935
public function store ( UploadedFile $ file , array $ attributes = [ ] ) { $ type = $ this -> resolveType ( $ file ) ; return $ this -> submit ( $ file , $ type , $ attributes ) ; }
Store method .
2,936
protected function submit ( UploadedFile $ file , $ type , array $ attributes ) { switch ( $ type ) { case 'image' : return ( new \ Routegroup \ Media \ Upload \ Image ) -> make ( $ file , $ attributes ) ; case 'audio' : return ( new \ Routegroup \ Media \ Upload \ Audio ) -> make ( $ file , $ attributes ) ; case 'video' : return ( new \ Routegroup \ Media \ Upload \ Video ) -> make ( $ file , $ attributes ) ; case 'archive' : return ( new \ Routegroup \ Media \ Upload \ Archive ) -> make ( $ file , $ attributes ) ; default : return ( new \ Routegroup \ Media \ Upload \ File ) -> make ( $ file , $ attributes ) ; } }
Returns moved file .
2,937
public function fromPath ( $ path , $ filetype = null ) { $ filesystem = new Filesystem ; $ file = new UploadedFile ( $ path , last ( explode ( '/' , $ path ) ) , $ filetype ? : $ filesystem -> mimeType ( $ path ) , $ filesystem -> size ( $ path ) , null , true ) ; return $ this -> store ( $ file ) ; }
Store file from given path .
2,938
protected function resolveType ( UploadedFile $ file ) { $ extension = $ file -> clientExtension ( ) ? : $ file -> extension ( ) ; foreach ( $ this -> knownExtensions ( ) as $ type => $ extensions ) { if ( in_array ( $ extension , $ extensions ) ) { return ends_with ( $ type , 's' ) ? substr ( $ type , 0 , - 1 ) : $ type ; } } return 'file' ; }
Resolves file type .
2,939
protected function init ( $ filepath ) { $ this -> file = new \ SplFileObject ( $ filepath ) ; if ( ! $ this -> file -> isFile ( ) ) { throw new \ LogicException ( 'This is not a file' , 1 ) ; } if ( ! $ this -> file -> isReadable ( ) ) { throw new \ Exception ( 'This file is not readable' , 1 ) ; } if ( ! $ this -> file -> isWritable ( ) ) { } $ this -> filepath = $ this -> file -> getPathName ( ) ; }
boots up class by using filepath to create file object .
2,940
public function add ( $ host , $ ip ) { $ this -> validHost ( $ host ) ; $ this -> validIp ( $ ip ) ; if ( $ this -> check ( $ host ) ) { throw new \ RuntimeException ( 'Host already exists in the file' ) ; } $ this -> backup ( ) ; $ record = "\n$ip $host" ; $ file = new \ SplFileObject ( $ this -> filepath , 'a' ) ; $ ok = $ file -> fwrite ( $ record ) ; if ( ! $ ok ) { throw new \ RuntimeException ( 'Could not write to file' ) ; } return true ; }
add new host to hosts file .
2,941
public function rollback ( ) { $ backupFile = "{$this->filepath}.bkup.1" ; if ( ! file_exists ( $ backupFile ) ) { throw new \ RuntimeException ( "Backup file ({$backupFile}) does not exists." ) ; } copy ( $ backupFile , $ this -> filepath ) ; return true ; }
roll back to latest backup .
2,942
public function backup ( ) { $ count = $ this -> backups - 1 ; for ( $ i = $ count ; $ i > 0 ; -- $ i ) { $ backupFile = "{$this->filepath}.bkup.{$i}" ; if ( file_exists ( $ backupFile ) ) { copy ( $ backupFile , "{$this->filepath}.bkup." . ( $ i + 1 ) ) ; } } copy ( $ this -> filepath , "{$this->filepath}.bkup.1" ) ; return true ; }
save a backup of current hosts file .
2,943
public function update ( $ host , $ ip ) { $ this -> validHost ( $ host ) ; $ this -> validIp ( $ ip ) ; return $ this -> remove ( $ host ) && $ this -> add ( $ host , $ ip ) ; }
update host in hosts file .
2,944
public function remove ( $ host ) { $ this -> validHost ( $ host ) ; if ( ! $ this -> check ( $ host ) ) { throw new \ RuntimeException ( 'Host does not exists in the file' ) ; } $ this -> backup ( ) ; $ tmpFilePath = $ this -> filepath . '.tmp' ; $ tmpFile = new \ SplFileObject ( $ tmpFilePath , 'w+' ) ; $ this -> file -> rewind ( ) ; while ( ! $ this -> file -> eof ( ) ) { $ pattern = '/\b' . $ host . '\b/i' ; if ( ! preg_match ( $ pattern , $ this -> file -> current ( ) ) ) { $ tmpFile -> fwrite ( $ this -> file -> current ( ) ) ; } $ this -> file -> next ( ) ; } copy ( $ tmpFilePath , $ this -> filepath ) ; unlink ( $ tmpFilePath ) ; return true ; }
remove host from hosts file .
2,945
public function parse ( $ url ) { $ hit = false ; foreach ( $ this -> _routes as $ rule => $ new_class ) { $ regex = trim ( $ rule , '/' ) ; if ( preg_match ( $ regex , $ url , $ parameters ) ) { $ class = preg_replace ( $ regex , $ new_class , $ url ) ; $ class = str_replace ( '/' , '_' , $ class ) ; unset ( $ parameters [ 0 ] ) ; $ hit = true ; break ; } } if ( $ hit === false ) { $ class = call_user_func ( $ this -> _fallback , $ url ) ; } $ class_shards = explode ( '\\' , $ class ) ; $ class_shards [ count ( $ class_shards ) - 1 ] = ucfirst ( strtolower ( $ class_shards [ count ( $ class_shards ) - 1 ] ) ) ; $ class = implode ( '\\' , $ class_shards ) ; return [ 'controller' => $ class , 'parameters' => isset ( $ parameters ) ? $ parameters : [ ] , ] ; }
Parses a given URL path to get the resulting class name and created parameters .
2,946
public function callback ( $ data ) { $ payload = $ data ; $ this -> logger -> debug ( $ payload ) ; $ decoded = JWT :: decode ( $ payload , $ this -> payapiApiKey , [ 'HS256' ] ) ; $ jsonData = json_decode ( $ decoded ) ; $ result = null ; if ( $ jsonData -> payment -> status == 'processing' ) { $ this -> logger -> debug ( "PROCESSING CALLBACK..." ) ; $ order_id = $ this -> helper -> createOrder ( $ jsonData ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } else { $ orderId = $ this -> getOrderId ( $ jsonData ) ; if ( $ orderId ) { if ( $ jsonData -> payment -> status == 'successful' ) { $ this -> logger -> debug ( "SUCCESSFUL CALLBACK..." ) ; $ order_id = $ this -> helper -> addPayment ( $ orderId ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } elseif ( $ jsonData -> payment -> status == 'failed' ) { $ this -> logger -> debug ( "FAILED CALLBACK..." ) ; $ order_id = $ this -> helper -> changeStatus ( $ orderId , "canceled" , "canceled" , "failed" ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } elseif ( $ jsonData -> payment -> status == 'cancelled' ) { $ this -> logger -> debug ( "CANCELLED CALLBACK..." ) ; $ order_id = $ this -> helper -> changeStatus ( $ orderId , "canceled" , "canceled" , "cancelled" ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } elseif ( $ jsonData -> payment -> status == 'chargeback' ) { $ this -> logger -> debug ( "CHARGEBACK CALLBACK..." ) ; $ order_id = $ this -> helper -> changeStatus ( $ orderId , "payment_review" , "payment_review" , "chargeback" ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } else { $ this -> logger -> debug ( "STATUS CALLBACK: " . $ jsonData -> payment -> status ) ; $ order_id = $ this -> helper -> changeStatus ( $ orderId , "payment_review" , "payment_review" , $ jsonData -> payment -> status ) ; $ result = [ 'platform' => 'magento' , 'order_id' => $ order_id ] ; } } } if ( isset ( $ result ) ) { $ this -> logger -> debug ( json_encode ( $ result ) ) ; return json_encode ( $ result ) ; } else { $ this -> logger -> debug ( "KO. COULD NOT CREATE ORDER OR ADD PAYMENT" ) ; throw new \ Magento \ Framework \ Exception \ LocalizedException ( __ ( 'Could not create the order correctly.' ) ) ; } }
Run PayApi callback actions .
2,947
public function setClient ( ClientInterface $ client , $ prefix = null ) { $ this -> client = $ client ; $ this -> prefix = $ prefix ; }
Set the HTTP client that is used to access the API .
2,948
public function getObject ( IRI $ coid ) { if ( ! COIDParser :: isValidCOID ( $ coid ) ) throw new \ Exception ( "Not a valid COID." ) ; $ uriString = ( string ) $ coid ; if ( isset ( $ this -> objects [ $ uriString ] ) ) return $ this -> objects [ $ uriString ] ; $ ts = microtime ( true ) ; if ( isset ( $ this -> options [ 'static_config_path' ] ) ) { $ location = realpath ( $ this -> options [ 'static_config_path' ] . DIRECTORY_SEPARATOR . $ coid -> getHost ( ) . str_replace ( '/' , DIRECTORY_SEPARATOR , $ coid -> getPath ( ) ) . DIRECTORY_SEPARATOR . 'object.jsonld' ) ; if ( $ location && file_exists ( $ location ) ) { $ object = $ location ; $ this -> logInfoWithTime ( 'Fetched <' . $ uriString . '> from static configuration.' , $ ts ) ; } } if ( ! isset ( $ object ) ) { $ object = $ this -> getFromCache ( $ uriString ) ; if ( isset ( $ object ) ) $ this -> logInfoWithTime ( 'Fetched <' . $ uriString . '> from object cache.' , $ ts ) ; } if ( ! isset ( $ object ) ) { try { $ response = $ this -> client -> get ( ( isset ( $ this -> prefix ) ? $ this -> prefix : '' ) . $ coid -> getHost ( ) . $ coid -> getPath ( ) . '/object' , [ 'headers' => [ 'Accept' => 'application/ld+json' ] ] ) ; $ object = ( string ) $ response -> getBody ( ) ; $ this -> putIntoCache ( $ uriString , $ object , $ this -> options [ 'cache_ttl' ] ) ; $ this -> logInfoWithTime ( 'Fetched <' . $ uriString . '> from Core API [' . $ response -> getStatusCode ( ) . '].' , $ ts ) ; } catch ( \ Exception $ e ) { $ this -> logInfoWithTime ( 'Object <' . $ uriString . '> not found in Core API [' . $ e -> getResponse ( ) -> getStatusCode ( ) . '].' , $ ts ) ; return null ; } } $ document = JsonLD :: getDocument ( $ object ) ; $ this -> objects [ $ uriString ] = $ document -> getGraph ( ) -> getNode ( $ uriString ) ; return $ this -> objects [ $ uriString ] ; }
Get an object description from CloudObjects . Attempts to get object from in - memory cache first stored static configurations next configured external cache third and finally calls the Object API on CloudObjects Core . Returns null if the object was not found .
2,949
public function get ( $ coid ) { if ( is_string ( $ coid ) ) return $ this -> getObject ( new IRI ( $ coid ) ) ; if ( is_object ( $ coid ) && get_class ( $ coid ) == 'ML\IRI\IRI' ) return $ this -> getObject ( $ coid ) ; throw new \ Exception ( 'COID must be passed as a string or an IRI object.' ) ; }
Get an object description from CloudObjects . Shorthand method for getObject which allows passing the COID as string instead of IRI .
2,950
public function getAttachment ( IRI $ coid , $ filename ) { $ object = $ this -> getObject ( $ coid ) ; if ( ! $ object ) return null ; $ ts = microtime ( true ) ; $ cacheId = $ object -> getId ( ) . '#' . $ filename ; $ fileData = $ this -> getFromCache ( $ cacheId ) ; if ( isset ( $ fileData ) ) { $ this -> logInfoWithTime ( 'Fetched attachment <' . $ filename . '> for <' . $ object -> getId ( ) . '> from object cache.' , $ ts ) ; list ( $ fileRevision , $ fileContent ) = explode ( '#' , $ fileData , 2 ) ; } if ( ! isset ( $ fileData ) || $ fileRevision != $ object -> getProperty ( self :: REVISION_PROPERTY ) -> getValue ( ) ) { try { $ response = $ this -> client -> get ( ( isset ( $ this -> prefix ) ? $ this -> prefix : '' ) . $ coid -> getHost ( ) . $ coid -> getPath ( ) . '/' . basename ( $ filename ) ) ; $ fileContent = $ response -> getBody ( ) -> getContents ( ) ; $ fileData = $ object -> getProperty ( self :: REVISION_PROPERTY ) -> getValue ( ) . '#' . $ fileContent ; $ this -> putIntoCache ( $ cacheId , $ fileData , 0 ) ; $ this -> logInfoWithTime ( 'Fetched attachment <' . $ filename . '> for <' . $ object -> getId ( ) . '> from Core API [' . $ response -> getStatusCode ( ) . '].' , $ ts ) ; } catch ( \ Exception $ e ) { $ this -> logInfoWithTime ( 'Attachment <' . $ filename . '> for <' . $ object -> getId ( ) . '> not found in Core API [' . $ e -> getResponse ( ) -> getStatusCode ( ) . '].' , $ ts ) ; } } return $ fileContent ; }
Get a object s attachment .
2,951
public function getAuthenticatingNamespaceObject ( ) { if ( ! isset ( $ this -> options [ 'auth_ns' ] ) ) throw new \ Exception ( "Missing 'auth_ns' configuration option." ) ; $ namespaceCoid = COIDParser :: fromString ( $ this -> options [ 'auth_ns' ] ) ; if ( COIDParser :: getType ( $ namespaceCoid ) != COIDParser :: COID_ROOT ) throw new \ Exception ( "The 'auth_ns' configuration option is not a valid namespace/root COID." ) ; return $ this -> getObject ( $ namespaceCoid ) ; }
Retrieve the object that describes the namespace provided with the auth_ns configuration option .
2,952
public function loadThemes ( $ path ) { $ this -> themes = [ ] ; $ dirs = scandir ( $ path ) ; foreach ( $ dirs as $ file ) { if ( is_dir ( $ path . '/' . $ file ) && file_exists ( $ path . '/' . $ file . '/theme.json' ) ) { $ theme = json_decode ( file_get_contents ( $ path . '/' . $ file . '/theme.json' ) , true ) ; $ this -> themes [ $ theme [ 'slug' ] ] = $ theme ; } } }
Initial Loading Themes .
2,953
public function absolutePath ( $ theme = null ) { if ( is_null ( $ theme ) ) { $ theme = $ this -> getCurrent ( ) ; } return $ this -> config [ 'paths' ] [ 'absolute' ] . '/' . $ theme ; }
Get Theme Absolute Path .
2,954
public function path ( $ file , $ theme = null ) { if ( is_null ( $ theme ) ) { $ theme = $ this -> getCurrent ( ) ; } return $ this -> config [ 'paths' ] [ 'base' ] . "/$theme/$file" ; }
Get Theme File Path .
2,955
protected function parseConfig ( $ config ) { if ( array_key_exists ( 'paths' , $ config ) && array_key_exists ( 'absolute' , $ config [ 'paths' ] ) ) { $ this -> loadThemes ( $ config [ 'paths' ] [ 'absolute' ] ) ; } if ( array_key_exists ( 'active' , $ config ) ) { $ this -> setCurrent ( $ config [ 'active' ] ) ; } }
Parse Config to Object .
2,956
public function add ( $ child , $ type , array $ execOptions = array ( ) , array $ initOptions = array ( ) ) { if ( ! is_string ( $ child ) && ! is_int ( $ child ) ) { throw new \ InvalidArgumentException ( sprintf ( 'child name should be string or, integer' ) ) ; } if ( null !== $ type && ! is_string ( $ type ) && ! $ type instanceof JobTypeinterface ) { throw new \ InvalidArgumentException ( 'type should be string or JobTypeinterface' ) ; } $ this -> children [ $ child ] = null ; $ this -> unresolvedChildren [ $ child ] = array ( 'type' => $ type , 'init_options' => $ initOptions , 'exec_options' => $ execOptions ) ; return $ this ; }
Add sub job to a job
2,957
public function create ( $ name , $ type = null , array $ initOptions = array ( ) , array $ execOptions = array ( ) ) { if ( null === $ type ) { $ type = 'job' ; } return $ this -> getJobFactory ( ) -> createNamedBuilder ( $ name , $ type , $ initOptions , $ execOptions ) ; }
Create new JobBuilder
2,958
public function getJob ( ) { $ this -> resolveChildren ( ) ; $ job = new Job ( $ this -> getJobConfig ( ) ) ; foreach ( $ this -> children as $ child ) { $ job -> add ( $ child -> getJob ( ) ) ; } return $ job ; }
Create the job with all children configure
2,959
public function set_gliver_fr_controller_trait_properties ( ) { $ this -> request_start_time = Registry :: $ gliver_app_start ; $ this -> site_title = Registry :: getConfig ( ) [ 'title' ] ; return $ this ; }
this method sets the basic app properties in controller
2,960
public function buildArgumentExpression ( Field $ field , $ index ) { $ type = $ field -> getType ( ) ; if ( isset ( $ type ) ) return '#{' . "$index:$type" . '}' ; return '#{' . $ index . '}' ; }
Returns an expression for a given argument index
2,961
public function createCache ( $ name ) : Cache { if ( ! $ this -> cacheExists ( $ name ) ) { $ this -> ensureCacheDir ( ) ; $ cache = $ this -> app -> make ( Cache :: class ) ; $ cache -> setName ( $ name ) ; $ cache -> createCacheDir ( ) ; $ this -> caches [ $ name ] = $ cache ; } return $ this -> caches [ $ name ] ; }
Creates a new cache .
2,962
public function getCache ( $ name ) : Cache { return $ this -> cacheExists ( $ name ) ? $ this -> caches [ $ name ] : $ this -> createCache ( $ name ) ; }
Gets a cache .
2,963
public static function isValidURL ( string $ url , bool $ query = false ) : bool { if ( true === $ query && ! filter_var ( $ url , FILTER_VALIDATE_URL , FILTER_FLAG_QUERY_REQUIRED ) === false ) { return true ; } if ( ! filter_var ( $ url , FILTER_VALIDATE_URL ) === false ) { return true ; } return false ; }
Check if URL is valid
2,964
public static function isValidEmail ( string $ email , bool $ sanitize = true ) : bool { if ( true === $ sanitize ) { $ email = filter_var ( $ email , FILTER_SANITIZE_EMAIL ) ; } return ! filter_var ( $ email , FILTER_VALIDATE_EMAIL ) === false ; }
Simple email validation
2,965
public function getEntitiesConfig ( $ entity_names = null , $ merge_standard = true ) { $ configured_entities = $ this -> setup -> getSynchronizerConfig ( 'entities' ) ; $ configured_entities = array_merge_recursive ( $ entity_names ) ; if ( $ entity_names === null ) { } else { } }
Return entity configuration
2,966
public function synchronize ( array $ entity_names ) { $ entities = $ this -> setup -> getMappedSyncEntities ( $ entity_names ) ; foreach ( $ entities as $ name => $ entity ) { $ cls = $ entity [ 'class' ] ; $ syncEntity = new $ cls ( $ this -> dbExecuter , $ this -> setup ) ; $ syncEntity -> setLegacySynchroAt ( $ this -> legacy_synchro_at ) ; $ syncEntity -> synchronize ( ) ; } }
Synchronize entities from config file
2,967
public function synchronizeDiscountCondition ( ) { $ akilia1Db = $ this -> akilia1Db ; $ db = $ this -> openstoreDb ; $ replace = " insert into $db.discount_condition( pricelist_id, customer_id, customer_group_id, brand_id, product_group_id, category_id, model_id, product_id, fixed_price, discount_1, discount_2, discount_3, discount_4, valid_from, valid_till, legacy_mapping, legacy_synchro_at ) select DISTINCT pl.pricelist_id, c.customer_id, cg.group_id as customer_group_id, pb.brand_id, pg.group_id as product_group_id, null as category_id, null as model_id, p.product_id, null as fixed_price, COALESCE(r.remise1, 0) as discount_1, COALESCE(r.remise2, 0) as discount_2, COALESCE(r.remise3, 0) as discount_3, COALESCE(r.remise4, 0) as discount_4, null as valid_from, null as valid_till, CONCAT_WS('&', CONCAT('pl:', COALESCE(pl.pricelist_id, '*')), -- no pricelist CONCAT('c:', COALESCE(c.customer_id , '*')), -- no customer CONCAT('cg:', COALESCE(cg.group_id , '*')), -- no customer_group CONCAT('pb:', COALESCE(pb.brand_id , '*')), -- no product_brand CONCAT('pg:', COALESCE(pg.group_id , '*')), -- no product_group CONCAT('pc:', COALESCE(null , '*')), -- no product_category CONCAT('pm:', COALESCE(null , '*')), -- no product_model CONCAT('p:', COALESCE(p.product_id , '*')), -- no product CONCAT('from:', COALESCE(null , '*')), -- valid_from CONCAT('till:', COALESCE(null , '*')) -- valid_till ) as legacy_mapping, '{$this->legacy_synchro_at}' as legacy_synchro_at from $akilia1Db.remises r inner join $db.customer c on c.legacy_mapping = r.id_client left outer join $db.product_brand pb on pb.legacy_mapping = r.id_marque left outer join $db.product_group pg on pg.legacy_mapping = r.id_famille left outer join $db.product p on p.legacy_mapping = r.id_article left outer join $db.pricelist pl on pl.legacy_mapping = r.code_tarif left outer join $db.customer_group cg on cg.legacy_mapping = r.id_groupe_client where (pl.flag_enable_discount_condition = 1 or pl.flag_enable_discount_condition is null) order by cg.group_id, c.customer_id, pl.pricelist_id, pb.brand_id, pg.group_id, p.product_id on duplicate key update discount_1 = COALESCE(r.remise1, 0), discount_2 = COALESCE(r.remise2, 0), discount_3 = COALESCE(r.remise3, 0), discount_4 = COALESCE(r.remise4, 0), fixed_price = null, -- not supported yet legacy_synchro_at = '{$this->legacy_synchro_at}' " ; $ this -> executeSQL ( "Replace discount conditions" , $ replace ) ; $ delete = " delete from $db.discount_condition where legacy_synchro_at <> '{$this->legacy_synchro_at}' and legacy_synchro_at is not null" ; $ this -> executeSQL ( "Delete eventual removed discount conditions" , $ delete ) ; }
Synchronize discount conditions
2,968
public static function bool ( int $ strength = self :: STRENGTH_MEDIUM ) : bool { return ( bool ) ( ord ( static :: bytes ( 1 , $ strength ) ) % 2 ) ; }
Generates a pseudo - random boolean value .
2,969
public function getRouteParts ( ) { if ( ! isset ( $ this -> _routeParts ) && isset ( $ this -> route ) ) { $ this -> _routeParts = explode ( '/' , ltrim ( $ this -> route , '/' ) ) ; if ( $ this -> _routeParts [ count ( $ this -> _routeParts ) - 1 ] === 'index' ) { array_pop ( $ this -> _routeParts ) ; } } if ( ! isset ( $ this -> _routeParts ) ) { return [ ] ; } return $ this -> _routeParts ; }
Get route parts .
2,970
public function commit ( ) { if ( $ this -> _transactionDepth === 0 ) { throw new PDOException ( 'Rollback error : There is no transaction started' ) ; } $ this -> _transactionDepth -- ; if ( $ this -> _transactionDepth === 0 ) { parent :: commit ( ) ; } else { $ this -> exec ( "RELEASE SAVEPOINT LEVEL{$this->_transactionDepth}" ) ; } }
Commit current transaction
2,971
public static function set ( $ key , $ value = false ) { self :: setPrefix ( ) ; if ( is_array ( $ key ) && $ value === false ) { foreach ( $ key as $ name => $ value ) { $ _SESSION [ self :: $ _sessionPrefix . $ name ] = $ value ; } } else { $ _SESSION [ self :: $ _sessionPrefix . $ key ] = $ value ; } }
Add value to a session
2,972
public static function pull ( $ key ) { self :: setPrefix ( ) ; $ value = $ _SESSION [ self :: $ _sessionPrefix . $ key ] ; unset ( $ _SESSION [ self :: $ _sessionPrefix . $ key ] ) ; return $ value ; }
Extract item from session then delete from the session finally return the item
2,973
public static function get ( $ key , $ secondKey = false ) { self :: setPrefix ( ) ; if ( $ secondKey == true ) { if ( isset ( $ _SESSION [ self :: $ _sessionPrefix . $ key ] [ $ secondKey ] ) ) { return $ _SESSION [ self :: $ _sessionPrefix . $ key ] [ $ secondKey ] ; } } else { if ( isset ( $ _SESSION [ self :: $ _sessionPrefix . $ key ] ) ) { return $ _SESSION [ self :: $ _sessionPrefix . $ key ] ; } } return false ; }
Get item from session
2,974
public static function destroy ( $ key = '' ) { if ( self :: $ _sessionStarted == true ) { if ( empty ( $ key ) ) { session_unset ( ) ; session_destroy ( ) ; } else { self :: setPrefix ( ) ; unset ( $ _SESSION [ self :: $ _sessionPrefix . $ key ] ) ; } } }
Empties and destroys the session
2,975
public function create ( DomainForm $ form ) : Domain { $ model = Domain :: create ( $ form -> name , $ form -> alias , $ form -> url ) ; $ this -> repository -> save ( $ model ) ; return $ model ; }
Domain item create .
2,976
public function edit ( $ id , DomainForm $ form ) : void { $ model = $ this -> repository -> get ( $ id ) ; $ model -> edit ( $ form -> name , $ form -> alias , $ form -> url ) ; $ this -> repository -> save ( $ model ) ; }
Domain item edit .
2,977
public function remove ( $ id ) : void { $ model = $ this -> repository -> get ( $ id ) ; $ this -> repository -> remove ( $ model ) ; }
Domain item remove .
2,978
public function results ( ) { $ out = [ '' ] ; $ total = $ this -> runner -> totalCount ; $ passed = count ( $ this -> runner -> passed ) ; $ failures = count ( $ this -> runner -> failures ) ; $ errors = count ( $ this -> runner -> errors ) ; $ skipped = count ( $ this -> runner -> skipped ) ; $ results = [ ] ; $ results [ ] = $ this -> green ( self :: INDICATOR ) . ' Passes ' . $ passed ; $ results [ ] = $ this -> red ( self :: INDICATOR ) . ' Failures ' . $ failures ; $ results [ ] = $ this -> yellow ( self :: INDICATOR ) . ' Errors ' . $ errors ; $ results [ ] = $ this -> magenta ( self :: INDICATOR ) . ' Skipped ' . $ skipped ; $ box = new Box ( $ results , [ 'borderColor' => self :: YELLOW , 'paddingX' => 1 , ] ) ; $ box -> setTitle ( 'Results' ) ; $ out [ ] = $ box ; foreach ( $ this -> runner -> failures as $ test ) { $ out [ ] = '' ; $ out [ ] = $ this -> red ( 'FAILED - ' . $ test -> name ) ; $ out [ ] = $ test -> getFailureMessage ( ) ; } foreach ( $ this -> runner -> errors as $ test ) { $ out [ ] = '' ; $ out [ ] = $ this -> yellow ( 'ERROR - ' . $ test -> name ) ; $ out [ ] = $ test -> getErrorMessage ( ) ; } $ count = $ this -> green ( "$passed / $total" ) ; if ( $ passed !== $ total ) { $ count = $ this -> red ( "$passed / $total" ) ; } $ out [ ] = '' ; $ out [ ] = "$count tests passed successfully." ; echo $ this -> render ( implode ( "\n" , $ out ) ) ; if ( $ this -> runner -> options -> coverage -> enable === true ) { echo "\n" ; echo $ this -> gray -> render ( 'Calculating Coverage...' ) ; echo "\n" ; $ this -> runner -> coverage -> calculate ( ) ; echo $ this -> runner -> coverage -> output ( ) ; } exit ( ( int ) ( $ passed !== $ total ) ) ; }
Print test results to the command line .
2,979
public function help ( ) { $ this -> setGlobalIndent ( 0 ) ; echo $ this -> yellow -> render ( 'Usage:' ) ; echo $ this ( ' phillip [options] [file|directory]' ) ; echo $ this ( '' ) ; echo $ this -> yellow -> render ( 'Options:' ) ; echo $ this ( ' -h, --help Show help text and exit.' ) ; echo $ this ( ' -v, --version Show version information and exit.' ) ; echo $ this ( ' -c, --coverage Show coverage data.' ) ; echo $ this ( ' -s, --suite <suite> Run a predefined test suite.' ) ; echo $ this ( ' -r, --random Run tests within each suite in random order.' ) ; }
Print help text to the command line .
2,980
public function version ( ) { $ this -> setGlobalIndent ( 0 ) ; $ version = file_get_contents ( __DIR__ . '/../../.version' ) ; echo $ this -> yellow -> render ( 'Phillip' ) ; echo $ this ( 'Version ' . trim ( $ version ) ) ; }
Print version information to the command line .
2,981
public function updateTable ( $ x , $ y , $ color ) { $ this -> goToXY ( $ x , $ y ) ; echo $ this -> setColor ( $ color ) -> encode ( self :: INDICATOR ) ; $ this -> x ++ ; $ this -> goToXY ( $ this -> xMax , $ this -> yMax ) ; }
Update the table with a color to show test state .
2,982
public function goToXY ( $ x , $ y ) { if ( $ this -> x < $ x ) { while ( $ this -> x < $ x ) { echo self :: RIGHT_KEYPRESS ; $ this -> x ++ ; } } if ( $ this -> x > $ x ) { while ( $ this -> x > $ x ) { echo self :: LEFT_KEYPRESS ; $ this -> x -- ; } } if ( $ this -> y > $ y ) { while ( $ this -> y > $ y ) { echo self :: UP_KEYPRESS ; $ this -> y -- ; } } if ( $ this -> y < $ y ) { while ( $ this -> y < $ y ) { echo self :: DOWN_KEYPRESS ; $ this -> y ++ ; } } }
Go to defined X Y coordinates in the terminal output .
2,983
private function getLineWidth ( ) { $ line_width = isset ( $ _ENV [ 'COLUMNS' ] ) && $ _ENV [ 'COLUMNS' ] ? $ _ENV [ 'COLUMNS' ] : 0 ; if ( $ line_width === 0 ) { $ line_width = exec ( 'tput cols' ) ; } return $ line_width ; }
Get the line width of the current terminal .
2,984
public function setValue ( $ value ) : void { if ( is_object ( $ value ) && ! ( $ value instanceof ArrayObject ) ) { $ this -> class = $ value ; if ( isset ( $ this -> value ) ) { $ old = clone $ this -> value ; $ work = clone $ value ; if ( $ work instanceof JsonSerializable ) { $ work = $ work -> jsonSerialize ( ) ; } foreach ( $ work as $ prop => $ status ) { $ value -> $ prop = isset ( $ old -> $ prop ) ? $ old -> $ prop : false ; } } $ this -> value = $ value ; } if ( ! isset ( $ this -> value ) ) { $ this -> value = clone $ this -> class ; } if ( is_array ( $ value ) || $ value instanceof ArrayObject ) { $ work = clone $ this -> value ; if ( $ work instanceof JsonSerializable ) { $ work = $ work -> jsonSerialize ( ) ; } foreach ( $ work as $ prop => $ status ) { $ this -> value -> $ prop = false ; } foreach ( $ value as $ prop ) { if ( is_string ( $ prop ) && $ this -> hasBit ( $ prop ) && isset ( $ this -> value -> $ prop ) ) { $ this -> value -> $ prop = true ; } } } $ found = [ ] ; foreach ( ( array ) $ this as $ element ) { if ( $ element -> getElement ( ) instanceof Hidden ) { continue ; } $ check = $ element -> getElement ( ) -> getValue ( ) ; if ( isset ( $ this -> value -> $ check ) && $ this -> value -> $ check ) { $ element -> getElement ( ) -> check ( ) ; } else { $ element -> getElement ( ) -> check ( false ) ; } $ found [ ] = $ check ; } }
Set the current value .
2,985
public function getValue ( ) : ArrayObject { $ array = [ ] ; foreach ( $ this as $ value ) { if ( $ value instanceof Hidden ) { continue ; } if ( $ value -> getElement ( ) -> checked ( ) ) { $ array [ ] = $ value -> getElement ( ) -> getValue ( ) ; } } return new ArrayObject ( $ array ) ; }
Get the current value .
2,986
public function getByteValue ( ) : int { $ bits = ( array ) $ this -> getValue ( ) ; return array_reduce ( $ bits , function ( $ carry , $ item ) { return $ carry | ( int ) $ item ; } , 0 ) ; }
Return the value of the element as a byte .
2,987
public function push ( Identity $ identity , object $ entity , State $ wished ) : self { if ( ! $ this -> states -> contains ( $ wished ) ) { throw new DomainException ; } $ this -> states = $ this -> states -> map ( static function ( State $ state , MapInterface $ entities ) use ( $ identity , $ entity , $ wished ) { if ( $ wished === $ state ) { return $ entities -> put ( $ identity , $ entity ) ; } return $ entities -> remove ( $ identity ) ; } ) ; return $ this ; }
Inject the given entity with the wished state
2,988
public function detach ( Identity $ identity ) : self { $ this -> states = $ this -> states -> map ( static function ( State $ state , MapInterface $ entities ) use ( $ identity ) { return $ entities -> remove ( $ identity ) ; } ) ; return $ this ; }
Remove the entity with the given identity from any state
2,989
public function stateFor ( Identity $ identity ) : State { foreach ( $ this -> states as $ state => $ entities ) { if ( $ entities -> contains ( $ identity ) ) { return $ state ; } } throw new IdentityNotManaged ; }
Return the state for the given identity
2,990
public function get ( Identity $ identity ) : object { return $ this -> states -> get ( $ this -> stateFor ( $ identity ) ) -> get ( $ identity ) ; }
Return the entity with the given identity
2,991
public function contains ( Identity $ identity ) : bool { try { $ this -> stateFor ( $ identity ) ; return true ; } catch ( IdentityNotManaged $ e ) { return false ; } }
Check if the given identity if known by the container
2,992
public function isConfigValid ( array $ config ) { $ isValid = true ; foreach ( $ this -> configValidators as $ configValidator ) { $ configName = $ configValidator -> getConfigName ( ) ; if ( ! isset ( $ config [ $ configName ] ) ) { throw new InvalidImageConfigException ( sprintf ( 'Invalid image config: %s' , $ configName ) ) ; } $ isValid = $ isValid && $ configValidator -> validate ( $ config [ $ configName ] , $ this -> defaultConfig ) ; } return $ isValid ; }
Check if image config is valid .
2,993
public static function Pvtob ( $ elong , $ phi , $ hm , $ xp , $ yp , $ sp , $ theta , array & $ pv ) { $ OM = 1.00273781191135448 * D2PI / DAYSEC ; $ xyzm = [ ] ; $ rpm = [ ] ; $ xyz = [ ] ; $ x ; $ y ; $ z ; $ s ; $ c ; IAU :: Gd2gc ( iauRefEllips :: WGS84 ( ) , $ elong , $ phi , $ hm , $ xyzm ) ; IAU :: Pom00 ( $ xp , $ yp , $ sp , $ rpm ) ; IAU :: Trxp ( $ rpm , $ xyzm , $ xyz ) ; $ x = $ xyz [ 0 ] ; $ y = $ xyz [ 1 ] ; $ z = $ xyz [ 2 ] ; $ s = sin ( $ theta ) ; $ c = cos ( $ theta ) ; $ pv [ 0 ] [ 0 ] = $ c * $ x - $ s * $ y ; $ pv [ 0 ] [ 1 ] = $ s * $ x + $ c * $ y ; $ pv [ 0 ] [ 2 ] = $ z ; $ pv [ 1 ] [ 0 ] = $ OM * ( - $ s * $ x - $ c * $ y ) ; $ pv [ 1 ] [ 1 ] = $ OM * ( $ c * $ x - $ s * $ y ) ; $ pv [ 1 ] [ 2 ] = 0.0 ; }
- - - - - - - - - i a u P v t o b - - - - - - - - -
2,994
private function getPointInBox ( array $ imageSize , array $ boxSize ) { $ width = 0 ; $ height = 0 ; list ( $ imageWidth , $ imageHeight ) = $ imageSize ; list ( $ boxWidth , $ boxHeight ) = $ boxSize ; if ( $ imageWidth < $ boxWidth ) { $ width = floor ( ( $ boxWidth - $ imageWidth ) / 2 ) ; } if ( $ imageHeight < $ boxHeight ) { $ height = floor ( ( $ boxHeight - $ imageHeight ) / 2 ) ; } return new Point ( $ width , $ height ) ; }
Get point in box .
2,995
public function set ( $ controller , $ data ) { $ id = microtime ( true ) . '_' . uniqid ( '_' , true ) . '.mq' ; $ item = [ 'id' => $ id , 'controller' => $ controller , 'data' => $ data , ] ; $ id_file = $ this -> _save_path . $ id ; file_put_contents ( $ id_file , json_encode ( $ item ) ) ; if ( ! is_file ( $ this -> _lockfile ) ) { file_put_contents ( $ this -> _lockfile , '' ) ; $ command = $ this -> _cli_path . ' ' . getcwd ( ) . '/index.php' . ' ' . $ controller . ' _morrow_messagequeue_startworker=true' ; $ this -> _execInBackground ( $ command ) ; } return $ id ; }
Enqueues a new Job in the message queue .
2,996
public function get ( $ id ) { if ( ! isset ( $ id ) ) throw new \ Exception ( 'ID for job is missing.' ) ; $ id_file = $ this -> _save_path . $ id ; if ( ! is_file ( $ id_file ) ) throw new \ Exception ( 'Job file for ID is missing.' ) ; $ item = json_decode ( file_get_contents ( $ id_file ) , true ) ; return $ item ; }
Retrieves the job data for an id .
2,997
public function process ( ) { $ job_id = $ this -> _input -> get ( '_morrow_messagequeue_id' ) ; if ( $ job_id !== null ) { $ job = $ this -> get ( $ job_id ) ; foreach ( $ job [ 'data' ] as $ key => $ value ) { $ this -> _input -> set ( $ key , $ value ) ; } return false ; } $ files = glob ( $ this -> _save_path . '*.mq' ) ; while ( count ( $ files ) > 0 ) { sort ( $ files ) ; $ item = json_decode ( file_get_contents ( $ files [ 0 ] ) , true ) ; $ command = $ this -> _cli_path . ' ' . getcwd ( ) . '/index.php' . ' ' . $ item [ 'controller' ] . ' _morrow_messagequeue_id=' . $ item [ 'id' ] ; exec ( $ command , $ output , $ return_var ) ; unlink ( $ files [ 0 ] ) ; $ files = glob ( $ this -> _save_path . '*.mq' ) ; } unlink ( $ this -> _lockfile ) ; return true ; }
Starts the worker which processes all enqueued jobs . If it could not be started the job data will be passed to the \ Morrow \ Input class .
2,998
private function flushBuffer ( ) { $ bufferLength = $ this -> numberOfBytes ( $ this -> buffer ) ; if ( $ bufferLength == 0 ) { return ; } $ bytesWritten = $ this -> decoratedObject -> write ( $ this -> buffer ) ; if ( $ bytesWritten < $ bufferLength ) { throw new \ RuntimeException ( sprintf ( 'Expected to flush buffer of %d bytes but only %d bytes were written.' , $ bufferLength , $ bytesWritten ) ) ; } $ this -> buffer = '' ; }
Writes all buffered bytes to the stream and clears the buffer .
2,999
public static function boot ( $ base_path , array $ options = [ ] ) { $ name = plugin_basename ( $ base_path ) ; if ( isset ( static :: $ instances [ $ name ] ) ) { throw new Exception ( sprintf ( 'Cannot boot `%s` again' , $ name ) ) ; } $ instance = new static ( $ base_path , $ options ) ; add_action ( $ instance -> get_action ( ) , function ( ) use ( $ instance , $ name ) { return static :: $ instances [ $ name ] = $ instance -> load_files ( ) -> get_instance ( ) ; } ) ; }
Boot the plugin .