idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
54,400
public function Success ( $ params = FALSE ) { if ( $ params ) { $ this -> result = array_merge ( $ this -> result , $ params ) ; } $ this -> result [ 'status' ] = 'ok' ; return TRUE ; }
Set a result success status
54,401
public function callInit ( $ module , $ method , $ args ) { if ( $ this -> api -> isAuthenticated ( ) ) { if ( ! $ this -> api -> user -> checkPermission ( $ module , $ method ) ) { return $ this -> Error ( 'invalid permission' ) ; } } return TRUE ; }
Executed before the module method call
54,402
protected function retryDecider ( ) { return function ( $ retries , RequestInterface $ request , ResponseInterface $ response = null ) { if ( $ retries >= $ this -> getMaxRetries ( ) ) { return false ; } $ shouldRetry = false ; if ( isset ( $ response ) && $ response -> getStatusCode ( ) >= 500 ) { $ shouldRetry = true ; } if ( $ shouldRetry ) { $ this -> logNotice ( sprintf ( 'Retrying %s %s %s/%s, %s' , $ request -> getMethod ( ) , $ request -> getUri ( ) , $ retries + 1 , $ this -> getMaxRetries ( ) , $ response ? 'status code: ' . $ response -> getStatusCode ( ) : '' ) ) ; } return $ shouldRetry ; } ; }
Determine whether the request needs to be retried or not
54,403
public function buildRoutes ( array $ routes ) { foreach ( $ routes as $ key => $ val ) { $ routes [ $ key ] [ 'name' ] = $ key ; $ routeObj = new Route ( $ routes [ $ key ] ) ; $ newRouteObjs [ ] = $ routeObj ; } return $ newRouteObjs ; }
Build Route object for each route
54,404
public function getRoute ( $ path = "" , $ name = "" ) { for ( $ i = 0 ; $ i < count ( $ this -> routes ) ; $ i ++ ) { $ checkRoute = $ this -> routes [ $ i ] ; if ( $ checkRoute -> getName ( ) === $ name || $ checkRoute -> getPath ( ) === $ path ) { return $ checkRoute ; } else if ( $ checkRoute -> getRegex ( ) != null ) { $ regex = $ checkRoute -> getRegex ( ) ; if ( preg_match ( $ regex , $ path ) ) { preg_match_all ( '/\/(\w+)/' , '/' . ltrim ( $ path , $ checkRoute -> getStaticPath ( ) ) , $ matches , PREG_SET_ORDER ) ; foreach ( $ matches as $ match ) { $ values [ ] = $ match [ 1 ] ; } $ checkRoute -> setValues ( $ values ) ; return $ checkRoute ; } } } return false ; }
Search the application routes
54,405
public function getControllerPath ( Route $ route ) { $ startDir = $ this -> paths [ 'src' ] . '/Controller/' ; if ( $ route -> getControllerPath ( ) != null ) { $ fullPath = $ startDir . $ route -> getControllerPath ( ) . '/' . $ route -> getController ( ) ; } else { $ fullPath = $ startDir . $ route -> getController ( ) ; } if ( file_exists ( $ fullPath ) ) { return $ fullPath ; } else { throw new \ Exception ( "Controller not found at path " . $ fullPath ) ; } }
Gets the path to the routes controller
54,406
public function initController ( $ controller , $ path ) { if ( $ path ) { $ controller = $ this -> name . '\\Controller\\' . $ path . '\\' . $ controller ; } else { $ controller = $ this -> name . '\\Controller\\' . $ controller ; } return new $ controller ( ) ; }
Initializes a new instance of a controller
54,407
public function runController ( $ controller = null , $ action = null , $ values = array ( ) ) { if ( $ action != null && method_exists ( $ controller , $ action ) ) { if ( $ values != null ) { call_user_func_array ( array ( $ controller , $ action ) , $ values ) ; } else { $ controller -> { $ action } ( ) ; } } else { $ controller ; } }
Runs a given controller
54,408
public function loadRoute ( $ uri ) { $ route = $ this -> getRoute ( $ uri ) ; if ( $ route ) { $ controllerPath = $ this -> getControllerPath ( $ route ) ; if ( $ controllerPath ) { require $ controllerPath ; $ controller = $ this -> initController ( $ route -> getControllerName ( ) , $ route -> getControllerPath ( ) ) ; $ this -> runController ( $ controller , $ route -> getAction ( ) , $ route -> getValues ( ) ) ; } } else { throw new \ Exception ( "No route was found that matched the requested URI." , 1 ) ; } }
Loads the route based one the URL
54,409
public function makeRequest ( $ method , array $ path = array ( ) , array $ headers = array ( ) , $ parameters = array ( ) ) { $ this -> authenticate ( ) ; return $ this -> makeRealRequest ( $ this -> client , $ method , $ this -> getPathFromArray ( $ path ) , $ parameters , $ headers ) ; }
Performs an http request to the storage .
54,410
public function makeCdnRequest ( $ method , array $ path = array ( ) , array $ headers = array ( ) ) { $ this -> authenticate ( ) ; if ( ! $ this -> getCdnEnabled ( ) ) { throw new Exceptions \ CDNNotEnabled ( ) ; } return $ this -> makeRealRequest ( $ this -> cdnClient , $ method , $ this -> getPathFromArray ( $ path ) , $ headers ) ; }
Performs an http request to the CDN .
54,411
public function getAccountInfo ( ) { $ response = $ this -> makeRequest ( Client :: HEAD ) ; $ nbContainers = 0 ; $ totalSize = 0 ; $ metadata = array ( ) ; foreach ( $ response [ 'headers' ] as $ name => $ value ) { $ name = strtolower ( $ name ) ; if ( 0 === strcmp ( $ name , 'x-account-container-count' ) ) { $ nbContainers = intval ( $ value ) ; } elseif ( 0 === strcmp ( $ name , 'x-account-bytes-used' ) ) { $ totalSize = intval ( $ value ) ; } elseif ( 0 === strpos ( $ name , 'x-account-meta-' ) ) { $ metadata [ substr ( $ name , 15 ) ] = $ value ; } } return array ( $ nbContainers , $ totalSize , $ metadata ) ; }
Return array with number of containers total bytes in the account and account metadata .
54,412
public function createContainer ( $ name , $ errorOnExisting = false ) { $ this -> validateContainerName ( $ name ) ; $ response = $ this -> makeRequest ( Client :: PUT , array ( $ name ) , array ( 'Content-Length' => 0 ) ) ; if ( $ errorOnExisting && 202 == $ response [ 'status' ] ) { throw new Exceptions \ ContainerExists ( $ name ) ; } return new Container ( $ this , $ name ) ; }
Create new container .
54,413
public function deleteContainer ( $ container ) { if ( is_object ( $ container ) && $ container instanceof Container ) { $ name = $ container -> getName ( ) ; } else { $ name = strval ( $ container ) ; } $ this -> validateContainerName ( $ name ) ; try { $ this -> makeRequest ( Client :: DELETE , array ( $ name ) ) ; } catch ( Exceptions \ ResponseError $ e ) { switch ( $ e -> getCode ( ) ) { case 409 : throw new Exceptions \ ContainerNotEmpty ( $ name ) ; break ; case 404 : throw new Exceptions \ NoSuchContainer ( ) ; break ; default : throw $ e ; break ; } } if ( $ this -> getCdnEnabled ( ) ) { $ this -> makeCdnRequest ( Client :: POST , array ( $ name ) , array ( 'X-CDN-Enabled' => 'False' , ) ) ; } }
Delete container .
54,414
public function getContainer ( $ name ) { $ this -> validateContainerName ( $ name ) ; try { $ response = $ this -> makeRequest ( Client :: HEAD , array ( $ name ) ) ; } catch ( Exceptions \ ResponseError $ e ) { if ( 404 == $ e -> getCode ( ) ) { throw new Exceptions \ NoSuchContainer ( ) ; } throw $ e ; } $ nbObjects = $ response [ 'headers' ] [ 'x-container-object-count' ] ; $ sizeUsed = $ response [ 'headers' ] [ 'x-container-bytes-used' ] ; $ metadata = array ( ) ; foreach ( $ response [ 'headers' ] as $ k => $ value ) { if ( 0 === strpos ( $ k , 'x-container-meta-' ) ) { $ metadata [ substr ( $ k , 17 ) ] = $ value ; } } return new Container ( $ this , $ name , $ nbObjects , $ sizeUsed , $ metadata ) ; }
Return container object .
54,415
public function getContainers ( array $ parameters = array ( ) ) { $ result = array ( ) ; foreach ( $ this -> getContainersInfo ( $ parameters ) as $ info ) { $ result [ ] = new Container ( $ this , $ info [ 'name' ] , $ info [ 'count' ] , $ info [ 'bytes' ] ) ; } return $ result ; }
Return array with containers .
54,416
public function getPublicContainersList ( ) { if ( ! $ this -> getCdnEnabled ( ) ) { throw new Exceptions \ CDNNotEnabled ( ) ; } $ response = $ this -> makeCdnRequest ( Client :: GET ) ; return explode ( "\n" , trim ( $ response [ 'body' ] ) ) ; }
Return names of public containers .
54,417
protected function getPathFromArray ( array $ path = array ( ) ) { $ tmp = array ( ) ; foreach ( $ path as $ value ) { $ tmp [ ] = rawurlencode ( $ value ) ; } return sprintf ( '/%s/%s' , rtrim ( $ this -> connectionUrlInfo [ 'path' ] , '/' ) , str_replace ( '%2F' , '/' , implode ( '/' , $ tmp ) ) ) ; }
Generate path for query string .
54,418
protected function authenticate ( ) { if ( ! $ this -> isAuthenticated ) { list ( $ url , $ this -> cdnUrl , $ this -> authToken ) = $ this -> auth -> authenticate ( ) ; if ( $ this -> useServicenet ) { $ url = str_replace ( 'https://' , 'https://snet-%s' , $ url ) ; } $ this -> connectionUrlInfo = Utils :: parseUrl ( $ url ) ; $ this -> httpConnect ( ) ; if ( $ this -> cdnUrl ) { $ this -> cdnConnect ( ) ; } $ this -> isAuthenticated = true ; } }
Authenticate and setup this instance with the values returned .
54,419
protected function httpConnect ( ) { $ this -> client = new Client ( array ( 'timeout' => $ this -> timeout ) ) ; $ this -> client -> setUserAgent ( $ this -> userAgent ) ; $ this -> client -> setBaseURL ( sprintf ( '%s://%s:%d' , $ this -> connectionUrlInfo [ 'scheme' ] , $ this -> connectionUrlInfo [ 'host' ] , $ this -> connectionUrlInfo [ 'port' ] ) ) ; }
Setup the http connection instance .
54,420
protected function cdnConnect ( ) { $ info = Utils :: parseUrl ( $ this -> cdnUrl ) ; $ this -> cdnEnabled = true ; $ this -> cdnClient = new Client ( array ( 'timeout' => $ this -> timeout ) ) ; $ this -> cdnClient -> setUserAgent ( $ this -> userAgent ) ; $ this -> cdnClient -> setBaseURL ( sprintf ( '%s://%s:%d' , $ info [ 'scheme' ] , $ info [ 'host' ] , $ info [ 'port' ] ) ) ; }
Setup the http connection instance for the CDN service .
54,421
protected function makeRealRequest ( Client $ client , $ method , $ path , $ parameters = array ( ) , array $ headers = array ( ) ) { $ headers [ 'X-Auth-Token' ] = $ this -> authToken ; return $ client -> sendRequest ( $ path , $ method , $ parameters , $ headers ) ; }
Performs the real http request .
54,422
protected function validateContainerName ( $ name ) { if ( empty ( $ name ) || ( false !== strpos ( $ name , '/' ) ) || strlen ( $ name ) > CONTAINER_NAME_LIMIT ) { throw new Exceptions \ InvalidContainerName ( ) ; } }
Validates the container name .
54,423
protected function getContainersRawData ( array $ parameters = array ( ) ) { $ cacheKey = md5 ( json_encode ( $ parameters ) ) ; if ( ! array_key_exists ( $ cacheKey , self :: $ listContainersCache ) ) { $ tmp = array ( ) ; foreach ( $ parameters as $ k => $ v ) { if ( in_array ( $ k , self :: $ allowedParameters ) ) { $ tmp [ $ k ] = $ v ; } } $ response = $ this -> makeRequest ( Client :: GET , array ( ) , array ( ) , $ tmp ) ; self :: $ listContainersCache [ $ cacheKey ] = $ response [ 'body' ] ; } return self :: $ listContainersCache [ $ cacheKey ] ; }
Return a raw response string with containers data .
54,424
public function https ( $ enable = true ) { $ this -> gravatar -> setUseHTTPS ( ) ; if ( ! $ enable ) { $ this -> gravatar -> setUseHTTP ( ) ; } return $ this ; }
Returns a HTTPS formatted URL instead ideal for sites that implement HTTPS and do not wish to trigger SSL warnings regarding some content on this page is not encrytped .
54,425
public function getStrategy ( $ id ) { if ( isset ( $ this -> strategies [ $ id ] ) ) { return $ this -> strategies [ $ id ] ; } if ( ! isset ( $ this -> availableStrategies [ $ id ] ) ) { throw new InvalidArgumentException ( "Auth strategy '$id' does not exist or has not been registered." ) ; } $ class = $ this -> availableStrategies [ $ id ] ; $ strategy = new $ class ( $ this ) ; $ this -> strategies [ $ id ] = $ strategy ; return $ strategy ; }
Gets an authentication strategy .
54,426
function setCurrentUser ( UserInterface $ user ) { $ this -> currentUser = $ user ; $ this -> app [ 'user' ] = $ user ; return $ this ; }
Sets the current user for this request .
54,427
public function authenticate ( $ strategy ) { return $ this -> getStrategy ( $ strategy ) -> authenticate ( $ this -> request , $ this -> response ) ; }
Handles a user authentication request .
54,428
public function signInUser ( UserInterface $ user , $ strategy = 'web' , $ remember = false ) { $ storage = $ this -> getStorage ( ) ; $ result = $ storage -> signIn ( $ user , $ this -> request , $ this -> response ) ; if ( ! $ result ) { throw new AuthException ( 'Could not sign in user' ) ; } $ twoFactor = $ this -> getTwoFactorStrategy ( ) ; if ( $ twoFactor && ! $ user -> isTwoFactorVerified ( ) && $ twoFactor -> needsVerification ( $ user ) ) { $ this -> setCurrentUser ( $ user ) ; return $ user -> markSignedOut ( ) ; } if ( $ remember ) { $ result = $ storage -> remember ( $ user , $ this -> request , $ this -> response ) ; if ( ! $ result ) { throw new AuthException ( 'Could not enable remember me for user session' ) ; } } if ( $ user -> id ( ) > 0 ) { $ user -> markSignedIn ( ) ; $ event = new AccountSecurityEvent ( ) ; $ event -> user_id = $ user -> id ( ) ; $ event -> type = AccountSecurityEvent :: LOGIN ; $ event -> ip = $ this -> request -> ip ( ) ; $ event -> user_agent = $ this -> request -> agent ( ) ; $ event -> auth_strategy = $ strategy ; $ event -> save ( ) ; } else { $ user -> markSignedOut ( ) ; } $ this -> setCurrentUser ( $ user ) ; return $ user ; }
Builds a signed in user object for a given user ID and signs the user into the session storage . This method should be used by authentication strategies to build a signed in session once a user is authenticated .
54,429
public function verifyTwoFactor ( UserInterface $ user , $ token , $ remember = false ) { $ this -> getTwoFactorStrategy ( ) -> verify ( $ user , $ token ) ; $ user -> markTwoFactorVerified ( ) ; if ( ! $ user -> isSignedIn ( ) ) { $ this -> signInUser ( $ user , '2fa' , $ remember ) ; } $ saved = $ this -> getStorage ( ) -> twoFactorVerified ( $ user , $ this -> request , $ this -> response ) ; if ( ! $ saved ) { throw new AuthException ( 'Unable to mark user session as two-factor verified' ) ; } return $ this ; }
Verifies a user s 2FA token .
54,430
public function signOutAllSessions ( UserInterface $ user ) { $ db = $ this -> getDatabase ( ) ; $ db -> update ( 'ActiveSessions' ) -> values ( [ 'valid' => 0 ] ) -> where ( 'user_id' , $ user -> id ( ) ) -> execute ( ) ; $ db -> delete ( 'PersistentSessions' ) -> where ( 'user_id' , $ user -> id ( ) ) -> execute ( ) ; return true ; }
Invalidates all sessions for a given user .
54,431
public function sendVerificationEmail ( UserInterface $ user ) { $ params = [ 'user_id' => $ user -> id ( ) , 'type' => UserLink :: VERIFY_EMAIL , ] ; $ this -> getDatabase ( ) -> delete ( 'UserLinks' ) -> where ( $ params ) -> execute ( ) ; $ link = new UserLink ( ) ; $ link -> create ( $ params ) ; return $ user -> sendEmail ( 'verify-email' , [ 'verify' => $ link -> link ] ) ; }
Sends a verification email to a user .
54,432
public function verifyEmailWithToken ( $ token ) { $ link = UserLink :: where ( 'link' , $ token ) -> where ( 'type' , UserLink :: VERIFY_EMAIL ) -> first ( ) ; if ( ! $ link ) { return false ; } $ userClass = $ this -> getUserClass ( ) ; $ user = $ userClass :: find ( $ link -> user_id ) ; $ user -> enable ( ) ; $ link -> delete ( ) ; $ user -> sendEmail ( 'welcome' ) ; return $ user ; }
Processes a verify email hash .
54,433
function invite ( $ email , array $ parameters = [ ] , array $ emailParameters = [ ] ) { return $ this -> getUserInviter ( ) -> invite ( $ email , $ parameters , $ emailParameters ) ; }
Invites a new user .
54,434
public function setName ( $ name ) { $ name = Str :: cast ( $ name ) ; $ this -> name = $ name -> lower ( ) ; return $ this ; }
Event name setter
54,435
public function setOrigin ( $ origin ) { if ( ! is_null ( $ this -> origin ) ) { throw new EventException ( 'Overwriting origin of an event is forbidden' , EventException :: ORIGIN_IS_IMMUTABLE ) ; } $ this -> origin = $ origin ; $ this -> status = self :: TRIGGERED ; return $ this ; }
Event origin setter
54,436
public function setContext ( $ context ) { if ( ! is_array ( $ context ) && ! $ context instanceof \ ArrayObject && ! $ context instanceof \ Iterator ) { throw new EventException ( 'Unexpected value type for context' , EventException :: INVALID_CONTEXT ) ; } $ context = Collection :: cast ( $ context ) ; $ this -> context = $ context ; return $ this ; }
Event context setter
54,437
public function execute ( ConnectUser $ listener , $ type , $ hasCode = false ) { $ provider = $ this -> socialite -> with ( $ type ) ; if ( ! $ hasCode ) { return $ this -> getAuthorizationFirst ( $ provider ) ; } $ data = $ this -> getUserData ( $ provider , $ type ) ; $ this -> session -> put ( 'orchestra.oneauth' , $ data ) ; return $ listener -> userHasConnected ( $ data , $ this -> auth ) ; }
Execute user authentication .
54,438
protected function getUserData ( Provider $ provider , $ type ) { $ user = $ provider -> user ( ) ; $ model = $ this -> attemptToConnectUser ( $ user , $ type ) ; $ data = [ 'provider' => $ type , 'user' => $ user ] ; $ this -> dispatcher -> fire ( 'orchestra.oneauth.user: saved' , [ $ model , $ data , $ this -> auth ] ) ; return $ data ; }
Get authorization first from provider .
54,439
protected function attemptToConnectUser ( User $ user , $ type ) { $ model = $ this -> getClientOrCreate ( $ user , $ type ) ; if ( ! is_null ( $ currentUser = $ this -> auth -> user ( ) ) ) { $ model -> setAttribute ( 'user_id' , $ currentUser -> getAuthIdentifier ( ) ) ; } $ model -> setAttribute ( 'token' , new Token ( [ 'access' => $ user -> token ] ) ) ; $ model -> save ( ) ; return $ model ; }
Attempt to connect with user authentication .
54,440
public static function instance ( ) : BooleanSyntax { if ( self :: $ instance === null ) self :: $ instance = new BooleanSyntax ; return self :: $ instance ; }
Returns the BooleanSyntax instance .
54,441
public function factory ( $ className , array $ params = [ ] ) { $ instanceHash = sha1 ( $ className . serialize ( $ params ) ) ; if ( isset ( $ this -> instances [ $ instanceHash ] ) ) { return $ this -> instances [ $ instanceHash ] ; } $ paramCount = count ( $ params ) ; if ( 0 === $ paramCount ) { $ instance = new $ className ( ) ; } elseif ( 1 === $ paramCount ) { $ instance = new $ className ( Arrays :: first ( $ params ) ) ; } elseif ( 2 === $ paramCount ) { $ instance = new $ className ( $ params [ 0 ] , $ params [ 1 ] ) ; } elseif ( 3 === $ paramCount ) { $ instance = new $ className ( $ params [ 0 ] , $ params [ 1 ] , $ params [ 2 ] ) ; } else { $ class = new \ ReflectionClass ( $ className ) ; $ instance = $ class -> newInstanceArgs ( $ args ) ; } return $ this -> setInstance ( $ instanceHash , $ instance ) ; }
Factory method for loading and instantiating new objects
54,442
protected function throwError ( $ errno , $ errstr , $ errfile , $ errline ) { $ msg = "" ; switch ( $ errno ) { case E_USER_ERROR : case E_USER_WARNING : $ msg .= "<b>ERROR</b> [$errno] $errstr<br />\n" ; $ msg .= " Fatal error on line $errline in file $errfile" ; $ msg .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n" ; $ msg .= "Aborting...<br />\n" ; throw new Exception ( $ msg ) ; break ; case E_USER_NOTICE : default : } return true ; }
Custom error - handling function for failed file include error surpression
54,443
public function response ( $ statusCode = null ) { $ response = $ this -> factory ( __NAMESPACE__ . '\Response' ) ; if ( is_numeric ( $ statusCode ) ) { $ response -> status ( $ statusCode ) ; } return $ response ; }
Send HTTP response header
54,444
public function trace ( $ msg = null , $ data = [ ] , $ function = null , $ file = null , $ line = null , $ internal = false ) { if ( ! static :: $ debug ) { return false ; } if ( null !== $ msg ) { $ entry = array ( 'message' => $ msg , 'data' => $ data , 'function' => $ function , 'file' => $ file , 'line' => $ line , 'internal' => ( int ) $ internal ) ; if ( ! $ internal ) { $ currentTime = microtime ( true ) ; $ currentMemory = memory_get_usage ( ) ; $ entry += array ( 'time' => ( $ currentTime - static :: $ traceTimeLast ) , 'time_total' => $ currentTime - static :: $ traceTimeStart , 'memory' => $ currentMemory - static :: $ traceMemoryLast , 'memory_total' => $ currentMemory - static :: $ traceMemoryStart ) ; static :: $ traceTimeLast = $ currentTime ; static :: $ traceMemoryLast = $ currentMemory ; } static :: $ trace [ ] = $ entry ; } return static :: $ trace ; }
Trace messages and return message stack Used for debugging and performance monitoring
54,445
public function module ( $ module , $ init = true , $ dispatchAction = null ) { $ sModule = preg_replace ( '/[^a-zA-Z0-9_]/' , '' , $ module ) ; $ sModule = str_replace ( ' ' , '\\' , ucwords ( str_replace ( '_' , ' ' , $ sModule ) ) ) ; $ sModuleClass = 'Module\\' . $ sModule . '\Controller' ; if ( ! class_exists ( $ sModuleClass ) ) { return false ; } $ sModuleObject = new $ sModuleClass ( $ this ) ; if ( true === $ init ) { if ( method_exists ( $ sModuleObject , 'init' ) ) { $ sModuleObject -> init ( $ dispatchAction ) ; } } return $ sModuleObject ; }
Load and return instantiated module class
54,446
public function plugin ( $ plugin , array $ pluginConfig = [ ] , $ init = true ) { if ( false !== strpos ( $ plugin , 'Module\\' ) ) { $ sPluginClass = $ plugin . '\Plugin' ; } else { $ sPlugin = str_replace ( ' ' , '\\' , ucwords ( str_replace ( '_' , ' ' , $ plugin ) ) ) ; $ sPluginClass = 'Plugin\\' . $ sPlugin . '\Plugin' ; } if ( ! class_exists ( $ sPluginClass , ( boolean ) $ init ) ) { if ( $ init ) { throw new \ InvalidArgumentException ( "Unable to load plugin '" . $ sPluginClass . "'. Remove from app configuration file or ensure plugin files exist in 'app' or 'Thin' load paths." ) ; } return false ; } return $ this -> factory ( $ sPluginClass , [ $ this , $ pluginConfig ] ) ; }
Load and return instantiated plugin class
54,447
public function dispatch ( $ module , $ action = 'index' , array $ params = [ ] ) { if ( $ module instanceof \ Thin \ Controller ) { $ sModuleObject = $ module ; } else { $ sModuleObject = $ this -> module ( $ module , true , $ action ) ; if ( false === $ sModuleObject ) { throw new Exception \ FileNotFound ( "Module '" . $ module . "' not found" ) ; } } $ this -> lastDispatch = array ( 'module' => $ module , 'action' => $ action , 'params' => $ params ) ; if ( ! is_callable ( array ( $ sModuleObject , $ action ) ) ) { throw new Exception \ FileNotFound ( "Module '" . $ module . "' does not have a callable method '" . $ action . "'" ) ; } $ result = call_user_func_array ( array ( $ sModuleObject , $ action ) , $ params ) ; return $ result ; }
Dispatch module action
54,448
public function dispatchRequest ( $ module , $ action = 'indexAction' , array $ params = [ ] ) { $ request = $ this -> request ( ) ; $ requestMethod = $ request -> method ( ) ; if ( strtolower ( $ requestMethod ) == strtolower ( $ action ) ) { $ action = $ action . ( false === strpos ( $ action , 'Method' ) ? 'Method' : '' ) ; } else { $ action = $ action . ( false === strpos ( $ action , 'Action' ) ? 'Action' : '' ) ; } $ request -> setParams ( $ params ) ; return $ this -> dispatch ( $ module , $ action , array ( $ request ) ) ; }
Dispatch module action from HTTP request Automatically limits call scope by appending Action or Method to module actions
54,449
public function url ( $ params = [ ] , $ routeName = null , $ queryParams = [ ] , $ qsAppend = false ) { $ urlBase = $ this -> config ( 'url.root' , '' ) ; $ isSecure = false ; if ( isset ( $ params [ 'secure' ] ) && true === $ params [ 'secure' ] ) { $ isSecure = true ; $ urlBase = str_replace ( 'http:' , 'https:' , $ urlBase ) ; unset ( $ params [ 'secure' ] ) ; } if ( is_string ( $ params ) ) { $ routeName = $ params ; $ params = [ ] ; } elseif ( ! Arrays :: is ( $ params ) ) { throw new Exception ( "First parameter of URL must be array or string route name" ) ; } $ queryString = "" ; $ request = $ this -> request ( ) ; if ( true === $ qsAppend && $ request -> query ( ) ) { $ queryParams = array_merge ( $ request -> query ( ) , $ queryParams ) ; } if ( count ( $ queryParams ) > 0 ) { $ queryString = http_build_query ( $ queryParams , '' , '&amp;' ) ; } else { $ queryString = false ; } $ url = str_replace ( '%2f' , '/' , strtolower ( $ this -> router ( ) -> url ( $ params , $ routeName ) ) ) ; if ( $ this -> config ( 'url.rewrite' ) ) { $ url = $ urlBase . $ url . ( ( $ queryString !== false ) ? '?' . $ queryString : '' ) ; } else { $ url = $ urlBase . '?u=' . $ url . ( ( $ queryString !== false ) ? '&amp;' . $ queryString : '' ) ; } $ url = str_replace ( '///' , '/' , $ url ) ; return $ url ; }
Generate URL from given params
54,450
public function truncate ( $ string , $ endlength = "30" , $ end = "..." ) { $ strlen = strlen ( $ string ) ; if ( $ strlen > $ endlength ) { $ trim = $ endlength - $ strlen ; $ string = substr ( $ string , 0 , $ trim ) ; $ string .= $ end ; } return $ string ; }
Truncates a string to a certian length & adds a ... to the end
54,451
public function formatUrl ( $ string ) { $ string = preg_replace ( '/([^a-zA-Z0-9_\-]+)/' , '-' , strtolower ( $ string ) ) ; $ string = preg_replace ( '/\s+/' , '-' , $ string ) ; $ string = preg_replace ( '|-+|' , '-' , $ string ) ; $ string = trim ( $ string , '-' ) ; return $ string ; }
Format given string to valid URL string
54,452
public function formatFilesize ( $ size ) { $ kb = 1024 ; $ mb = 1048576 ; $ gb = 1073741824 ; $ tb = 1099511627776 ; if ( $ size < $ kb ) { return $ size . " B" ; } else if ( $ size < $ mb ) { return round ( $ size / $ kb , 2 ) . " KB" ; } else if ( $ size < $ gb ) { return round ( $ size / $ mb , 2 ) . " MB" ; } else if ( $ size < $ tb ) { return round ( $ size / $ gb , 2 ) . " GB" ; } else { return round ( $ size / $ tb , 2 ) . " TB" ; } }
Filesize Calculating function Retuns the size of a file in a human format
54,453
public function arrayFlipConvert ( array $ input ) { $ output = [ ] ; foreach ( $ input as $ key => $ val ) { foreach ( $ val as $ key2 => $ val2 ) { $ output [ $ key2 ] [ $ key ] = $ val2 ; } } return $ output ; }
Convert to useful array style from HTML form input style Useful for matching up input arrays without having to increment a number in field names
54,454
public function arrayMergeRecursiveReplace ( ) { $ params = func_get_args ( ) ; $ return = array_shift ( $ params ) ; foreach ( $ params as $ array ) { foreach ( $ array as $ key => $ value ) { if ( is_numeric ( $ key ) && ( ! in_array ( $ value , $ return ) ) ) { if ( Arrays :: is ( $ value ) ) { $ return [ ] = $ this -> arrayMergeRecursiveReplace ( $ return [ $ key ] , $ value ) ; } else { $ return [ ] = $ value ; } } else { if ( isset ( $ return [ $ key ] ) && Arrays :: is ( $ value ) && Arrays :: is ( $ return [ $ key ] ) ) { $ return [ $ key ] = $ this -> arrayMergeRecursiveReplace ( $ return [ $ key ] , $ value ) ; } else { $ return [ $ key ] = $ value ; } } } } return $ return ; }
Merges any number of arrays of any dimensions the later overwriting previous keys unless the key is numeric in whitch case duplicated values will not be added .
54,455
public function errorHandler ( $ errno , $ errstr , $ errfile , $ errline ) { $ errorMsg = $ errstr . " (Line: " . $ errline . ")" ; if ( $ errno != E_WARNING && $ errno != E_NOTICE && $ errno != E_STRICT ) { throw new Exception ( $ errorMsg , $ errno ) ; } else { return false ; } }
Custom error reporting
54,456
public function dump ( ) { $ objects = func_get_args ( ) ; $ content = "\n<pre>\n" ; foreach ( $ objects as $ object ) { $ content .= print_r ( $ object , true ) ; } return $ content . "\n</pre>\n" ; }
Print out an array or object contents in preformatted text Useful for debugging and quickly determining contents of variables
54,457
public function addMethod ( $ method , $ callback ) { $ this -> traceInternal ( "Added '" . $ method . "' to " . __METHOD__ . "()" ) ; $ this -> callbacks [ $ method ] = $ callback ; }
Add a custom user method via PHP5 . 3 closure or PHP callback
54,458
public function connect ( $ retry = false ) { return $ this -> _backoff ( function ( ) { return $ this -> _connection -> connect ( ) ; } , $ retry ? false : 1 ) ; }
Establishes connection .
54,459
public function enqueue ( $ queue , $ body , array $ options = [ ] ) { if ( $ this -> _usingQueue !== $ queue ) { $ this -> _usingQueue = $ queue ; if ( $ this -> _scope ) { $ queue = "{$this->_scope}_{$queue}" ; } if ( ! $ this -> _connection -> useTube ( $ queue ) ) { throw new Exception ( "Could not use queue `{$queue}`." ) ; } } $ options += [ 'priority' => 0 , 'delay' => 0 , 'ttr' => 600 ] ; if ( $ options [ 'priority' ] > Client :: MAX_PRIORITY ) { throw new Exception ( "Priority `{$options['priority']}` exceeds maximum priority." ) ; } if ( $ options [ 'priority' ] < Client :: MIN_PRIORITY ) { throw new Exception ( "Priority `{$options['priority']}` is less than minimum priority." ) ; } $ message = "Enqueuing job with body:\n{$body}\nand options:\n" . var_export ( $ options , true ) ; $ this -> _log -> debug ( $ message ) ; return $ this -> _connection -> put ( $ options [ 'priority' ] , $ options [ 'delay' ] , $ options [ 'ttr' ] , $ body ) ; }
Enqueues a job honors scope .
54,460
public function reserve ( array $ queues , $ timeout ) { if ( $ this -> _watchingQueues !== $ queues ) { $ this -> _watchingQueues = $ queues ; foreach ( $ queues as $ queue ) { if ( $ this -> _scope ) { $ queue = "{$this->_scope}_{$queue}" ; } $ this -> _log -> debug ( "Watching queue `{$queue}`." ) ; $ this -> _connection -> watch ( $ queue ) ; } } if ( ! $ result = $ this -> _connection -> reserve ( $ timeout ) ) { return $ result ; } $ this -> _log -> debug ( "Got job `{$result['id']}`." ) ; return new Job ( $ this , $ this -> _log , $ result ) ; }
Reserves a job . Blocks until either given timeout is reached or a job becomes available . Honors scope .
54,461
public function failJob ( $ id ) { $ this -> _log -> debug ( "Failing job `{$id}`." ) ; return $ this -> _connection -> bury ( $ id , Job :: PRIORITY_LOW ) ; }
Buries a job used i . e . when a job has failed to perform . When burying use new low priority as it can be expected that when jobs get kicked back into the ready queue again we want regular jobs to not be disturbed .
54,462
protected function _backoff ( $ callback , $ maxTries = 1 ) { $ e = null ; $ result = null ; for ( $ tries = 0 ; $ tries < $ maxTries || $ maxTries === false ; $ tries ++ ) { try { if ( $ result = $ callback ( ) ) { return $ result ; } } catch ( Exception $ e ) { } if ( $ tries ) { $ retryIn = pow ( 2 , $ tries ) ; $ this -> _log -> notice ( "Backing off at try #{$tries}; will retry in {$retryIn}s." ) ; sleep ( $ retryIn ) ; } } $ this -> _log -> notice ( "Backing off failed at try #{$tries}." ) ; if ( $ e ) { throw $ e ; } return $ result ; }
Helper method for wrapping any call to provide exponential back off functionality . Backs off when the callback throws an exception or returns false . If failing entirely will rethrow last thrown exception or if that is not available return the last result .
54,463
public static function fork ( $ callable ) { if ( ! is_callable ( $ callable ) ) { throw new \ RuntimeException ( 'Callable is not callable.' ) ; } $ pid = pcntl_fork ( ) ; if ( $ pid < 0 ) { throw new \ RuntimeException ( 'Unable to fork' ) ; } if ( $ pid == 0 ) { call_user_func ( $ callable ) ; exit ; } $ tracker = new PidTracker ( $ pid ) ; return $ tracker ; }
Fork the process and run the callable in the child process .
54,464
public function isAlive ( ) { if ( $ this -> pid < 1 ) { return false ; } $ status = null ; $ pid = pcntl_wait ( $ status , WNOHANG ) ; switch ( $ pid ) { case - 1 : throw new \ RuntimeException ( 'pcntl_wait failed.' ) ; case $ this -> pid : $ this -> pid = - 1 ; return false ; case 0 : return true ; } return true ; }
Checks whether the process is still alive .
54,465
public function killAndWait ( ) { $ status = 0 ; $ this -> kill ( ) ; if ( $ this -> pid > 0 ) { $ pid = pcntl_wait ( $ status ) ; if ( $ pid == $ this -> pid ) { $ this -> pid = - 1 ; } } }
Kill the process and wait for it to finish .
54,466
public function undo ( ) { end ( $ this -> history ) ; for ( $ i = 0 ; $ i < $ this -> history_offset ; $ i ++ ) { prev ( $ this -> history ) ; } $ index = prev ( $ this -> history ) ; if ( ! empty ( $ index ) ) { $ this -> current_passage = $ index ; $ this -> history_offset ++ ; $ this -> storyline = array_slice ( $ this -> storyline , 0 , - 1 ) ; return $ this -> getCurrentPassage ( ) ; } return false ; }
Undo the last action from the user . You can use this function to browse back the actions of the user .
54,467
public function redo ( ) { end ( $ this -> history ) ; for ( $ i = 0 ; $ i < $ this -> history_offset - 1 ; $ i ++ ) { prev ( $ this -> history ) ; } $ index = current ( $ this -> history ) ; if ( ! empty ( $ index ) ) { $ this -> current_passage = $ index ; $ this -> history_offset -- ; $ this -> storyline [ ] = $ this -> current_passage ; } return $ this -> getCurrentPassage ( ) ; }
Redo the last undo from the user . You can use this function to browse forward all the undos of the user .
54,468
public function followLink ( $ next_passage ) { $ current = $ this -> getCurrentPassage ( ) ; $ valid_link = false ; if ( is_array ( $ current -> links ) ) { foreach ( $ current -> links as $ link ) { if ( $ link [ 'link' ] == $ next_passage ) { $ valid_link = true ; } } } if ( $ valid_link && isset ( $ this -> passages [ $ next_passage ] ) ) { $ this -> current_passage = $ next_passage ; $ this -> history [ ] = $ this -> current_passage ; $ this -> storyline [ ] = $ this -> current_passage ; if ( $ this -> history_offset != 0 ) { $ this -> history = array_slice ( $ this -> history , 0 , - $ this -> history_offset ) ; $ this -> history_offset = 0 ; } return $ this -> getCurrentPassage ( ) ; } }
Follow a given link to move on the story .
54,469
public function moveTo ( $ passage ) { if ( isset ( $ this -> passages [ $ passage ] ) ) { $ this -> current_passage = $ passage ; $ this -> history [ ] = $ this -> current_passage ; $ this -> storyline [ ] = $ this -> current_passage ; return $ this -> getCurrentPassage ( ) ; } return false ; }
Move the story to a given passage specially useful to start from the given point .
54,470
private function processJson ( $ json ) { $ twee_array = json_decode ( $ json , true ) ; if ( ! isset ( $ twee_array [ 'data' ] ) or empty ( $ twee_array [ 'data' ] ) ) { throw new RuntimeException ( "The provided JSON did not decode or is empty." ) ; } foreach ( $ twee_array [ 'data' ] as $ entity ) { $ type = $ this -> getTypeFromTags ( $ entity [ 'tags' ] ) ; if ( empty ( $ type ) ) { $ type = $ this -> getTypeFromTitle ( $ entity [ 'title' ] ) ; } switch ( $ type ) { case 'passage' : $ passage = new TweePassage ( $ entity ) ; $ this -> passages [ $ passage -> title ] = $ passage ; if ( in_array ( 'start' , $ passage -> tags ) ) { $ this -> current_passage = $ passage -> title ; $ this -> history [ ] = $ this -> current_passage ; $ this -> storyline [ ] = $ this -> current_passage ; } break ; case 'title' : $ this -> title = $ entity [ 'text' ] ; break ; case 'script' : $ this -> scripts [ ] = $ entity [ 'text' ] ; break ; case 'stylesheet' : $ this -> stylesheets [ ] = $ entity [ 'text' ] ; break ; default : throw new \ RuntimeException ( "Unknown entity type!" ) ; } } return true ; }
Process the JSON exported from Twee and create the story object
54,471
private function getTypeFromTags ( $ tags ) { $ tag_types = array ( 'stylesheet' , 'script' ) ; foreach ( $ tag_types as $ tag ) { if ( in_array ( $ tag , $ tags ) ) { return $ tag ; } } return false ; }
Get the type of entity based on its tags .
54,472
private function getTypeFromTitle ( $ title ) { $ title_types = array ( 'stylesheet' => 'UserStylesheet' , 'script' => 'UserScript' , 'title' => 'StoryTitle' , ) ; foreach ( $ title_types as $ type => $ name ) { if ( $ title == $ name ) { return $ type ; } } return 'passage' ; }
Get the type of entity based on its title .
54,473
protected function fetchLazy ( ) { if ( $ this -> columnData && $ this -> columnNamesWithPrefix && $ this -> columnNames ) { return ; } $ this -> columnNames = [ ] ; $ this -> columnNamesWithPrefix = [ ] ; foreach ( $ this -> getColumnData ( ) as $ value ) { $ this -> columnNamesWithPrefix [ $ value [ 'Field' ] ] = "`$this->prefix`.`{$value['Field']}`" ; $ this -> columnNames [ ] = $ value [ 'Field' ] ; } }
fills in the column data
54,474
public function addAction ( $ action , $ callback ) { if ( ! is_callable ( $ callback ) ) { throw new \ Exception ( 'Callback is not callable.' ) ; } $ this -> getLogger ( ) -> info ( '[SERVICE] Registering: ' . $ action ) ; $ this -> actions [ $ action ] = $ callback ; return $ this ; }
Add an action to this Worker .
54,475
public function stop ( $ signal = null ) { if ( null !== $ signal ) { $ this -> getLogger ( ) -> info ( '[SERVICE] Stop called, because of signal #' . $ signal . '.' ) ; } else { $ this -> getLogger ( ) -> info ( '[SERVICE] Stop called' ) ; } $ this -> running = false ; }
Indicates that this Service should be stopped .
54,476
public function onWorkerMessage ( MessageInterface $ msg ) { if ( $ msg instanceof Protocol \ ActionListRequest ) { $ this -> getLogger ( ) -> debug ( '[SERVICE] Returning list of actions.' ) ; $ this -> stream -> send ( new Protocol \ ActionListResponse ( $ this -> getActionList ( ) ) ) ; return ; } if ( $ msg instanceof Protocol \ ExecuteJobRequest ) { $ requestId = $ msg -> getRequestId ( ) ; $ action = $ msg -> getAction ( ) ; $ this -> getLogger ( ) -> debug ( '[SERVICE] Job for action: ' . $ action . ' with id: ' . $ requestId ) ; $ params = array ( ) ; $ serialized = $ msg -> getParams ( ) ; foreach ( $ serialized as $ param ) { $ params [ ] = $ this -> getSerializer ( ) -> unserialize ( $ param ) ; } if ( ! isset ( $ this -> actions [ $ action ] ) ) { $ this -> getLogger ( ) -> notice ( '[SERVICE] Action ' . $ action . ' not found.' ) ; $ this -> stream -> send ( new Protocol \ ActionNotFound ( $ requestId , $ action ) ) ; return ; } $ return = $ this -> execute ( $ action , $ params ) ; $ sendReturn = $ this -> getSerializer ( ) -> serialize ( $ return ) ; $ this -> stream -> send ( new Protocol \ ExecuteJobResponse ( $ requestId , $ sendReturn ) ) ; return ; } throw new RuntimeException ( 'Invalid request.' ) ; }
Handles a message send by the worker .
54,477
public function run ( ) { pcntl_signal ( SIGINT , array ( $ this , 'stop' ) ) ; pcntl_signal ( SIGTERM , array ( $ this , 'stop' ) ) ; $ this -> running = true ; while ( $ this -> running ) { $ this -> process ( ) ; } }
Run and execute a service .
54,478
public function runSchedule ( ) { if ( $ this -> getScheduler ( ) -> isEmpty ( ) ) { return ; } if ( ! $ this -> getScheduler ( ) -> top ( ) -> isDue ( ) ) { return ; } $ schedule = $ this -> getScheduler ( ) -> extract ( ) ; $ this -> getLogger ( ) -> debug ( 'Running schedule ' . $ schedule -> getName ( ) . ' with expression: ' . $ schedule -> getExpression ( ) . '.' ) ; $ schedule -> run ( ) ; $ this -> getScheduler ( ) -> insert ( $ schedule ) ; }
When the first schedule is due this function will run and reschedule it .
54,479
protected function calculatePollTimeout ( ) { if ( $ this -> getScheduler ( ) -> isEmpty ( ) ) { return 60000 ; } $ nextSchedule = $ this -> getScheduler ( ) -> top ( ) ; $ nextTime = $ nextSchedule -> getNextRunDate ( ) ; $ timeout = $ nextTime - time ( ) ; if ( $ timeout > 60 ) { $ timeout = 60 ; } if ( $ timeout < 0 ) { return 0 ; } return $ timeout * 1000 ; }
Calculates the poll timeout based on the next schedule .
54,480
private function removeDefaultStructure ( ) { $ confirm = $ this -> confirm ( 'Are you sure? It will delete some directories with all files in them.)' ) ; if ( $ confirm ) { try { $ this -> makeBackup ( ) ; if ( ! file_exists ( HCNewProject :: CONFIG ) ) $ this -> abort ( 'Missing project configuration file for laravel version' ) ; $ json = validateJSONFromPath ( HCNewProject :: CONFIG ) ; foreach ( $ json [ 'remove_folders' ] as $ location ) $ this -> deleteDirectory ( $ location , true ) ; foreach ( $ json [ 'remove_files' ] as $ location ) { $ this -> info ( 'Deleting file: ' . $ location ) ; File :: delete ( $ location ) ; } foreach ( $ json [ 'create_folders' ] as $ location ) { $ this -> info ( 'Creating folder: ' . $ location ) ; $ this -> createDirectory ( $ location ) ; } $ this -> createFileFromTemplate ( [ "destination" => 'app/' . HCNewService :: CONFIG_PATH , "templateDestination" => __DIR__ . '/templates/shared/hc.config.hctpl' , "content" => [ "serviceProviderNameSpace" => "app" , ] , ] ) ; foreach ( $ json [ 'create_files' ] as $ source => $ destinations ) { if ( ! is_array ( $ destinations ) ) $ this -> createProjectFile ( $ source , $ destinations ) ; else foreach ( $ destinations as $ destination ) $ this -> createProjectFile ( $ source , $ destination ) ; } foreach ( $ json [ 'copy_folders' ] as $ source => $ destinations ) { if ( ! is_array ( $ destinations ) ) File :: copyDirectory ( __DIR__ . "/templates/$source" , base_path ( $ destinations ) ) ; else foreach ( $ destinations as $ destination ) File :: copyDirectory ( __DIR__ . "/templates/$source" , base_path ( $ destination ) ) ; } replaceTextInFile ( 'composer.json' , [ '"App\\\\"' => '"app\\\\"' ] ) ; replaceTextInFile ( 'config/auth.php' , [ '=> App\User::class' => '=> interactivesolutions\honeycombacl\app\models\HCUsers::class' ] ) ; replaceTextInFile ( 'config/auth.php' , [ 'password_resets' => 'hc_users_password_resets' ] ) ; replaceTextInFile ( 'config/database.php' , [ 'utf8\'' => 'utf8mb4\'' , 'utf8_' => 'utf8mb4_' ] ) ; } catch ( Exception $ e ) { $ this -> comment ( 'Error occurred!' ) ; $ this -> error ( 'Error code: ' . $ e -> getCode ( ) ) ; $ this -> error ( 'Error message: ' . $ e -> getMessage ( ) ) ; $ this -> info ( '' ) ; $ this -> info ( 'Rolling back configuration.' ) ; $ this -> restore ( ) ; $ this -> abort ( '' ) ; } } }
Removing default structure of application
54,481
private function createProjectFile ( string $ source , string $ destination ) { try { $ this -> createFileFromTemplate ( [ "destination" => $ destination , "templateDestination" => __DIR__ . '/templates/project/' . $ source ] ) ; } catch ( Exception $ e ) { } }
Creating project file
54,482
private function makeBackup ( ) { $ this -> createDirectory ( $ this -> backupDirectory ) ; $ this -> createDirectory ( $ this -> backupDirectory . '/config' ) ; File :: copyDirectory ( 'app' , $ this -> backupDirectory . '/app' ) ; File :: copyDirectory ( 'bootstrap' , $ this -> backupDirectory . '/bootstrap' ) ; File :: copyDirectory ( 'routes' , $ this -> backupDirectory . '/routes' ) ; File :: copy ( 'composer.json' , $ this -> backupDirectory . '/composer.json' ) ; File :: copy ( 'config/auth.php' , $ this -> backupDirectory . '/config/auth.php' ) ; File :: copy ( 'config/database.php' , $ this -> backupDirectory . '/config/database.php' ) ; }
Making backup for app and bootstrap folders
54,483
private function restore ( ) { $ this -> deleteDirectory ( 'app' ) ; $ this -> deleteDirectory ( 'bootstrap' ) ; $ this -> deleteDirectory ( 'routes' ) ; $ this -> info ( 'Copying back App' ) ; File :: copyDirectory ( $ this -> backupDirectory . '/app' , 'app' ) ; $ this -> info ( 'Copying back bootstrap' ) ; File :: copyDirectory ( $ this -> backupDirectory . '/bootstrap' , 'bootstrap' ) ; $ this -> info ( 'Copying back routes' ) ; File :: copyDirectory ( $ this -> backupDirectory . '/routes' , 'routes' ) ; File :: copy ( $ this -> backupDirectory . '/composer.json' , 'composer.json' ) ; File :: copy ( $ this -> backupDirectory . '/config/auth.php' , 'config/auth.php' ) ; File :: copy ( $ this -> backupDirectory . '/config/database.php' , 'config/database.php' ) ; $ this -> info ( 'Backup successful' ) ; }
Restoring on fail from backup directory
54,484
public function createRequest ( $ method = RequestInterface :: GET , $ uri = null , $ headers = null , $ body = null ) { $ request = parent :: createRequest ( $ method , $ uri , $ headers , $ body ) ; $ hTimestamp = $ this -> getTimestamp ( ) ; $ baseSig = Keyring :: getAppSecret ( ) . '+' . Keyring :: getConsumerKey ( ) . '+' . $ method . '+' . $ request -> getUrl ( ) . '+' . $ body . '+' . $ hTimestamp ; $ sig = '$1$' . sha1 ( $ baseSig ) ; $ request -> addHeader ( 'X-Zelift-Application' , Keyring :: getAppKey ( ) ) ; $ request -> addHeader ( 'X-Zelift-Timestamp' , $ hTimestamp ) ; $ request -> addHeader ( 'X-Zelift-Consumer' , Keyring :: getConsumerKey ( ) ) ; $ request -> addHeader ( 'X-Zelift-Signature' , $ sig ) ; return $ request ; }
Override ti add Zelift auth
54,485
public static function init ( Event $ event , ScriptInterface $ cmd ) { if ( ! self :: $ _inited ) { try { self :: $ _event = $ event ; self :: $ _cmd = $ cmd ; if ( false === @ class_exists ( '\WebDocBook\Filesystem\Helper' ) ) { include_once __DIR__ . '/../Filesystem/Helper.php' ; } if ( false === @ class_exists ( '\WebDocBook\Kernel' ) ) { include_once __DIR__ . '/../Kernel.php' ; } self :: parseArguments ( ) ; if ( ! defined ( \ WebDocBook \ Kernel :: BASEDIR_CONSTNAME ) ) { self :: parseExtra ( ) ; } \ WebDocBook \ Kernel :: boot ( true ) ; } catch ( \ Exception $ e ) { self :: error ( $ e ) ; } self :: $ _inited = true ; } }
Initialize WebDocBook environment
54,486
public function getRows ( ) { $ data = $ this -> datatable -> setPerPage ( 3 ) -> ajax ( ) -> original ; $ rows = [ ] ; foreach ( $ data [ 'data' ] as $ row ) { $ decorated = array_merge ( $ this -> datatable -> getQuickSearchRow ( $ row ) , [ 'total' => $ data [ 'recordsFiltered' ] ] ) ; $ rows [ ] = $ decorated ; } return $ rows ; }
decorated row getter
54,487
public function getEtag ( ) { if ( $ this -> etag === false ) { $ this -> etag = $ this -> generateEtag ( ) ; } return $ this -> etag ; }
Retrieve ETag for single resource
54,488
protected function generateEtag ( ) { $ keys = array ( ) ; $ updatedAt = '' ; if ( is_array ( $ this -> data ) ) { $ keys = array_keys ( $ this -> data ) ; if ( isset ( $ this -> data [ 'updated_at' ] ) ) { $ updatedAt = $ this -> data -> updated_at ; } } if ( is_object ( $ this -> data ) ) { $ objectVars = get_object_vars ( $ this -> data ) ; $ keys = array_keys ( $ objectVars ) ; unset ( $ objectVars ) ; if ( isset ( $ this -> data -> updated_at ) ) { $ updatedAt = $ this -> data -> updated_at ; } } $ etag = '' ; if ( empty ( $ keys ) ) { return $ etag ; } foreach ( $ keys as $ item ) { $ etag .= $ item ; } $ etag .= $ updatedAt ; return md5 ( $ etag ) ; }
Generate ETag for single resource
54,489
public static function getClassProfile ( $ classname ) { if ( ! is_string ( $ classname ) || empty ( $ classname ) ) { throw new \ InvalidArgumentException ( "Argument is not a valid class name" ) ; } if ( array_key_exists ( $ classname , self :: $ profiles ) ) { return self :: $ profiles [ $ classname ] ; } if ( ! class_exists ( $ classname , true ) ) { throw new \ RuntimeException ( "Class %s could not be found" ) ; } self :: $ profiles [ $ classname ] = new ClassProfile ( $ classname ) ; return self :: $ profiles [ $ classname ] ; }
Obtains a class profile by its name
54,490
public function xpath ( $ path ) { if ( $ path { 0 } === '/' ) { $ this -> rewind ( ) ; if ( $ this -> valid ( ) ) { return $ this -> current ( ) -> xpath ( $ path ) ; } return $ this -> _getEmptyElement ( ) ; } return $ this -> _eachGetIterator ( 'xpath' , $ path ) ; }
Runs XPath query on XML data
54,491
public static function img ( $ src , $ alt = '' , array $ attributes = [ ] ) { $ attributes = array_merge ( [ 'src' => $ src , 'alt' => $ alt ] , $ attributes ) ; return self :: tag ( 'img' , $ attributes ) ; }
Create IMG Tag
54,492
public static function meta ( $ name = 'name' , $ value , $ content , array $ attributes = [ ] ) { $ attributes = array_merge ( [ $ name => $ value , 'content' => $ content ] , $ attributes ) ; return self :: tag ( 'meta' , $ attributes ) ; }
Create META Tag
54,493
public static function link ( $ href = '' , $ text = '' , array $ attributes = [ ] ) { $ attributes = array_merge ( [ 'href' => $ href , ] , $ attributes ) ; return self :: tag ( 'a' , $ attributes ) -> text ( $ text ) ; }
Create ANCHOR Tag
54,494
public static function style ( $ href = '' , array $ attributes = [ ] ) { $ attributes = array_merge ( [ 'rel' => 'stylesheet' , 'href' => $ href , 'type' => 'text/css' ] , $ attributes ) ; return self :: tag ( 'link' , $ attributes ) ; }
Create STYLE Tag
54,495
public function findByCode ( $ code ) { foreach ( $ this -> sections as $ section ) { if ( $ section -> getCharCodeFrom ( ) <= $ code && $ section -> getCharCodeTo ( ) >= $ code ) { return $ section ; } } return null ; }
Find section by code
54,496
public function get ( $ token ) { foreach ( $ this -> getEntityManager ( ) -> getConnection ( ) -> fetchAll ( 'SELECT * FROM oauth_access_token WHERE access_token=:token' , [ 'token' => $ token ] ) as $ row ) { return ( new AccessTokenEntity ( $ this -> server ) ) -> setId ( $ row [ 'access_token' ] ) -> setExpireTime ( $ row [ 'expire_time' ] ) ; } ; return null ; }
Get an instance of Entity \ AccessTokenEntity
54,497
protected function isSameAsEntity ( Entity $ entity ) : bool { return $ this === $ entity || ( $ this instanceof IdentifiableEntity && $ entity instanceof IdentifiableEntity && get_class ( $ this ) === get_class ( $ entity ) && $ this -> getId ( ) === $ entity -> getId ( ) ) ; }
Check if this entity is the same as another entity
54,498
protected function matchesFilter ( array $ filter ) : bool { foreach ( $ filter as $ key => $ comp ) { $ value = ( $ this -> $ key ?? null ) ; $ match = is_scalar ( $ value ) && is_scalar ( $ comp ) ? ( string ) $ value === ( string ) $ comp : $ value === $ comp ; if ( ! $ match ) { return false ; } } return true ; }
Check if entity matches given values .
54,499
protected function matchedId ( $ filter ) : bool { if ( ! $ this instanceof IdentifiableEntity ) { return false ; } $ id = $ this -> getId ( ) ; return is_scalar ( $ id ) && is_scalar ( $ filter ) ? ( string ) $ id === ( string ) $ filter : $ id === $ filter ; }
Check if entity matches given id .