code
stringlengths
17
296k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public static function stack() { return self::$data; }
Return the current header stack @return string[][]
stack
php
zendframework/zend-diactoros
test/TestAsset/HeaderStack.php
https://github.com/zendframework/zend-diactoros/blob/master/test/TestAsset/HeaderStack.php
BSD-3-Clause
public static function has($header) { foreach (self::$data as $item) { if ($item['header'] === $header) { return true; } } return false; }
Verify if there's a header line on the stack @param string $header @return bool
has
php
zendframework/zend-diactoros
test/TestAsset/HeaderStack.php
https://github.com/zendframework/zend-diactoros/blob/master/test/TestAsset/HeaderStack.php
BSD-3-Clause
function find_file_upward( $files, $dir = null, $stop_check = null ) { $files = (array) $files; if ( is_null( $dir ) ) { $dir = getcwd(); } while ( @is_readable( $dir ) ) { // Stop walking up when the supplied callable returns true being passed the $dir if ( is_callable( $stop_check ) && call_user_func( $stop_check, $dir ) ) { return null; } foreach ( $files as $file ) { $path = $dir . DIRECTORY_SEPARATOR . $file; if ( file_exists( $path ) ) { return $path; } } $parent_dir = dirname( $dir ); if ( empty($parent_dir) || $parent_dir === $dir ) { break; } $dir = $parent_dir; } return null; }
Search for file by walking up the directory tree until the first file is found or until $stop_check($dir) returns true @param string|array The files (or file) to search for @param string|null The directory to start searching from; defaults to CWD @param callable Function which is passed the current dir each time a directory level is traversed @return null|string Null if the file was not found
find_file_upward
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function args_to_str( $args ) { return ' ' . implode( ' ', array_map( 'escapeshellarg', $args ) ); }
Composes positional arguments into a command string. @param array @return string
args_to_str
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function esc_cmd( $cmd ) { if ( func_num_args() < 2 ) trigger_error( 'esc_cmd() requires at least two arguments.', E_USER_WARNING ); $args = func_get_args(); $cmd = array_shift( $args ); return vsprintf( $cmd, array_map( 'escapeshellarg', $args ) ); }
Given a template string and an arbitrary number of arguments, returns the final command, with the parameters escaped.
esc_cmd
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function launch_editor_for_input( $input, $filename = 'WP-CLI' ) { check_proc_available( 'launch_editor_for_input' ); $tmpdir = get_temp_dir(); do { $tmpfile = basename( $filename ); $tmpfile = preg_replace( '|\.[^.]*$|', '', $tmpfile ); $tmpfile .= '-' . substr( md5( rand() ), 0, 6 ); $tmpfile = $tmpdir . $tmpfile . '.tmp'; $fp = @fopen( $tmpfile, 'x' ); if ( ! $fp && is_writable( $tmpdir ) && file_exists( $tmpfile ) ) { $tmpfile = ''; continue; } if ( $fp ) { fclose( $fp ); } } while( ! $tmpfile ); if ( ! $tmpfile ) { \WP_CLI::error( 'Error creating temporary file.' ); } $output = ''; file_put_contents( $tmpfile, $input ); $editor = getenv( 'EDITOR' ); if ( !$editor ) { if ( isset( $_SERVER['OS'] ) && false !== strpos( $_SERVER['OS'], 'indows' ) ) $editor = 'notepad'; else $editor = 'vi'; } $descriptorspec = array( STDIN, STDOUT, STDERR ); $process = proc_open( "$editor " . escapeshellarg( $tmpfile ), $descriptorspec, $pipes ); $r = proc_close( $process ); if ( $r ) { exit( $r ); } $output = file_get_contents( $tmpfile ); unlink( $tmpfile ); if ( $output === $input ) return false; return $output; }
Launch system's $EDITOR for the user to edit some text. @access public @category Input @param string $content Some form of text to edit (e.g. post content) @return string|bool Edited text, if file is saved from editor; false, if no change to file.
launch_editor_for_input
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function is_windows() { return false !== ( $test_is_windows = getenv( 'WP_CLI_TEST_IS_WINDOWS' ) ) ? (bool) $test_is_windows : strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; }
Check if we're running in a Windows environment (cmd.exe). @return bool
is_windows
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function replace_path_consts( $source, $path ) { $replacements = array( '__FILE__' => "'$path'", '__DIR__' => "'" . dirname( $path ) . "'", ); $old = array_keys( $replacements ); $new = array_values( $replacements ); return str_replace( $old, $new, $source ); }
Replace magic constants in some PHP source code. @param string $source The PHP code to manipulate. @param string $path The path to use instead of the magic constants
replace_path_consts
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function increment_version( $current_version, $new_version ) { // split version assuming the format is x.y.z-pre $current_version = explode( '-', $current_version, 2 ); $current_version[0] = explode( '.', $current_version[0] ); switch ( $new_version ) { case 'same': // do nothing break; case 'patch': $current_version[0][2]++; $current_version = array( $current_version[0] ); // drop possible pre-release info break; case 'minor': $current_version[0][1]++; $current_version[0][2] = 0; $current_version = array( $current_version[0] ); // drop possible pre-release info break; case 'major': $current_version[0][0]++; $current_version[0][1] = 0; $current_version[0][2] = 0; $current_version = array( $current_version[0] ); // drop possible pre-release info break; default: // not a keyword $current_version = array( array( $new_version ) ); break; } // reconstruct version string $current_version[0] = implode( '.', $current_version[0] ); $current_version = implode( '-', $current_version ); return $current_version; }
Increments a version string using the "x.y.z-pre" format Can increment the major, minor or patch number by one If $new_version == "same" the version string is not changed If $new_version is not a known keyword, it will be used as the new version string directly @param string $current_version @param string $new_version @return string
increment_version
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function get_named_sem_ver( $new_version, $original_version ) { if ( ! Comparator::greaterThan( $new_version, $original_version ) ) { return ''; } $parts = explode( '-', $original_version ); $bits = explode( '.', $parts[0] ); $major = $bits[0]; if ( isset( $bits[1] ) ) { $minor = $bits[1]; } if ( isset( $bits[2] ) ) { $patch = $bits[2]; } if ( ! is_null( $minor ) && Semver::satisfies( $new_version, "{$major}.{$minor}.x" ) ) { return 'patch'; } else if ( Semver::satisfies( $new_version, "{$major}.x.x" ) ) { return 'minor'; } else { return 'major'; } }
Compare two version strings to get the named semantic version. @access public @param string $new_version @param string $original_version @return string $name 'major', 'minor', 'patch'
get_named_sem_ver
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function get_flag_value( $assoc_args, $flag, $default = null ) { return isset( $assoc_args[ $flag ] ) ? $assoc_args[ $flag ] : $default; }
Return the flag value or, if it's not set, the $default value. Because flags can be negated (e.g. --no-quiet to negate --quiet), this function provides a safer alternative to using `isset( $assoc_args['quiet'] )` or similar. @access public @category Input @param array $assoc_args Arguments array. @param string $flag Flag to get the value. @param mixed $default Default value for the flag. Default: NULL @return mixed
get_flag_value
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function parse_ssh_url( $url, $component = -1 ) { preg_match( '#^((docker|docker\-compose|ssh|vagrant):)?(([^@:]+)@)?([^:/~]+)(:([\d]*))?((/|~)(.+))?$#', $url, $matches ); $bits = array(); foreach( array( 2 => 'scheme', 4 => 'user', 5 => 'host', 7 => 'port', 8 => 'path', ) as $i => $key ) { if ( ! empty( $matches[ $i ] ) ) { $bits[ $key ] = $matches[ $i ]; } } switch ( $component ) { case PHP_URL_SCHEME: return isset( $bits['scheme'] ) ? $bits['scheme'] : null; case PHP_URL_USER: return isset( $bits['user'] ) ? $bits['user'] : null; case PHP_URL_HOST: return isset( $bits['host'] ) ? $bits['host'] : null; case PHP_URL_PATH: return isset( $bits['path'] ) ? $bits['path'] : null; case PHP_URL_PORT: return isset( $bits['port'] ) ? $bits['port'] : null; default: return $bits; } }
Parse a SSH url for its host, port, and path. Similar to parse_url(), but adds support for defined SSH aliases. ``` host OR host/path/to/wordpress OR host:port/path/to/wordpress ``` @access public @return mixed
parse_ssh_url
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function report_batch_operation_results( $noun, $verb, $total, $successes, $failures ) { $plural_noun = $noun . 's'; $past_tense_verb = past_tense_verb( $verb ); $past_tense_verb_upper = ucfirst( $past_tense_verb ); if ( $failures ) { if ( $successes ) { WP_CLI::error( "Only {$past_tense_verb} {$successes} of {$total} {$plural_noun}." ); } else { WP_CLI::error( "No {$plural_noun} {$past_tense_verb}." ); } } else { if ( $successes ) { WP_CLI::success( "{$past_tense_verb_upper} {$successes} of {$total} {$plural_noun}." ); } else { $message = $total > 1 ? ucfirst( $plural_noun ) : ucfirst( $noun ); WP_CLI::success( "{$message} already {$past_tense_verb}." ); } } }
Report the results of the same operation against multiple resources. @access public @category Input @param string $noun Resource being affected (e.g. plugin) @param string $verb Type of action happening to the noun (e.g. activate) @param integer $total Total number of resource being affected. @param integer $successes Number of successful operations. @param integer $failures Number of failures.
report_batch_operation_results
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function parse_str_to_argv( $arguments ) { preg_match_all ('/(?<=^|\s)([\'"]?)(.+?)(?<!\\\\)\1(?=$|\s)/', $arguments, $matches ); $argv = isset( $matches[0] ) ? $matches[0] : array(); $argv = array_map( function( $arg ){ foreach( array( '"', "'" ) as $char ) { if ( $char === substr( $arg, 0, 1 ) && $char === substr( $arg, -1 ) ) { $arg = substr( $arg, 1, -1 ); break; } } return $arg; }, $argv ); return $argv; }
Parse a string of command line arguments into an $argv-esqe variable. @access public @category Input @param string $arguments @return array
parse_str_to_argv
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function basename( $path, $suffix = '' ) { return urldecode( \basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) ); }
Locale-independent version of basename() @access public @param string $path @param string $suffix @return string
basename
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function isPiped() { $shellPipe = getenv('SHELL_PIPE'); if ($shellPipe !== false) { return filter_var($shellPipe, FILTER_VALIDATE_BOOLEAN); } else { return (function_exists('posix_isatty') && !posix_isatty(STDOUT)); } }
Checks whether the output of the current script is a TTY or a pipe / redirect Returns true if STDOUT output is being redirected to a pipe or a file; false is output is being sent directly to the terminal. If an env variable SHELL_PIPE exists, returned result depends it's value. Strings like 1, 0, yes, no, that validate to booleans are accepted. To enable ASCII formatting even when shell is piped, use the ENV variable SHELL_PIPE=0 @access public @return bool
isPiped
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function phar_safe_path( $path ) { if ( ! inside_phar() ) { return $path; } return str_replace( PHAR_STREAM_PREFIX . WP_CLI_PHAR_PATH . '/', PHAR_STREAM_PREFIX, $path ); }
Get a Phar-safe version of a path. For paths inside a Phar, this strips the outer filesystem's location to reduce the path to what it needs to be within the Phar archive. Use the __FILE__ or __DIR__ constants as a starting point. @param string $path An absolute path that might be within a Phar. @return string A Phar-safe version of the path.
phar_safe_path
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function is_bundled_command( $command ) { static $classes; if ( null === $classes ) { $classes = array(); $class_map = WP_CLI_VENDOR_DIR . '/composer/autoload_commands_classmap.php'; if ( file_exists( WP_CLI_VENDOR_DIR . '/composer/') ) { $classes = include $class_map; } } if ( is_object( $command ) ) { $command = get_class( $command ); } return is_string( $command ) ? array_key_exists( $command, $classes ) : false; }
Check whether a given Command object is part of the bundled set of commands. This function accepts both a fully qualified class name as a string as well as an object that extends `WP_CLI\Dispatcher\CompositeCommand`. @param \WP_CLI\Dispatcher\CompositeCommand|string $command @return bool
is_bundled_command
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function force_env_on_nix_systems( $command ) { $env_prefix = '/usr/bin/env '; $env_prefix_len = strlen( $env_prefix ); if ( is_windows() ) { if ( 0 === strncmp( $command, $env_prefix, $env_prefix_len ) ) { $command = substr( $command, $env_prefix_len ); } } else { if ( 0 !== strncmp( $command, $env_prefix, $env_prefix_len ) ) { $command = $env_prefix . $command; } } return $command; }
Maybe prefix command string with "/usr/bin/env". Removes (if there) if Windows, adds (if not there) if not. @param string $command @return string
force_env_on_nix_systems
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
function check_proc_available( $context = null, $return = false ) { if ( ! function_exists( 'proc_open' ) || ! function_exists( 'proc_close' ) ) { if ( $return ) { return false; } $msg = 'The PHP functions `proc_open()` and/or `proc_close()` are disabled. Please check your PHP ini directive `disable_functions` or suhosin settings.'; if ( $context ) { WP_CLI::error( sprintf( "Cannot do '%s': %s", $context, $msg ) ); } else { WP_CLI::error( $msg ); } } return true; }
Check that `proc_open()` and `proc_close()` haven't been disabled. @param string $context Optional. If set will appear in error message. Default null. @param bool $return Optional. If set will return false rather than error out. Default false. @return bool
check_proc_available
php
10up/MU-Migration
features/bootstrap/utils.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/utils.php
MIT
public function __toString() { $out = "$ $this->command\n"; $out .= "$this->stdout\n$this->stderr"; $out .= "cwd: $this->cwd\n"; $out .= "run time: $this->run_time\n"; $out .= "exit status: $this->return_code"; return $out; }
Return properties of executed command as a string. @return string
__toString
php
10up/MU-Migration
features/bootstrap/ProcessRun.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/ProcessRun.php
MIT
public function run_check() { $r = $this->run(); // $r->STDERR is incorrect, but kept incorrect for backwards-compat if ( $r->return_code || !empty( $r->STDERR ) ) { throw new \RuntimeException( $r ); } return $r; }
Run the command, but throw an Exception on error. @return ProcessRun
run_check
php
10up/MU-Migration
features/bootstrap/Process.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/Process.php
MIT
function checkThatYamlStringContainsYamlString( $actualYaml, $expectedYaml ) { $actualValue = Mustangostang\Spyc::YAMLLoad( $actualYaml ); $expectedValue = Mustangostang\Spyc::YAMLLoad( $expectedYaml ); if ( !$actualValue ) { return false; } return compareContents( $expectedValue, $actualValue ); }
Compare two strings containing YAML to ensure that @a $actualYaml contains at least what the YAML string @a $expectedYaml contains. @return whether or not @a $actualYaml contains @a $expectedJson @retval true @a $actualYaml contains @a $expectedJson @retval false @a $actualYaml does not contain @a $expectedJson @param[in] $actualYaml the YAML string to be tested @param[in] $expectedYaml the expected YAML string
checkThatYamlStringContainsYamlString
php
10up/MU-Migration
features/bootstrap/support.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/support.php
MIT
private static function get_process_env_variables() { // Ensure we're using the expected `wp` binary $bin_dir = getenv( 'WP_CLI_BIN_DIR' ) ?: realpath( __DIR__ . '/../../bin' ); $vendor_dir = realpath( __DIR__ . '/../../vendor/bin' ); $env = array( 'PATH' => $bin_dir . ':' . $vendor_dir . ':' . getenv( 'PATH' ), 'BEHAT_RUN' => 1, 'HOME' => sys_get_temp_dir() . '/wp-cli-home', ); if ( $config_path = getenv( 'WP_CLI_CONFIG_PATH' ) ) { $env['WP_CLI_CONFIG_PATH'] = $config_path; } if ( $term = getenv( 'TERM' ) ) { $env['TERM'] = $term; } if ( $php_args = getenv( 'WP_CLI_PHP_ARGS' ) ) { $env['WP_CLI_PHP_ARGS'] = $php_args; } if ( $travis_build_dir = getenv( 'TRAVIS_BUILD_DIR' ) ) { $env['TRAVIS_BUILD_DIR'] = $travis_build_dir; } if ( $github_token = getenv( 'GITHUB_TOKEN' ) ) { $env['GITHUB_TOKEN'] = $github_token; } return $env; }
Get the environment variables required for launched `wp` processes
get_process_env_variables
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function cache_wp_files() { $wp_version_suffix = ( $wp_version = getenv( 'WP_VERSION' ) ) ? "-$wp_version" : ''; self::$cache_dir = sys_get_temp_dir() . '/wp-cli-test-core-download-cache' . $wp_version_suffix; if ( is_readable( self::$cache_dir . '/wp-config-sample.php' ) ) return; $cmd = Utils\esc_cmd( 'wp core download --force --path=%s', self::$cache_dir ); if ( $wp_version ) { $cmd .= Utils\esc_cmd( ' --version=%s', $wp_version ); } Process::create( $cmd, null, self::get_process_env_variables() )->run_check(); }
We cache the results of `wp core download` to improve test performance. Ideally, we'd cache at the HTTP layer for more reliable tests.
cache_wp_files
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function terminate_proc( $master_pid ) { $output = `ps -o ppid,pid,command | grep $master_pid`; foreach ( explode( PHP_EOL, $output ) as $line ) { if ( preg_match( '/^\s*(\d+)\s+(\d+)/', $line, $matches ) ) { $parent = $matches[1]; $child = $matches[2]; if ( $parent == $master_pid ) { self::terminate_proc( $child ); } } } if ( ! posix_kill( (int) $master_pid, 9 ) ) { $errno = posix_get_last_error(); // Ignore "No such process" error as that's what we want. if ( 3 /*ESRCH*/ !== $errno ) { throw new RuntimeException( posix_strerror( $errno ) ); } } }
Terminate a process and any of its children.
terminate_proc
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public static function create_cache_dir() { if ( self::$suite_cache_dir ) { self::remove_dir( self::$suite_cache_dir ); } self::$suite_cache_dir = sys_get_temp_dir() . '/' . uniqid( 'wp-cli-test-suite-cache-' . self::$temp_dir_infix . '-', TRUE ); mkdir( self::$suite_cache_dir ); return self::$suite_cache_dir; }
Create a temporary WP_CLI_CACHE_DIR. Exposed as SUITE_CACHE_DIR in "Given an empty cache" step.
create_cache_dir
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public function __construct( array $parameters ) { if ( getenv( 'WP_CLI_TEST_DBUSER' ) ) { self::$db_settings['dbuser'] = getenv( 'WP_CLI_TEST_DBUSER' ); } if ( false !== getenv( 'WP_CLI_TEST_DBPASS' ) ) { self::$db_settings['dbpass'] = getenv( 'WP_CLI_TEST_DBPASS' ); } if ( getenv( 'WP_CLI_TEST_DBHOST' ) ) { self::$db_settings['dbhost'] = getenv( 'WP_CLI_TEST_DBHOST' ); } //load constants require_once 'mu-migration.php'; $this->drop_db(); $this->set_cache_dir(); $this->variables['CORE_CONFIG_SETTINGS'] = Utils\assoc_args_to_str( self::$db_settings ); $this->variables['MU_MIGRATION_VERSION'] = TENUP_MU_MIGRATION_VERSION; }
Initializes context. Every scenario gets its own context object. @param array $parameters context parameters (set them up through behat.yml)
__construct
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public function replace_variables( $str ) { $ret = preg_replace_callback( '/\{([A-Z_]+)\}/', array( $this, '_replace_var' ), $str ); if ( false !== strpos( $str, '{WP_VERSION-' ) ) { $ret = $this->_replace_wp_versions( $ret ); } return $ret; }
Replace {VARIABLE_NAME}. Note that variable names can only contain uppercase letters and underscores (no numbers).
replace_variables
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public function create_run_dir() { if ( !isset( $this->variables['RUN_DIR'] ) ) { self::$run_dir = $this->variables['RUN_DIR'] = sys_get_temp_dir() . '/' . uniqid( 'wp-cli-test-run-' . self::$temp_dir_infix . '-', TRUE ); mkdir( $this->variables['RUN_DIR'] ); } }
Create the RUN_DIR directory, unless already set for this scenario.
create_run_dir
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private function set_cache_dir() { $path = sys_get_temp_dir() . '/wp-cli-test-cache'; if ( ! file_exists( $path ) ) { mkdir( $path ); } $this->variables['CACHE_DIR'] = $path; }
CACHE_DIR is a cache for downloaded test data such as images. Lives until manually deleted.
set_cache_dir
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public function background_proc( $cmd ) { $descriptors = array( 0 => STDIN, 1 => array( 'pipe', 'w' ), 2 => array( 'pipe', 'w' ), ); $proc = proc_open( $cmd, $descriptors, $pipes, $this->variables['RUN_DIR'], self::get_process_env_variables() ); sleep(1); $status = proc_get_status( $proc ); if ( !$status['running'] ) { throw new RuntimeException( stream_get_contents( $pipes[2] ) ); } else { $this->running_procs[] = $proc; } }
Start a background process. Will automatically be closed when the tests finish.
background_proc
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public static function remove_dir( $dir ) { Process::create( Utils\esc_cmd( 'rm -rf %s', $dir ) )->run_check(); }
Remove a directory (recursive).
remove_dir
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
public static function copy_dir( $src_dir, $dest_dir ) { Process::create( Utils\esc_cmd( "cp -r %s/* %s", $src_dir, $dest_dir ) )->run_check(); }
Copy a directory (recursive). Destination directory must exist.
copy_dir
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function log_run_times_before_scenario( $event ) { if ( $scenario_key = self::get_scenario_key( $event ) ) { self::$scenario_run_times[ $scenario_key ] = -microtime( true ); } }
Record the start time of the scenario into the `$scenario_run_times` array.
log_run_times_before_scenario
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function log_run_times_after_scenario( $event ) { if ( $scenario_key = self::get_scenario_key( $event ) ) { self::$scenario_run_times[ $scenario_key ] += microtime( true ); self::$scenario_count++; if ( count( self::$scenario_run_times ) > self::$num_top_scenarios ) { arsort( self::$scenario_run_times ); array_pop( self::$scenario_run_times ); } } }
Save the run time of the scenario into the `$scenario_run_times` array. Only the top `self::$num_top_scenarios` are kept.
log_run_times_after_scenario
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function get_scenario_key( $event ) { $scenario_key = ''; if ( $file = self::get_event_file( $event, $line ) ) { $scenario_grandparent = Utils\basename( dirname( dirname( $file ) ) ); $scenario_key = $scenario_grandparent . ' ' . Utils\basename( $file ) . ':' . $line; } return $scenario_key; }
Get the scenario key used for `$scenario_run_times` array. Format "<grandparent-dir> <feature-file>:<line-number>", eg "core-command core-update.feature:221".
get_scenario_key
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
private static function log_proc_method_run_time( $key, $start_time ) { $run_time = microtime( true ) - $start_time; if ( ! isset( self::$proc_method_run_times[ $key ] ) ) { self::$proc_method_run_times[ $key ] = array( 0, 0 ); } self::$proc_method_run_times[ $key ][0] += $run_time; self::$proc_method_run_times[ $key ][1]++; }
Log the run time of a proc method (one that doesn't use Process but does (use a function that does) a `proc_open()`).
log_proc_method_run_time
php
10up/MU-Migration
features/bootstrap/FeatureContext.php
https://github.com/10up/MU-Migration/blob/master/features/bootstrap/FeatureContext.php
MIT
function is_woocommerce_active() { return in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ); }
Checks if WooCommerce is active. @return bool
is_woocommerce_active
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function is_zip_file( $filename ) { $fh = fopen( $filename, 'r' ); if ( ! $fh ) { return false; } $blob = fgets( $fh, 5 ); fclose( $fh ); if ( strpos( $blob, 'PK' ) !== false ) { return true; } else { return false; } }
Checks if $filename is a zip file by checking it's first few bytes sequence. @param string $filename @return bool
is_zip_file
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function parse_url_for_search_replace( $url ) { $parsed_url = parse_url( esc_url( $url ) ); $path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : ''; return $parsed_url['host'] . $path; }
Parses a url for use in search-replace by removing its protocol. @param string $url @return string
parse_url_for_search_replace
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function move_folder( $source, $dest ) { if ( ! file_exists( $dest ) ) { mkdir( $dest ); } foreach ( $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $source, \RecursiveDirectoryIterator::SKIP_DOTS ), \RecursiveIteratorIterator::SELF_FIRST ) as $item ) { if ( $item->isDir() ) { $dir = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); if ( ! file_exists( $dir ) ) { mkdir( $dir ); } } else { $dest_file = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); if ( ! file_exists( $dest_file ) ) { rename( $item, $dest_file ); } } } }
Recursively copies a directory and its files. @param string $source @param string $dest
move_folder
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function get_db_prefix( $blog_id ) { global $wpdb; if ( $blog_id > 1 ) { $new_db_prefix = $wpdb->base_prefix . $blog_id . '_'; } else { $new_db_prefix = $wpdb->prefix; } return $new_db_prefix; }
Retrieves the db prefix based on the $blog_id. @uses wpdb @param int $blog_id @return string
get_db_prefix
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function light_add_user_to_blog( $blog_id, $user_id, $role ) { $user = get_userdata( $user_id ); if ( ! $user ) { restore_current_blog(); return new \WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) ); } if ( ! get_user_meta( $user_id, 'primary_blog', true ) ) { update_user_meta( $user_id, 'primary_blog', $blog_id ); $details = get_blog_details( $blog_id ); update_user_meta( $user_id, 'source_domain', $details->domain ); } $user->set_role( $role ); /** * Fires immediately after a user is added to a site. * * @since MU * * @param int $user_id User ID. * @param string $role User role. * @param int $blog_id Blog ID. */ do_action( 'add_user_to_blog', $user_id, $role, $blog_id ); wp_cache_delete( $user_id, 'users' ); wp_cache_delete( $blog_id . '_user_count', 'blog-details' ); }
Does the same thing that add_user_to_blog does, but without calling switch_to_blog(). @param int $blog_id @param int $user_id @param string $role @return \WP_Error
light_add_user_to_blog
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function stop_the_insanity() { global $wpdb, $wp_actions, $wp_filter, $wp_object_cache; //reset queries $wpdb->queries = array(); // Prevent wp_actions from growing out of control $wp_actions = array(); if ( is_object( $wp_object_cache ) ) { $wp_object_cache->group_ops = array(); $wp_object_cache->stats = array(); $wp_object_cache->memcache_debug = array(); $wp_object_cache->cache = array(); if ( method_exists( $wp_object_cache, '__remoteset' ) ) { $wp_object_cache->__remoteset(); } } /* * The WP_Query class hooks a reference to one of its own methods * onto filters if update_post_term_cache or * update_post_meta_cache are true, which prevents PHP's garbage * collector from cleaning up the WP_Query instance on long- * running processes. * * By manually removing these callbacks (often created by things * like get_posts()), we're able to properly unallocate memory * once occupied by a WP_Query object. * */ if ( isset( $wp_filter['get_term_metadata'] ) ) { /* * WordPress 4.7 has a new Hook infrastructure, so we need to make sure * we're accessing the global array properly. */ if ( class_exists( 'WP_Hook' ) && $wp_filter['get_term_metadata'] instanceof \WP_Hook ) { $filter_callbacks = &$wp_filter['get_term_metadata']->callbacks; } else { $filter_callbacks = &$wp_filter['get_term_metadata']; } if ( isset( $filter_callbacks[10] ) ) { foreach ( $filter_callbacks[10] as $hook => $content ) { if ( preg_match( '#^[0-9a-f]{32}lazyload_term_meta$#', $hook ) ) { unset( $filter_callbacks[10][ $hook ] ); } } } } }
Frees up memory for long running processes.
stop_the_insanity
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function addTransaction( $orig_filename ) { $context = stream_context_create(); $orig_file = fopen( $orig_filename, 'r', 1, $context ); $temp_filename = tempnam( sys_get_temp_dir(), 'php_prepend_' ); file_put_contents( $temp_filename, 'START TRANSACTION;' . PHP_EOL ); file_put_contents( $temp_filename, $orig_file, FILE_APPEND ); file_put_contents( $temp_filename, 'COMMIT;', FILE_APPEND ); fclose( $orig_file ); unlink( $orig_filename ); rename( $temp_filename, $orig_filename ); }
Add START TRANSACTION and COMMIT to the sql export. shamelessly stolen from http://stackoverflow.com/questions/1760525/need-to-write-at-beginning-of-file-with-php @param string $orig_filename SQL dump file name.
addTransaction
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function maybe_switch_to_blog( $blog_id ) { if ( is_multisite() ) { switch_to_blog( $blog_id ); } }
Switches to another blog if on Multisite @param $blog_id
maybe_switch_to_blog
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function maybe_restore_current_blog() { if ( is_multisite() ) { restore_current_blog(); } }
Restore the current blog if on multisite
maybe_restore_current_blog
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function extract( $filename, $dest_dir ) { $zippy = Zippy::load(); $site_package = $zippy->open( $filename ); mkdir( $dest_dir ); $site_package->extract( $dest_dir ); }
Extracts a zip file to the $dest_dir. @uses Zippy @param string $filename @param string $dest_dir
extract
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
function zip( $zip_file, $files_to_zip ) { return Zippy::load()->create( $zip_file, $files_to_zip, true ); }
Creates a zip files with the provided files/folder to zip @param string $zip_files The name of the zip file @param array $files_to_zip The files to include in the zip file @return void
zip
php
10up/MU-Migration
includes/helpers.php
https://github.com/10up/MU-Migration/blob/master/includes/helpers.php
MIT
public static function getCSVHeaders() { $headers = array( // General Info. 'ID', 'user_login', 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'role', 'user_status', 'display_name', // User Meta. 'rich_editing', 'admin_color', 'show_admin_bar_front', 'first_name', 'last_name', 'nickname', 'aim', 'yim', 'jabber', 'description', ); $custom_headers = apply_filters( 'mu_migration/export/user/headers', array() ); if ( ! empty( $custom_headers ) ) { $headers = array_merge( $headers, $custom_headers ); } return $headers; }
Returns the Headers (first row) for the CSV export file. @return array @internal
getCSVHeaders
php
10up/MU-Migration
includes/commands/class-mu-migration-export.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-export.php
MIT
private function move_uploads( $uploads_dir, $blog_id ) { if ( file_exists( $uploads_dir ) ) { \WP_CLI::log( __( 'Moving Uploads...', 'mu-migration' ) ); Helpers\maybe_switch_to_blog( $blog_id ); $dest_uploads_dir = wp_upload_dir(); Helpers\maybe_restore_current_blog(); Helpers\move_folder( $uploads_dir, $dest_uploads_dir['basedir'] ); } }
Moves the uploads folder to the right location. @param string $uploads_dir @param int $blog_id
move_uploads
php
10up/MU-Migration
includes/commands/class-mu-migration-import.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-import.php
MIT
private function move_themes( $themes_dir ) { if ( file_exists( $themes_dir ) ) { WP_CLI::log( __( 'Moving Themes...', 'mu-migration' ) ); $themes = new \DirectoryIterator( $themes_dir ); $installed_themes = get_theme_root(); foreach ( $themes as $theme ) { if ( $theme->isDir() ) { $fullPluginPath = $themes_dir . '/' . $theme->getFilename(); if ( ! file_exists( $installed_themes . '/' . $theme->getFilename() ) ) { WP_CLI::log( sprintf( __( 'Moving %s to themes folder' ), $theme->getFilename() ) ); rename( $fullPluginPath, $installed_themes . '/' . $theme->getFilename() ); Helpers\runcommand( 'theme enable', [ $theme->getFilename() ] ); } } } } }
Moves the themes to the right location. @param string $themes_dir
move_themes
php
10up/MU-Migration
includes/commands/class-mu-migration-import.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-import.php
MIT
private function create_new_site( $meta_data ) { $parsed_url = parse_url( esc_url( $meta_data->url ) ); $site_id = get_main_network_id(); $parsed_url['path'] = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '/'; if ( domain_exists( $parsed_url['host'], $parsed_url['path'], $site_id ) ) { return false; } $blog_id = insert_blog( $parsed_url['host'], $parsed_url['path'], $site_id ); if ( ! $blog_id ) { return false; } return $blog_id; }
Creates a new site within multisite. @param object $meta_data @return bool|false|int
create_new_site
php
10up/MU-Migration
includes/commands/class-mu-migration-import.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-import.php
MIT
private function check_for_sed_presence( $exit_on_error = false ) { $sed = \WP_CLI::launch( 'echo "wp_" | sed "s/wp_/wp_5_/g"', false, true ); if ( 'wp_5_' !== trim( $sed->stdout, "\x0A" ) ) { if ( $exit_on_error ) { \WP_CLI::error( __( 'sed not present, please install sed', 'mu-migration' ) ); } return false; } return true; }
Checks whether sed is available or not. @param bool $exit_on_error If set to true the script will be terminated if sed is not available. @return bool
check_for_sed_presence
php
10up/MU-Migration
includes/commands/class-mu-migration-import.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-import.php
MIT
private function send_reset_link( $user_data ) { $user_login = $user_data->user_login; $user_email = $user_data->user_email; $key = get_password_reset_key( $user_data ); if ( is_wp_error( $key ) ) { return $key; } $message = __( 'A password reset has been requested for the following account:' ) . "\r\n\r\n"; $message .= network_home_url( '/' ) . "\r\n\r\n"; $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n"; $message .= __( 'In order to log in again you have to reset your password.' ) . "\r\n\r\n"; $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n"; $message .= '<' . network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ), 'login' ) . ">\r\n"; if ( is_multisite() ) { $blogname = $GLOBALS['current_site']->site_name; } else { /* * The blogname option is escaped with esc_html on the way into the database * in sanitize_option we want to reverse this for the plain text arena of emails. */ $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); } $title = sprintf( __( '[%s] Password Reset' ), $blogname ); /** * Filters the subject of the password reset email. * * @since 2.8.0 * @since 4.4.0 Added the `$user_login` and `$user_data` parameters. * * @param string $title Default email title. * @param string $user_login The username for the user. * @param \WP_User $user_data WP_User object. */ $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data ); /** * Filters the message body of the password reset mail. * * @since 2.8.0 * @since 4.1.0 Added `$user_login` and `$user_data` parameters. * * @param string $message Default mail message. * @param string $key The activation key. * @param string $user_login The username for the user. * @param \WP_User $user_data WP_User object. */ $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data ); if ( $message && ! wp_mail( $user_email, wp_specialchars_decode( $title ), $message ) ) { WP_CLI::log( __( 'The email could not be sent', 'mu-migration' ) ); } return true; }
Handles sending password retrieval email to user (based on retrieve_password). @param $user_data @return bool|\WP_Error
send_reset_link
php
10up/MU-Migration
includes/commands/class-mu-migration-users.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-users.php
MIT
protected function all_posts( $query_args, $callback, $verbose = true ) { if ( ! is_callable( $callback ) ) { self::error( __( "The provided callback is invalid", 'mu-migration' ) ); } $default_args = array( 'post_type' => 'post', 'posts_per_page' => 1000, 'post_status' => array( 'publish', 'pending', 'draft', 'future', 'private' ), 'cache_results ' => false, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'offset' => 0, ); /** * Filters the default args for querying posts in the all_posts method. * * @since 0.2.0 * * @param array $default_args */ $default_args = apply_filters( 'mu-migration/all_posts/default_args', $default_args ); $query_args = wp_parse_args( $query_args, $default_args ); $query = new \WP_Query( $query_args ); $counter = 0; $found_posts = 0; while ( $query->have_posts() ) { $query->the_post(); $callback(); if ( 0 === $counter ) { $found_posts = $query->found_posts; } $counter++; if ( 0 === $counter % $query_args['posts_per_page'] ) { Helpers\stop_the_insanity(); $this->log( sprintf( __( 'Posts Updated: %d/%d', 'mu-migration' ), $counter, $found_posts ), true ); $query_args['offset'] += $query_args['posts_per_page']; $query = new \WP_Query( $query_args ); } } wp_reset_postdata(); $this->success( sprintf( __( '%d posts were updated', 'mu-migration' ), $counter ), $verbose ); }
Runs through all posts and executes the provided callback for each post. @param array $query_args @param callable $callback @param bool $verbose
all_posts
php
10up/MU-Migration
includes/commands/class-mu-migration-base.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration-base.php
MIT
public function __invoke( $args, $assoc_args ) { \cli\line( 'MU-Migration version: %Yv' . TENUP_MU_MIGRATION_VERSION . '%n' ); \cli\line(); \cli\line( 'Created by Nícholas André at 10up' ); \cli\line( 'Github: https://github.com/10up/MU-Migration' ); \cli\line(); }
Displays General Info about MU-Migration and WordPress @param array $args @param array $assoc_args
__invoke
php
10up/MU-Migration
includes/commands/class-mu-migration.php
https://github.com/10up/MU-Migration/blob/master/includes/commands/class-mu-migration.php
MIT
public function read($sql) { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql); if ( ! is_file($filepath) OR FALSE === ($cachedata = file_get_contents($filepath))) { return FALSE; } return unserialize($cachedata); }
Retrieve a cached query The URI being requested will become the name of the cache sub-folder. An MD5 hash of the SQL statement will become the cache file name. @param string $sql @return string
read
php
ronknight/InventorySystem
system/database/DB_cache.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_cache.php
MIT
public function delete($segment_one = '', $segment_two = '') { if ($segment_one === '') { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); } if ($segment_two === '') { $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); } $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; delete_files($dir_path, TRUE); }
Delete cache files within a particular directory @param string $segment_one @param string $segment_two @return void
delete
php
ronknight/InventorySystem
system/database/DB_cache.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_cache.php
MIT
public function delete_all() { delete_files($this->db->cachedir, TRUE, TRUE); }
Delete all existing cache files @return void
delete_all
php
ronknight/InventorySystem
system/database/DB_cache.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_cache.php
MIT
public function db_connect() { return TRUE; }
DB connect This is just a dummy method that all drivers will override. @return mixed
db_connect
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function db_pconnect() { return $this->db_connect(TRUE); }
Persistent database connection @return mixed
db_pconnect
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function reconnect() { }
Reconnect Keep / reestablish the db connection if no queries have been sent for a length of time exceeding the server's idle timeout. This is just a dummy method to allow drivers without such functionality to not declare it, while others will override it. @return void
reconnect
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function db_select() { return TRUE; }
Select database This is just a dummy method to allow drivers without such functionality to not declare it, while others will override it. @return bool
db_select
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function platform() { return $this->dbdriver; }
The name of the platform in use (mysql, mssql, etc...) @return string
platform
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if (FALSE === ($sql = $this->_version())) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $query = $this->query($sql)->row(); return $this->data_cache['version'] = $query->ver; }
Database version number Returns a string containing the version of the database being used. Most drivers will override this method. @return string
version
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function simple_query($sql) { if ( ! $this->conn_id) { if ( ! $this->initialize()) { return FALSE; } } return $this->_execute($sql); }
Simple Query This is a simplified version of the query() function. Internally we only use it when running transaction commands since they do not require all the features of the main query() function. @param string the sql query @return mixed
simple_query
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function trans_off() { $this->trans_enabled = FALSE; }
Disable Transactions This permits transactions to be disabled at run-time. @return void
trans_off
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function trans_strict($mode = TRUE) { $this->trans_strict = is_bool($mode) ? $mode : TRUE; }
Enable/disable Transaction Strict Mode When strict mode is enabled, if you are running multiple groups of transactions, if one group fails all subsequent groups will be rolled back. If strict mode is disabled, each group is treated autonomously, meaning a failure of one group will not affect any others @param bool $mode = TRUE @return void
trans_strict
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function trans_status() { return $this->_trans_status; }
Lets you retrieve the transaction flag to determine if it has failed @return bool
trans_status
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function is_write_type($sql) { return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX|MERGE)\s/i', $sql); }
Determines if a query is a "write" type. @param string An SQL query string @return bool
is_write_type
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function elapsed_time($decimals = 6) { return number_format($this->benchmark, $decimals); }
Calculate the aggregate query elapsed time @param int The number of decimal places @return string
elapsed_time
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function total_queries() { return $this->query_count; }
Returns the total number of queries @return int
total_queries
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function last_query() { return end($this->queries); }
Returns the last query that was executed @return string
last_query
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function escape_like_str($str) { return $this->escape_str($str, TRUE); }
Escape LIKE String Calls the individual driver for platform specific escaping for LIKE conditions @param string|string[] @return mixed
escape_like_str
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _escape_str($str) { return str_replace("'", "''", remove_invisible_characters($str, FALSE)); }
Platform-dependent string escape @param string @return string
_escape_str
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function primary($table) { $fields = $this->list_fields($table); return is_array($fields) ? current($fields) : FALSE; }
Primary Retrieves the primary key. It assumes that the row in the first position is the primary key @param string $table Table name @return string
primary
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function count_all($table = '') { if ($table === '') { return 0; } $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() === 0) { return 0; } $query = $query->row(); $this->_reset_select(); return (int) $query->numrows; }
"Count All" query Generates a platform-specific query string that counts all records in the specified database @param string @return int
count_all
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function list_tables($constrain_by_prefix = FALSE) { // Is there a cached result? if (isset($this->data_cache['table_names'])) { return $this->data_cache['table_names']; } if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix))) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $this->data_cache['table_names'] = array(); $query = $this->query($sql); foreach ($query->result_array() as $row) { // Do we know from which column to get the table name? if ( ! isset($key)) { if (isset($row['table_name'])) { $key = 'table_name'; } elseif (isset($row['TABLE_NAME'])) { $key = 'TABLE_NAME'; } else { /* We have no other choice but to just get the first element's key. * Due to array_shift() accepting its argument by reference, if * E_STRICT is on, this would trigger a warning. So we'll have to * assign it first. */ $key = array_keys($row); $key = array_shift($key); } } $this->data_cache['table_names'][] = $row[$key]; } return $this->data_cache['table_names']; }
Returns an array of table names @param string $constrain_by_prefix = FALSE @return array
list_tables
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function table_exists($table_name) { return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables()); }
Determine if a particular table exists @param string $table_name @return bool
table_exists
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function field_exists($field_name, $table_name) { return in_array($field_name, $this->list_fields($table_name)); }
Determine if a particular field exists @param string @param string @return bool
field_exists
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function field_data($table) { $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE))); return ($query) ? $query->field_data() : FALSE; }
Returns an object with field data @param string $table the table name @return array
field_data
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function escape_identifiers($item) { if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers)) { return $item; } elseif (is_array($item)) { foreach ($item as $key => $value) { $item[$key] = $this->escape_identifiers($value); } return $item; } // Avoid breaking functions and literal values inside queries elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE) { return $item; } static $preg_ec = array(); if (empty($preg_ec)) { if (is_array($this->_escape_char)) { $preg_ec = array( preg_quote($this->_escape_char[0], '/'), preg_quote($this->_escape_char[1], '/'), $this->_escape_char[0], $this->_escape_char[1] ); } else { $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/'); $preg_ec[2] = $preg_ec[3] = $this->_escape_char; } } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item); } } return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item); }
Escape the SQL Identifiers This function escapes column and table names @param mixed @return mixed
escape_identifiers
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _insert($table, $keys, $values) { return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; }
Insert statement Generates a platform-specific insert string from the supplied data @param string the table name @param array the insert keys @param array the insert values @return string
_insert
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _has_operator($str) { return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str)); }
Tests whether the string has an SQL operator @param string @return bool
_has_operator
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _get_operator($str) { static $_operators; if (empty($_operators)) { $_les = ($this->_like_escape_str !== '') ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/') : ''; $_operators = array( '\s*(?:<|>|!)?=\s*', // =, <=, >=, != '\s*<>?\s*', // <, <> '\s*>\s*', // > '\s+IS NULL', // IS NULL '\s+IS NOT NULL', // IS NOT NULL '\s+EXISTS\s*\(.*\)', // EXISTS(sql) '\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql) '\s+BETWEEN\s+', // BETWEEN value AND value '\s+IN\s*\(.*\)', // IN(list) '\s+NOT IN\s*\(.*\)', // NOT IN (list) '\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s'] '\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s'] ); } return preg_match('/'.implode('|', $_operators).'/i', $str, $match) ? $match[0] : FALSE; }
Returns the SQL string operator @param string @return string
_get_operator
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function call_function($function) { $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_'; if (FALSE === strpos($driver, $function)) { $function = $driver.$function; } if ( ! function_exists($function)) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } return (func_num_args() > 1) ? call_user_func_array($function, array_slice(func_get_args(), 1)) : call_user_func($function); }
Enables a native PHP function to be run, using a platform agnostic wrapper. @param string $function Function name @return mixed
call_function
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function cache_delete($segment_one = '', $segment_two = '') { return $this->_cache_init() ? $this->CACHE->delete($segment_one, $segment_two) : FALSE; }
Delete the cache files associated with a particular URI @param string $segment_one = '' @param string $segment_two = '' @return bool
cache_delete
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _close() { $this->conn_id = FALSE; }
Close DB Connection This method would be overridden by most of the drivers. @return void
_close
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
protected function _reset_select() { }
Dummy method that allows Query Builder class to be disabled and keep count_all() working. @return void
_reset_select
php
ronknight/InventorySystem
system/database/DB_driver.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_driver.php
MIT
public function database_exists($database_name) { return in_array($database_name, $this->list_databases()); }
Determine if a particular database exists @param string $database_name @return bool
database_exists
php
ronknight/InventorySystem
system/database/DB_utility.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_utility.php
MIT
public function result_object() { if (count($this->result_object) > 0) { return $this->result_object; } // In the event that query caching is on, the result_id variable // will not be a valid resource so we'll simply return an empty // array. if ( ! $this->result_id OR $this->num_rows === 0) { return array(); } if (($c = count($this->result_array)) > 0) { for ($i = 0; $i < $c; $i++) { $this->result_object[$i] = (object) $this->result_array[$i]; } return $this->result_object; } is_null($this->row_data) OR $this->data_seek(0); while ($row = $this->_fetch_object()) { $this->result_object[] = $row; } return $this->result_object; }
Query result. "object" version. @return array
result_object
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function result_array() { if (count($this->result_array) > 0) { return $this->result_array; } // In the event that query caching is on, the result_id variable // will not be a valid resource so we'll simply return an empty // array. if ( ! $this->result_id OR $this->num_rows === 0) { return array(); } if (($c = count($this->result_object)) > 0) { for ($i = 0; $i < $c; $i++) { $this->result_array[$i] = (array) $this->result_object[$i]; } return $this->result_array; } is_null($this->row_data) OR $this->data_seek(0); while ($row = $this->_fetch_assoc()) { $this->result_array[] = $row; } return $this->result_array; }
Query result. "array" version. @return array
result_array
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function set_row($key, $value = NULL) { // We cache the row data for subsequent uses if ( ! is_array($this->row_data)) { $this->row_data = $this->row_array(0); } if (is_array($key)) { foreach ($key as $k => $v) { $this->row_data[$k] = $v; } return; } if ($key !== '' && $value !== NULL) { $this->row_data[$key] = $value; } }
Assigns an item into a particular column slot @param mixed $key @param mixed $value @return void
set_row
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function custom_row_object($n, $type) { isset($this->custom_result_object[$type]) OR $this->custom_result_object($type); if (count($this->custom_result_object[$type]) === 0) { return NULL; } if ($n !== $this->current_row && isset($this->custom_result_object[$type][$n])) { $this->current_row = $n; } return $this->custom_result_object[$type][$this->current_row]; }
Returns a single result row - custom object version @param int $n @param string $type @return object
custom_row_object
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function row_object($n = 0) { $result = $this->result_object(); if (count($result) === 0) { return NULL; } if ($n !== $this->current_row && isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; }
Returns a single result row - object version @param int $n @return object
row_object
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function row_array($n = 0) { $result = $this->result_array(); if (count($result) === 0) { return NULL; } if ($n !== $this->current_row && isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; }
Returns a single result row - array version @param int $n @return array
row_array
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function num_fields() { return 0; }
Number of fields in the result set Overridden by driver result classes. @return int
num_fields
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT
public function list_fields() { return array(); }
Fetch Field Names Generates an array of column names. Overridden by driver result classes. @return array
list_fields
php
ronknight/InventorySystem
system/database/DB_result.php
https://github.com/ronknight/InventorySystem/blob/master/system/database/DB_result.php
MIT