idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
54,300
public function getBySlug ( $ slug ) { if ( ! isset ( $ this -> entitiesBySlug [ $ slug ] ) ) { throw new DomainErrorException ( 'Unable to find entity for slug ' . $ slug . '!' ) ; } return $ this -> entitiesBySlug [ $ slug ] ; }
Get an entity from by slug
54,301
protected function buildMessage ( $ message , $ indent = '' ) { switch ( true ) { case is_array ( $ message ) : $ this -> buildArrayMessage ( $ message , $ indent ) ; break ; case method_exists ( $ message , '__toString' ) : case is_string ( $ message ) : $ this -> message = $ message . PHP_EOL ; break ; default : throw new InvalidArgumentException ( 'Incorrect message type. Must be string, array or object with __toString method.' ) ; break ; } return $ this ; }
recurrent function to convert array into message
54,302
public static function generateKey ( $ length = Constants :: GENERICHASH_KEYBYTES ) { Helpers :: rangeCheck ( $ length , Constants :: GENERICHASH_KEYBYTES_MAX , Constants :: GENERICHASH_KEYBYTES_MIN , 'Hash' , 'generateKey' ) ; return self :: hash ( Entropy :: bytes ( $ length ) , '' , $ length ) ; }
Generates a hashing key for further repeatable hashes .
54,303
public static function hash ( $ msg , $ key = '' , $ length = Constants :: GENERICHASH_BYTES ) { Helpers :: rangeCheck ( $ length , Constants :: GENERICHASH_BYTES_MAX , Constants :: GENERICHASH_BYTES_MIN , 'Hash' , 'hash' ) ; Helpers :: isString ( $ msg , 'Hash' , 'hash' ) ; Helpers :: isString ( $ key , 'Hash' , 'hash' ) ; return \ Sodium \ crypto_generichash ( $ msg , $ key , $ length ) ; }
Hash a message and return a string .
54,304
public static function shortHash ( $ msg , $ key ) { Helpers :: isString ( $ msg , 'Hash' , 'shortHash' ) ; Helpers :: isString ( $ key , 'Hash' , 'shortHash' ) ; return \ Sodium \ crypto_shorthash ( $ msg , $ key ) ; }
Quickly hash the message using the assigned key using randomness .
54,305
public static function hashPassword ( $ password ) { Helpers :: isString ( $ password , 'Hash' , 'hashPassword' ) ; return \ Sodium \ crypto_pwhash_scryptsalsa208sha256_str ( $ password , Constants :: PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE , Constants :: PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE ) ; }
Hashes a password for storage and later comparison .
54,306
public static function verifyPassword ( $ password , $ passwordHash ) { Helpers :: isString ( $ password , 'Hash' , 'verifyPassword' ) ; Helpers :: isString ( $ passwordHash , 'Hash' , 'verifyPassword' ) ; if ( \ Sodium \ crypto_pwhash_scryptsalsa208sha256_str_verify ( $ passwordHash , $ password ) ) { \ Sodium \ memzero ( $ password ) ; return true ; } else { \ Sodium \ memzero ( $ password ) ; return false ; } }
Test if a password is valid against it s stored hash .
54,307
public function getFiltersJson ( ) { $ result = [ ] ; if ( false === is_array ( $ this -> getFilters ( ) ) ) { return "{}" ; } foreach ( $ this -> getFilters ( ) as $ filterIndex => $ items ) { foreach ( $ items as $ item ) { $ result [ $ filterIndex ] [ ] = [ 'id' => $ item -> getId ( ) , 'text' => $ item -> getText ( ) , ] ; } } return json_encode ( $ result ) ; }
Get Filters as JSON
54,308
protected function propertiesToArray ( ReflectionObject $ reflection ) { $ properties = $ reflection -> getProperties ( ReflectionProperty :: IS_PUBLIC ) ; $ data = [ ] ; foreach ( $ properties as $ property ) { if ( $ property -> class !== __CLASS__ ) { $ data [ $ property -> name ] = $ this -> { $ property -> name } ; } } return $ data ; }
Convert all the public properties to an array .
54,309
protected function methodsToArray ( ReflectionObject $ reflection ) { $ methods = $ reflection -> getMethods ( ReflectionMethod :: IS_PUBLIC ) ; $ data = [ ] ; foreach ( $ methods as $ method ) { if ( $ method -> class !== __CLASS__ && substr ( $ method -> name , 0 , 2 ) !== '__' ) { $ data [ $ method -> name ] = $ this -> { $ method -> name } ( ) ; } } return $ data ; }
Convert all the public methods to an array .
54,310
protected function hasAccessibleMethod ( $ key ) { if ( method_exists ( $ this , $ key ) ) { $ reflection = new ReflectionMethod ( $ this , $ key ) ; return $ reflection -> isPublic ( ) ; } return false ; }
Determine if the given method is public .
54,311
protected function hasAccessibleProperty ( $ key ) { if ( isset ( $ this -> $ key ) ) { $ reflection = new ReflectionProperty ( $ this , $ key ) ; return $ reflection -> isPublic ( ) ; } return false ; }
Determine if the given property is public .
54,312
public function save ( array $ options = array ( ) ) { if ( ! $ this -> exists ) { $ this -> recordEvents ( new PostWasCreatedEvent ( $ this ) ) ; } $ saved = parent :: save ( $ options ) ; return $ saved ; }
Save Post ensuring a Category is assigned
54,313
public function getMediaToken ( $ mediaContentKey , $ clientUserId = null , array $ optParams = [ ] ) { if ( ! isset ( $ optParams [ 'security_key' ] ) ) { $ optParams [ 'security_key' ] = $ this -> serviceAccount -> getKey ( ) ; } if ( ! isset ( $ optParams [ 'media_content_key' ] ) ) { $ optParams [ 'media_content_key' ] = $ mediaContentKey ; } if ( ! empty ( $ clientUserId ) ) { $ optParams [ 'client_user_id' ] = $ clientUserId ; } if ( ! isset ( $ optParams [ 'expire_time' ] ) ) { $ optParams [ 'expire_time' ] = 7200 ; } $ response = $ this -> getResponseJSON ( 'POST' , 'media_auth/media_token/get_media_link_by_userid.json' , [ ] , $ optParams ) ; if ( ! isset ( $ response -> result -> media_token ) ) { throw new ClientException ( 'Response is invalid.' ) ; } return $ response -> result -> media_token ; }
will be depricated
54,314
public static function all ( ) : array { $ class = get_called_class ( ) ; if ( isset ( self :: $ items [ $ class ] ) ) { return self :: $ items [ $ class ] ; } $ constants = static :: constants ( ) ; $ items = [ ] ; foreach ( $ constants as $ key => $ value ) { $ items [ $ value ] = new $ class ( $ key , $ value ) ; } return self :: $ items [ $ class ] = $ items ; }
Get all enum items of particular enum class
54,315
public static function only ( array $ values ) : array { $ items = [ ] ; foreach ( $ values as $ value ) { $ item = static :: get ( $ value ) ; $ items [ $ item -> value ( ) ] = $ item ; } return $ items ; }
Returns enum instances only with given values
54,316
public static function get ( $ value ) : self { $ class = get_called_class ( ) ; if ( $ value instanceof self ) { $ value = $ value -> value ( ) ; } if ( ! static :: has ( $ value ) ) { throw EnumException :: invalidEnumValue ( $ class , $ value ) ; } return static :: all ( ) [ $ value ] ; }
Returns an enum item with given value
54,317
public function is ( $ value , bool $ strict = false ) : bool { if ( $ this === $ value ) { return true ; } if ( $ strict && ( ! is_object ( $ value ) || get_class ( $ this ) !== get_class ( $ value ) ) ) { return false ; } if ( $ value instanceof self ) { $ value = $ value -> value ( ) ; } return $ this -> value ( ) == $ value ; }
Compares enum object with given value .
54,318
public function in ( array $ values ) : bool { foreach ( $ values as $ value ) { if ( $ this -> is ( $ value ) ) { return true ; } } return false ; }
Checks if this enum is contained in the given array of values
54,319
private static function constants ( ) : array { $ class = get_called_class ( ) ; if ( isset ( self :: $ constants [ $ class ] ) ) { return self :: $ constants [ $ class ] ; } $ reflection = new \ ReflectionClass ( $ class ) ; return self :: $ constants [ $ class ] = $ reflection -> getConstants ( ) ; }
Returns constants map of given class
54,320
public function tree ( $ hash = '' , $ deep = 0 , $ exclude = '' ) { $ path = $ hash ? $ this -> decode ( $ hash ) : $ this -> root ; if ( ( $ dir = $ this -> stat ( $ path ) ) == false || $ dir [ 'mime' ] != 'directory' ) { return false ; } $ dirs = $ this -> gettree ( $ path , $ deep > 0 ? $ deep - 1 : $ this -> treeDeep - 1 , $ this -> decode ( $ exclude ) ) ; array_unshift ( $ dirs , $ dir ) ; return $ dirs ; }
Return subfolders for required folder or false on error
54,321
public function putContents ( $ hash , $ content ) { if ( $ this -> commandDisabled ( 'edit' ) ) { return $ this -> setError ( elFinder :: ERROR_PERM_DENIED ) ; } $ path = $ this -> decode ( $ hash ) ; if ( ! ( $ file = $ this -> file ( $ hash ) ) ) { return $ this -> setError ( elFinder :: ERROR_FILE_NOT_FOUND ) ; } if ( ! $ file [ 'write' ] ) { return $ this -> setError ( elFinder :: ERROR_PERM_DENIED ) ; } $ this -> clearcache ( ) ; return $ this -> _filePutContents ( $ path , $ content ) ? $ this -> stat ( $ path ) : false ; }
Put content in text file and return file info .
54,322
public function archive ( $ hashes , $ mime ) { if ( $ this -> commandDisabled ( 'archive' ) ) { return $ this -> setError ( elFinder :: ERROR_PERM_DENIED ) ; } $ archiver = isset ( $ this -> archivers [ 'create' ] [ $ mime ] ) ? $ this -> archivers [ 'create' ] [ $ mime ] : false ; if ( ! $ archiver ) { return $ this -> setError ( elFinder :: ERROR_ARCHIVE_TYPE ) ; } $ files = array ( ) ; foreach ( $ hashes as $ hash ) { if ( ( $ file = $ this -> file ( $ hash ) ) == false ) { return $ this -> error ( elFinder :: ERROR_FILE_NOT_FOUND , '#' + $ hash ) ; } if ( ! $ file [ 'read' ] ) { return $ this -> error ( elFinder :: ERROR_PERM_DENIED ) ; } $ path = $ this -> decode ( $ hash ) ; if ( ! isset ( $ dir ) ) { $ dir = $ this -> _dirname ( $ path ) ; $ stat = $ this -> stat ( $ dir ) ; if ( ! $ stat [ 'write' ] ) { return $ this -> error ( elFinder :: ERROR_PERM_DENIED ) ; } } $ files [ ] = $ this -> _basename ( $ path ) ; } $ name = ( count ( $ files ) == 1 ? $ files [ 0 ] : 'Archive' ) . '.' . $ archiver [ 'ext' ] ; $ name = $ this -> uniqueName ( $ dir , $ name , '' ) ; $ this -> clearcache ( ) ; return ( $ path = $ this -> _archive ( $ dir , $ files , $ name , $ archiver ) ) ? $ this -> stat ( $ path ) : false ; }
Add files to archive
54,323
protected function decode ( $ hash ) { if ( strpos ( $ hash , $ this -> id ) === 0 ) { $ h = substr ( $ hash , strlen ( $ this -> id ) ) ; $ h = base64_decode ( strtr ( $ h , '-_.' , '+/=' ) ) ; $ path = $ this -> uncrypt ( $ h ) ; return $ this -> _abspath ( $ path ) ; } }
Decode path from hash
54,324
public function uniqueName ( $ dir , $ name , $ suffix = ' copy' , $ checkNum = true ) { $ ext = '' ; if ( preg_match ( '/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i' , $ name , $ m ) ) { $ ext = '.' . $ m [ 1 ] ; $ name = substr ( $ name , 0 , strlen ( $ name ) - strlen ( $ m [ 0 ] ) ) ; } if ( $ checkNum && preg_match ( '/(' . $ suffix . ')(\d*)$/i' , $ name , $ m ) ) { $ i = ( int ) $ m [ 2 ] ; $ name = substr ( $ name , 0 , strlen ( $ name ) - strlen ( $ m [ 2 ] ) ) ; } else { $ i = 1 ; $ name .= $ suffix ; } $ max = $ i + 100000 ; while ( $ i <= $ max ) { $ n = $ name . ( $ i > 0 ? $ i : '' ) . $ ext ; if ( ! $ this -> stat ( $ this -> _joinPath ( $ dir , $ n ) ) ) { $ this -> clearcache ( ) ; return $ n ; } $ i ++ ; } return $ name . md5 ( $ dir ) . $ ext ; }
Return new unique name based on file name and suffix
54,325
protected function gettree ( $ path , $ deep , $ exclude = '' ) { $ dirs = array ( ) ; ! isset ( $ this -> dirsCache [ $ path ] ) && $ this -> cacheDir ( $ path ) ; foreach ( $ this -> dirsCache [ $ path ] as $ p ) { $ stat = $ this -> stat ( $ p ) ; if ( $ stat && empty ( $ stat [ 'hidden' ] ) && $ path != $ exclude && $ stat [ 'mime' ] == 'directory' ) { $ dirs [ ] = $ stat ; if ( $ deep > 0 && ! empty ( $ stat [ 'dirs' ] ) ) { $ dirs = array_merge ( $ dirs , $ this -> gettree ( $ p , $ deep - 1 ) ) ; } } } return $ dirs ; }
Return subdirs tree
54,326
protected function canCreateTmb ( $ path , $ stat ) { return $ this -> tmbPathWritable && strpos ( $ path , $ this -> tmbPath ) === false && $ this -> imgLib && strpos ( $ stat [ 'mime' ] , 'image' ) === 0 && ( $ this -> imgLib == 'gd' ? $ stat [ 'mime' ] == 'image/jpeg' || $ stat [ 'mime' ] == 'image/png' || $ stat [ 'mime' ] == 'image/gif' : true ) ; }
Return true if thumnbnail for required file can be created
54,327
protected function formatDate ( $ ts ) { if ( $ ts > $ this -> today ) { return 'Today ' . date ( $ this -> options [ 'timeFormat' ] , $ ts ) ; } if ( $ ts > $ this -> yesterday ) { return 'Yesterday ' . date ( $ this -> options [ 'timeFormat' ] , $ ts ) ; } return date ( $ this -> options [ 'dateFormat' ] , $ ts ) ; }
Return smart formatted date
54,328
public function reconnect ( ) { if ( $ this -> getMaxReconnects ( ) < $ this -> getReconnectCount ( ) ) { return false ; } $ this -> increaseReconnectCount ( ) ; return $ this -> ping ( ) ; }
since this method is a wrapper for the tryReconnect only limited we set a max amount of retries . increase the counter and reconnect as often as defined
54,329
public function setValue ( $ value ) { parent :: setValue ( $ value ) ; if ( $ this -> hasAttribute ( 'value' ) ) { $ this -> getAttributes ( ) -> remove ( 'value' ) ; } return $ this ; }
Adds the value to the select
54,330
public static function createFromException ( \ Exception $ e , $ http_status = Response :: STATUS_ERROR ) { return new Error ( $ e -> getMessage ( ) , $ http_status , $ e -> getFile ( ) , $ e -> getLine ( ) , $ e ) ; }
Special static Error creator from any Exception
54,331
public function createTagVersionRequest ( $ baseUrl , $ consumerName , $ version , $ tagName ) { $ url = $ baseUrl . '/pacticipants/' . $ consumerName . '/versions/' . $ version . '/tags/' . $ tagName ; $ request = new Request ( 'PUT' , $ url , [ "Content-Type" => "application/json" ] ) ; return $ request ; }
Creates request for tagging version
54,332
public function createRetrievePactRequest ( $ baseUrl , $ consumerName , $ providerName , $ version , $ tagName = null ) { $ url = $ baseUrl . '/pacts/provider/' . $ providerName . '/consumer/' . $ consumerName ; $ suffix = '' ; if ( $ version === 'latest' ) { $ suffix .= '/latest' ; } else { $ suffix .= '/versions/' . $ version ; } if ( $ tagName ) { $ suffix .= '/' . $ tagName ; } $ url .= $ suffix ; $ request = new Request ( 'GET' , $ url , [ "Content-Type" => "application/json" ] ) ; return $ request ; }
Creates request for retrieving pact file
54,333
public static function generateGUID ( ) { $ guidStr = '' ; for ( $ i = 1 ; $ i <= 16 ; $ i ++ ) { $ b = ( int ) mt_rand ( 0 , 0xff ) ; if ( $ i == 7 ) { $ b &= 0x0f ; $ b |= 0x40 ; } if ( $ i == 9 ) { $ b &= 0x3f ; $ b |= 0x80 ; } $ guidStr .= sprintf ( '%02s' , base_convert ( $ b , 10 , 16 ) ) ; if ( $ i == 4 || $ i == 6 || $ i == 8 || $ i == 10 ) { $ guidStr .= '-' ; } } return $ guidStr ; }
Generates GUID .
54,334
public static function snake ( $ str , $ delimiter = '_' ) { $ str = preg_replace ( '/([A-Z ])/' , ' $1' , $ str ) ; $ str = preg_replace ( '/\s+/' , $ delimiter , trim ( $ str ) ) ; $ str = strtolower ( $ str ) ; return $ str ; }
Converts string into snaked style .
54,335
public function setDebugLogger ( IDebugLogger $ debug_logger ) { $ this -> debug_logger = $ debug_logger ; if ( $ this -> debug_logger ) { $ this -> debug_logger -> afterDebugLoggerRegistered ( $ this ) ; } }
Set debug logger
54,336
public function getMachine ( Smalldb $ smalldb , string $ type ) { if ( isset ( $ this -> machine_type_cache [ $ type ] ) ) { return $ this -> machine_type_cache [ $ type ] ; } if ( ! $ this -> initialized ) { throw new InitializationException ( "Backend not initialized." ) ; } else { $ m = $ this -> machine_type_cache [ $ type ] = $ this -> createMachine ( $ smalldb , $ type ) ; if ( $ m && $ this -> debug_logger ) { $ m -> setDebugLogger ( $ this -> debug_logger ) ; $ this -> debug_logger -> afterMachineCreated ( $ this , $ type , $ m ) ; } return $ m ; } }
Get state machine of given type create it if necessary .
54,337
public function readInput ( $ inputStream = STDIN ) { $ output = new ConsoleOutput ( ) ; $ sttyMode = shell_exec ( 'stty -g' ) ; shell_exec ( 'stty -icanon -echo intr undef' ) ; $ this -> userInput = '' ; $ this -> cursorPosition = 0 ; if ( ( $ commands = $ this -> history -> getCommands ( ) ) != [ ] ) { end ( $ commands ) ; $ this -> history -> setCommands ( $ commands ) ; } $ this -> countUpPressed = 0 ; while ( ! feof ( $ inputStream ) ) { $ c = fread ( $ inputStream , 1 ) ; if ( "\177" === $ c ) { $ this -> onBackspacePressed ( ) ; } elseif ( ord ( $ c ) == 1 ) { $ this -> moveCursorToBeginOfInputLine ( ) ; } elseif ( ord ( $ c ) == 3 ) { } elseif ( ord ( $ c ) == 5 ) { $ this -> moveCursorToEndOfLine ( ) ; } elseif ( ord ( $ c ) == 11 ) { $ this -> removeInputRightFromCursor ( ) ; } elseif ( "\033" === $ c ) { $ c .= fread ( $ inputStream , 2 ) ; if ( isset ( $ c [ 2 ] ) && ( 'A' === $ c [ 2 ] || 'B' === $ c [ 2 ] ) ) { $ this -> clearLine ( ) ; if ( 'A' === $ c [ 2 ] ) { $ this -> onUpArrowPressed ( ) ; } elseif ( 'B' === $ c [ 2 ] ) { $ this -> onDownArrowPressed ( ) ; } } elseif ( isset ( $ c [ 2 ] ) && ( 'D' === $ c [ 2 ] ) ) { $ this -> onLeftArrowPressed ( ) ; } elseif ( isset ( $ c [ 2 ] ) && ( 'C' === $ c [ 2 ] ) ) { $ this -> onRightArrowPressed ( ) ; } } elseif ( ord ( $ c ) < 32 ) { if ( "\t" === $ c || "\n" === $ c ) { if ( "\n" === $ c ) { $ this -> onEnterPressed ( ) ; break ; } } continue ; } else { $ this -> userInput = substr ( $ this -> userInput , 0 , $ this -> cursorPosition ) . $ c . substr ( $ this -> userInput , $ this -> cursorPosition ) ; $ this -> cursorPosition ++ ; } $ this -> printCurrentUserInput ( ) ; } shell_exec ( sprintf ( 'stty %s' , $ sttyMode ) ) ; $ userInput = trim ( $ this -> userInput ) ; return $ userInput ; }
Reads the input from the input stream .
54,338
private function restoreLastUserInput ( ) { $ this -> userInput = $ this -> lastInput ; $ this -> cursorPosition = mb_strlen ( $ this -> userInput ) ; }
Restores the last user input .
54,339
protected function default_table_name ( ) { $ class_name = explode ( "\\" , get_called_class ( ) ) ; return $ this -> prefix . strtolower ( $ class_name [ count ( $ class_name ) - 1 ] ) ; }
Generate default table name
54,340
protected function init ( ) { $ this -> register_cli ( ) ; if ( ! $ this -> name ) { $ this -> name = $ this -> default_table_name ( ) ; } add_action ( 'admin_init' , function ( ) { if ( wp_doing_ajax ( ) ) { return ; } $ this -> create_table ( ) ; } , $ this -> priority ) ; }
Register table if needed .
54,341
protected function get_place_holders ( $ args ) { $ wheres = [ ] ; foreach ( $ args as $ key => $ val ) { if ( ! isset ( $ this -> default_placeholder [ $ key ] ) ) { throw new \ Exception ( sprintf ( __ ( 'Model %1$s has no column "%2$s".' , 'karma' ) , get_called_class ( ) , $ key ) , 500 ) ; } $ wheres [ ] = $ this -> default_placeholder [ $ key ] ; } return $ wheres ; }
Get place holders .
54,342
public function bulk_insert ( array $ records ) { $ cols = [ ] ; foreach ( $ records as $ record ) { foreach ( $ record as $ key => $ value ) { $ cols [ ] = $ key ; } break ; } $ current_time = current_time ( 'mysql' , $ this -> use_gmt ( ) ) ; foreach ( [ 'created' , 'updated' ] as $ key ) { if ( ! in_array ( $ key , $ cols ) ) { $ cols [ ] = $ key ; $ records = array_map ( function ( $ values ) use ( $ key ) { $ values [ $ key ] = current_time ( 'mysql' , true ) ; return $ values ; } , $ records ) ; } } $ value_expression = implode ( ', ' , array_map ( function ( $ values ) { $ escaped_values = [ ] ; foreach ( $ values as $ key => $ value ) { $ escaped_values [ ] = $ this -> db -> prepare ( $ this -> get_place_holder ( $ key ) , $ value ) ; } return sprintf ( '(%s)' , implode ( ', ' , $ escaped_values ) ) ; } , $ records ) ) ; $ cols = implode ( ', ' , array_map ( function ( $ col ) { return "`{$col}`" ; } , $ cols ) ) ; $ query = <<<SQL INSERT INTO {$this->table} ( {$cols} ) VALUES {$value_expression}SQL ; return $ this -> db -> query ( $ query ) ; }
Insert multiple values
54,343
final public function delete ( array $ where , $ table = '' , $ place_holders = [ ] ) { if ( ! $ place_holders ) { try { $ place_holders = $ this -> get_place_holders ( $ where ) ; } catch ( \ Exception $ e ) { return false ; } } return $ this -> db -> delete ( $ table ? : $ this -> table , $ where , $ place_holders ) ; }
Delete data .
54,344
public function register_cli ( ) { if ( ! defined ( 'WP_CLI' ) || ! WP_CLI ) { return ; } self :: $ list [ $ this -> table ] = get_called_class ( ) ; if ( self :: $ initialized ) { return ; } \ WP_CLI :: add_command ( "schema" , \ Hametuha \ Pattern \ Command :: class ) ; self :: $ initialized = false ; }
Register CLI command
54,345
public function generateWhere ( ? array $ clauses , string $ prepend = '' ) : string { if ( null === $ clauses || count ( $ clauses ) < 1 ) { return '' ; } $ clauses = array_values ( array_filter ( $ clauses , function ( $ val ) { return $ val !== '' ; } ) ) ; $ return = implode ( ' AND ' , $ clauses ) ; if ( $ return !== '' ) { $ return = $ prepend . ' ' . $ return ; } return $ return ; }
Takes snippets of where clauses to generate an anded where clause .
54,346
protected function validateConfiguration ( array $ config ) : bool { if ( ! is_array ( $ config ) ) { throw new DatabaseConnectionException ( 'The configuration is not an array.' ) ; } if ( ! isset ( $ config [ 'server' ] ) ) { throw new DatabaseConnectionException ( 'The configuration does not contain a host.' ) ; } if ( ! isset ( $ config [ 'username' ] ) ) { throw new DatabaseConnectionException ( 'The configuration does not contain a username.' ) ; } if ( ! isset ( $ config [ 'password' ] ) ) { throw new DatabaseConnectionException ( 'The configuration does not contain a password.' ) ; } return true ; }
Checks the configuration array for required elements . By default checks the server username and password elements are set . Override to check for additional elements required for a specific database .
54,347
public function apply ( $ testable , array $ config = array ( ) ) { $ message = 'Casting in the incorrect format, try: "(array) $object;"' ; $ tokens = $ testable -> tokens ( ) ; $ filtered = $ testable -> findAll ( $ this -> tokens ) ; foreach ( $ filtered as $ id ) { $ token = $ tokens [ $ id ] ; $ html = '' ; foreach ( array_slice ( $ tokens , $ id , 3 ) as $ t ) { $ html .= $ t [ 'content' ] ; } if ( preg_match ( $ this -> pattern , $ html ) === 0 ) { $ this -> addViolation ( array ( 'message' => $ message , 'line' => $ token [ 'line' ] , ) ) ; } } }
Iterates tokens looking for cast tokens then testing against a regex
54,348
public function buildForm ( FormBuilderInterface $ builder , array $ options ) { $ builder -> addModelTransformer ( $ this ) -> addEventListener ( FormEvents :: PRE_SET_DATA , function ( FormEvent $ event ) use ( $ builder , $ options ) { $ form = $ event -> getForm ( ) ; $ data = array ( 'template_types' => null , 'templates' => array ( ) , ) ; $ templateFormBuilder = $ builder -> create ( 'templates' , null , array ( 'compound' => true , 'auto_initialize' => false , ) ) ; $ templateTypeChoices = array ( ) ; foreach ( $ options [ 'theme' ] -> getTemplateTypes ( ) as $ templateType ) { $ variation = $ this -> variationResolver -> resolve ( ( new VariationContext ( ) ) -> denormalize ( array ( 'theme' => $ options [ 'theme' ] , 'content_type' => $ contentType = $ options [ 'content_type' ] , 'template_type' => $ templateType , ) ) ) ; if ( ! $ templateType -> supportsContentType ( $ contentType -> getName ( ) , $ variation -> getConfiguration ( 'templates' , $ templateType -> getName ( ) , 'contents' , array ( ) ) ) ) { continue ; } $ templateTypeChoices [ $ templateType -> getId ( ) ] = $ templateType ; $ template = $ options [ 'content' ] ? $ this -> templateLoader -> retrieveLocal ( $ templateType , $ options [ 'content' ] ) : $ this -> templateLoader -> retrieveGlobal ( $ templateType , $ contentType ) ; if ( ! $ template ) { continue ; } $ data [ 'templates' ] [ $ templateType -> getName ( ) ] = $ template ; $ templateFormBuilder -> add ( $ templateType -> getName ( ) , TemplateType :: class , array ( 'auto_initialize' => false , 'content_type' => $ options [ 'content_type' ] , 'theme' => $ options [ 'theme' ] , 'template_type' => $ templateType , 'variation' => $ variation , ) ) ; } $ form -> add ( 'template_types' , ChoiceType :: class , array ( 'required' => true , 'expanded' => false , 'auto_initialize' => false , 'choices' => $ templateTypeChoices , 'mapped' => false , 'choice_value' => 'name' , 'choice_label' => 'name' , ) ) -> add ( $ templateFormBuilder -> getForm ( ) ) ; $ event -> setData ( $ data ) ; } ) ; }
Theme form prototype definition .
54,349
public static function add ( array $ translates , string $ locale = null ) : void { $ locale = ( $ locale === null ) ? I18n :: $ locale : $ locale ; if ( isset ( I18n :: $ dictionary [ $ locale ] ) ) { I18n :: $ dictionary [ $ locale ] += $ translates ; } else { I18n :: $ dictionary [ $ locale ] = $ translates ; } }
Add translation keys
54,350
public function toDatatablesString ( ) { $ string = "" ; $ fields = $ this :: getFields ( ) ; foreach ( $ fields as $ field ) { $ value = call_user_func ( array ( $ this , 'get' . $ field ) ) ; if ( $ value instanceof \ DateTime ) { $ value = $ value -> format ( 'Y-m-d' ) ; } $ string .= $ value . "," ; } $ string = trim ( $ string , "," ) ; $ string = str_replace ( "\n" , "" , $ string ) ; return $ string ; }
String with comma separated values .
54,351
public function get ( $ key ) { $ storageValue = null ; if ( true === array_key_exists ( $ key , $ this -> storage ) ) { $ storageValue = $ this -> storage [ $ key ] ; } return $ storageValue ; }
Gets a value from a key in the storage
54,352
public function setProfile ( $ profile ) { $ this -> _profile = $ profile ; $ this -> setConfig ( $ this -> getProfileConfig ( 'parser' ) ) ; $ this -> reset ( $ this -> _string , true ) ; $ this -> defaults ( ) ; return $ this ; }
Change the active profile .
54,353
public function getProfileConfig ( $ key ) { if ( empty ( $ this -> _profile ) ) { return $ this -> _configs -> get ( 'bbcoder::profile.default.' . $ key ) ; } if ( $ this -> _configs -> has ( 'bbcoder::profile.' . $ this -> _profile . '.' . $ key ) ) { return $ this -> _configs -> get ( 'bbcoder::profile.' . $ this -> _profile . '.' . $ key ) ; } return $ this -> _configs -> get ( 'bbcoder::profile.default.' . $ key ) ; }
Load the profile s config .
54,354
public function defaults ( ) { foreach ( $ this -> getProfileConfig ( 'filters' ) as $ filter ) { $ this -> addFilter ( new $ filter ) ; } foreach ( $ this -> getProfileConfig ( 'hooks' ) as $ hook => $ config ) { $ this -> addHook ( new $ hook ( $ config ) ) ; } $ this -> whitelist ( $ this -> getProfileConfig ( 'whitelist' ) ) ; $ this -> blacklist ( $ this -> getProfileConfig ( 'blacklist' ) ) ; $ this -> addPath ( $ this -> _configs -> get ( 'bbcoder::cpath' ) ) ; return $ this ; }
Set defaults for the profile .
54,355
function add ( Expr $ next ) { if ( $ this -> isNull ( ) ) { throw new \ UnexpectedValueException ( "Cannot add anything to NULL" ) ; } if ( $ this -> next ) { $ this -> next -> add ( $ next ) ; } else { $ this -> next = $ next ; } return $ this ; }
Append an expresssion
54,356
public function fetch ( ) { if ( is_null ( $ this -> config ) ) { $ this -> config = $ this -> loadConfiguration ( ) ; } return $ this -> config ; }
Fetches the configuration . If no option is specified it ll search the local path for a file with the expected filename . If an option is provided it ll try to load the configuration from that file . If no configuration is found then it returns false . There is no enforced return type .
54,357
protected function updateLogFile ( ) { if ( $ this -> fileIsChanged ( ) ) { fclose ( $ this -> fileHandle ) ; $ logFile = $ this -> genLogFile ( true ) ; $ this -> file = $ logFile ; $ this -> fileHandle = @ fopen ( $ logFile , 'ab' ) ; if ( ! $ this -> fileHandle ) { $ this -> stderr ( "Could not open the log file {$logFile}" ) ; } } }
update the log file name . If log_split is not empty and manager running to long time .
54,358
public function genLogFile ( $ createDir = false ) { if ( ! ( $ type = $ this -> spiltType ) || ! ( $ file = $ this -> file ) ) { return $ this -> file ; } $ info = pathinfo ( $ file ) ; $ dir = $ info [ 'dirname' ] ; $ name = $ info [ 'filename' ] ?? 'gw-manager' ; $ ext = $ info [ 'extension' ] ?? 'log' ; if ( $ createDir ) { Directory :: mkdir ( $ dir , 0775 ) ; } $ str = $ this -> getLogFileDate ( ) ; return "{$dir}/{$name}_{$str}.{$ext}" ; }
gen real LogFile
54,359
protected function sysLog ( $ msg , $ level ) { switch ( $ level ) { case self :: EMERG : $ priority = LOG_EMERG ; break ; case self :: ERROR : $ priority = LOG_ERR ; break ; case self :: WARN : $ priority = LOG_WARNING ; break ; case self :: DEBUG : $ priority = LOG_DEBUG ; break ; case self :: INFO : case self :: PROC_INFO : case self :: WORKER_INFO : default : $ priority = LOG_INFO ; break ; } if ( ! $ ret = syslog ( $ priority , $ msg ) ) { $ this -> stderr ( "Unable to write to syslog\n" ) ; } return $ ret ; }
Logs data to the syslog
54,360
public function created ( EntryInterface $ entry ) { $ this -> commands -> dispatch ( new CreateTypeStream ( $ entry ) ) ; parent :: created ( $ entry ) ; }
Fired after a page type is created .
54,361
public function deleted ( EntryInterface $ entry ) { $ this -> commands -> dispatch ( new DeleteTypeStream ( $ entry ) ) ; parent :: deleted ( $ entry ) ; }
Fired after a page type is deleted .
54,362
static public function bootstrap ( $ root = '' , $ data_folder = '' ) { if ( self :: $ is_init ) { return self :: $ is_init ; } if ( $ root != '' ) { self :: $ root_folder = $ root ; } else { throw new \ Exception ( 'Root folder must be setted.' ) ; } if ( $ data_folder != '' ) { self :: $ data_folder = self :: $ root_folder . '/' . $ data_folder ; } else { throw new \ Exception ( 'Data folder must be setted.' ) ; } self :: $ app = new DataApplication ( self :: $ data_folder ) ; self :: $ is_init = true ; self :: $ app -> renders -> register ( new DefaultRender ( ) ) ; self :: $ app -> renders -> register ( new MarkdownRender ( ) ) ; return self :: $ is_init ; }
Initializes the engine .
54,363
static public function register_render ( $ instance ) { if ( $ instance == null ) { throw new \ Exception ( 'Instance is null.' ) ; } self :: $ app -> renders -> register ( $ instance ) ; }
Register a new render component .
54,364
static public function run ( ) { foreach ( self :: $ dbs as $ db ) { $ db -> execute ( self :: files ( ) ) ; } foreach ( self :: $ writers as $ writer ) { $ writer -> execute ( self :: files ( ) ) ; } }
Run ... Execute the execute method in each database component to generate data . Execute the execute method in each writer to write pages .
54,365
public function create ( LanguageListener $ listener , Request $ request ) { if ( $ request -> isMethod ( 'post' ) ) { $ form = $ this -> presenter -> form ( ) ; if ( ! $ form -> isValid ( ) ) { return $ listener -> createFailed ( $ form -> getMessageBag ( ) ) ; } try { $ data = $ form -> getData ( ) ; $ this -> languageRepository -> insert ( $ data ) ; } catch ( Exception $ ex ) { Log :: warning ( $ e ) ; return $ listener -> createFailed ( $ ex -> getMessage ( ) ) ; } return $ listener -> createSucceed ( ) ; } return $ this -> presenter -> create ( ) ; }
create new language form
54,366
public function publish ( LanguageListener $ listener , $ type ) { try { $ languages = Languages :: all ( ) ; foreach ( $ languages as $ language ) { $ this -> publisher -> publish ( $ language ) ; } return $ listener -> publishSucceed ( $ type ) ; } catch ( Exception $ e ) { Log :: warning ( $ e ) ; return $ listener -> publishFailed ( $ type , $ e -> getMessage ( ) ) ; } }
processing publish action
54,367
public function import ( LanguageListener $ listener , $ type , $ locale = null ) { $ input = Input :: all ( ) ; $ locale = is_null ( $ locale ) ? app ( ) -> getLocale ( ) : $ locale ; $ uploadedFile = array_get ( $ input , 'file' ) ; if ( ! app ( 'request' ) -> isMethod ( 'post' ) ) { return $ this -> presenter -> import ( ) ; } elseif ( ! is_null ( $ uploadedFile ) and ( $ uploadedFile instanceof LaravelUploadedFile ) ) { return $ this -> uploadTemporary ( $ uploadedFile , $ input ) ; } elseif ( ! is_null ( $ uploadedFile ) and is_string ( $ uploadedFile ) ) { return ( $ this -> translationRepository -> importTranslations ( $ uploadedFile , $ type ) ) ? $ listener -> importSuccess ( $ type , $ locale ) : $ listener -> importFailed ( ) ; } return $ listener -> importFailed ( ) ; }
processing import action
54,368
protected function uploadTemporary ( LaravelUploadedFile $ uploadedFile , array $ input ) { $ file = $ this -> resolveTempFileName ( $ uploadedFile ) ; $ uploadedFile -> directory = $ file [ 'directory' ] ; $ uploadedFile -> filename = $ file [ 'filename' ] ; Validator :: resolver ( function ( $ translator , $ data , $ rules , $ messages ) { return new CsvCustomValidator ( $ translator , $ data , $ rules , $ messages ) ; } ) ; $ validation = $ this -> validator -> on ( 'upload' ) -> with ( $ input , [ ] , [ 'source' => trans ( 'antares/foundation::response.modules.validator.invalid-structure' ) ] ) ; if ( $ validation -> fails ( ) ) { return Response :: make ( $ validation -> getMessageBag ( ) -> first ( ) , 400 ) ; } return ( $ uploadedFile -> move ( $ uploadedFile -> directory , $ uploadedFile -> filename ) ) ? Response :: json ( [ 'path' => $ uploadedFile -> directory . DIRECTORY_SEPARATOR . $ uploadedFile -> filename ] , 200 ) : Response :: make ( trans ( 'Unable to upload file.' ) , 400 ) ; }
Validates and uploads csv file do temporary directory
54,369
public function export ( LanguageListener $ listener , $ locale , $ type ) { try { $ separator = app ( 'config' ) -> get ( 'antares/translations::export.separator' ) ; $ translations = Languages :: where ( 'code' , $ locale ) -> whereHas ( 'translations' , function ( $ query ) use ( $ type ) { $ query -> where ( 'area' , $ type ) -> orderBy ( 'key' , 'desc' ) ; } ) -> first ( ) -> translations ; $ lines = [ implode ( $ separator , [ 'Segment' , 'Locale' , 'Key' , 'Translation' ] ) ] ; foreach ( $ translations as $ translation ) { $ data = [ str_replace ( 'antares/' , '' , $ translation -> group ) , $ locale , '"' . $ translation -> key . '"' , '"' . $ translation -> value . '"' , ] ; array_push ( $ lines , implode ( $ separator , $ data ) ) ; } $ filename = 'export_' . date ( 'Y_m_d_H_i_s' ) . '_' . $ locale . '.csv' ; return Response :: make ( implode ( PHP_EOL , $ lines ) , '200' , array ( 'Content-Type' => 'text/csv' , 'Content-Disposition' => 'attachment; filename="' . $ filename ) ) ; } catch ( Exception $ e ) { dd ( $ e ) ; Log :: warning ( $ e ) ; return $ listener -> exportFailed ( $ e -> getMessage ( ) ) ; } }
processing export action
54,370
public function change ( LanguageListener $ listener , $ locale ) { try { Session :: put ( 'locale' , $ locale ) ; app ( ) -> setLocale ( $ locale ) ; return $ listener -> changeSuccess ( ) ; } catch ( Exception $ e ) { Log :: warning ( $ e ) ; return $ listener -> changeFailed ( $ e -> getMessage ( ) ) ; } }
processing change active language
54,371
protected function deleteLangFiles ( $ path ) { if ( is_dir ( $ path ) ) { $ this -> filesystem -> cleanDirectory ( $ path ) ; $ this -> filesystem -> deleteDirectory ( $ path ) ; return true ; } return false ; }
deleteing lang files
54,372
public function setDefault ( LanguageListener $ listener , $ id ) { DB :: beginTransaction ( ) ; try { $ current = Languages :: query ( ) -> where ( 'is_default' , 1 ) -> firstOrFail ( ) ; $ current -> is_default = 0 ; $ current -> save ( ) ; $ language = Languages :: query ( ) -> findOrFail ( $ id ) ; $ language -> is_default = 1 ; $ language -> save ( ) ; } catch ( Exception $ ex ) { DB :: rollback ( ) ; return $ listener -> defaultFailed ( $ ex -> getMessage ( ) ) ; } DB :: commit ( ) ; return $ listener -> defaultSuccess ( ) ; }
Sets default language
54,373
public static function start ( $ app ) { $ app -> boot ( ) ; $ artisan = require __DIR__ . '/start.php' ; $ artisan -> setAutoExit ( false ) ; if ( isset ( $ app [ 'events' ] ) ) { $ app [ 'events' ] -> fire ( 'artisan.start' , array ( $ artisan ) ) ; } return $ artisan ; }
Start a new Console application .
54,374
public function sendJson ( $ data ) { if ( $ data === null ) { $ this -> terminate ( ) ; } else { $ this -> sendResponse ( new JsonResponse ( $ data ) ) ; } }
Sends JSON data to the output .
54,375
public function byLanguage ( $ language = null ) { if ( ! $ language ) { if ( Yii :: $ app -> id === 'app-backend' ) { $ language = Yii :: $ app -> wavecms -> editedLanguage ; } else { $ language = Yii :: $ app -> language ; } } return $ this -> andWhere ( [ 'REGEXP' , News :: tableName ( ) . '.languages' , '(^|;)(' . $ language . ')(;|$)' ] ) ; }
Get news by language
54,376
private function parseKey ( $ data , $ key ) { if ( isset ( $ data [ $ key ] ) ) { $ value = ( int ) $ data [ $ key ] ; $ this -> scoreTiers [ ] = new ScoreTier ( $ key , $ value ) ; return $ value ; } throw new InvalidDataException ( ) ; }
Parses a score tier from the
54,377
public function getTierByScore ( $ score ) { if ( $ score < $ this -> min ) { $ score = $ this -> min ; } elseif ( $ score > $ this -> max ) { $ score = $ this -> max ; } $ count = count ( $ this -> scoreTiers ) ; $ current = $ this -> scoreTiers [ 0 ] ; for ( $ i = 1 ; $ i < $ count ; $ i ++ ) { $ next = $ this -> scoreTiers [ $ i ] ; if ( $ score < $ next -> minimum ) { break ; } $ current = $ next ; } return $ current -> key ; }
Get the score tier string for the given score .
54,378
public static function getRoutesFromSettings ( array $ settings ) : array { $ routes = [ ] ; foreach ( $ settings [ 'routing' ] as $ method => $ urls ) { if ( ! isset ( $ routes [ $ method ] ) ) { $ routes [ $ method ] = [ ] ; } foreach ( $ urls as $ url ) { array_push ( $ routes [ $ method ] , ( array ) $ url ) ; } } return $ routes ; }
Builds a clean route array from the given type settings
54,379
public static function reflectionRoutes ( App $ app , Slim $ slim ) : void { $ types = $ app -> getTypes ( ) ; $ slim -> get ( '/@types' , self :: jsonResponse ( function ( ) use ( $ types ) { $ return = [ ] ; foreach ( $ types as $ name => $ type ) { $ type = $ type -> getSettings ( ) ; $ list = [ '@type' => $ name , 'title' => $ type [ 'title' ] , 'description' => $ type [ 'description' ] ] ; array_push ( $ return , $ list ) ; } return $ return ; } ) ) ; $ slim -> get ( '/@types/{type}' , self :: jsonResponse ( function ( $ req , $ res , $ args ) use ( $ types ) { if ( ! isset ( $ types [ $ args [ 'type' ] ] ) ) { return new Error ( sprintf ( "Type '%s' is not defined." , $ args [ 'type' ] ) ) ; } $ settings = $ types [ $ args [ 'type' ] ] -> getSettings ( ) ; $ routes = [ ] ; foreach ( $ settings [ 'routing' ] as $ method => $ routingList ) { $ routes [ $ method ] = array_map ( function ( $ item ) { return $ item [ 'url' ] ; } , $ routingList ) ; } return [ 'type' => $ args [ 'type' ] , 'title' => $ settings [ 'title' ] , 'description' => $ settings [ 'description' ] , 'routes' => $ routes , 'data' => ( isset ( $ settings [ 'data' ] ) ) ? $ settings [ 'data' ] : [ ] , ] ; } ) ) ; }
Adds the system information routes to the system
54,380
public static function jsonResponse ( callable $ fun ) : callable { return function ( Request $ request , Response $ response , array $ args ) use ( $ fun ) { return $ response -> withJson ( $ fun ( $ request , $ response , $ args ) ) ; } ; }
Wrapper to archive a JSON - Response for the given route
54,381
final function send ( ) { if ( ! $ command = $ this -> Command ) throw new \ Exception ( 'No Command Is Specified.' ) ; $ methodName = $ command -> getMethodName ( ) ; $ nameSpace = implode ( '_' , $ command -> getNamespace ( ) ) ; $ alterCall = $ nameSpace . '_' . $ methodName ; if ( ! method_exists ( $ this , $ alterCall ) ) throw new \ BadMethodCallException ( sprintf ( 'Method (%s) is not defined in Platform as (%s).' , $ command -> getMethodName ( ) , $ alterCall ) ) ; $ r = $ this -> { $ alterCall } ( $ command ) ; if ( ! $ r instanceof iResponse ) throw new \ Exception ( sprintf ( 'Result from (%s) must be instance of iResponse. given: (%s).' , $ alterCall , \ Poirot \ Std \ flatten ( $ r ) ) ) ; return $ r ; }
Build Response with send Expression over Transporter
54,382
public function sendStream ( SendResponseEvent $ event ) { if ( $ event -> contentSent ( ) ) { return $ this ; } $ response = $ event -> getResponse ( ) ; $ stream = $ response -> getStream ( ) ; while ( ! feof ( $ stream ) ) { echo fread ( $ stream , 8192 ) ; } fclose ( $ stream ) ; $ event -> setContentSent ( ) ; }
Send the stream
54,383
public function getStockCount ( string $ productNumber ) : int { Assert :: that ( $ productNumber ) -> minLength ( 1 , 'The length of $productNumber has to be > 0' ) ; $ product = $ this -> getDataProduct ( $ productNumber ) ; return ( int ) $ product [ 'stockCount' ] ; }
Will return the stock count for the specified product number
54,384
public function incrementOrDecrementStockCount ( string $ productNumber , int $ amount ) : array { Assert :: that ( $ productNumber ) -> minLength ( 1 , 'The length of $productNumber has to be > 0' ) ; $ oldStockCount = $ this -> getStockCount ( $ productNumber ) ; $ newStockCount = $ oldStockCount + $ amount ; $ this -> setStockCount ( $ productNumber , $ newStockCount ) ; return [ 'oldStockCount' => $ oldStockCount , 'newStockCount' => $ newStockCount , ] ; }
Will increment or decrement the stock count for the given product number
54,385
public function incrementStockCount ( string $ productNumber , int $ amount ) : array { Assert :: that ( $ productNumber ) -> minLength ( 1 , 'The length of $productNumber has to be > 0' ) ; return $ this -> incrementOrDecrementStockCount ( $ productNumber , abs ( $ amount ) ) ; }
Will increment the stock count for the given product number
54,386
public function actionRequestPasswordReset ( ) { $ model = new PasswordResetRequestForm ( ) ; if ( $ model -> load ( Yii :: $ app -> getRequest ( ) -> post ( ) ) && $ model -> validate ( ) ) { if ( $ model -> sendEmail ( ) ) { Yii :: $ app -> getSession ( ) -> setFlash ( 'success' , yii :: t ( 'cms' , 'Check your email for further instructions.' ) ) ; return $ this -> goHome ( ) ; } else { Yii :: $ app -> getSession ( ) -> setFlash ( 'error' , 'Sorry, we are unable to reset password for email provided.' ) ; } } return $ this -> render ( 'requestPasswordResetToken' , [ 'model' => $ model , ] ) ; }
Requests password reset .
54,387
public function findView ( $ viewPath ) { $ viewPath = str_replace ( array ( '.php' , '.vphp' ) , '' , $ viewPath ) ; if ( sizeof ( $ view = preg_grep ( '/' . addcslashes ( $ viewPath , '/\\' ) . '(\.php|\.vphp)/ui' , $ this -> views ) ) ) { usort ( $ view , array ( $ this , 'sortStrings' ) ) ; return end ( $ view ) ; } return false ; }
Find view file by its part in module view resources and return full path to it .
54,388
protected function viewContext ( $ view_path ) { $ new = & $ this -> view_data [ $ view_path ] ; $ old = & $ this -> view_data [ $ this -> view_context ] ; if ( $ this -> view_context !== $ view_path ) { if ( ! isset ( $ this -> view_data [ $ view_path ] ) ) { $ new = array ( ) ; if ( isset ( $ old ) ) { $ new = array_merge ( $ new , $ old ) ; } $ new [ self :: VD_HTML ] = '' ; } $ this -> data = & $ new ; $ this -> view_context = $ view_path ; } }
Perform module view context switching
54,389
protected function cache_refresh ( & $ file , $ clear = true , $ folder = null ) { $ folder = isset ( $ folder ) ? rtrim ( $ folder , '/' ) . '/' : '' ; $ path = $ this -> cache_path . $ folder ; if ( ! file_exists ( $ path ) ) { mkdir ( $ path , 0777 , true ) ; } $ file = $ path . $ file ; if ( ! file_exists ( $ file ) ) { if ( $ clear ) { File :: clear ( $ path , pathinfo ( $ file , PATHINFO_EXTENSION ) ) ; } return true ; } return false ; }
Create unique module cache folder structure in local web - application .
54,390
function filter ( $ in , $ out , & $ consumed , $ closing ) { $ unfiltered = $ this -> _getDataFromBucket ( $ in , $ consumed ) ; $ filtered = $ unfiltered ; foreach ( $ this -> params [ 'bad_words' ] as $ badWord ) { $ regex = "[(^|\s)({$badWord})($|\s)]i" ; preg_match_all ( $ regex , $ filtered , $ matches ) ; $ filtered = preg_replace ( $ regex , "$1{$this->_getReplacement()}$3" , $ filtered ) ; } return $ this -> _writeBackDataOut ( $ out , $ filtered ) ; }
Filter Stream Through Buckets
54,391
protected function getClassProviders ( \ ReflectionClass $ class ) { $ annotations = Omocha :: getAnnotations ( $ class ) ; $ providers = $ annotations -> find ( 'Provider' , Filter :: TYPE_STRING ) ; if ( ! empty ( $ providers ) ) { $ classes = [ ] ; foreach ( $ providers as $ provider ) { $ classes [ ] = $ provider -> getValue ( ) ; } return $ classes ; } if ( $ annotations -> has ( 'ExtendInject' ) ) { $ extend = $ annotations -> get ( 'ExtendInject' ) -> getValue ( ) ; if ( $ extend ) { $ parent = $ class -> getParentClass ( ) ; return $ parent instanceof \ ReflectionClass ? $ this -> getClassProviders ( $ parent ) : [ ] ; } } return [ ] ; }
Obtains all providers for a given class
54,392
protected function parseArgumentName ( $ argumentName ) { if ( ! preg_match ( '@^\$?(\w+)$@' , $ argumentName , $ matches ) ) { throw new \ RuntimeException ( sprintf ( "Invalid annotation expression found in %s __construct" , $ this -> className ) ) ; } return $ matches [ 1 ] ; }
Parses a contructor argument expression
54,393
public function rellenar ( array $ datos ) { foreach ( $ datos as $ llave => $ valor ) { $ this -> $ llave = $ valor ; } return $ this ; }
Rellena los campos usando un arreglo .
54,394
public static function contar ( array $ filtro = null ) { $ metadatos = get_class_vars ( static :: class ) ; $ temp = Aplicacion :: instanciar ( ) -> obtenerBdRelacional ( ) -> seleccionar ( 'COUNT(*) as c' , $ metadatos [ '__nombreTabla' ] ) -> donde ( $ filtro ) -> obtenerPrimero ( ) ; if ( $ temp === false ) { return false ; } else { return $ temp [ 'c' ] ; } }
Obtiene la cantidad de registros que posee el modelo puede aplicar un filtro a la consulta .
54,395
public function insertar ( ) { $ bd = Aplicacion :: instanciar ( ) -> obtenerBdRelacional ( ) ; $ parametros = [ ] ; $ llavePrimaria = ( array ) $ this -> __llavePrimaria ; foreach ( $ this -> __campos as $ campo => $ meta ) { $ esLlave = in_array ( $ campo , $ llavePrimaria ) ; if ( ! empty ( $ meta [ 'requerido' ] ) && $ this -> campoVacio ( $ campo ) ) { if ( ! ( $ esLlave && $ this -> __llavePrimariaAutonum ) ) { throw new \ RuntimeException ( "Falta el campo requerido '{$campo}'." ) ; } } if ( isset ( $ this -> { $ campo } ) ) { $ parametros [ $ campo . '|' . $ meta [ 'tipo' ] ] = $ this -> { $ campo } ; } } if ( $ bd -> insertar ( $ this -> __nombreTabla , $ parametros ) -> ejecutar ( ) ) { if ( $ this -> __llavePrimariaAutonum && ! is_array ( $ this -> __llavePrimaria ) ) { $ this -> { $ this -> __llavePrimaria } = $ bd -> ultimoIdInsertado ( ) ; } return true ; } return false ; }
Inserta un registro del modelo usando las propiedades modificadas .
54,396
public function guardar ( ) { $ bd = Aplicacion :: instanciar ( ) -> obtenerBdRelacional ( ) ; $ llavePrimaria = ( array ) $ this -> __llavePrimaria ; $ filtro = [ ] ; foreach ( $ llavePrimaria as $ campo ) { if ( $ this -> campoVacio ( $ campo ) && ! $ this -> __llavePrimariaAutonum ) { throw new \ RuntimeException ( "Falta el campo requerido '{$campo}'." ) ; } $ filtro [ $ campo . '|' . $ this -> __campos [ $ campo ] [ 'tipo' ] ] = $ this -> { $ campo } ; } $ existe = $ bd -> seleccionar ( '*' , $ this -> __nombreTabla ) -> donde ( $ filtro ) -> limitar ( 1 ) -> obtenerPrimero ( ) ; if ( $ existe ) { return $ this -> actualizar ( ) ; } return $ this -> insertar ( ) ; }
Guarda un registro del modelo usando las propiedades modificadas . Si el registro ya existe entonces lo modifica usando las mismas propiedades .
54,397
public function actualizar ( ) { $ filtro = [ ] ; $ parametros = [ ] ; $ llavePrimaria = ( array ) $ this -> __llavePrimaria ; foreach ( $ this -> __campos as $ campo => $ meta ) { if ( ! empty ( $ meta [ 'requerido' ] ) && $ this -> campoVacio ( $ campo ) ) { throw new \ RuntimeException ( "Falta el campo requerido '{$campo}'." ) ; } if ( isset ( $ this -> { $ campo } ) ) { $ parametros [ $ campo . '|' . $ meta [ 'tipo' ] ] = $ this -> { $ campo } ; } } foreach ( $ llavePrimaria as $ campo ) { if ( $ this -> campoVacio ( $ campo ) ) { throw new \ RuntimeException ( "Falta rellenar el campo llave '{$campo}'." ) ; } $ filtro [ $ campo . '|' . $ this -> __campos [ $ campo ] [ 'tipo' ] ] = $ this -> { $ campo } ; } return Aplicacion :: instanciar ( ) -> obtenerBdRelacional ( ) -> actualizar ( $ this -> __nombreTabla , $ parametros ) -> donde ( $ filtro ) -> ejecutar ( ) ; }
Actualiza registro del modelo filtrando con llaves .
54,398
public function eliminar ( ) { $ filtro = [ ] ; $ llavePrimaria = ( array ) $ this -> __llavePrimaria ; foreach ( $ llavePrimaria as $ campo ) { if ( $ this -> campoVacio ( $ campo ) ) { throw new \ RuntimeException ( "Falta rellenar el campo llave '{$campo}'." ) ; } $ filtro [ $ campo . '|' . $ this -> __campos [ $ campo ] [ 'tipo' ] ] = $ this -> { $ campo } ; } return Aplicacion :: instanciar ( ) -> obtenerBdRelacional ( ) -> eliminar ( $ this -> __nombreTabla ) -> donde ( $ filtro ) -> ejecutar ( ) ; }
Elimina registros filtrando con propiedades alteradas .
54,399
public function getResult ( ) { if ( ! isset ( $ this -> result [ 'status' ] ) ) { $ this -> result [ 'status' ] = 'fail' ; if ( ! isset ( $ this -> result [ 'message' ] ) ) { $ this -> result [ 'message' ] = 'no method return status set' ; } } return $ this -> result ; }
Return module result