idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
24,100
protected function initializeNullObject ( $ arguments = null ) { $ this -> nullObject = $ this -> maybeInstantiateFindable ( $ this -> nullObject , $ arguments ) ; }
Initialize the NullObject .
24,101
protected function initializeFindables ( $ arguments = null ) : Findables { return $ this -> findables -> map ( function ( $ findable ) use ( $ arguments ) { return $ this -> initializeFindable ( $ findable , $ arguments ) ; } ) ; }
Initialize the Findables that can be iterated .
24,102
protected function maybeInstantiateFindable ( $ findable , $ arguments = null ) : Findable { if ( is_string ( $ findable ) ) { $ findable = $ this -> instantiateFindableFromString ( $ findable , $ arguments ) ; } if ( is_callable ( $ findable ) ) { $ findable = $ this -> instantiateFindableFromCallable ( $ findable , $ arguments ) ; } if ( ! $ findable instanceof Findable ) { throw new FailedToInstantiateFindable ( sprintf ( _ ( 'Could not instantiate Findable "%s".' ) , serialize ( $ findable ) ) ) ; } return $ findable ; }
Maybe instantiate a Findable if it is not yet an object .
24,103
public function ping ( $ params = [ ] , $ optParams = [ ] ) { return $ this -> sendRequest ( [ ] , [ 'restAction' => 'view' , 'restId' => 'ping' , 'getParams' => $ optParams , ] , function ( $ response ) { return isset ( $ response -> data ) ? new Ping ( $ response -> data ) : $ response ; } ) ; }
Pings a Shardimage server and fetches statistical data about the request .
24,104
public function encodeUtf8 ( $ data ) { if ( $ data === null || $ data === '' ) { return $ data ; } if ( is_array ( $ data ) ) { foreach ( $ data as $ key => $ value ) { $ data [ $ key ] = $ this -> encodeUtf8 ( $ value ) ; } return $ data ; } else { if ( ! mb_check_encoding ( $ data , 'UTF-8' ) ) { return mb_convert_encoding ( $ data , 'UTF-8' ) ; } return $ data ; } }
Encodes an ISO - 8859 - 1 string or array to UTF - 8 .
24,105
public function getDateTimeFormatString ( ) { $ format = $ this -> getDateTimeType ( ) . 'Format' ; $ page = $ this -> getObjPage ( ) ; if ( $ page && $ page -> $ format ) { return $ page -> $ format ; } return Config :: get ( $ format ) ; }
Retrieve the selected type or fallback to date if none selected .
24,106
public static function boot ( ) { parent :: boot ( ) ; static :: deleting ( function ( $ model ) { $ model -> children ( ) -> detach ( ) ; $ model -> parents ( ) -> detach ( ) ; } ) ; }
Model event .
24,107
public function makeChildOf ( CategoryInterface $ category ) { $ this -> save ( ) ; $ this -> parents ( ) -> sync ( array ( $ category -> getKey ( ) ) ) ; return $ this ; }
Make new category into some parent .
24,108
public function deleteWithChildren ( ) { $ ids = array ( ) ; $ children = $ this -> getChildren ( ) -> toArray ( ) ; array_walk_recursive ( $ children , function ( $ i , $ k ) use ( & $ ids ) { if ( $ k == 'id' ) $ ids [ ] = $ i ; } ) ; foreach ( $ ids as $ id ) { $ this -> destroy ( $ id ) ; } }
Delete category with all children .
24,109
public function collectInspectionsOnApplicationFinish ( EventInterface $ event ) { $ inspection = $ this -> inspector -> inspect ( $ event ) ; $ uuid = $ this -> uuidGenerator -> generateUUID ( ) ; $ this -> inspectionRepository -> add ( $ uuid , $ inspection ) ; $ event -> setParam ( self :: PARAM_INSPECTION , $ inspection ) ; $ event -> setParam ( self :: PARAM_INSPECTION_ID , $ uuid ) ; return $ uuid ; }
Collects and persists the current inspection results
24,110
public function route ( $ routes , $ class = null , $ fallback = null ) { return $ this -> getCssClass ( $ this -> isRoute ( $ routes ) , $ class , $ fallback ) ; }
Get the active class if the current route is in haystack routes .
24,111
public function path ( $ routes , $ class = null , $ fallback = null ) { return $ this -> getCssClass ( $ this -> isPath ( $ routes ) , $ class , $ fallback ) ; }
Get the active class if the current path is in haystack paths .
24,112
protected function is ( $ object , $ routes ) { list ( $ routes , $ ignored ) = $ this -> parseRoutes ( Arr :: wrap ( $ routes ) ) ; return $ this -> isIgnored ( $ ignored ) ? false : call_user_func_array ( [ $ object , 'is' ] , $ routes ) ; }
Check if one the given routes is active .
24,113
protected function parseRoutes ( array $ allRoutes ) { return Collection :: make ( $ allRoutes ) -> partition ( function ( $ route ) { return ! Str :: startsWith ( $ route , [ 'not:' ] ) ; } ) -> transform ( function ( Collection $ routes , $ index ) { return $ index === 0 ? $ routes : $ routes -> transform ( function ( $ route ) { return substr ( $ route , 4 ) ; } ) ; } ) -> toArray ( ) ; }
Separate ignored routes from the whitelist routes .
24,114
protected function redirectToReferer ( ) : RedirectResponse { $ url = $ this -> requestService -> fetchRefererUrl ( ) ; if ( '' === $ url ) { throw CannotRedirectToEmptyRefererUrlException :: create ( ) ; } return $ this -> redirect ( $ url ) ; }
Redirects to url of referer
24,115
public function read ( AbstractStream $ stream ) { return $ stream -> getBuffer ( ) -> readInt ( $ this -> getSize ( ) , $ this -> getSigned ( ) , $ this -> getEndian ( ) ) ; }
Read data from Stream and cast it to integer .
24,116
public function validate ( $ value , Constraint $ constraint ) { if ( ! $ constraint -> class ) { throw new ConstraintDefinitionException ( 'Target is not specified' ) ; } $ class = $ constraint -> class ; if ( ! class_exists ( $ class ) ) { throw new TargetClassNotExistException ( 'Target class not exist.' ) ; } $ constraint -> choices = $ class :: getValues ( ) ; $ constraint -> multiple = true ; parent :: validate ( $ value , $ constraint ) ; }
Checks if the passed value is valid
24,117
public static function getTypeFromFileName ( string $ fileName ) : string { $ fileExtension = strtolower ( Miscellaneous :: getFileExtension ( $ fileName ) ) ; if ( false === ( new static ( ) ) -> isCorrectType ( $ fileExtension ) ) { throw UnknownConfigurationFileTypeException :: createException ( $ fileExtension ) ; } return $ fileExtension ; }
Returns type of configuration file based on name of the file
24,118
public function encrypt ( $ message , $ userPublicKey , $ userAuthToken , $ regenerateKeys = false ) { if ( self :: MAX_MESSAGE_LENGTH < strlen ( $ message ) ) { throw new \ RuntimeException ( sprintf ( 'Length of message must not be greater than %d octets.' , self :: MAX_MESSAGE_LENGTH ) ) ; } $ message = self :: padMessage ( $ message ) ; if ( $ regenerateKeys ) { $ this -> initialize ( ) ; } $ userPublicKey = Base64Url :: decode ( $ userPublicKey ) ; $ userAuthToken = Base64Url :: decode ( $ userAuthToken ) ; $ sharedSecret = $ this -> getSharedSecret ( $ userPublicKey ) ; $ ikm = ! empty ( $ userAuthToken ) ? self :: hkdf ( $ userAuthToken , $ sharedSecret , 'Content-Encoding: auth' . chr ( 0 ) , 32 ) : $ sharedSecret ; $ context = $ this -> createContext ( $ userPublicKey ) ; $ contentEncryptionKey = self :: hkdf ( $ this -> salt , $ ikm , self :: createInfo ( 'aesgcm' , $ context ) , 16 ) ; $ nonce = self :: hkdf ( $ this -> salt , $ ikm , self :: createInfo ( 'nonce' , $ context ) , 12 ) ; if ( version_compare ( PHP_VERSION , '7.1' ) >= 0 ) { $ encryptedText = openssl_encrypt ( $ message , 'aes-128-gcm' , $ contentEncryptionKey , OPENSSL_RAW_DATA , $ nonce , $ tag ) ; } else { list ( $ encryptedText , $ tag ) = \ AESGCM \ AESGCM :: encrypt ( $ contentEncryptionKey , $ nonce , $ message , '' ) ; } return $ encryptedText . $ tag ; }
Encrypt the message for Web Push .
24,119
private function initialize ( ) { $ this -> privateKey = $ this -> generator -> createPrivateKey ( ) ; $ this -> publicKey = $ this -> privateKey -> getPublicKey ( ) ; $ this -> salt = openssl_random_pseudo_bytes ( 16 ) ; $ this -> publicKeyContent = hex2bin ( $ this -> serializer -> serialize ( $ this -> publicKey -> getPoint ( ) ) ) ; }
Generate key pare and salt .
24,120
private function getSharedSecret ( $ userPublicKey ) { $ userPublicKeyPoint = $ this -> serializer -> unserialize ( $ this -> curve , bin2hex ( $ userPublicKey ) ) ; $ userPublicKeyObject = $ this -> generator -> getPublicKeyFrom ( $ userPublicKeyPoint -> getX ( ) , $ userPublicKeyPoint -> getY ( ) , $ this -> generator -> getOrder ( ) ) ; $ point = $ userPublicKeyObject -> getPoint ( ) -> mul ( $ this -> privateKey -> getSecret ( ) ) -> getX ( ) ; return hex2bin ( $ this -> adapter -> decHex ( ( string ) $ point ) ) ; }
Get shared secret from user public key and server private key .
24,121
protected function populateErrorData ( \ Throwable $ e , array $ data ) : \ Throwable { static $ cache = [ ] ; static $ props = [ 'code' , 'message' , 'file' , 'line' ] ; $ type = ( $ e instanceof \ Error ) ? \ Error :: class : \ Exception :: class ; if ( ! isset ( $ cache [ $ type ] ) ) { $ cache [ $ type ] = [ ] ; foreach ( $ props as $ k ) { $ ref = new \ ReflectionProperty ( $ type , $ k ) ; $ ref -> setAccessible ( true ) ; $ cache [ $ type ] [ $ k ] = $ ref ; } } foreach ( $ props as $ k ) { if ( isset ( $ data [ $ k ] ) ) { $ cache [ $ type ] [ $ k ] -> setValue ( $ e , $ data [ $ k ] ) ; } } return $ e ; }
Populate properties of the given error from unserialized data .
24,122
public function run ( ) { $ force = $ this -> controller -> force ; $ this -> stdout ( "initialize ip database:\n" , Console :: FG_GREEN ) ; foreach ( $ this -> ipv4 -> getQueries ( ) as $ name => $ query ) { $ providers = $ query -> getProviders ( ) ; if ( empty ( $ providers ) ) { $ this -> download ( $ query , $ name , $ force ) ; } else { $ this -> division ( ) ; $ this -> generate ( $ query , $ name , $ force ) ; } } }
initialize ip database
24,123
public function injectToolbarHtml ( MvcEvent $ event ) { if ( ! $ inspection = $ event -> getParam ( ApplicationInspectorListener :: PARAM_INSPECTION ) ) { return ; } $ response = $ event -> getResponse ( ) ; if ( ! $ response instanceof Response ) { return ; } $ headers = $ response -> getHeaders ( ) ; $ contentType = $ headers -> get ( 'Content-Type' ) ; if ( $ contentType ) { if ( ! $ contentType instanceof ContentType ) { return ; } if ( false === strpos ( strtolower ( $ contentType -> getFieldValue ( ) ) , 'html' ) ) { return ; } } $ response -> setContent ( preg_replace ( '/<\/body>/i' , $ this -> renderer -> render ( $ this -> inspectionRenderer -> render ( $ inspection ) ) . '</body>' , $ response -> getContent ( ) , 1 ) ) ; }
Attaches the HTML rendered for the toolbar to the output if the output is recognized as an HTML HTTP response
24,124
public function modifiedDate ( WP_Post $ post , string $ format ) : string { Assert :: stringNotEmpty ( $ format ) ; $ postDate = get_the_modified_date ( $ format , $ post ) ; $ this -> bailIfInvalidValue ( $ postDate , $ post ) ; return $ postDate ; }
Retrieve the Modified Date for a Post
24,125
public function modifiedTime ( WP_Post $ post , string $ format ) : string { Assert :: stringNotEmpty ( $ format ) ; $ postDate = get_the_modified_time ( $ format , $ post ) ; $ this -> bailIfInvalidValue ( $ postDate , $ post ) ; return $ postDate ; }
Retrieve the Modified Time for a Post
24,126
public function date ( WP_Post $ post , string $ format ) : string { Assert :: stringNotEmpty ( $ format ) ; $ postDate = get_the_date ( $ format , $ post ) ; $ this -> bailIfInvalidValue ( $ postDate , $ post ) ; return $ postDate ; }
Retrieve the Written Date for a Post
24,127
public function time ( WP_Post $ post , string $ format ) : string { Assert :: stringNotEmpty ( $ format ) ; $ postTime = get_the_time ( $ format , $ post ) ; $ this -> bailIfInvalidValue ( $ postTime , $ post ) ; return $ postTime ; }
Retrieve the Written Time for a Post
24,128
public function dateTime ( WP_Post $ post , string $ format , string $ separator ) : string { Assert :: stringNotEmpty ( $ format ) ; Assert :: stringNotEmpty ( $ separator ) ; $ postDate = $ this -> date ( $ post , $ format ) ; $ postTime = $ this -> time ( $ post , $ format ) ; return implode ( [ $ postDate , $ postTime ] , $ separator ) ; }
Retrieve the Written Date Time for a Post
24,129
protected function createCallback ( string $ method ) : \ Closure { return \ Closure :: bind ( static function ( ... $ args ) use ( $ method ) { return self :: $ method ( ... $ args ) ; } , null , $ this -> type ) ; }
Create a closure that can execute a protected or private static method .
24,130
public function exists ( $ token ) { $ reset = PasswordReset :: where ( 'token' , $ token ) -> first ( ) ; return $ reset and ! $ reset -> isExpired ( ) ; }
Checks if a certain password reset exists .
24,131
public function countries ( array $ countryCodes = null ) : array { if ( ! Configure :: read ( 'countries' ) ) { Configure :: load ( 'CkTools.countries' ) ; } if ( $ countryCodes ) { $ countries = Configure :: read ( 'countries' ) ; $ subset = [ ] ; foreach ( $ countryCodes as $ countryCode ) { $ subset [ $ countryCode ] = $ countries [ $ countryCode ] ?? $ countryCode ; } return $ subset ; } return Configure :: read ( 'countries' ) ; }
Returns a map of countries with their translations
24,132
public function country ( string $ country ) : string { if ( ! Configure :: read ( 'countries' ) ) { Configure :: load ( 'CkTools.countries' ) ; } $ countries = Configure :: read ( 'countries' ) ; return $ countries [ $ country ] ?? $ country ; }
Returns the translated version of the given country
24,133
public function datepickerInput ( string $ field , array $ options = [ ] ) : string { $ options = Hash :: merge ( [ 'type' => 'date' , ] , $ options ) ; return $ this -> Form -> input ( $ field , $ options ) ; }
Render a datepicker input to be processed by DatePicker . js
24,134
public function editButton ( EntityInterface $ entity , array $ options = [ ] ) : string { $ options = Hash :: merge ( [ 'url' => null , 'title' => __d ( 'ck_tools' , 'edit' ) , 'icon' => 'fa fa-pencil' , 'escape' => false , 'class' => 'btn btn-default btn-xs btn-edit' , ] , $ options ) ; $ url = $ options [ 'url' ] ; $ title = $ options [ 'title' ] ; $ icon = $ options [ 'icon' ] ; unset ( $ options [ 'url' ] , $ options [ 'title' ] , $ options [ 'icon' ] ) ; if ( ! $ url ) { list ( $ plugin , $ controller ) = pluginSplit ( $ entity -> source ( ) ) ; $ url = [ 'plugin' => $ this -> _View -> request -> plugin , 'controller' => $ controller , 'action' => 'edit' , $ entity -> id , ] ; $ url = $ this -> augmentUrlByBackParam ( $ url ) ; } if ( $ icon ) { $ title = '<i class="' . $ icon . '"></i> ' . '<span class="button-text">' . $ title . '</span>' ; $ options [ 'escape' ] = false ; } return $ this -> Html -> link ( $ title , $ url , $ options ) ; }
Renders an edit button
24,135
public function addButton ( string $ title = null , array $ options = [ ] ) : string { if ( ! $ title ) { $ title = __d ( 'ck_tools' , 'add' ) ; } $ options = Hash :: merge ( [ 'url' => null , 'icon' => 'fa fa-plus' , 'class' => 'btn btn-default btn-xs btn-add' , ] , $ options ) ; $ url = $ options [ 'url' ] ; if ( ! $ url ) { $ url = [ 'action' => 'add' ] ; $ url = $ this -> augmentUrlByBackParam ( $ url ) ; } $ icon = $ options [ 'icon' ] ; unset ( $ options [ 'url' ] , $ options [ 'icon' ] ) ; if ( $ icon ) { $ title = '<i class="' . $ icon . '"></i> ' . '<span class="button-text">' . $ title . '</span>' ; $ options [ 'escape' ] = false ; } return $ this -> Html -> link ( $ title , $ url , $ options ) ; }
Renders an add button
24,136
public function formButtons ( array $ options = [ ] ) : string { $ url = [ 'action' => 'index' ] ; $ options = Hash :: merge ( [ 'useReferer' => false , 'horizontalLine' => true , 'cancelButton' => true , 'saveButtonTitle' => __d ( 'ck_tools' , 'save' ) , 'cancelButtonTitle' => __d ( 'ck_tools' , 'cancel' ) , ] , $ options ) ; if ( ! empty ( $ options [ 'useReferer' ] ) && $ this -> request -> referer ( ) !== '/' ) { $ url = $ this -> request -> referer ( ) ; } $ formButtons = '<div class="submit-group">' ; if ( $ options [ 'horizontalLine' ] ) { $ formButtons .= '<hr>' ; } $ formButtons .= $ this -> Form -> button ( $ options [ 'saveButtonTitle' ] , [ 'class' => 'btn-success' ] ) ; if ( $ options [ 'cancelButton' ] ) { $ formButtons .= $ this -> backButton ( $ options [ 'cancelButtonTitle' ] , $ url , [ 'class' => 'btn btn-default cancel-button' , 'icon' => null ] ) ; } $ formButtons .= '</div>' ; return $ formButtons ; }
Renders form buttons
24,137
public function backButton ( string $ title = null , $ url = null , array $ options = [ ] ) : string { $ options = Hash :: merge ( [ 'icon' => 'arrow-left' , 'escape' => false , ] , $ options ) ; if ( ! $ title ) { $ title = '<span class="button-text">' . __d ( 'ck_tools' , 'Back' ) . '</span>' ; } $ here = $ this -> getRequestedAction ( ) ; if ( $ this -> request -> getSession ( ) -> check ( 'back_action.' . $ here ) ) { $ url = $ this -> request -> getSession ( ) -> read ( 'back_action.' . $ here ) ; } if ( empty ( $ url ) ) { $ url = [ 'action' => 'index' , ] ; } return $ this -> button ( $ title , $ url , $ options ) ; }
Renders a back button using the back actions within the session
24,138
public function nestedList ( array $ data , string $ content , int $ level = 0 , array $ isActiveCallback = null ) : string { $ tabs = "\n" . str_repeat ( ' ' , $ level * 2 ) ; $ liTabs = $ tabs . ' ' ; $ output = $ tabs . '<ul>' ; foreach ( $ data as $ record ) { $ liClasses = [ ] ; $ liContent = $ content ; if ( $ isActiveCallback !== null ) { $ additionalArguments = ! empty ( $ isActiveCallback [ 'arguments' ] ) ? $ isActiveCallback [ 'arguments' ] : [ ] ; $ isActive = call_user_func_array ( $ isActiveCallback [ 'callback' ] , [ & $ record , $ additionalArguments ] ) ; if ( $ isActive ) { $ liClasses [ ] = 'active' ; } } preg_match_all ( "/\{\{([a-z0-9\._]+)\}\}/i" , $ liContent , $ matches ) ; if ( ! empty ( $ matches ) ) { $ variables = array_unique ( $ matches [ 1 ] ) ; foreach ( $ variables as $ modelField ) { $ liContent = str_replace ( '{{' . $ modelField . '}}' , $ record [ $ modelField ] , $ liContent ) ; } } if ( ! empty ( $ record [ 'children' ] ) ) { $ liClasses [ ] = 'has-children' ; } $ output .= $ liTabs . '<li class="' . implode ( ' ' , $ liClasses ) . '">' . $ liContent ; if ( isset ( $ record [ 'children' ] [ 0 ] ) ) { $ output .= $ this -> nestedList ( $ record [ 'children' ] , $ content , $ level + 1 , $ isActiveCallback ) ; $ output .= $ liTabs . '</li>' ; } else { $ output .= '</li>' ; } } $ output .= $ tabs . '</ul>' ; return $ output ; }
Renders a nested list
24,139
public function historyBackButton ( array $ options = [ ] ) : string { $ options = Hash :: merge ( [ 'icon' => 'fa fa-arrow-left' , 'class' => 'btn btn-default btn-xs' , ] , $ options ) ; $ div = '<div class="' . $ options [ 'class' ] . '" onclick="history.back()">' ; $ i = '<i class="' . $ options [ 'icon' ] . '"></i>' ; return $ div . $ i . ' ' . __d ( 'ck_tools' , 'history_back_button' ) . '</div>' ; }
Renders a div with an onclick - hanlder which uses the history API of the Browser
24,140
public function displayStructuredData ( array $ data , array $ options = [ ] ) : string { $ options = Hash :: merge ( [ 'expanded' => true , 'expandLinkText' => __d ( 'ck_tools' , 'utility.toggle_content' ) , 'type' => 'array' , ] , $ options ) ; switch ( $ options [ 'type' ] ) { case 'table' : $ list = $ this -> arrayToTable ( $ data , $ options ) ; break ; case 'array' : default : $ list = $ this -> arrayToUnorderedList ( $ data ) ; break ; } if ( ! $ options [ 'expanded' ] ) { $ id = 'dsd-' . uniqid ( ) ; $ out = $ this -> Html -> link ( $ options [ 'expandLinkText' ] , 'javascript:' , [ 'type' => 'button' , 'data-toggle' => 'collapse' , 'aria-expanded' => 'false' , 'aria-controls' => $ id , 'data-target' => '#' . $ id , ] ) ; $ out .= '<div class="collapse" id="' . $ id . '">' . $ list . '</div>' ; } else { $ out = $ list ; } return $ out ; }
Display an array in human - readable format and provide options to toggle its display
24,141
protected function createMessageBody ( MessageInterface $ message ) { $ body = [ ] ; if ( $ message instanceof BaseOptionedModel ) { $ body = $ message -> getOptions ( ) ; } $ body [ 'message' ] = $ message -> getText ( ) ; return json_encode ( $ body ) ; }
Create message body .
24,142
protected function createSignatureToken ( $ origin , \ DateTime $ expiration = null ) { if ( is_null ( $ expiration ) ) { $ expiration = new \ DateTime ( '+ 1 hours' ) ; } $ signer = new ES256 ( ) ; $ privateKey = new Key ( 'file://' . $ this -> getParameter ( 'privateKey' ) ) ; $ builder = new Builder ( ) ; $ token = $ builder -> setAudience ( $ origin ) -> setExpiration ( $ expiration -> getTimestamp ( ) ) -> sign ( $ signer , $ privateKey ) -> getToken ( ) ; return $ token ; }
Create the JWT signed by using ES256 .
24,143
public function encodeJson ( $ data ) : string { if ( $ data instanceof JsonSerializable ) { $ data = $ data -> jsonSerialize ( ) ; } $ result = json_encode ( $ this -> utf8Encoding -> encodeUtf8 ( $ data ) , 512 , JSON_THROW_ON_ERROR ) ; if ( $ result === false ) { throw new JsonException ( 'Json encoding failed' ) ; } return $ result ; }
Encode an array to JSON .
24,144
public function getOptionParser ( ) : ConsoleOptionParser { $ parser = parent :: getOptionParser ( ) ; $ updateFromCatalogParser = parent :: getOptionParser ( ) ; $ updateFromCatalogParser -> addOption ( 'domain' , [ 'default' => 'default' , 'help' => 'The domain to use' , ] ) ; $ updateFromCatalogParser -> addOption ( 'overwrite' , [ 'default' => false , 'help' => 'If set, there will be no interactive question whether to continue.' , 'boolean' => true , ] ) ; $ updateFromCatalogParser -> addOption ( 'strip-references' , [ 'boolean' => true , 'help' => 'Whether to remove file usage references from resulting po and mo files.' , ] ) ; return $ parser -> setDescription ( [ 'CkTools Shell' , '' , 'Utilities' , ] ) -> addSubcommand ( 'updateFromCatalog' , [ 'help' => 'Updates the PO file from the given catalog' , 'parser' => $ updateFromCatalogParser , ] ) ; }
Manage the available sub - commands along with their arguments and help
24,145
public function updateFromCatalog ( ) : void { $ domain = $ this -> params [ 'domain' ] ; $ localePath = ROOT . '/src/Locale/' ; $ catalogFile = $ localePath . $ domain . '.pot' ; if ( ! file_exists ( $ catalogFile ) ) { $ this -> abort ( sprintf ( 'Catalog File %s not found.' , $ catalogFile ) ) ; } $ poFiles = [ ] ; $ folder = new Folder ( $ localePath ) ; $ tree = $ folder -> tree ( ) ; foreach ( $ tree [ 1 ] as $ file ) { $ basename = basename ( $ file ) ; if ( $ domain . '.po' === $ basename ) { $ poFiles [ ] = $ file ; } } if ( empty ( $ poFiles ) ) { $ this -> abort ( sprintf ( 'I could not find any matching po files in the given locale path (%s) for the domain (%s)' , $ localePath , $ domain ) ) ; } if ( ! $ this -> params [ 'overwrite' ] ) { $ this -> out ( 'I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $ catalogFile ) ; foreach ( $ poFiles as $ poFile ) { $ this -> out ( ' - ' . $ poFile ) ; } $ response = $ this -> in ( 'Would you like to continue?' , [ 'y' , 'n' ] , 'n' ) ; if ( $ response !== 'y' ) { $ this -> abort ( 'Aborted' ) ; } } foreach ( $ poFiles as $ poFile ) { $ catalogEntries = Translations :: fromPoFile ( $ catalogFile ) ; $ moFile = str_replace ( '.po' , '.mo' , $ poFile ) ; $ translationEntries = Translations :: fromPoFile ( $ poFile ) ; $ newTranslationEntries = $ catalogEntries -> mergeWith ( $ translationEntries , Merge :: REFERENCES_THEIRS ) ; $ newTranslationEntries -> deleteHeaders ( ) ; foreach ( $ translationEntries -> getHeaders ( ) as $ key => $ value ) { $ newTranslationEntries -> setHeader ( $ key , $ value ) ; } if ( $ this -> params [ 'strip-references' ] ) { foreach ( $ newTranslationEntries as $ translation ) { $ translation -> deleteReferences ( ) ; } } $ newTranslationEntries -> toPoFile ( $ poFile ) ; $ newTranslationEntries -> toMoFile ( $ moFile ) ; $ this -> out ( 'Updated ' . $ poFile ) ; $ this -> out ( 'Updated ' . $ moFile ) ; } }
Updates the catalog file from the given po file
24,146
public function register ( callable $ callback ) : void { $ hint = $ this -> handlerHint ( $ callback ) ; $ this -> handlers [ $ hint ] = $ callback ; }
Register a new exception handler .
24,147
protected function getHttpStatusCode ( Exception $ exception ) : int { if ( $ exception instanceof ApiException ) { return $ exception -> apiMessage -> getHttpStatusCode ( ) ; } if ( $ exception instanceof HttpExceptionInterface && method_exists ( $ exception , 'getStatusCode' ) ) { return $ exception -> getStatusCode ( ) ; } return 500 ; }
Get the Http status code from the exception .
24,148
protected function handlerHint ( callable $ callback ) : string { $ reflection = new ReflectionFunction ( $ callback ) ; $ exception = $ reflection -> getParameters ( ) [ 0 ] ; return $ exception -> getClass ( ) -> getName ( ) ; }
Get the hint for an exception handler .
24,149
protected function createNewTokens ( ) { $ logger = $ this -> getLogger ( ) ; $ logger -> debug ( 'Starting request to create fresh access & refresh tokens' ) ; $ body = [ 'client_id' => 'anonymous' , 'grant_type' => 'password' , 'response_type' => 'token' , 'scope' => 'openid' , 'username' => $ this -> credentials -> getUsername ( ) , 'password' => $ this -> credentials -> getPassword ( ) , ] ; $ response = $ this -> sendPostRequest ( $ body ) ; $ logger -> debug ( 'Successfully retrieved new access & refresh tokens' , $ response ) ; return [ 'accessToken' => new Token ( $ response [ 'access_token' ] , $ this -> tokenExtractor -> extract ( $ response [ 'access_token' ] ) ) , 'refreshToken' => new Token ( $ response [ 'refresh_token' ] , $ this -> tokenExtractor -> extract ( $ response [ 'refresh_token' ] ) ) , ] ; }
Create completely fresh Access + Refresh tokens .
24,150
protected function createAccessTokenFromRefreshToken ( Token $ refreshToken ) { $ logger = $ this -> getLogger ( ) ; $ logger -> debug ( 'Starting request to create fresh access token from refresh token' ) ; $ body = [ 'client_id' => 'anonymous' , 'grant_type' => 'refresh_token' , 'refresh_token' => $ refreshToken -> getTokenString ( ) , ] ; $ response = $ this -> sendPostRequest ( $ body ) ; $ logger -> debug ( 'Successfully retrieved new access token' , $ response ) ; return new Token ( $ response [ 'access_token' ] , $ this -> tokenExtractor -> extract ( $ response [ 'access_token' ] ) ) ; }
Create a new access token for a video manager using a refresh token .
24,151
protected function logTokenData ( ) { $ this -> getLogger ( ) -> debug ( 'Token information' , [ 'accessTokenExists' => isset ( $ this -> accessToken ) , 'accessTokenExpiration' => isset ( $ this -> accessToken ) ? $ this -> accessToken -> getTokenData ( ) [ 'exp' ] : null , 'accessTokenHasExpired' => isset ( $ this -> accessToken ) ? $ this -> accessToken -> expired ( ) : null , 'refreshTokenExists' => isset ( $ this -> refreshToken ) , 'refreshTokenExpiration' => isset ( $ this -> refreshToken ) ? $ this -> refreshToken -> getTokenData ( ) [ 'exp' ] : null , 'refreshTokenHasExpired' => isset ( $ this -> refreshToken ) ? $ this -> refreshToken -> expired ( ) : null , 'localTime' => time ( ) , ] ) ; }
Log information about which tokens we have .
24,152
public function getToken ( ) { $ logger = $ this -> getLogger ( ) ; $ this -> logTokenData ( ) ; $ cacheKey = sha1 ( sprintf ( '%s.%s' , __METHOD__ , json_encode ( func_get_args ( ) ) ) ) ; $ cacheItem = $ this -> cacheItemPool -> getItem ( $ cacheKey ) ; if ( ! $ this -> accessToken && $ cacheItem -> isHit ( ) ) { $ this -> accessToken = $ cacheItem -> get ( ) ; } if ( ! is_null ( $ this -> accessToken ) && $ this -> accessToken -> expired ( ) && ! is_null ( $ this -> refreshToken ) && ! $ this -> refreshToken -> expired ( ) ) { $ logger -> info ( 'Access token has expired - getting new one for same video manager with refresh token' ) ; $ this -> accessToken = $ this -> createAccessTokenFromRefreshToken ( $ this -> refreshToken ) ; } elseif ( is_null ( $ this -> accessToken ) || ( ! is_null ( $ this -> refreshToken ) && $ this -> refreshToken -> expired ( ) ) ) { $ logger -> info ( 'No access token, or refresh token has expired - generate completely new ones' ) ; $ tokenData = $ this -> createNewTokens ( ) ; $ this -> accessToken = $ tokenData [ 'accessToken' ] ; $ this -> refreshToken = $ tokenData [ 'refreshToken' ] ; } $ cacheItem -> set ( $ this -> accessToken ) ; $ cacheItem -> expiresAt ( ( new \ DateTime ( ) ) -> setTimestamp ( $ this -> accessToken -> getTokenData ( ) [ 'exp' ] ) -> sub ( new \ DateInterval ( 'PT30S' ) ) ) ; $ this -> cacheItemPool -> save ( $ cacheItem ) ; return $ this -> accessToken -> getTokenString ( ) ; }
Retrieve a valid token .
24,153
private function sendPostRequest ( array $ body ) { $ requestBodyKey = version_compare ( ClientInterface :: VERSION , '6.0' , '>=' ) ? 'form_params' : 'body' ; $ response = $ this -> httpClient -> post ( '' , [ $ requestBodyKey => $ body , ] ) ; return \ json_decode ( $ response -> getBody ( ) , true ) ; }
Sends a post request to the OAuth endpoint Supports both guzzle 5 and 6 versions .
24,154
protected function awaitFirstResult ( Context $ context , array $ tasks , CancellationHandler $ cancel , array & $ errors ) : \ Generator { if ( empty ( $ tasks ) ) { return ; } try { $ result = yield $ context -> first ( $ tasks , $ cancel , $ errors ) ; } catch ( MultiReasonException $ e ) { $ result = null ; } return $ result ; }
Helper method that collects errors thrown by promises into an array and allways resolves .
24,155
protected function query ( Context $ context , string $ server , string $ host , int $ type ) : \ Generator { $ response = yield $ this -> getUdpConnector ( $ server ) -> send ( $ context , $ this -> createRequest ( $ host , $ type ) ) ; if ( $ response -> isTruncated ( ) ) { $ response = yield $ this -> getTcpConnector ( $ server ) -> send ( $ context , $ this -> createRequest ( $ host , $ type ) ) ; } $ resolved = [ ] ; $ ttl = \ PHP_INT_MAX ; foreach ( $ response -> getAnswers ( ) as $ record ) { if ( $ record [ 'type' ] === $ type ) { $ resolved [ ] = new Address ( $ record [ 'data' ] ) ; $ ttl = \ min ( $ ttl , $ record [ 'ttl' ] ) ; } } if ( empty ( $ resolved ) ) { throw new \ RuntimeException ( \ sprintf ( 'Unable to resolve host "%s" into an IP using DNS server %s' , $ host , $ server ) ) ; } return [ 'ttl' => \ max ( 1 , \ min ( 300 , $ ttl ) ) , 'ips' => $ resolved ] ; }
Lookup IP addresses using DNS server .
24,156
protected function getUdpConnector ( string $ server ) : UdpConnector { if ( empty ( $ this -> udp [ $ server ] ) ) { $ this -> udp [ $ server ] = new UdpConnector ( $ server , $ this -> timeout ) ; } return $ this -> udp [ $ server ] ; }
Get a UDP connector for the given server .
24,157
protected function getTcpConnector ( string $ server ) : TcpConnector { if ( empty ( $ this -> tcp [ $ server ] ) ) { $ this -> tcp [ $ server ] = new TcpConnector ( $ server , $ this -> timeout ) ; } return $ this -> tcp [ $ server ] ; }
Get a TCP connector for the given server .
24,158
protected function createRequest ( string $ host , int $ type ) : Request { $ request = new Request ( ) ; $ request -> addQuestion ( $ host , $ type ) ; $ request -> setRecursionDesired ( true ) ; return $ request ; }
Create a request for the given host and record type .
24,159
private function parseAttribute ( string $ html ) : string { $ remainingHtml = ltrim ( $ html ) ; try { preg_match ( "/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i" , $ remainingHtml , $ attributeMatches ) ; $ attributeName = $ attributeMatches [ 2 ] ; $ remainingHtml = mb_substr ( mb_strstr ( $ remainingHtml , $ attributeName ) , mb_strlen ( $ attributeName ) ) ; if ( $ this -> isAttributeValueless ( $ remainingHtml ) ) { $ this -> attributes [ trim ( $ attributeName ) ] = true ; return $ remainingHtml ; } return $ this -> parseAttributeValue ( $ html , $ remainingHtml , $ attributeName ) ; } catch ( ParseException $ e ) { if ( $ this -> getThrowOnError ( ) ) { throw $ e ; } } return '' ; }
Will parse attributes .
24,160
public function run ( ) { $ count = 0 ; $ start = microtime ( true ) ; while ( true ) { try { return call_user_func ( $ this -> callable ) ; } catch ( \ Throwable $ e ) { if ( ! $ e instanceof $ this -> exceptionType ) { throw $ e ; } if ( $ this -> timeout > - 1 && microtime ( true ) - $ start > ( $ this -> timeout / self :: SECONDS ) ) { throw $ e ; } if ( $ this -> count > - 1 && ++ $ count >= $ this -> count ) { throw $ e ; } if ( array_key_exists ( self :: BEFORE_PAUSE_HOOK , $ this -> hooks ) ) { call_user_func ( $ this -> hooks [ self :: BEFORE_PAUSE_HOOK ] , $ e ) ; } usleep ( $ this -> pause ) ; if ( array_key_exists ( self :: AFTER_PAUSE_HOOK , $ this -> hooks ) ) { call_user_func ( $ this -> hooks [ self :: AFTER_PAUSE_HOOK ] , $ e ) ; } } } }
Runs the retry loop .
24,161
public function setHook ( string $ hook , callable $ callable ) : self { $ availableHooks = [ self :: BEFORE_PAUSE_HOOK , self :: AFTER_PAUSE_HOOK ] ; if ( ! in_array ( $ hook , $ availableHooks ) ) { throw new \ InvalidArgumentException ( 'Invalid hook. Available hooks: ' . join ( ', ' , $ availableHooks ) ) ; } $ this -> hooks [ $ hook ] = $ callable ; return $ this ; }
Sets the hook callback function which will be called if exceptions will raise .
24,162
public function setExceptionType ( string $ exceptionType ) : self { try { $ ref = new \ ReflectionClass ( $ exceptionType ) ; if ( ! $ ref -> implementsInterface ( \ Throwable :: class ) ) { throw new \ InvalidArgumentException ( 'Exception class must implement Throwable interface' ) ; } } catch ( \ ReflectionException $ e ) { throw new \ InvalidArgumentException ( 'Exception class not found' ) ; } $ this -> exceptionType = $ exceptionType ; return $ this ; }
Sets the exception class name which should be catched during tries .
24,163
public function update ( $ params , $ optParams = [ ] ) { if ( ! $ params instanceof Cloud ) { throw new InvalidParamException ( Cloud :: class . ' is required!' ) ; } return $ this -> sendRequest ( [ ] , [ 'restAction' => 'update' , 'restId' => $ params -> id , 'postParams' => $ params -> toArray ( ) , 'getParams' => $ optParams , ] , function ( $ response ) { return isset ( $ response -> data ) ? new Cloud ( $ response -> data ) : $ response ; } ) ; }
Updates a cloud .
24,164
public function delete ( $ params , $ optParams = [ ] ) { if ( $ params instanceof Cloud ) { $ params = $ params -> id ; } return $ this -> sendRequest ( [ ] , [ 'restAction' => 'delete' , 'restId' => $ params , 'getParams' => $ optParams , ] , function ( $ response ) { return $ response -> success ; } ) ; }
Deletes a cloud .
24,165
public function parse ( string $ html ) : TokenCollection { self :: $ allHtml = $ html ; $ tokens = new TokenCollection ( ) ; $ remainingHtml = trim ( $ html ) ; while ( mb_strlen ( $ remainingHtml ) > 0 ) { $ token = TokenFactory :: buildFromHtml ( $ remainingHtml , null , $ this -> throwOnError ) ; if ( ! $ token instanceof Token ) { break ; } $ remainingHtml = $ token -> parse ( $ remainingHtml ) ; $ tokens [ ] = $ token ; } return $ tokens ; }
Will parse html into tokens .
24,166
public function parse ( AbstractStream $ stream ) { try { return parent :: parse ( $ stream ) ; } catch ( \ OutOfBoundsException $ e ) { if ( $ this -> isUntilEof ( ) ) { return $ this -> dataSet -> getData ( ) ; } throw $ e ; } }
Call parse method on arrayed field needed times .
24,167
protected function generateText ( $ node ) { $ buffer = '' ; $ value = explode ( "\n" , $ node [ 'value' ] ) ; $ last = count ( $ value ) - 1 ; foreach ( $ value as $ i => $ line ) { $ line = str_replace ( "'" , '\\\'' , $ line ) ; if ( $ i === $ last ) { $ buffer .= $ this -> prettyPrint ( sprintf ( self :: BLOCK_TEXT_LAST , $ line ) ) ; continue ; } $ buffer .= $ this -> prettyPrint ( sprintf ( self :: BLOCK_TEXT_LINE , $ line ) ) ; } return $ buffer ; }
Partially renders the text tokens
24,168
protected function generatePartials ( ) { $ partials = $ this -> handlebars -> getPartials ( ) ; foreach ( $ partials as $ name => $ partial ) { $ partials [ $ name ] = sprintf ( self :: BLOCK_OPTIONS_HASH_KEY_VALUE , $ name , "'" . str_replace ( "'" , '\\\'' , $ partial ) . "'" ) ; } return $ this -> prettyPrint ( self :: BLOCK_OPTIONS_OPEN ) . $ this -> prettyPrint ( '\r\t' ) . implode ( $ this -> prettyPrint ( ',\r\t' ) , $ partials ) . $ this -> prettyPrint ( self :: BLOCK_OPTIONS_CLOSE ) ; }
Generates partials to add to the layout This is a placeholder incase we want to add in the future
24,169
protected function parseArguments ( $ string ) { Argument :: i ( ) -> test ( 1 , 'string' ) ; $ args = array ( ) ; $ hash = array ( ) ; $ regex = array ( '([a-zA-Z0-9]+\="[^"]*")' , '([a-zA-Z0-9]+\=\'[^\']*\')' , '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)' , '("[^"]*")' , '(\'[^\']*\')' , '([^\s]+)' ) ; preg_match_all ( '#' . implode ( '|' , $ regex ) . '#is' , $ string , $ matches ) ; $ stringArgs = $ matches [ 0 ] ; $ name = array_shift ( $ stringArgs ) ; $ hashRegex = array ( '([a-zA-Z0-9]+\="[^"]*")' , '([a-zA-Z0-9]+\=\'[^\']*\')' , '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)' , ) ; foreach ( $ stringArgs as $ arg ) { if ( ! ( substr ( $ arg , 0 , 1 ) === "'" && substr ( $ arg , - 1 ) === "'" ) && ! ( substr ( $ arg , 0 , 1 ) === '"' && substr ( $ arg , - 1 ) === '"' ) && preg_match ( '#' . implode ( '|' , $ hashRegex ) . '#is' , $ arg ) ) { list ( $ hashKey , $ hashValue ) = explode ( '=' , $ arg , 2 ) ; $ hash [ $ hashKey ] = $ this -> parseArgument ( $ hashValue ) ; continue ; } $ args [ ] = $ this -> parseArgument ( $ arg ) ; } return array ( $ name , $ args , $ hash ) ; }
Handlebars will give arguments in a string This will transform them into a legit argument array
24,170
protected function parseArgument ( $ arg ) { if ( strpos ( $ arg , '"' ) === 0 || strpos ( $ arg , "'" ) === 0 ) { return "'" . str_replace ( "'" , '\\\'' , substr ( $ arg , 1 , - 1 ) ) . "'" ; } if ( strtolower ( $ arg ) === 'null' || strtolower ( $ arg ) === 'true' || strtolower ( $ arg ) === 'false' || is_numeric ( $ arg ) ) { return $ arg ; } $ arg = str_replace ( array ( '[' , ']' , '(' , ')' ) , '' , $ arg ) ; $ arg = str_replace ( "'" , '\\\'' , $ arg ) ; return sprintf ( self :: BLOCK_ARGUMENT_VALUE , $ arg ) ; }
If there s a quote null bool int float ... it s the literal value
24,171
protected function getLogger ( ) { if ( ! isset ( $ this -> logger ) ) { $ this -> logger = new Logger ( 'api-client' ) ; $ this -> logger -> setHandlers ( [ new NullHandler ( ) , ] ) ; } return $ this -> logger ; }
Get the logger instance associated with this instance .
24,172
public function addRating ( $ videoId , $ rating ) { $ this -> validateRating ( $ rating ) ; $ customMetaData = $ this -> getVideo ( $ videoId ) -> getCustomMetadata ( ) ; $ average = $ this -> getRatingAverage ( $ videoId ) ; $ count = $ this -> getRatingCount ( $ videoId ) ; $ newCount = $ count + 1 ; $ customMetaData [ $ this -> metadataFieldCount ] = $ newCount ; $ customMetaData [ $ this -> metadataFieldAverage ] = ( ( $ average * $ count ) + $ rating ) / $ newCount ; $ this -> storeCustomMetaData ( $ customMetaData , $ videoId ) ; }
Increases the count of all ratings by one and calculates a new average rating value .
24,173
private function getCustomMetaDataField ( $ videoId , $ customMetaDataField ) { $ customMetaData = $ this -> getVideo ( $ videoId ) -> getCustomMetadata ( ) ; return array_key_exists ( $ customMetaDataField , $ customMetaData ) ? ( float ) $ customMetaData [ $ customMetaDataField ] : 0 ; }
Returns a meta data field of a video always as a number .
24,174
private function storeCustomMetaData ( $ customMetaData , $ videoId ) { $ this -> client -> setCustomMetaData ( $ this -> vmId , $ videoId , $ this -> filterCustomMetaData ( $ customMetaData ) ) ; $ this -> getVideo ( $ videoId ) -> setCustomMetadata ( $ customMetaData ) ; }
Stores the custom meta data fields with the api client .
24,175
private function getVideo ( $ videoId ) { if ( ! array_key_exists ( $ videoId , $ this -> videos ) ) { $ options = new VideoRequestParameters ( ) ; $ options -> setIncludeCustomMetadata ( true ) ; $ this -> videos [ $ videoId ] = $ this -> client -> getVideo ( $ this -> vmId , $ videoId , $ options ) ; } return $ this -> videos [ $ videoId ] ; }
Fetches and returns video from api client and stores it locally . This way api client will be requested only once for every video .
24,176
private function filterCustomMetaData ( $ customMetaData ) { foreach ( $ customMetaData as $ key => $ data ) { if ( ! in_array ( $ key , [ $ this -> metadataFieldCount , $ this -> metadataFieldAverage ] ) ) { unset ( $ customMetaData [ $ key ] ) ; } } return $ customMetaData ; }
Returns custom meta data fields which are related to rating .
24,177
public function push ( $ value , int $ repeat = null ) : self { if ( $ repeat !== null && $ repeat <= 0 ) { throw new InvalidArgumentException ( sprintf ( static :: MSG_NEGATIVE_ARGUMENT_NOT_ALLOWED , 2 , 1 ) ) ; } for ( $ i = 0 ; $ i < ( $ repeat ?? 1 ) ; $ i ++ ) { $ this -> values [ ] = $ value ; } return $ this ; }
Pushes specified value into array
24,178
public function pushAll ( array $ values ) : self { foreach ( $ values as $ value ) { $ this -> push ( $ value ) ; } return $ this ; }
Pushes multiple values to array
24,179
public function update ( $ params , $ optParams = [ ] ) { if ( ! $ params instanceof AccessToken ) { throw new InvalidParamException ( AccessToken :: class . ' is required!' ) ; } $ class = get_class ( $ params ) ; return $ this -> sendRequest ( [ ] , [ 'restAction' => 'update' , 'restId' => $ params -> id , 'postParams' => $ params -> toArray ( ) , 'getParams' => $ optParams , ] , function ( $ response ) use ( $ class ) { return isset ( $ response -> data ) ? new $ class ( $ response -> data ) : $ response ; } ) ; }
Updates an access token .
24,180
public function view ( $ params , $ optParams = [ ] ) { if ( ! $ params instanceof AccessToken ) { throw new InvalidParamException ( AccessToken :: class . ' is required!' ) ; } $ class = get_class ( $ params ) ; return $ this -> sendRequest ( [ ] , [ 'restAction' => 'view' , 'restId' => $ params -> id , 'getParams' => $ optParams , ] , function ( $ response ) use ( $ class ) { return isset ( $ response -> data ) ? new $ class ( $ response -> data ) : $ response ; } ) ; }
Fetches an access token .
24,181
private function extractContent ( $ docComment , $ annotationClass ) { $ isRecording = false ; $ content = '' ; $ docComment = preg_replace ( '/^[ \t]*(\*\/? ?|\/\*\*)/m' , '' , $ docComment ) ; $ search = '(' . preg_quote ( $ annotationClass , '/' ) . '|' . substr ( $ annotationClass , strrpos ( $ annotationClass , '\\' ) + 1 ) . ')' ; $ lines = preg_split ( '/\n|\r\n/' , $ docComment ) ; foreach ( $ lines as $ line ) { if ( $ isRecording === false && preg_match ( '/^@' . $ search . '(\s|\(|$)/' , $ line ) ) { $ isRecording = true ; } elseif ( $ isRecording ) { if ( preg_match ( '/^@/' , $ line ) ) { break ; } $ content .= $ line . PHP_EOL ; } } return trim ( $ content ) ; }
Extract content below doc comment annotation
24,182
public static function parametrize ( $ str , $ params ) { $ keys = array_keys ( $ params ) ; $ vals = array_values ( $ params ) ; array_walk ( $ keys , function ( & $ key ) { $ key = '%' . $ key . '%' ; } ) ; return str_replace ( $ keys , $ vals , $ str ) ; }
Parametrize string using array of params .
24,183
public static function findOne ( $ pattern , $ entries ) { $ found = [ ] ; foreach ( $ entries as $ entry ) { if ( static :: match ( $ pattern , $ entry ) ) { $ found [ ] = $ entry ; } } return $ found ; }
Filter and return entries that match specified pattern .
24,184
public function run ( $ type = 'default' ) { $ this -> stdout ( "dump {$type}:\n" , Console :: FG_GREEN ) ; switch ( $ type ) { case 'default' : foreach ( $ this -> ipv4 -> getQueries ( ) as $ name => $ query ) { $ this -> dumpDefault ( $ query , $ name ) ; } break ; case 'division' : foreach ( $ this -> ipv4 -> getQueries ( ) as $ name => $ query ) { $ this -> dumpDivision ( $ query , $ name ) ; } break ; case 'division_id' : foreach ( $ this -> ipv4 -> getQueries ( ) as $ name => $ query ) { if ( FileQuery :: is_a ( $ query ) ) { $ this -> dumpDivisionWithId ( $ query , $ name ) ; } } break ; default : $ this -> stderr ( "Unknown type \"{$type}\".\n" , Console :: FG_GREY , Console :: BG_RED ) ; break ; } }
dump ip database
24,185
public static function typeField ( $ type = '' , $ locale = null , $ name = 'type' ) : string { $ result = '<input type="hidden" value="' . $ type . '" name="' ; if ( ! $ locale ) { return $ result . $ name . '">' ; } return $ result . 'trans[' . $ locale . '][files][]">' ; }
Generates the hidden field that links the file to a specific type .
24,186
public function setPageTitle ( array $ config ) : void { foreach ( $ config as $ item ) { if ( isset ( $ item [ 'active' ] ) && $ item [ 'active' ] ) { $ this -> _View -> assign ( 'title' , $ item [ 'title' ] ) ; break ; } } }
Set page title automatically based on the current menu item
24,187
protected function _hasAllowedChildren ( array $ children ) : bool { foreach ( $ children as $ child ) { if ( $ this -> Auth -> urlAllowed ( $ child [ 'url' ] ) ) { return true ; } } return false ; }
Checks if the given array of item children contains at least one URL that is allowed to the current user .
24,188
protected function _isItemActive ( array $ item ) : bool { if ( empty ( $ item [ 'url' ] ) ) { return false ; } $ current = $ this -> _currentUrl ; if ( ! empty ( $ item [ 'url' ] [ 'plugin' ] ) && $ item [ 'url' ] [ 'plugin' ] != $ current [ 'plugin' ] ) { return false ; } if ( $ item [ 'url' ] [ 'controller' ] == $ current [ 'controller' ] && $ item [ 'url' ] [ 'action' ] == $ current [ 'action' ] ) { $ this -> _controllerActive = $ current [ 'controller' ] ; $ this -> _actionActive = $ item [ 'url' ] [ 'action' ] ; return true ; } if ( ! empty ( $ this -> _actionActive ) && $ item [ 'url' ] [ 'controller' ] == $ current [ 'controller' ] ) { $ this -> _controllerActive = $ current [ 'controller' ] ; return true ; } return false ; }
Checks if the given item URL should be marked active in the menu
24,189
public function setFeatureAv ( ChildFeatureAv $ v = null ) { if ( $ v === null ) { $ this -> setFeatureAvId ( NULL ) ; } else { $ this -> setFeatureAvId ( $ v -> getId ( ) ) ; } $ this -> aFeatureAv = $ v ; if ( $ v !== null ) { $ v -> addFeatureTypeAvMeta ( $ this ) ; } return $ this ; }
Declares an association between this object and a ChildFeatureAv object .
24,190
public function getFeatureAv ( ConnectionInterface $ con = null ) { if ( $ this -> aFeatureAv === null && ( $ this -> feature_av_id !== null ) ) { $ this -> aFeatureAv = FeatureAvQuery :: create ( ) -> findPk ( $ this -> feature_av_id , $ con ) ; } return $ this -> aFeatureAv ; }
Get the associated ChildFeatureAv object
24,191
public function setFeatureFeatureType ( ChildFeatureFeatureType $ v = null ) { if ( $ v === null ) { $ this -> setFeatureFeatureTypeId ( NULL ) ; } else { $ this -> setFeatureFeatureTypeId ( $ v -> getId ( ) ) ; } $ this -> aFeatureFeatureType = $ v ; if ( $ v !== null ) { $ v -> addFeatureTypeAvMeta ( $ this ) ; } return $ this ; }
Declares an association between this object and a ChildFeatureFeatureType object .
24,192
public function getFeatureFeatureType ( ConnectionInterface $ con = null ) { if ( $ this -> aFeatureFeatureType === null && ( $ this -> feature_feature_type_id !== null ) ) { $ this -> aFeatureFeatureType = ChildFeatureFeatureTypeQuery :: create ( ) -> findPk ( $ this -> feature_feature_type_id , $ con ) ; } return $ this -> aFeatureFeatureType ; }
Get the associated ChildFeatureFeatureType object
24,193
public function status ( $ status ) { if ( ! ( $ status instanceof Status ) ) { $ status = new Status ( $ status ) ; } $ this -> status = $ status ; return $ this ; }
Set status to given Status instance or status code .
24,194
public function withDetail ( $ key , $ message ) { assert ( ! is_null ( $ key ) , 'Key must not be null' ) ; assert ( ! is_null ( $ message ) , 'Message must not be null' ) ; $ this -> details [ strval ( $ key ) ] = $ message ; return $ this ; }
Record detail using key and message .
24,195
protected function createUser ( array $ credentials ) { $ entity = static :: ENTITY_CLASSNAME ; if ( count ( array_only ( $ credentials , [ 'email' , 'password' , 'username' ] ) ) < 3 ) { throw new \ InvalidArgumentException ( "Missing arguments." ) ; } $ user = new $ entity ( $ credentials [ 'email' ] , $ credentials [ 'password' ] , $ credentials [ 'username' ] ) ; $ rest = array_except ( $ credentials , [ 'email' , 'username' , 'password' ] ) ; if ( ! empty ( $ rest ) ) { $ user -> update ( $ rest ) ; } return $ user ; }
Create a new user based on the given credentials .
24,196
public function sort ( ) : ServiceResponse { $ this -> request -> allowMethod ( 'post' ) ; if ( ! empty ( $ this -> sortModelName ) && ! empty ( $ this -> request -> getData ( 'foreignKey' ) ) ) { $ table = TableRegistry :: getTableLocator ( ) -> get ( $ this -> sortModelName ) ; $ entity = $ table -> get ( $ this -> request -> getData ( 'foreignKey' ) ) ; $ entity -> sort = $ this -> request -> getData ( 'sort' ) ; if ( $ table -> save ( $ entity ) ) { return new ServiceResponse ( ApiReturnCode :: SUCCESS , [ $ entity -> id , $ this -> request -> getData ( 'sort' ) , ] ) ; } return new ServiceResponse ( ApiReturnCode :: INTERNAL_ERROR , [ ] ) ; } throw new NotFoundException ( ) ; }
endpoint for sorting ajax calls
24,197
public function setIndentStyle ( $ indentStyle ) { if ( ! in_array ( $ indentStyle , [ null , Lexer :: INDENT_TAB , Lexer :: INDENT_SPACE ] ) ) { throw new \ InvalidArgumentException ( 'indentStyle needs to be null or one of the INDENT_* constants of the lexer' ) ; } $ this -> indentStyle = $ indentStyle ; return $ this ; }
Sets the current indentation style to a new one .
24,198
public function setIndentWidth ( $ indentWidth ) { if ( ! is_null ( $ indentWidth ) && ( ! is_int ( $ indentWidth ) || $ indentWidth < 1 ) ) { throw new \ InvalidArgumentException ( 'indentWidth needs to be null or an integer above 0' ) ; } $ this -> indentWidth = $ indentWidth ; return $ this ; }
Sets the currently used indentation width .
24,199
public function getHydratorFor ( $ objectClass ) { if ( ! isset ( $ this -> hydratorInstances [ $ objectClass ] ) ) { $ this -> hydratorInstances [ $ objectClass ] = $ this -> createHydratorFor ( $ objectClass ) ; } return $ this -> hydratorInstances [ $ objectClass ] ; }
Factory method to get an hydrator instance or create an hydrator if no instance available .