idx int64 0 60.3k | question stringlengths 64 4.24k | target stringlengths 5 618 |
|---|---|---|
27,100 | public function slice ( $ offset , $ limit = null , $ keys = true ) { return new static ( \ array_slice ( $ this -> items , $ offset , $ limit , $ keys ) ) ; } | Extracts a portion of the Collection returning a new Collection |
27,101 | public function transform ( callable $ callable ) { $ ret = new static ( ) ; foreach ( $ this as $ key => $ value ) { $ ret -> set ( $ key , $ callable ( $ value , $ key ) ) ; } return $ ret ; } | Creates a new Collection containing the results of the callable in the same keys |
27,102 | public function value ( $ key , $ default = null ) { $ value = $ this -> get ( $ key ) ; if ( ! $ value ) { return $ this -> valueExecutor ( $ default , $ value , $ key ) ; } return $ value ; } | Returns the value for the specified key or if there is no value returns the default |
27,103 | public function walk ( $ callback , $ userdata = null ) { $ elements = $ this -> items ; \ array_walk ( $ elements , $ callback , $ userdata ) ; return new static ( $ elements ) ; } | Applies the callback to all elements in the Collection returning a new Collection |
27,104 | protected function valueAccessor ( $ value , $ returnNull = false ) { if ( Support :: isCallable ( $ value ) ) { return $ value ; } return function ( $ item ) use ( $ value , $ returnNull ) { if ( is_null ( $ value ) ) { return $ returnNull ? null : $ item ; } if ( Support :: isTraversable ( $ item ) ) { return array_key_exists ( $ value , $ item ) ? $ item [ $ value ] : null ; } if ( is_object ( $ item ) && isset ( $ item -> { $ value } ) ) { return $ item -> { $ value } ; } if ( is_object ( $ item ) && method_exists ( $ item , $ value ) ) { return $ item -> { $ value } ( ) ; } if ( is_object ( $ item ) && method_exists ( $ item , 'get' . ucwords ( $ value ) ) ) { return $ item -> { 'get' . ucwords ( $ value ) } ( ) ; } return $ returnNull ? null : $ item ; } ; } | Providers a callable for fetching data from a collection item |
27,105 | public function getConfigOption ( $ option ) { if ( ! array_key_exists ( $ option , $ this -> config ) ) { throw new UnexpectedValueException ( "Unexpected option name: {$option}" ) ; } return $ this -> config [ $ option ] ; } | Returns the value of given configuration option . |
27,106 | public function configure ( $ option , $ value ) { if ( ! array_key_exists ( $ option , $ this -> config ) ) { throw new InvalidArgumentException ( "Invalid option name: {$option}" ) ; } $ this -> config [ $ option ] = $ value ; } | Sets a configuration option to given value . |
27,107 | public function dump ( $ value ) { switch ( gettype ( $ value ) ) { case "boolean" : { $ output = $ value ? "true" : "false" ; return $ this -> config [ "bool_lowercase" ] ? $ output : strtoupper ( $ output ) ; } case "NULL" : { return $ this -> config [ "null_lowercase" ] ? "null" : "NULL" ; } case "integer" : { return ( string ) $ value ; } case "double" : { if ( $ this -> config [ "round_double" ] !== false ) { $ value = round ( $ value , $ this -> config [ "round_double" ] , PHP_ROUND_HALF_UP ) ; } return ( string ) $ value ; } case "string" : { if ( strlen ( $ value ) > $ this -> config [ "str_max_length" ] ) { $ value = substr ( $ value , 0 , $ this -> config [ "str_max_length" ] ) . "..." ; } if ( $ this -> config [ "replace_newline" ] ) { $ value = str_replace ( PHP_EOL , "\\n" , $ value ) ; } return "\"{$value}\"" ; } case "array" : { return $ this -> printArray ( $ value ) . PHP_EOL ; } case "object" : { return $ this -> printObject ( $ value ) ; } } } | This method helps you get string representations of various PHP data types . |
27,108 | protected function printArray ( array $ value , $ level = 1 ) { if ( count ( $ value ) < 1 ) { return "[]" ; } $ result = "[" . PHP_EOL ; $ isAssoc = ( array_keys ( $ value ) !== range ( 0 , count ( $ value ) - 1 ) ) ; $ counter = 0 ; foreach ( $ value as $ key => $ element ) { $ counter ++ ; if ( $ counter > $ this -> config [ "array_max_elements" ] ) { $ result .= str_repeat ( $ this -> config [ "array_indenting" ] , $ level ) ; $ result .= "..." . PHP_EOL ; break ; } if ( is_array ( $ element ) ) { $ element = $ this -> printArray ( $ element , $ level + 1 ) ; } elseif ( is_object ( $ element ) ) { $ element = $ this -> printObject ( $ element , $ level + 1 ) ; } else { $ element = $ this -> dump ( $ element ) ; } $ result .= str_repeat ( $ this -> config [ "array_indenting" ] , $ level ) ; if ( ! $ isAssoc ) { $ result .= $ element ; } else { $ result .= sprintf ( "%s => %s" , $ this -> dump ( $ key ) , $ element ) ; } $ result .= "," . PHP_EOL ; } $ result .= str_repeat ( $ this -> config [ "array_indenting" ] , $ level - 1 ) ; $ result .= "]" ; return $ result ; } | Returns a string representation of given array . |
27,109 | protected function printObject ( $ value , $ level = 0 ) { $ reflector = new ReflectionClass ( $ value ) ; $ result = $ this -> getGeneralObjectInfo ( $ value ) . PHP_EOL ; if ( ! $ this -> config [ "object_limited_info" ] ) { if ( count ( $ parents = $ this -> getAllParentClassNames ( $ reflector ) ) > 0 ) { $ result .= sprintf ( "Classes: %s" . PHP_EOL , implode ( ", " , $ parents ) ) ; } if ( count ( $ interfaces = $ reflector -> getInterfaceNames ( ) ) > 0 ) { $ result .= sprintf ( "Interfaces: %s" . PHP_EOL , implode ( ", " , $ interfaces ) ) ; } if ( count ( $ traits = $ this -> getAllTraitNames ( $ reflector ) ) > 0 ) { $ result .= sprintf ( "Traits: %s" . PHP_EOL , implode ( ", " , $ traits ) ) ; } } if ( $ info = $ this -> getPropertyValues ( $ reflector , $ value , $ level + 1 ) ) { $ result .= str_repeat ( $ this -> config [ "array_indenting" ] , $ level ) . "Properties:" . PHP_EOL . $ info ; } return $ result ; } | Returns a string representation of given object . |
27,110 | public function initWithJson ( array $ p_datas = [ ] ) { $ props = $ this -> getProperties ( ) ; $ this -> init ( ) ; foreach ( $ p_datas as $ name => $ value ) { foreach ( $ props as $ prp => $ property ) { $ test = $ prp ; if ( array_key_exists ( FFCST :: PROPERTY_PUBLIC , $ property ) ) { $ test = $ property [ FFCST :: PROPERTY_PUBLIC ] ; } if ( $ test == $ name ) { $ setter = 'set' . \ FreeFW \ Tools \ PBXString :: toCamelCase ( $ name , true ) ; $ this -> $ setter ( $ value ) ; break ; } } } return $ this ; } | Init object with datas |
27,111 | public function setCells ( $ items ) { Yii :: beginProfile ( __CLASS__ . ':' . __FUNCTION__ ) ; while ( ! empty ( $ items ) ) { $ this -> currentRow -> addCells ( $ items ) ; if ( ! empty ( $ items ) ) { $ this -> _currentRow = null ; } } Yii :: endProfile ( __CLASS__ . ':' . __FUNCTION__ ) ; } | Set cells . |
27,112 | public function getCurrentRow ( ) { if ( isset ( $ this -> _currentRow ) && $ this -> _currentRow -> isFilled ( ) ) { $ this -> _currentRow = null ; } if ( is_null ( $ this -> _currentRow ) ) { $ this -> _currentRow = Yii :: createObject ( array_merge ( [ 'class' => $ this -> rowClass ] , $ this -> baseRow ) ) ; $ this -> _rows [ ] = $ this -> _currentRow ; } return $ this -> _currentRow ; } | Get current row . |
27,113 | protected static function buildComponent ( string $ className ) { if ( ! isset ( self :: $ components [ $ className ] ) ) { self :: $ components [ $ className ] = Container :: buildObject ( "\\Osf\\View\\Component\\" . $ className ) ; if ( ! ( self :: $ components [ $ className ] instanceof Component \ AbstractComponent ) ) { throw new ArchException ( 'Component [' . $ className . '] must be an AbstractComponent' ) ; } } return self :: $ components [ $ className ] ; } | Manage components instances |
27,114 | public static function registerScripts ( HelperInterface $ layout ) { foreach ( self :: $ components as $ component ) { foreach ( $ component -> getScripts ( ) as $ script ) { switch ( $ script [ 0 ] ) { case 'headjs' : $ layout -> headTags -> appendFile ( $ script [ 1 ] , $ script [ 2 ] , $ script [ 3 ] ) ; break ; case 'headcss' : $ layout -> headTags -> appendStylesheet ( $ script [ 1 ] , $ script [ 2 ] , $ script [ 3 ] ) ; break ; case 'footjs' : $ layout -> footTags -> appendFile ( $ script [ 1 ] , $ script [ 2 ] , $ script [ 3 ] ) ; break ; case 'footcss' : $ layout -> footTags -> appendStylesheet ( $ script [ 1 ] , $ script [ 2 ] , $ script [ 3 ] ) ; break ; case 'script' : $ layout -> footTags -> appendScript ( $ script [ 1 ] ) ; break ; } } } } | Attache les fichiers et styles des composants au layout |
27,115 | public function getSourceFromCurrentUser ( $ user ) { $ token = $ user -> token ( ) ; $ client = $ token -> client ; if ( $ client -> personal_access_client ) { $ name = $ token -> name ; $ sourceable_id = $ token -> token_id ; $ sourceable_type = 'token' ; } else { $ name = $ client -> name ; $ sourceable_id = $ client -> id ; $ sourceable_type = 'client' ; } $ source = $ user -> sources ( ) -> sourceableFilter ( $ sourceable_id , $ sourceable_type ) -> first ( ) ; if ( $ source ) return $ source ; $ source = new Source ( ) ; $ source -> sourceable_id = $ sourceable_id ; $ source -> name = $ name ; $ source -> sourceable_type = $ sourceable_type ; $ source -> user_id = $ user -> id ; $ source -> save ( ) ; return $ source ; } | Why create this intermediary table rather then referring to the oauth_clients table directly? |
27,116 | public function stringToObject ( $ data , array $ options = [ ] ) { $ data = trim ( $ data ) ; if ( substr ( $ data , 0 , 1 ) !== '{' && substr ( $ data , - 1 , 1 ) !== '}' ) { return Format :: getInstance ( 'Yaml' ) -> stringToObject ( $ data , $ options ) ; } $ decoded = json_decode ( $ data ) ; if ( $ decoded === null ) { throw new \ RuntimeException ( sprintf ( 'Error decoding JSON data: %s' , json_last_error_msg ( ) ) ) ; } return ( object ) $ decoded ; } | Parse a JSON formatted string and convert it into an object |
27,117 | public function getParameterBag ( $ identifier ) { if ( isset ( $ this -> parameterBags [ $ identifier ] ) ) { return $ this -> parameterBags [ $ identifier ] ; } return null ; } | Get a specific ParameterBag based on identifier . |
27,118 | public function colors ( WP_Customize_Manager $ wp_customize ) { $ wp_customize -> add_panel ( 'colors' , array ( 'title' => esc_html__ ( 'Colors' , 'rock' ) , 'description' => 'Get what you need.' , 'priority' => 40 , ) ) ; $ wp_customize -> add_section ( 'colors-scheme' , array ( 'title' => esc_html__ ( 'Color Schemes' , 'rock' ) , 'panel' => 'colors' , ) ) ; $ wp_customize -> add_section ( 'colors-header' , array ( 'title' => esc_html__ ( 'Header' , 'rock' ) , 'panel' => 'colors' , ) ) ; $ wp_customize -> add_section ( 'colors-menu' , array ( 'title' => esc_html__ ( 'Menu' , 'rock' ) , 'panel' => 'colors' , ) ) ; $ wp_customize -> add_section ( 'colors-buttons' , array ( 'title' => esc_html__ ( 'Buttons' , 'rock' ) , 'panel' => 'colors' , ) ) ; $ wp_customize -> add_section ( 'colors-content' , array ( 'title' => esc_html__ ( 'Content' , 'rock' ) , 'panel' => 'colors' , ) ) ; $ wp_customize -> add_section ( 'colors-footer' , array ( 'title' => esc_html__ ( 'Footer' , 'rock' ) , 'panel' => 'colors' , ) ) ; foreach ( $ this -> colors as $ name => $ args ) { $ this -> register_color_setting ( $ wp_customize , $ name , $ args ) ; } } | Register color panel sections controls and settings . |
27,119 | public function register_color_setting ( WP_Customize_Manager $ wp_customize , $ name , array $ args ) { if ( empty ( $ name ) || empty ( $ args [ 'default' ] ) ) { return ; } $ name = sanitize_key ( $ name ) ; $ wp_customize -> add_setting ( $ name , array ( 'default' => sanitize_hex_color_no_hash ( $ args [ 'default' ] ) , 'sanitize_callback' => ( 'header_textcolor' === $ name ) ? array ( $ wp_customize , '_sanitize_header_textcolor' ) : 'sanitize_hex_color_no_hash' , 'sanitize_js_callback' => 'maybe_hash_hex_color' , 'transport' => 'postMessage' , ) ) ; $ wp_customize -> add_control ( new WP_Customize_Color_Control ( $ wp_customize , $ name , array ( 'label' => ! empty ( $ args [ 'label' ] ) ? $ args [ 'label' ] : $ name , 'description' => ! empty ( $ args [ 'description' ] ) ? $ args [ 'description' ] : null , 'section' => ! empty ( $ args [ 'section' ] ) ? $ args [ 'section' ] : 'colors-content' , 'priority' => ! empty ( $ args [ 'priority' ] ) ? absint ( $ args [ 'priority' ] ) : null , 'active_callback' => ! empty ( $ args [ 'active_callback' ] ) ? $ args [ 'active_callback' ] : null , ) ) ) ; } | Register a custom color setting . |
27,120 | public function enqueue_colors_inline_css ( ) { foreach ( $ this -> colors as $ name => $ args ) { $ this -> add_color_inline_css ( $ name , $ args ) ; } } | Enqueue inline CSS for custom colors . |
27,121 | public function add_color_inline_css ( $ name , array $ args ) { if ( empty ( $ name ) || empty ( $ args [ 'css' ] ) ) { return ; } $ default = $ this -> get_default_color ( $ name , 'default' ) ; $ hex = trim ( get_theme_mod ( $ name , $ default ) , '#' ) ; $ css = sprintf ( Rock_Customizer :: parse_css_rules ( $ args [ 'css' ] ) , '#' . $ hex ) ; if ( ! empty ( $ args [ 'rgba_css' ] ) ) { $ css .= sprintf ( Rock_Customizer :: parse_css_rules ( $ args [ 'rgba_css' ] ) , implode ( ', ' , rock_hex2rgb ( $ hex ) ) ) ; } wp_add_inline_style ( Rock_Customizer :: $ stylesheet , $ css ) ; } | Add color inline CSS . |
27,122 | public function get_default_color ( $ color , $ scheme = '' , $ hash = false ) { if ( ! function_exists ( 'sanitize_hex_color' ) || ! function_exists ( 'sanitize_hex_color_no_hash' ) ) { require_once ABSPATH . 'wp-includes/class-wp-customize-manager.php' ; } $ scheme = empty ( $ scheme ) ? $ this -> get_current_color_scheme_array ( ) : $ this -> color_schemes [ $ this -> sanitize_color_scheme ( $ scheme ) ] ; $ hex = isset ( $ scheme [ 'colors' ] [ $ color ] ) ? trim ( $ scheme [ 'colors' ] [ $ color ] , '#' ) : null ; return ( $ hash ) ? sanitize_hex_color ( '#' . $ hex ) : sanitize_hex_color_no_hash ( $ hex ) ; } | Return the default HEX value for a color in a scheme . |
27,123 | public function get_rgba_css ( ) { $ colors = array ( ) ; foreach ( $ this -> colors as $ name => $ args ) { if ( ! empty ( $ name ) && ! empty ( $ args [ 'rgba_css' ] ) && is_array ( $ args [ 'rgba_css' ] ) ) { $ colors [ $ name ] = $ args [ 'rgba_css' ] ; } } return $ colors ; } | Return an array of CSS for colors supporting RGBA . |
27,124 | public function color_scheme ( WP_Customize_Manager $ wp_customize ) { if ( count ( $ this -> color_schemes ) < 2 ) { return ; } $ wp_customize -> add_setting ( 'color_scheme' , array ( 'default' => 'default' , 'sanitize_callback' => array ( $ this , 'sanitize_color_scheme' ) , 'transport' => 'postMessage' , ) ) ; $ choices = array_combine ( array_keys ( $ this -> color_schemes ) , wp_list_pluck ( $ this -> color_schemes , 'label' ) ) ; $ wp_customize -> add_control ( 'color_scheme' , array ( 'label' => esc_html__ ( 'Base Color Scheme' , 'rock' ) , 'section' => 'colors-scheme' , 'type' => 'select' , 'choices' => $ choices , 'priority' => 1 , ) ) ; } | Register a color scheme setting . |
27,125 | public function colors_control_js ( ) { $ suffix = SCRIPT_DEBUG ? '' : '.min' ; wp_enqueue_script ( 'rock-colors-control' , get_template_directory_uri ( ) . "/assets/js/admin/colors-control{$suffix}.js" , array ( 'customize-controls' , 'iris' , 'underscore' , 'wp-util' ) , ROCK_VERSION , true ) ; wp_localize_script ( 'rock-colors-control' , 'colorSchemes' , $ this -> color_schemes ) ; } | Enqueue color scheme control in the Customizer . |
27,126 | public function colors_preview_css ( ) { ?> <script type="text/html" id="tmpl-rock-colors-css"> <?php foreach ( $ this -> colors as $ name => $ args ) { if ( empty ( $ name ) || empty ( $ args [ 'css' ] ) || ! is_array ( $ args [ 'css' ] ) ) { continue ; } printf ( Rock_Customizer :: parse_css_rules ( $ args [ 'css' ] ) , sprintf ( '{{ data.%s }}' , $ name ) ) ; } ?> </script> <?php $ rgba_colors = $ this -> get_rgba_css ( ) ; if ( ! $ rgba_colors ) { echo '<script type="text/html" id="tmpl-rock-colors-css-rgba"></script>' ; } ?> <script type="text/html" id="tmpl-rock-colors-css-rgba"> <?php foreach ( $ rgba_colors as $ name => $ css ) { printf ( Rock_Customizer :: parse_css_rules ( $ css ) , sprintf ( '{{ data.%s }}' , $ name ) ) ; } ?> </script> <?php } | Inline style for color scheme |
27,127 | public function sanitize_color_scheme ( $ scheme ) { return ( $ this -> color_scheme_exists ( $ scheme ) && $ this -> is_valid_color_scheme_array ( $ this -> color_schemes [ $ scheme ] ) ) ? $ scheme : 'default' ; } | Sanitize a color scheme by ensuring it exists and is valid . |
27,128 | public function header ( ) { $ args = ( array ) apply_filters ( 'rock_custom_header_args' , array ( 'default-text-color' => $ this -> get_default_color ( 'header_textcolor' , 'default' ) , 'width' => 2400 , 'height' => 1300 , 'flex-height' => true , 'wp-head-callback' => array ( $ this , 'header_css' ) , ) ) ; add_theme_support ( 'custom-header' , $ args ) ; $ defaults = ( array ) apply_filters ( 'rock_default_hero_images' , array ( 'default' => array ( 'url' => 'assets/images/hero.jpg' , 'thumbnail_url' => 'assets/images/hero-thumbnail.jpg' , ) , ) ) ; foreach ( $ defaults as $ name => & $ args ) { $ path = trailingslashit ( get_stylesheet_directory ( ) ) ; $ url = trailingslashit ( get_stylesheet_directory_uri ( ) ) ; if ( ! file_exists ( $ path . $ args [ 'url' ] ) ) { unset ( $ defaults [ $ name ] ) ; continue ; } $ args [ 'url' ] = $ url . $ args [ 'url' ] ; $ args [ 'thumbnail_url' ] = file_exists ( $ path . $ args [ 'thumbnail_url' ] ) ? $ url . $ args [ 'thumbnail_url' ] : $ args [ 'url' ] ; } if ( $ defaults ) { register_default_headers ( $ defaults ) ; } } | Add custom header support . |
27,129 | public function header_css ( ) { $ color = get_header_textcolor ( ) ; $ css = $ this -> get_color_css ( 'header_textcolor' ) ; if ( 'blank' === $ color ) { $ css = array ( '.site-title, .site-description' => array ( 'position' => 'absolute' , 'clip' => 'rect(1px, 1px, 1px, 1px)' , ) , ) ; } if ( $ color && $ css ) { printf ( "<style type='text/css'>\n%s\n</style>" , sprintf ( Rock_Customizer :: parse_css_rules ( $ css ) , $ color ) ) ; } } | Custom header CSS . |
27,130 | public function color_overlay_transparency ( WP_Customize_Manager $ wp_customize ) { $ wp_customize -> add_setting ( 'hero_image_color_overlay' , array ( 'default' => $ this -> get_color_overlay_transparency_default_value ( ) , 'sanitize_callback' => 'absint' , 'transport' => 'postMessage' , ) ) ; $ wp_customize -> add_control ( 'hero_image_color_overlay' , array ( 'label' => esc_html__ ( 'Hero Background Overlay' , 'rock' ) , 'description' => esc_html__ ( 'Control the color overlay transparency when using a custom Header Image.' , 'rock' ) , 'section' => 'colors-header' , 'priority' => 20 , 'active_callback' => 'rock_has_hero_image' , 'type' => 'range' , 'input_attrs' => array ( 'min' => 0 , 'max' => 100 , 'step' => 1 , ) , ) ) ; } | Add setting and control for the hero image color overlay transparency . |
27,131 | public function getTreeItemFullPath ( $ itemId , MapperTreeItemInterface $ tree ) { $ path = $ this -> findRecursiveFullPath ( $ itemId , $ tree ) ; if ( 0 < count ( $ path ) ) { $ path [ $ tree -> getId ( ) ] = $ tree -> getTitle ( ) ; $ path = array_reverse ( $ path , true ) ; } return $ path ; } | Get mapper tree item full path . |
27,132 | private function findRecursiveFullPath ( $ itemId , MapperTreeItemInterface $ tree ) { foreach ( $ tree -> getChildren ( ) as $ child ) { if ( $ itemId === $ child -> getId ( ) ) { return [ $ itemId => $ child -> getTitle ( ) ] ; } else { $ path = $ this -> findRecursiveFullPath ( $ itemId , $ child ) ; if ( 0 < count ( $ path ) ) { $ path [ $ child -> getId ( ) ] = $ child -> getTitle ( ) ; return $ path ; } } } return [ ] ; } | Find recursive full path . |
27,133 | protected function currentStackMiddleware ( ) : MiddlewareStorage { if ( count ( $ this -> middleware ) === 0 ) { $ middleware = method_exists ( $ this , '__invoke' ) ? $ this : new FakeMiddlewareInvokable ( ) ; $ this -> middleware [ ] = new MiddlewareStorage ( $ middleware ) ; } $ middleware = end ( $ this -> middleware ) ; return $ middleware ; } | Initialize middleware stack this recommended to intended for middleware empty |
27,134 | public static function clearQueryArg ( $ code ) { if ( StringTools :: left ( $ code , 1 ) == '/' ) { $ code = StringTools :: right ( $ code , StringTools :: len ( $ code ) - 1 ) ; } if ( StringTools :: right ( $ code , 1 ) == '/' ) { $ code = StringTools :: left ( $ code , StringTools :: len ( $ code ) - 1 ) ; } return $ code ; } | Clean the Url code |
27,135 | public static function redirectToSame ( $ exceptedArgs = array ( ) , $ addedArgs = array ( ) , $ anchor = null ) { self :: initialize ( ) ; header ( 'Location: ' . self :: getCurrentUrl ( $ exceptedArgs , $ addedArgs , $ anchor ) ) ; exit ; } | Redirect to the same page |
27,136 | public static function getUrlFromCode ( $ code , $ addedArgs = array ( ) , $ anchor = null ) { self :: initialize ( ) ; $ code = self :: clearQueryArg ( $ code ) ; if ( $ code == '_root' ) { return WebApp :: url ( ) ; } if ( StringTools :: right ( $ code , 1 ) != '/' ) { $ code .= '/' ; } $ args = array ( 'q' => $ code ) ; $ args = array_merge ( $ args , $ addedArgs ) ; return Url :: getUrl ( null , $ args , true , $ anchor ) ; } | Get a full url from an url code |
27,137 | public static function getCurrentUrl ( $ exceptedArgs = array ( ) , $ addedArgs = array ( ) , $ anchor = null ) { self :: initialize ( ) ; return Url :: getCurrentUrl ( null , $ addedArgs , $ exceptedArgs , true , $ anchor ) ; } | Return the current url |
27,138 | public function get ( $ item ) { return isset ( $ this -> config [ $ item ] ) ? $ this -> config [ $ item ] : null ; } | Gets configuration . |
27,139 | public static function human ( $ str ) { $ out = str_replace ( '_' , ' ' , $ str ) ; $ out = ucwords ( strtolower ( $ out ) ) ; $ out = preg_replace ( '/\s{2,}/' , ' ' , $ out ) ; $ out = preg_replace ( '/^\s/' , '' , $ out ) ; $ out = preg_replace ( '/\s$/' , '' , $ out ) ; if ( strlen ( $ out ) === 0 ) { return $ out ; } $ stop_words_lower = self :: stopWordsLower ( ) ; $ words = explode ( ' ' , $ out ) ; $ out_words = array ( ) ; foreach ( $ words as $ n => $ word ) { $ out_word = $ word ; $ specials = array ( '/^id$/i' => 'ID' , '/^ids$/i' => 'IDs' , '/^url$/i' => 'URL' , '/^urls$/i' => 'URLs' , '/^cta$/i' => 'CTA' , '/^api$/i' => 'API' , '/^faq$/i' => 'FAQ' , '/^ip$/i' => 'IP' , '/^why$/' => 'why' , '/^Why$/' => 'Why' , ) ; $ special_word = false ; foreach ( $ specials as $ regex => $ special ) { if ( ! preg_match ( $ regex , $ word ) ) { continue ; } $ special_word = true ; $ out_word = $ special ; } if ( $ special_word ) { $ out_words [ ] = $ out_word ; continue ; } if ( ! preg_match ( '/[aeiou]/i' , $ word ) ) { $ out_word = strtoupper ( $ out_word ) ; } $ lower = strtolower ( $ word ) ; if ( in_array ( $ lower , $ stop_words_lower ) && $ n !== 0 ) { $ out_word = $ lower ; } $ out_words [ ] = $ out_word ; } $ out = join ( ' ' , $ out_words ) ; $ first_word_lower = strtolower ( $ words [ 0 ] ) ; $ first_word_lower_no_contraction = preg_replace ( "/'s$/" , '' , $ first_word_lower ) ; $ is_question = in_array ( $ first_word_lower_no_contraction , self :: questionWords ( ) ) ; $ has_question_mark = ( bool ) preg_match ( '/\?+$/' , $ out ) ; if ( $ is_question && ! $ has_question_mark ) { $ out .= '?' ; } return $ out ; } | Humanize the string |
27,140 | public static function machine ( $ str , $ separator = '_' ) { $ out = strtolower ( $ str ) ; $ out = preg_replace ( '/[^a-z0-9' . $ separator . ']/' , $ separator , $ out ) ; $ out = preg_replace ( '/' . $ separator . '{2,}/' , $ separator , $ out ) ; $ out = preg_replace ( '/^' . $ separator . '/' , '' , $ out ) ; $ out = preg_replace ( '/' . $ separator . '$/' , '' , $ out ) ; return $ out ; } | Machinize the string |
27,141 | public static function pascal ( $ str , $ force = false ) { $ words = ( $ force ) ? explode ( ' ' , self :: mechanize ( $ str , ' ' ) ) : preg_split ( '/[\W_]/' , self :: transliterate ( $ str ) ) ; $ words = array_map ( 'ucfirst' , $ words ) ; return join ( '' , $ words ) ; } | Convert to Pascal case |
27,142 | public static function convert ( $ input , $ from , $ to ) { if ( ! method_exists ( self :: class , $ to ) ) { return $ input ; } if ( in_array ( $ from , [ 'camel' , 'pascal' ] ) ) { $ converted = self :: $ from ( $ input ) ; $ converted = preg_replace ( '/([a-z])([A-Z])/' , '$1 $2' , $ converted ) ; $ converted = preg_replace ( '/(\D)?(\d+)(\D)?/' , '$1 $2 $3' , $ converted ) ; return self :: $ to ( $ converted ) ; } if ( method_exists ( self :: class , $ from ) ) { return self :: $ to ( self :: $ from ( $ input ) ) ; } return self :: $ to ( $ input ) ; } | Convert between two string formats |
27,143 | public static function shortenWords ( $ input , $ num_words = 35 , $ hellip = '…' ) { $ words = explode ( ' ' , $ input ) ; return ( count ( $ words ) <= $ num_words ) ? join ( ' ' , $ words ) : join ( ' ' , array_slice ( $ words , 0 , $ num_words ) ) . $ hellip ; } | Shorten a string |
27,144 | public static function shortenWordsByChar ( $ input , $ num_chars = 35 , $ hellip = ' …' ) { if ( strlen ( $ input ) <= $ num_chars ) { return $ input ; } $ shortened = substr ( $ input , 0 , $ num_chars ) ; $ shortened_words = array_filter ( explode ( ' ' , $ shortened ) ) ; end ( $ shortened_words ) ; $ last_key = key ( $ shortened_words ) ; $ words = explode ( ' ' , $ input ) ; $ words = array_slice ( $ words , 0 , $ last_key + 1 ) ; if ( $ words [ $ last_key ] !== $ shortened_words [ $ last_key ] ) { unset ( $ words [ $ last_key ] ) ; } return join ( ' ' , $ words ) . $ hellip ; } | Shorten a string by character limit preserving words |
27,145 | protected function init ( array $ user_options = array ( ) , $ logname = null ) { $ this -> logname = $ logname ; if ( true === self :: $ isInited ) return ; foreach ( self :: $ config as $ _static => $ _value ) { $ this -> $ _static = $ _value ; } foreach ( $ user_options as $ _static => $ _value ) { if ( isset ( $ this -> $ _static ) && is_array ( $ this -> $ _static ) ) { $ this -> $ _static = array_merge ( $ this -> $ _static , is_array ( $ _value ) ? $ _value : array ( $ _value ) ) ; } else { $ this -> $ _static = $ _value ; } } self :: $ isInited = true ; } | Load the configuration info |
27,146 | protected function addRecord ( $ level , $ message , array $ context = array ( ) ) { $ message = $ this -> interpolate ( $ message , $ context ) ; $ record = array ( 'message' => ( string ) $ message , 'context' => $ context , 'level' => self :: getLevelCode ( $ level ) , 'level_name' => strtoupper ( $ level ) , 'datetime' => new \ DateTime ( ) , 'ip' => self :: getUserIp ( ) , 'pid' => @ getmypid ( ) , 'extra' => array ( ) , ) ; return self :: write ( self :: getLogRecord ( $ record ) . "\n" , $ level ) ; } | Create a new log record and writes it |
27,147 | protected function write ( $ line , $ level = 100 ) { $ logfile = $ this -> getFilePath ( $ level ) ; $ rotator = $ this -> getRotator ( $ logfile ) ; $ return = $ rotator -> write ( $ line ) ; if ( $ this -> isErrorLevel ( $ level ) && true === $ this -> duplicate_errors ) self :: write ( $ line , 100 ) ; return $ return ; } | Write a new line in the logfile |
27,148 | protected function getRotator ( $ filename ) { if ( ! array_key_exists ( $ filename , self :: $ rotators ) ) { self :: $ rotators [ $ filename ] = new FileRotator ( $ filename , FileRotator :: ROTATE_PERIODIC , $ this -> rotator ) ; } return self :: $ rotators [ $ filename ] ; } | Get a rotator for a specific logfile |
27,149 | protected function isErrorLevel ( $ level ) { if ( ! is_numeric ( $ level ) ) $ level = $ this -> getLevelCode ( $ level ) ; return ( bool ) ( $ level > 300 ) ; } | Is the current log level an error one |
27,150 | protected function getLevelName ( $ level ) { return in_array ( $ level , self :: $ levels ) ? array_search ( $ level , self :: $ levels ) : '--' ; } | Get a level name |
27,151 | protected function getLogRecord ( $ record ) { $ prefix = $ suffix = array ( ) ; $ date = $ record [ 'datetime' ] -> format ( $ this -> datetime_format ) ; $ prefix [ ] = '[' . $ date . ']' ; if ( ! empty ( $ record [ 'ip' ] ) ) $ prefix [ ] = '[ip ' . $ record [ 'ip' ] . ']' ; if ( ! empty ( $ record [ 'pid' ] ) ) $ prefix [ ] = '[pid ' . $ record [ 'pid' ] . ']' ; $ prefix [ ] = $ record [ 'level_name' ] . ' :' ; if ( ! empty ( $ record [ 'context' ] ) ) { $ suffix [ ] = '[' . $ this -> writeArray ( $ record [ 'context' ] ) . ']' ; } if ( ! empty ( $ record [ 'extra' ] ) ) { $ suffix [ ] = '[' . $ this -> writeArray ( $ record [ 'extra' ] ) . ']' ; } return join ( ' ' , $ prefix ) . ' ' . preg_replace ( "/\n*$/" , ' ' , $ record [ 'message' ] ) . ' ' . join ( ' ' , $ suffix ) ; } | Build a log line from a complex array |
27,152 | protected function getFilePath ( $ level = 100 ) { $ filename = $ this -> getFileName ( $ level ) ; $ filext = '.' . trim ( $ this -> logfile_extension , '.' ) ; $ filename = str_replace ( $ filext , '' , $ filename ) . $ filext ; return rtrim ( $ this -> directory , '/' ) . '/' . $ filename ; } | Get the log file path |
27,153 | protected function getFileName ( $ level = 100 ) { return ! empty ( $ this -> logname ) ? $ this -> logname : ( $ this -> isErrorLevel ( $ level ) ? $ this -> error_logfile : $ this -> logfile ) ; } | Get the log file name |
27,154 | public static function getUserIp ( ) { if ( isset ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ) $ ip = $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ; elseif ( isset ( $ _SERVER [ 'HTTP_CLIENT_IP' ] ) ) $ ip = $ _SERVER [ 'HTTP_CLIENT_IP' ] ; else $ ip = $ _SERVER [ 'REMOTE_ADDR' ] ; return $ ip ; } | Get the user IP address |
27,155 | public static function writeArray ( $ array ) { $ data = array ( ) ; foreach ( $ array as $ var => $ val ) { if ( is_array ( $ val ) && ! is_object ( $ val ) ) { $ data [ $ var ] = self :: writeArray ( $ val ) ; } else { $ data [ $ var ] = self :: writeArrayItem ( $ val ) ; } } return serialize ( $ data ) ; } | Write an array on one line |
27,156 | public static function writeArrayItem ( $ item ) { $ str = '' ; try { $ str .= serialize ( $ item ) ; } catch ( \ Exception $ e ) { if ( is_object ( $ item ) ) { $ str .= get_class ( $ item ) . '#' ; } $ str .= spl_object_hash ( $ item ) ; } return $ str ; } | Safely transform an array item in string |
27,157 | public function preSetData ( FormEvent $ event ) { $ form = $ event -> getForm ( ) ; $ data = $ event -> getData ( ) ; if ( null === $ data ) { throw new \ InvalidArgumentException ( 'Can\'t handle null datas.' ) ; } if ( ! is_array ( $ data ) && ! ( $ data instanceof \ Traversable && $ data instanceof \ ArrayAccess ) ) { throw new UnexpectedTypeException ( $ data , 'array or (\Traversable and \ArrayAccess)' ) ; } foreach ( $ form as $ name => $ child ) { $ form -> remove ( $ name ) ; } foreach ( $ this -> schema -> getGroups ( ) as $ schemaGroup ) { $ form -> add ( $ schemaGroup -> getName ( ) , new GroupType ( ) , array ( 'label' => $ schemaGroup -> getTitle ( ) ) ) ; $ groupForm = $ form -> get ( $ schemaGroup -> getName ( ) ) ; foreach ( $ schemaGroup -> getDefinitions ( ) as $ schemaDefinition ) { if ( true === $ schemaDefinition -> getVirtual ( ) ) { continue ; } $ this -> appendProperForm ( $ groupForm , $ schemaDefinition ) ; $ this -> appendProperData ( $ data , $ schemaDefinition ) ; } } $ event -> setData ( $ data ) ; } | Pre set data event handler . |
27,158 | public function onSubmit ( FormEvent $ event ) { $ data = $ event -> getData ( ) ; if ( null === $ data ) { $ data = array ( ) ; } if ( ! is_array ( $ data ) && ! ( $ data instanceof \ Traversable && $ data instanceof \ ArrayAccess ) ) { throw new UnexpectedTypeException ( $ data , 'array or (\Traversable and \ArrayAccess)' ) ; } foreach ( $ this -> schema -> getGroups ( ) as $ schemaGroup ) { foreach ( $ schemaGroup -> getDefinitions ( ) as $ schemaDefinition ) { if ( true === $ schemaDefinition -> getVirtual ( ) ) { continue ; } $ identifier = $ schemaDefinition -> getIdentifier ( ) ; if ( $ data -> offsetExists ( $ identifier ) ) { $ characteristic = $ data -> offsetGet ( $ identifier ) ; if ( $ this -> isNullOrEqualsParentData ( $ characteristic ) ) { $ data -> offsetUnset ( $ identifier ) ; $ this -> em -> remove ( $ characteristic ) ; } else { $ characteristic -> setIdentifier ( $ identifier ) ; } } else { throw new \ RuntimeException ( sprintf ( 'Missing [%s] characteristic data.' , $ identifier ) ) ; } } } $ event -> setData ( $ data ) ; } | Submit event handler . |
27,159 | private function isNullOrEqualsParentData ( CharacteristicInterface $ characteristic ) { if ( $ characteristic -> isNull ( ) ) { return true ; } elseif ( null !== $ this -> parentDatas && null !== $ parentCharacteristic = $ this -> parentDatas -> findCharacteristicByIdentifier ( $ characteristic -> getIdentifier ( ) ) ) { return $ parentCharacteristic -> equals ( $ characteristic ) ; } return false ; } | Returns whether the characteristic is null or equals parent s or not . |
27,160 | private function appendProperForm ( FormInterface $ form , Definition $ definition ) { $ identifier = $ definition -> getIdentifier ( ) ; if ( $ form -> has ( $ identifier ) ) { return ; } $ type = sprintf ( 'ekyna_%s_characteristic' , $ definition -> getType ( ) ) ; $ options = array ( ) ; if ( $ definition -> getType ( ) == 'choice' ) { $ options [ 'identifier' ] = $ identifier ; } $ parentData = null ; if ( null !== $ this -> parentDatas && null !== $ characteristic = $ this -> parentDatas -> findCharacteristicByIdentifier ( $ identifier ) ) { $ parentData = $ characteristic -> display ( $ definition ) ; } $ form -> add ( $ identifier , $ type , array_merge ( array ( 'property_path' => '[' . $ identifier . ']' , 'label' => $ definition -> getTitle ( ) , 'parent_data' => $ parentData , ) , $ options ) ) ; } | Appends a form that matches the characteristic type . |
27,161 | private function appendProperData ( Collection $ data , Definition $ definition ) { $ identifier = $ definition -> getIdentifier ( ) ; if ( $ data -> offsetExists ( $ identifier ) ) { return ; } $ characteristic = $ this -> manager -> createCharacteristicFromDefinition ( $ definition ) ; $ data -> set ( $ identifier , $ characteristic ) ; } | Fills the data with the proper characteristic type . |
27,162 | public function setSubdirectory ( $ subdirectory ) { $ this -> subdirectory = $ subdirectory ; $ this -> regexPattern = VariableUrl :: createRegexMask ( $ subdirectory . $ this -> pattern ) ; return $ this ; } | Sets the subdirectory prefix for this route . |
27,163 | public function setAcceptableMethods ( array $ acceptableMethods ) { $ this -> acceptableMethods = $ acceptableMethods ; $ this -> addConstraint ( function ( Request $ request ) use ( $ acceptableMethods ) { return in_array ( $ request -> getMethod ( ) , $ acceptableMethods ) ; } ) ; } | Sets a list of acceptable HTTP method for this route to match . |
27,164 | public function matchesPattern ( Request $ request ) { if ( preg_match ( $ this -> regexPattern , $ request -> getRequestUri ( ) ) <= 0 ) { return false ; } return true ; } | Matches a request against the pattern configured on this route . |
27,165 | public function meetsConstraints ( Request $ request ) { foreach ( $ this -> constraints as $ constraint ) { if ( ! $ constraint ( $ request ) ) { return false ; } } return true ; } | Matches a request against the constraints configured on this route . |
27,166 | public function action ( Context $ context = null ) { $ targetFunc = null ; $ classObject = null ; if ( empty ( $ context ) ) { $ context = new Context ( ) ; } if ( $ this -> isCallable ( ) ) { $ targetFunc = $ this -> getTarget ( ) ; } else { $ targetFunc = $ this -> translateToClassCallable ( $ context ) ; $ classObject = $ targetFunc [ 0 ] ; } if ( ! $ this -> filters -> trigger ( Filters :: BEFORE_ROUTE , $ context ) ) { return null ; } $ returnValue = null ; $ continue = true ; if ( $ classObject != null ) { $ beforeCallable = [ $ classObject , 'before' ] ; if ( is_callable ( $ beforeCallable ) ) { $ returnValue = $ this -> executeAction ( $ beforeCallable , $ context ) ; if ( $ returnValue && $ returnValue instanceof Response ) { $ continue = false ; } } } if ( $ continue ) { $ returnValue = $ this -> executeAction ( $ targetFunc , $ context ) ; } $ this -> filters -> trigger ( Filters :: AFTER_ROUTE , $ context ) ; return $ returnValue ; } | Executes this route s action . |
27,167 | private function executeAction ( callable $ targetFunc , Context $ context ) { $ returnValue = null ; $ paramValues = $ context -> determineParamValues ( $ targetFunc ) ; try { $ returnValue = call_user_func_array ( $ targetFunc , $ paramValues ) ; } catch ( \ Exception $ ex ) { $ context -> registerInstance ( $ ex ) ; $ this -> filters -> trigger ( Filters :: ON_EXCEPTION , $ context ) ; if ( ! $ this -> filters -> anyHandlersForEvent ( Filters :: ON_EXCEPTION ) ) { throw $ ex ; } } return $ returnValue ; } | Executes a route action given a callable and a context . |
27,168 | private function translateToClassCallable ( Context $ context ) { $ targetParts = explode ( '@' , strval ( $ this -> getTarget ( ) ) , 2 ) ; $ targetClass = $ targetParts [ 0 ] ; $ targetFuncName = count ( $ targetParts ) > 1 ? $ targetParts [ 1 ] : 'action' ; if ( ! class_exists ( $ targetClass , true ) ) { throw new RoutingException ( 'Could not locate class: ' . $ targetClass ) ; } $ classObj = null ; $ parameterList = $ context -> determineParamValuesForConstructor ( $ targetClass ) ; try { $ reflection = new \ ReflectionClass ( $ targetClass ) ; $ classObj = $ reflection -> newInstanceArgs ( $ parameterList ) ; } catch ( \ TypeError $ ex ) { throw new RoutingException ( 'Type error thrown when calling constructor on ' . $ targetClass , 0 , $ ex ) ; } $ targetFunc = [ $ classObj , $ targetFuncName ] ; if ( ! is_callable ( $ targetFunc ) ) { throw new RoutingException ( 'Route target function is not callable: ' . $ this -> getTarget ( ) ) ; } return $ targetFunc ; } | Attempts to translate this route s target to a function within a controller class . |
27,169 | public function process ( MessageInterface $ message ) { $ event = $ this -> getProcessEvent ( ) ; $ event -> setWorker ( $ this ) ; $ event -> setMessage ( $ message ) ; $ events = $ this -> getEventManager ( ) ; $ results = $ events -> trigger ( ProcessEvent :: EVENT_PROCESSOR , $ event , function ( $ result ) { return ( $ result instanceof ProcessorInterface ) ; } ) ; $ processor = $ results -> last ( ) ; if ( ! $ processor instanceof ProcessorInterface ) { throw new \ RuntimeException ( sprintf ( '%s: no processor selected!' , __METHOD__ ) ) ; } $ processor -> setWorker ( $ this ) ; $ event -> setProcessor ( $ processor ) ; $ result = $ processor -> process ( $ message ) ; $ event -> setResult ( $ result ) ; $ events -> trigger ( ProcessEvent :: EVENT_PROCESS_POST , $ event ) ; return $ result ; } | Process a message |
27,170 | public function send ( QueueClientInterface $ queue , $ message , SendParametersInterface $ params = null ) { $ queue -> send ( $ message , $ params ) ; } | Send a message to the queue |
27,171 | public function receive ( QueueClientInterface $ queue , $ maxMessages = 1 , ReceiveParametersInterface $ params = null ) { $ messages = $ queue -> receive ( $ maxMessages , $ params ) ; $ lastResult = [ ] ; foreach ( $ messages as $ message ) { if ( $ message instanceof MessageInterface ) { $ lastResult = $ this -> process ( $ message ) ; if ( $ queue -> canDeleteMessage ( ) ) { $ queue -> delete ( $ message ) ; } } } return $ lastResult ; } | Receive and process one or more incoming messages |
27,172 | public function await ( QueueClientInterface $ queue , ReceiveParametersInterface $ params = null ) { $ worker = $ this ; $ this -> await = true ; $ lastResult = [ ] ; $ callback = function ( QueueEvent $ event ) use ( $ worker , $ queue , & $ lastResult ) { $ messages = $ event -> getMessages ( ) ; foreach ( $ messages as $ message ) { $ lastResult = $ worker -> process ( $ message ) ; if ( $ queue -> canDeleteMessage ( ) ) { $ queue -> delete ( $ message ) ; } } if ( $ worker -> isAwaitingStopped ( ) ) { $ event -> stopAwait ( true ) ; } return ! $ worker -> isAwaitingStopped ( ) ; } ; $ callbackHandler = $ queue -> getEventManager ( ) -> attach ( QueueEvent :: EVENT_RECEIVE , $ callback ) ; $ queue -> await ( $ params ) ; $ queue -> getEventManager ( ) -> detach ( $ callbackHandler ) ; return $ lastResult ; } | Wait for and process incoming messages |
27,173 | public function setEntityTable ( $ entityTable ) { if ( ! is_string ( $ entityTable ) || empty ( $ entityTable ) ) { throw new \ InvalidArgumentException ( 'The entity table is invalid.' ) ; } $ this -> entityTable = $ entityTable ; return $ this ; } | Set the entity table |
27,174 | public function findById ( $ entityId ) { $ this -> adapter -> select ( $ this -> entityTable , "id = {$entityId}" ) ; if ( ( $ data = $ this -> adapter -> fetch ( ) ) !== false ) { return $ this -> createEntity ( $ data ) ; } return null ; } | Find an entity by its ID |
27,175 | public function insert ( $ entity ) { if ( ! $ entity instanceof $ this -> entityClass ) { throw new \ InvalidArgumentException ( "The entity to be inserted must be an instance of {$this->entityClass}." ) ; } return $ this -> adapter -> insert ( $ this -> entityTable , $ entity -> toArray ( ) ) ; } | Insert a new entity in the storage |
27,176 | public function update ( $ entity ) { if ( ! $ entity instanceof $ this -> entityClass ) { throw new \ InvalidArgumentException ( "The entity to be updated must be an instance of {$this->entityClass}." ) ; } $ entityId = $ entity -> id ; $ data = $ entity -> toArray ( ) ; unset ( $ data [ 'id' ] ) ; return $ this -> adapter -> update ( $ this -> entityTable , $ data , "id = $entityId" ) ; } | Update an existing entity in the storage |
27,177 | public function delete ( $ entityId , $ col = 'id' ) { if ( is_null ( $ entityId ) || ( ! is_numeric ( $ entityId ) && ! is_a ( $ entityId , $ this -> entityClass ) ) ) { throw new \ InvalidArgumentException ( "Invalid entity or entityId argument." ) ; } if ( $ entityId instanceof $ this -> entityClass ) { $ entityId = $ entityId -> id ; } return $ this -> adapter -> delete ( $ this -> entityTable , "$col = $entityId" ) ; } | Delete one or more entities from the storage |
27,178 | public static function makeDB ( \ Native5 \ Core \ Database \ DBConfig $ configuration ) { if ( empty ( $ configuration ) ) throw new \ Exception ( 'Empty connection settings provided' ) ; $ port = $ configuration -> getPort ( ) ; $ port = ! empty ( $ port ) ? $ port : 3306 ; $ dsn = $ configuration -> getType ( ) . ':host=' . $ configuration -> getHost ( ) . ';port=' . $ port . ';dbname=' . $ configuration -> getName ( ) ; $ dbKey = md5 ( $ dsn . '.' . $ configuration -> getUser ( ) ) ; if ( isset ( self :: $ _dbs [ $ dbKey ] ) && ! empty ( self :: $ _dbs [ $ dbKey ] ) && self :: $ _dbs [ $ dbKey ] -> checkConnection ( ) ) return self :: $ _dbs [ $ dbKey ] ; return ( self :: $ _dbs [ $ dbKey ] = new \ Native5 \ Core \ Database \ DB ( $ configuration ) ) ; } | instance method for instantiating a DB object |
27,179 | protected static function BuildCache ( ) { self :: CalculateData ( self :: $ Categories ) ; self :: JoinRecentPosts ( self :: $ Categories ) ; Gdn :: Cache ( ) -> Store ( self :: CACHE_KEY , self :: $ Categories , array ( Gdn_Cache :: FEATURE_EXPIRY => 600 ) ) ; } | Build and augment the category cache |
27,180 | public static function GivePoints ( $ UserID , $ Points , $ Source = 'Other' , $ CategoryID = 0 , $ Timestamp = FALSE ) { if ( $ CategoryID ) { $ Category = self :: Categories ( $ CategoryID ) ; if ( $ Category ) $ CategoryID = GetValue ( 'PointsCategoryID' , $ Category ) ; else $ CategoryID = 0 ; } UserModel :: GivePoints ( $ UserID , $ Points , array ( $ Source , 'CategoryID' => $ CategoryID ) , $ Timestamp ) ; } | Give a user points specific to this category . |
27,181 | public function GetID ( $ CategoryID , $ DatasetType = DATASET_TYPE_OBJECT ) { return $ this -> SQL -> GetWhere ( 'Category' , array ( 'CategoryID' => $ CategoryID ) ) -> FirstRow ( $ DatasetType ) ; } | Get data for a single category selected by ID . Disregards permissions . |
27,182 | public function GetDescendantCountByCode ( $ Code ) { $ Category = $ this -> GetByCode ( $ Code ) ; if ( $ Category ) return round ( ( $ Category -> TreeRight - $ Category -> TreeLeft - 1 ) / 2 ) ; return 0 ; } | Return the number of descendants for a specific category . |
27,183 | public static function GetAncestors ( $ CategoryID , $ CheckPermissions = TRUE ) { $ Categories = self :: Categories ( ) ; $ Result = array ( ) ; if ( is_numeric ( $ CategoryID ) ) { if ( isset ( $ Categories [ $ CategoryID ] ) ) $ Category = $ Categories [ $ CategoryID ] ; } else { foreach ( $ Categories as $ ID => $ Value ) { if ( $ Value [ 'UrlCode' ] == $ CategoryID ) { $ Category = $ Categories [ $ ID ] ; break ; } } } if ( ! isset ( $ Category ) ) return $ Result ; $ Result [ $ Category [ 'CategoryID' ] ] = $ Category ; $ Max = 20 ; while ( isset ( $ Categories [ $ Category [ 'ParentCategoryID' ] ] ) ) { if ( $ Max <= 0 ) break ; $ Max -- ; if ( $ CheckPermissions && ! $ Category [ 'PermsDiscussionsView' ] ) { $ Category = $ Categories [ $ Category [ 'ParentCategoryID' ] ] ; continue ; } if ( $ Category [ 'CategoryID' ] == - 1 ) break ; if ( is_numeric ( $ CategoryID ) ) $ ID = $ Category [ 'CategoryID' ] ; else $ ID = $ Category [ 'UrlCode' ] ; $ Result [ $ ID ] = $ Category ; $ Category = $ Categories [ $ Category [ 'ParentCategoryID' ] ] ; } $ Result = array_reverse ( $ Result , TRUE ) ; return $ Result ; } | Get all of the ancestor categories above this one . |
27,184 | public function GetFiltered ( $ RestrictIDs = FALSE , $ Permissions = FALSE , $ ExcludeWhere = FALSE ) { $ Categories = self :: Categories ( ) ; if ( $ RestrictIDs && ! is_array ( $ RestrictIDs ) ) $ RestrictIDs = array ( $ RestrictIDs ) ; elseif ( $ this -> Watching ) $ RestrictIDs = self :: CategoryWatch ( ) ; switch ( $ Permissions ) { case 'Vanilla.Discussions.Add' : $ Permissions = 'PermsDiscussionsAdd' ; break ; case 'Vanilla.Disussions.Edit' : $ Permissions = 'PermsDiscussionsEdit' ; break ; default : $ Permissions = 'PermsDiscussionsView' ; break ; } $ IDs = array_keys ( $ Categories ) ; foreach ( $ IDs as $ ID ) { if ( $ ID < 0 ) unset ( $ Categories [ $ ID ] ) ; elseif ( ! $ Categories [ $ ID ] [ $ Permissions ] ) unset ( $ Categories [ $ ID ] ) ; elseif ( is_array ( $ ExcludeWhere ) ) { foreach ( $ ExcludeWhere as $ Filter => $ FilterValue ) if ( GetValue ( $ Filter , $ Categories [ $ ID ] , FALSE ) == $ FilterValue ) unset ( $ Categories [ $ ID ] ) ; } elseif ( is_array ( $ RestrictIDs ) && ! in_array ( $ ID , $ RestrictIDs ) ) unset ( $ Categories [ $ ID ] ) ; } Gdn :: UserModel ( ) -> JoinUsers ( $ Categories , array ( 'LastUserID' ) ) ; $ Result = new Gdn_DataSet ( $ Categories , DATASET_TYPE_ARRAY ) ; $ Result -> DatasetType ( DATASET_TYPE_OBJECT ) ; return $ Result ; } | Get a list of categories considering several filters |
27,185 | public function GetFullByUrlCode ( $ UrlCode ) { $ Data = ( object ) self :: Categories ( $ UrlCode ) ; $ CategoryIDs = DiscussionModel :: CategoryPermissions ( ) ; if ( is_array ( $ CategoryIDs ) && ! in_array ( GetValue ( 'CategoryID' , $ Data ) , $ CategoryIDs ) ) $ Data = FALSE ; return $ Data ; } | Get full data for a single category by its URL slug . Respects permissions . |
27,186 | public function GetWhereCache ( $ Where ) { $ Result = array ( ) ; foreach ( self :: Categories ( ) as $ Index => $ Row ) { $ Match = true ; foreach ( $ Where as $ Column => $ Value ) { $ RowValue = GetValue ( $ Column , $ Row , NULL ) ; if ( $ RowValue != $ Value && ! ( is_array ( $ Value ) && in_array ( $ RowValue , $ Value ) ) ) { $ Match = false ; break ; } } if ( $ Match ) $ Result [ $ Index ] = $ Row ; } return $ Result ; } | A simplified version of GetWhere that polls the cache instead of the database . |
27,187 | public function HasChildren ( $ CategoryID ) { $ ChildData = $ this -> SQL -> Select ( 'CategoryID' ) -> From ( 'Category' ) -> Where ( 'ParentCategoryID' , $ CategoryID ) -> Get ( ) ; return $ ChildData -> NumRows ( ) > 0 ? TRUE : FALSE ; } | Check whether category has any children categories . |
27,188 | public function SaveTree ( $ TreeArray ) { $ PermTree = $ this -> SQL -> Select ( 'CategoryID, PermissionCategoryID, TreeLeft, TreeRight, Depth, Sort, ParentCategoryID' ) -> From ( 'Category' ) -> Get ( ) ; $ PermTree = $ PermTree -> Index ( $ PermTree -> ResultArray ( ) , 'CategoryID' ) ; usort ( $ TreeArray , array ( 'CategoryModel' , '_TreeSort' ) ) ; $ Saves = array ( ) ; foreach ( $ TreeArray as $ I => $ Node ) { $ CategoryID = GetValue ( 'item_id' , $ Node ) ; if ( $ CategoryID == 'root' ) $ CategoryID = - 1 ; $ ParentCategoryID = GetValue ( 'parent_id' , $ Node ) ; if ( in_array ( $ ParentCategoryID , array ( 'root' , 'none' ) ) ) $ ParentCategoryID = - 1 ; $ PermissionCategoryID = GetValueR ( "$CategoryID.PermissionCategoryID" , $ PermTree , 0 ) ; $ PermCatChanged = FALSE ; if ( $ PermissionCategoryID != $ CategoryID ) { $ PermissionCategoryID = GetValueR ( "$ParentCategoryID.PermissionCategoryID" , $ PermTree , 0 ) ; if ( $ CategoryID != - 1 && ! GetValueR ( "$ParentCategoryID.Touched" , $ PermTree ) ) { throw new Exception ( "Category $ParentCategoryID not touched before touching $CategoryID." ) ; } if ( $ PermTree [ $ CategoryID ] [ 'PermissionCategoryID' ] != $ PermissionCategoryID ) $ PermCatChanged = TRUE ; $ PermTree [ $ CategoryID ] [ 'PermissionCategoryID' ] = $ PermissionCategoryID ; } $ PermTree [ $ CategoryID ] [ 'Touched' ] = TRUE ; $ Row = $ PermTree [ $ CategoryID ] ; if ( $ Node [ 'left' ] != $ Row [ 'TreeLeft' ] || $ Node [ 'right' ] != $ Row [ 'TreeRight' ] || $ Node [ 'depth' ] != $ Row [ 'Depth' ] || $ ParentCategoryID != $ Row [ 'ParentCategoryID' ] || $ Node [ 'left' ] != $ Row [ 'Sort' ] || $ PermCatChanged ) { $ Set = array ( 'TreeLeft' => $ Node [ 'left' ] , 'TreeRight' => $ Node [ 'right' ] , 'Depth' => $ Node [ 'depth' ] , 'Sort' => $ Node [ 'left' ] , 'ParentCategoryID' => $ ParentCategoryID , 'PermissionCategoryID' => $ PermissionCategoryID ) ; $ this -> SQL -> Update ( 'Category' , $ Set , array ( 'CategoryID' => $ CategoryID ) ) -> Put ( ) ; $ Saves [ ] = array_merge ( array ( 'CategoryID' => $ CategoryID ) , $ Set ) ; } } self :: ClearCache ( ) ; return $ Saves ; } | Saves the category tree based on a provided tree array . We are using the Nested Set tree model . |
27,189 | public function SaveUserTree ( $ CategoryID , $ Set ) { $ Categories = $ this -> GetSubtree ( $ CategoryID ) ; foreach ( $ Categories as $ Category ) { $ this -> SQL -> Replace ( 'UserCategory' , $ Set , array ( 'UserID' => Gdn :: Session ( ) -> UserID , 'CategoryID' => $ Category [ 'CategoryID' ] ) ) ; } $ Key = 'UserCategory_' . Gdn :: Session ( ) -> UserID ; Gdn :: Cache ( ) -> Remove ( $ Key ) ; } | Grab the Category IDs of the tree . |
27,190 | public static function SetCache ( $ ID = FALSE , $ Data = FALSE ) { $ Categories = Gdn :: Cache ( ) -> Get ( self :: CACHE_KEY ) ; self :: $ Categories = NULL ; if ( ! $ Categories ) return ; if ( ! $ ID || ! is_array ( $ Categories ) ) { Gdn :: Cache ( ) -> Remove ( self :: CACHE_KEY ) ; return ; } if ( ! array_key_exists ( $ ID , $ Categories ) ) { Gdn :: Cache ( ) -> Remove ( self :: CACHE_KEY ) ; return ; } $ Category = $ Categories [ $ ID ] ; $ Category = array_merge ( $ Category , $ Data ) ; $ Categories [ $ ID ] = $ Category ; self :: $ Categories = $ Categories ; unset ( $ Categories ) ; self :: BuildCache ( ) ; self :: JoinUserData ( self :: $ Categories , TRUE ) ; } | Grab and update the category cache |
27,191 | public function ApplyUpdates ( ) { if ( ! C ( 'Vanilla.NestedCategoriesUpdate' ) ) { $ Construct = Gdn :: Database ( ) -> Structure ( ) ; $ Construct -> Table ( 'Category' ) -> Column ( 'TreeLeft' , 'int' , TRUE ) -> Column ( 'TreeRight' , 'int' , TRUE ) -> Column ( 'Depth' , 'int' , TRUE ) -> Column ( 'CountComments' , 'int' , '0' ) -> Column ( 'LastCommentID' , 'int' , TRUE ) -> Set ( 0 , 0 ) ; if ( $ this -> SQL -> GetWhere ( 'Category' , array ( 'CategoryID' => - 1 ) ) -> NumRows ( ) == 0 ) $ this -> SQL -> Insert ( 'Category' , array ( 'CategoryID' => - 1 , 'TreeLeft' => 1 , 'TreeRight' => 4 , 'Depth' => 0 , 'InsertUserID' => 1 , 'UpdateUserID' => 1 , 'DateInserted' => Gdn_Format :: ToDateTime ( ) , 'DateUpdated' => Gdn_Format :: ToDateTime ( ) , 'Name' => 'Root' , 'UrlCode' => '' , 'Description' => 'Root of category tree. Users should never see this.' ) ) ; $ this -> RebuildTree ( ) ; SaveToConfig ( 'Vanilla.NestedCategoriesUpdate' , 1 ) ; } } | If looking at the root node make sure it exists and that the nested set columns exist in the table . |
27,192 | protected function getAttribute ( BBcodeElementNodeInterface $ el , $ attribute ) { $ attributes = $ el -> getAttribute ( ) ; if ( isset ( $ attributes [ self :: TAG_NAME ] ) ) { $ attributes = json_decode ( $ attributes [ self :: TAG_NAME ] ) ; if ( isset ( $ attributes -> $ attribute ) ) { return $ attributes -> $ attribute ; } } return '' ; } | Get requested media legend |
27,193 | protected function getResponderForFailedRoute ( Route $ route ) { $ rule = $ route -> failedRule ; if ( $ this -> has ( $ rule ) ) { return $ this -> get ( $ rule ) ; } if ( isset ( $ this -> defaults [ $ rule ] ) ) { return [ $ this , $ this -> defaults [ $ rule ] ] ; } return [ $ this , 'other' ] ; } | Get responder for failed route |
27,194 | protected function methodNotAllowed ( Request $ request , Response $ response , Route $ route ) { $ request ; $ response = $ response -> withStatus ( 405 ) -> withHeader ( 'Allow' , implode ( ', ' , $ route -> allows ) ) -> withHeader ( 'Content-Type' , 'application/json' ) ; $ response -> getBody ( ) -> write ( json_encode ( $ route -> allows ) ) ; return $ response ; } | Method not allowed |
27,195 | protected function notFound ( Request $ request , Response $ response , Route $ route ) { $ request ; $ route ; $ response = $ response -> withStatus ( 404 ) ; $ response -> getBody ( ) -> write ( '404 Not Found' ) ; return $ response ; } | Resource not found |
27,196 | protected function other ( Request $ request , Response $ response , Route $ route ) { $ request ; $ response = $ response -> withStatus ( 500 ) -> withHeader ( 'Content-Type' , 'text/plain' ) ; $ message = sprintf ( 'Route "%s" failed for rule "%s"' , $ route -> name , $ route -> failedRule ) ; $ response -> getBody ( ) -> write ( $ message ) ; return $ response ; } | Other rule failed |
27,197 | protected function getRepository ( ) : AbstractRepository { return $ this -> getRepositoryFactory ( ) -> getRepositoryForEntity ( AbstractRepository :: getEntityNameFromClassName ( $ this -> getEntityClassName ( ) ) , $ this -> connectionName ) ; } | Gets the repository corresponding to the managed entity |
27,198 | protected function entityImplements ( string $ interfaceName ) : bool { $ reflectionClass = new \ ReflectionClass ( $ this -> getEntityClassName ( ) ) ; return $ reflectionClass -> implementsInterface ( $ interfaceName ) ; } | Checks if entity class name implements interface |
27,199 | public function getNew ( ) : AbstractEntity { $ newEntity = $ this -> getRepository ( ) -> getNew ( ) ; $ this -> prepareEntityForNew ( $ newEntity ) ; return $ newEntity ; } | Gets a new intance of an entity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.