code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function exists(BucketInterface $bucket, string $name): bool { return $this->files->exists($this->getPath($bucket, $name)); }
{@inheritdoc}
public function size(BucketInterface $bucket, string $name): ?int { if (!$this->files->exists($this->getPath($bucket, $name))) { return null; } return $this->files->size($this->getPath($bucket, $name)); }
{@inheritdoc}
public function put(BucketInterface $bucket, string $name, StreamInterface $stream): bool { $path = $this->getPath($bucket, $name); $mode = $bucket->getOption('mode', FilesInterface::RUNTIME); //Pre-ensuring location $this->files->ensureDirectory(dirname($path), $mode); $resource = StreamWrapper::getResource($stream); try { $target = fopen($path, 'w'); if (stream_copy_to_stream($resource, $target) === false) { throw new ServerException("Unable to put to '{$path}'"); } } finally { StreamWrapper::release($resource); fclose($resource); } return $this->files->setPermissions($path, $mode); }
{@inheritdoc}
public function getStream(BucketInterface $bucket, string $name): StreamInterface { if (!$this->exists($bucket, $name)) { throw new ServerException( "Unable to create stream for '{$name}', object does not exists" ); } //Getting readonly stream return stream_for(fopen($this->getPath($bucket, $name), 'rb')); }
{@inheritdoc}
public function delete(BucketInterface $bucket, string $name) { if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to delete object, file not found"); } $this->files->delete($this->getPath($bucket, $name)); }
{@inheritdoc}
public function rename(BucketInterface $bucket, string $oldName, string $newName): bool { return $this->internalMove( $bucket, $this->getPath($bucket, $oldName), $this->getPath($bucket, $newName) ); }
{@inheritdoc}
public function copy(BucketInterface $bucket, BucketInterface $destination, string $name): bool { return $this->internalCopy( $destination, $this->getPath($bucket, $name), $this->getPath($destination, $name) ); }
{@inheritdoc}
public function replace( BucketInterface $bucket, BucketInterface $destination, string $name ): bool { return $this->internalMove( $destination, $this->getPath($bucket, $name), $this->getPath($destination, $name) ); }
{@inheritdoc}
protected function internalMove( BucketInterface $bucket, string $filename, string $destination ): bool { if (!$this->files->exists($filename)) { throw new ServerException("Unable to move '{$filename}', object does not exists"); } $mode = $bucket->getOption('mode', FilesInterface::RUNTIME); //Pre-ensuring location $this->files->ensureDirectory(dirname($destination), $mode); if (!$this->files->move($filename, $destination)) { throw new ServerException("Unable to move '{$filename}' to '{$destination}'."); } return $this->files->setPermissions($destination, $mode); }
Move helper, ensure target directory existence, file permissions and etc. @param BucketInterface $bucket @param string $filename @param string $destination @return bool @throws ServerException
protected function getPath(BucketInterface $bucket, string $name): string { if (empty($this->options['home'])) { return $this->files->normalizePath($bucket->getOption('directory') . $name); } return $this->files->normalizePath( $this->options['home'] . '/' . $bucket->getOption('directory') . $name ); }
Get full file location on server including homedir. @param BucketInterface $bucket @param string $name @return string
public function getBucket(string $name): array { if (!$this->hasBucket($name)) { throw new ConfigException("Undefined bucket `{$name}`"); } $bucket = $this->config['buckets'][$name]; if (!array_key_exists('options', $bucket)) { throw new ConfigException("Bucket `{$name}` must specify `options`"); } if (!array_key_exists('prefix', $bucket)) { throw new ConfigException("Bucket `{$name}` must specify `prefix`"); } if (!array_key_exists('server', $bucket)) { throw new ConfigException("Bucket `{$name}` must specify `server` name."); } return $bucket; }
Get bucket options. @param string $name @return array @throws ConfigException
public function resolveBucket(string $address, string &$name = null): string { $bucket = null; $length = 0; foreach ($this->prefixes as $id => $prefix) { if (strpos($address, $prefix) === 0 && strlen($prefix) > $length) { $bucket = $id; $length = strlen($prefix); } } if (empty($bucket)) { throw new ResolveException("Unable to resolve bucket of `{$address}`."); } $name = substr($address, $length); return $bucket; }
Locate bucket name using object address. @param string $address @param string $name @return string @throws ResolveException
public function withOption(string $name, $value): BucketInterface { $bucket = clone $this; $bucket->options[$name] = $value; return $bucket; }
{@inheritdoc}
public function size(string $name): ?int { $this->getLogger()->info(sprintf( "get size of '%s' in '%s' bucket.", $this->getAddress($name), $this->getName() )); $benchmark = $this->benchmark( $this->getName(), "size::{$this->getAddress($name)}" ); try { return $this->server->size($this, $name); } catch (ServerException $e) { throw new BucketException($e->getMessage(), $e->getCode(), $e); } finally { $benchmark->complete(); } }
{@inheritdoc}
public function put(string $name, $source): string { $this->getLogger()->info(sprintf( "put '%s' in '%s' bucket.", $this->getAddress($name), $this->getName() )); $casted = !($source instanceof StreamInterface); $stream = $this->castStream($source); $benchmark = $this->benchmark( $this->getName(), "put::{$this->getAddress($name)}" ); try { $this->server->put($this, $name, $stream); if ($casted) { $stream->detach(); } //Reopening return $this->getAddress($name); } catch (ServerException $e) { throw new BucketException($e->getMessage(), $e->getCode(), $e); } finally { $benchmark->complete(); } }
{@inheritdoc}
public function getStream(string $name): StreamInterface { $this->getLogger()->info(sprintf( "get stream for '%s' in '%s' bucket.", $this->getAddress($name), $this->getName() )); $benchmark = $this->benchmark( $this->getName(), "stream::{$this->getAddress($name)}" ); try { return $this->getServer()->getStream($this, $name); } catch (ServerException $e) { throw new BucketException($e->getMessage(), $e->getCode(), $e); } finally { $benchmark->complete(); } }
{@inheritdoc}
public function rename(string $oldName, string $newName): string { if ($oldName == $newName) { return $oldName; } $this->getLogger()->info(sprintf( "rename '%s' to '%s' in '%s' bucket.", $this->getAddress($oldName), $this->getAddress($newName), $this->getName() )); $benchmark = $this->benchmark( $this->getName(), "rename::{$this->getAddress($oldName)}" ); try { $this->server->rename($this, $oldName, $newName); return $this->getAddress($newName); } catch (ServerException $e) { throw new BucketException($e->getMessage(), $e->getCode(), $e); } finally { $benchmark->complete(); } }
{@inheritdoc}
public function copy(BucketInterface $destination, string $name): string { if ($destination === $this) { return $this->getAddress($name); } //Internal copying if ($this->getServer() === $destination->getServer()) { $this->getLogger()->info(sprintf( "internal copy of '%s' to '%s' from '%s' bucket.", $this->getAddress($name), $destination->getAddress($name), $this->getName() )); $benchmark = $this->benchmark( $this->getName(), "copy::{$this->getAddress($name)}" ); try { $this->getServer()->copy($this, $destination, $name); } catch (ServerException $e) { throw new BucketException($e->getMessage(), $e->getCode(), $e); } finally { $benchmark->complete(); } } else { $this->getLogger()->info(sprintf( "external copy of '%s'.'%s' to '%s'.'%s'.", $this->getName(), $this->getAddress($name), $destination->getName(), $destination->getAddress($name) )); $destination->put($name, $stream = $this->getStream($name)); $stream->detach(); } return $destination->getAddress($name); }
{@inheritdoc}
protected function castStream($source): StreamInterface { if ($source instanceof UploadedFileInterface || $source instanceof StreamableInterface) { $source = $source->getStream(); } if ($source instanceof StreamInterface) { //This step is important to prevent user errors $source->rewind(); return $source; } if (is_resource($source)) { return stream_for($source); } if (empty($source)) { //Guzzle? return stream_for(''); } if ($this->isFilename($source)) { //Must never pass user string in here, use Stream return stream_for(fopen($source, 'rb')); } //We do not allow source names in a string form throw new BucketException( "Source must be a valid resource, stream or filename, invalid value given" ); }
Cast stream associated with origin data. @param string|StreamInterface|resource $source @return StreamInterface
protected function isFilename($source): bool { if (!is_string($source)) { return false; } if (!preg_match('/[^A-Za-z0-9.#\\-$]/', $source)) { return false; } //To filter out binary strings $source = strval(str_replace("\0", "", $source)); return file_exists($source); }
Check if given string is proper filename. @param mixed $source @return bool
public static function on($command,callable $callback,$description=''){ $parts = preg_split('/\s+/',$command); static::$commands[array_shift($parts)] = [$parts,$callback,$description]; }
Bind a callback to a command route @param string $command The command route, use ":" before a parameter for extraction. @param callable $callback The callback to be binded to the route.
public static function help(callable $callback = null){ $callback ? is_callable($callback) && static::$help = $callback : static::$help && call_user_func(static::$help); }
Bind a callback to the "help" route. @param callable $callback The callback to be binded to the route. If omitted triggers the callback.
public static function error(callable $callback = null){ $callback ? is_callable($callback) && static::$error = $callback : static::$error && call_user_func(static::$error); }
Bind a callback when an error occurs. @param callable $callback The callback to be binded to the route. If omitted triggers the callback.
public static function input($key=null,$default=null){ return $key ? (isset(static::$options[$key]) ? static::$options[$key] : (is_callable($default)?call_user_func($default):$default)) : static::$options; }
Get a passed option @param string $key The name of the option paramenter @param mixed $default The default value if parameter is omitted. (if a callable it will be evaluated) @return mixed
public static function commands(){ $results = []; foreach(static::$commands as $name => $cmd){ $results[] = [ 'name' => $name, 'params' => preg_replace('/:(\w+)/','[$1]',implode(' ',$cmd[0])), 'description' => $cmd[2], ]; } return $results; }
Returns an explanation for the supported commands @method commands @return array The commands and their description.
public static function run($args=null){ if (PHP_SAPI != 'cli') return false; if($args) { $_args = $args; static::$file = basename(isset($_SERVER['PHP_SELF'])?$_SERVER['PHP_SELF']:__FILE__); } else { $_args = $_SERVER['argv']; static::$file = basename(array_shift($_args)); } foreach($_args as $e) if(strpos($e,'-')===0) { $h = explode('=',$e); static::$options[ltrim(current($h),'-')] = isset($h[1])?$h[1]:true; } else { static::$arguments[] = $e; } if(isset(static::$arguments[0])){ $command = array_shift(static::$arguments); if (empty(static::$commands[$command])) return static::triggerError("Unknown command [".$command."]."); $cmd = static::$commands[$command]; $pars_vector = []; foreach ($cmd[0] as $_idx => $segment) { if ($segment[0]==':'){ // Extract paramenter if (isset(static::$arguments[$_idx])){ $pars_vector[] = static::$arguments[$_idx]; } else return static::triggerError("Command [".$command."] needs more parameters"); } else { // Match command if (empty(static::$arguments[$_idx]) || $segment!=static::$arguments[$_idx]) return static::triggerError("Command [".$command."] is incomplete."); } } $returns = call_user_func_array($cmd[1], $pars_vector); echo is_scalar($returns) ? "$returns" : json_encode($returns, JSON_PRETTY_PRINT); return true; } else { static::help(); return false; } }
Dispatch the router @param string[] $args The arguments array. @return boolean True if route was correctly dispatched.
public static function write($message){ if( preg_match('~<[^>]+>~',$message)) { // Use preg_replace_callback for fast regex matches navigation echo strtr(preg_replace_callback('~^(.*)<([^>]+)>(.+)</\2>(.*)$~USm',function($m){ static::write($m[1]); $color = strtoupper(trim($m[2])); if( isset(static::$shell_colors[$color]) ) echo static::$shell_colors[$color]; static::$color_stack[] = $color; static::write($m[3]); array_pop(static::$color_stack); $back_color = array_pop(static::$color_stack) ?: static::$color_stack[]='NORMAL'; if( isset(static::$shell_colors[$back_color]) ) echo static::$shell_colors[$back_color]; static::write($m[4]); },strtr($message,["\n"=>"&BR;"])),["&BR;"=>PHP_EOL]); } else { echo strtr($message,["&BR;"=>PHP_EOL]); } }
Prints a message to the console with color formatting. @param string $message The html-like encoded message @return void
public static function edit($text,$filename=''){ $EDITOR = getenv('EDITOR')?:'nano'; $tmp = tempnam(sys_get_temp_dir(), "E-").strtr($filename,'/','_'); file_put_contents($tmp, $text); passthru("$EDITOR $tmp"); $result = file_get_contents($tmp); unlink($tmp); return $result; }
Edit a temporary block of text with $EDITOR (or nano as fallback) @param string $text The initial text of the document. @param string $filename The (fake) filename passed to the editor (for syntax highlighting hint). @return string The edited contents
public function match($URL, $method='get'){ $method = strtolower($method); // * is an http method wildcard if (empty($this->methods[$method]) && empty($this->methods['*'])) return false; return (bool) ( $this->dynamic ? preg_match($this->matcher_pattern, '/'.trim($URL,'/')) : rtrim($URL,'/') == rtrim($this->pattern,'/') ); }
Check if route match on a specified URL and HTTP Method. @param [type] $URL The URL to check against. @param string $method The HTTP Method to check against. @return boolean
public function runIfMatch($URL, $method='get'){ return $this->match($URL,$method) ? $this->run($this->extractArgs($URL),$method) : null; }
Check if route match URL and HTTP Method and run if it is valid. @param [type] $URL The URL to check against. @param string $method The HTTP Method to check against. @return array The callback response.
public function & via(...$methods){ $this->methods = []; foreach ($methods as $method){ $this->methods[strtolower($method)] = true; } return $this; }
Defines the HTTP Methods to bind the route onto. Example: <code> Route::on('/test')->via('get','post','delete'); </code> @return Route
public function & rules(array $rules){ foreach ((array)$rules as $varname => $rule){ $this->rules[$varname] = $rule; } $this->pattern = $this->compilePatternAsRegex( $this->URLPattern, $this->rules ); $this->matcher_pattern = $this->compilePatternAsRegex( $this->URLPattern, $this->rules, false ); return $this; }
Defines the regex rules for the named parameter in the current URL pattern Example: <code> Route::on('/proxy/:number/:url') ->rules([ 'number' => '\d+', 'url' => '.+', ]); </code> @param array $rules The regex rules @return Route
public static function & map($URLPattern, $callbacks = []){ $route = new static($URLPattern); $route->callback = []; foreach ($callbacks as $method => $callback) { $method = strtolower($method); if (Request::method() !== $method) continue; $route->callback[$method] = $callback; $route->methods[$method] = 1; } return $route; }
Map a HTTP Method => callable array to a route. Example: <code> Route::map('/test'[ 'get' => function(){ echo "HTTP GET"; }, 'post' => function(){ echo "HTTP POST"; }, 'put' => function(){ echo "HTTP PUT"; }, 'delete' => function(){ echo "HTTP DELETE"; }, ]); </code> @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. @param array $callbacks The HTTP Method => callable map. @return Route
public function getURL($params = []){ $params = (array)$params; return new URL(rtrim(preg_replace('(/+)','/',preg_replace_callback('(:(\w+))',function($m) use ($params){ return isset($params[$m[1]]) ? $params[$m[1]].'/' : ''; },strtr($this->URLPattern,['('=>'',')'=>'']))),'/')?:'/'); }
Reverse routing : obtain a complete URL for a named route with passed parameters @param array $params The parameter map of the route dynamic values. @return URL
public static function URL($name, $params = []){ return ($r = static::tagged($name)) ? $r-> getURL($params) : new URL(); }
Helper for reverse routing : obtain a complete URL for a named route with passed parameters @param string $name The name tag of the route. @param array $params The parameter map of the route dynamic values. @return string
protected static function compilePatternAsRegex($pattern, $rules=[], $extract_params=true){ return '#^'.preg_replace_callback('#:([a-zA-Z]\w*)#',$extract_params // Extract named parameters ? function($g) use (&$rules){ return '(?<' . $g[1] . '>' . (isset($rules[$g[1]])?$rules[$g[1]]:'[^/]+') .')'; } // Optimized for matching : function($g) use (&$rules){ return isset($rules[$g[1]]) ? $rules[$g[1]] : '[^/]+'; }, str_replace(['.',')','*'],['\.',')?','.+'],$pattern)).'$#'; }
Compile an URL schema to a PREG regular expression. @param string $pattern The URL schema. @return string The compiled PREG RegEx.
protected static function extractVariablesFromURL($pattern, $URL=null, $cut=false){ $URL = $URL ?: Request::URI(); $pattern = $cut ? str_replace('$#','',$pattern).'#' : $pattern; $args = []; if ( !preg_match($pattern,'/'.trim($URL,'/'),$args) ) return false; foreach ($args as $key => $value) { if (false === is_string($key)) unset($args[$key]); } return $args; }
Extract the URL schema variables from the passed URL. @param string $pattern The URL schema with the named parameters @param string $URL The URL to process, if omitted the current request URI will be used. @param boolean $cut If true don't limit the matching to the whole URL (used for group pattern extraction) @return array The extracted variables
public static function add($route){ if (is_a($route, 'Route')){ // Add to tag map if ($route->tag) static::$tags[$route->tag] =& $route; // Optimize tree if (Options::get('core.route.auto_optimize', true)){ $base =& static::$optimized_tree; foreach (explode('/',trim(preg_replace('#^(.+?)\(?:.+$#','$1',$route->URLPattern),'/')) as $segment) { $segment = trim($segment,'('); if (!isset($base[$segment])) $base[$segment] = []; $base =& $base[$segment]; } $base[] =& $route; } } // Add route to active group if ( isset(static::$group[0]) ) static::$group[0]->add($route); return static::$routes[implode('', static::$prefix)][] = $route; }
Add a route to the internal route repository. @param Route $route @return Route
public static function group($prefix, $callback){ // Skip definition if current request doesn't match group. $pre_prefix = rtrim(implode('',static::$prefix),'/'); $URI = Request::URI(); $args = []; $group = false; switch (true) { // Dynamic group case static::isDynamic($prefix) : $args = static::extractVariablesFromURL($prx=static::compilePatternAsRegex("$pre_prefix$prefix"), null, true); if ( $args !== false ) { // Burn-in $prefix as static string $partial = preg_match_all(str_replace('$#', '#', $prx), $URI, $partial) ? $partial[0][0] : ''; $prefix = $partial ? preg_replace('#^'.implode('',static::$prefix).'#', '', $partial) : $prefix; } // Static group case ( 0 === strpos("$URI/", "$pre_prefix$prefix/") ) || ( ! Options::get('core.route.pruning', true) ) : static::$prefix[] = $prefix; if (empty(static::$group)) static::$group = []; array_unshift(static::$group, $group = new RouteGroup()); // Call the group body function call_user_func_array($callback, $args ?: []); array_shift(static::$group); array_pop(static::$prefix); if (empty(static::$prefix)) static::$prefix = ['']; break; } return $group ?: new RouteGroup(); }
Define a route group, if not immediately matched internal code will not be invoked. @param string $prefix The url prefix for the internal route definitions. @param string $callback This callback is invoked on $prefix match of the current request URI.
public static function loadPHP($filepath,$prefix_path=null){ ob_start(); $results = include($filepath); ob_end_clean(); if($results) { $results = static::filterWith(["load.php", "load"], $results); static::loadArray($results,$prefix_path); } }
Load a PHP configuration file (script must return array) @param string $filepath The path of the PHP config file @param string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
public static function loadINI($filepath,$prefix_path=null){ $results = parse_ini_file($filepath,true); if($results) { $results = static::filterWith(["load.ini", "load"], $results); static::loadArray($results,$prefix_path); } }
Load an INI configuration file @param string $filepath The path of the INI config file @param string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
public static function loadJSON($filepath,$prefix_path=null){ $data = file_get_contents($filepath); $results = $data?json_decode($data,true):[]; if($results) { $results = static::filterWith(["load.json", "load"], $results); static::loadArray($results,$prefix_path); } }
Load a JSON configuration file @param string $filepath The path of the JSON config file @param string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
public static function loadArray(array $array,$prefix_path=null){ $array = static::filterWith(["load.array", "load"], $array); if ($prefix_path){ static::set($prefix_path,$array); } else { static::merge($array); } self::trigger('loaded'); }
Load an array to the configuration @param array $array The array to load @param string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
public static function loadENV($dir,$envname='.env',$prefix_path=null){ $dir = rtrim($dir,'/'); $results = []; foreach(file("$dir/$envname", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line){ $line = trim($line); if ($line[0]=='#' || strpos($line,'=')===false) continue; list($key,$value) = explode('=',$line,2); $key = trim(str_replace(['export ', "'", '"'], '', $key)); $value = stripslashes(trim($value,'"\'')); $results[$key] = preg_replace_callback('/\${([a-zA-Z0-9_]+)}/',function($m) use (&$results){ return isset($results[$m[1]]) ? $results[$m[1]] : ''; },$value); putenv("$key={$results[$key]}"); $_ENV[$key] = $results[$key]; } if($results) { $results = static::filterWith(["load.env", "load"], $results); static::loadArray($results,$prefix_path); } }
Load an ENV file @param string $dir The directory of the ENV file @param string $envname The filename for the ENV file (Default to `.env`) @param string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
public function getBucket(string $bucket): BucketInterface { if (empty($bucket)) { throw new StorageException("Bucket name is not specified."); } $bucket = $this->config->resolveAlias($bucket); if (isset($this->buckets[$bucket])) { return $this->buckets[$bucket]; } $config = $this->config->getBucket($bucket); return $this->buckets[$bucket] = new StorageBucket( $this->getServer($config['server']), $bucket, $config['prefix'], $config['options'] ); }
{@inheritdoc}
public function getServer(string $server): ServerInterface { if (isset($this->servers[$server])) { return $this->servers[$server]; } if (!$this->config->hasServer($server)) { throw new StorageException("Undefined storage server `{$server}`."); } return $this->servers[$server] = $this->config->getServer($server)->resolve($this->factory); }
{@inheritdoc}
public function put(string $bucket, string $name, $source = ''): ObjectInterface { return $this->open($this->getBucket($bucket)->put($name, $source)); }
{@inheritdoc}
public function open(string $address): ObjectInterface { $bucket = $this->resolver->resolveBucket($address, $name); return new StorageObject($this->getBucket($bucket), $name); }
{@inheritdoc}
public function createInjection(\ReflectionClass $class, string $context = null) { if (empty($context)) { throw new StorageException("Storage bucket can be requested without specified context"); } return $this->getBucket($context); }
{@inheritdoc}
public static function register($name, $dsn, $username=null, $password=null, $options=[]){ return self::$connections[$name] = new SQLConnection($dsn, $username, $password, $options); }
Register a new datasource @param string $name The assigned name for the datasource @param string $dsn PDO DSN URL @param string $username User credentials @param string $password User credentials @param array $options Options to pass to the PDO constructor @return SQLConnection The datasource resource
public static function connect($dsn, $username=null, $password=null, $options=[]){ return self::register('default', $dsn, $username, $password, $options); }
Register the default datasource @param string $dsn PDO DSN URL @param string $username User credentials @param string $password User credentials @param array $options Options to pass to the PDO constructor @return SQLConnection The datasource resource
public static function defaultTo($name){ if (isset(self::$connections[$name])){ self::$current = $name; return true; } else return false; }
Bind the default datasource to another named connection @param string $name The datasource name @return bool `true` if correctly changed
public static function close($name=null){ if ($name === null) { foreach (self::$connections as $conn) $conn->close(); return true; } else if (isset(self::$connections[$name])){ self::$connections[$name]->close(); return true; } else return false; }
Close one or all (if no parameter passed) registered datasource connections @param string $name The datasource name, omit for close all of them @return bool `true` if one or more datasource where closed
public static function using($name){ if (empty(self::$connections[$name])) throw new \Exception("[SQL] Unknown connection named '$name'."); return self::$connections[$name]; }
Datasource connection accessor @param strinf $name The datasource name @return SQLConnect The datasource connection
public function prepare($query, $pdo_params=[]){ if(!$this->connection()) return false; return isset($this->queries[$query]) ? $this->queries[$query] : ($this->queries[$query] = $this->connection()->prepare($query, $pdo_params)); }
Prepares a SQL query string @param string $query The query @param array $pdo_params The extra PDO parameters @return boolean
public static function persistenceOptions($options=null){ static $_options = ['table'=>null,'key'=>'id']; if ($options === null) return $_options; if (is_array($options)) { foreach ($_options as $key => &$value) { if (isset($options[$key])) $value = $options[$key]; } return $_options; } else { if (empty($_options['table'])) { $self = get_called_class(); if (defined("$self::_PRIMARY_KEY_")){ $x = explode('.', $self::_PRIMARY_KEY_); $_options = [ 'table' => current($x), 'key' => isset($x[1])?$x[1]:'id', ]; } else { // User pluralized class name as default table switch(substr($s = strtolower($self),-1)){ case 'y': $table = substr($s,0,-1).'ies'; break; case 's': $table = substr($s,0,-1).'es'; break; default: $table = $s.'s'; break; } // Default ID $_options = [ 'table' => $table, 'key' => 'id', ]; } } return isset($_options[$options]) ? $_options[$options] : ''; } }
[Internal] : Retrieve/Set persistence options This function can be used to get all options passing null, setting options passing an associative array or retrieve a single value passing a string @param mixed $options The options passed to the persistence layer. @return mixed All options array or a single value
public static function load($pk){ $table = static::persistenceOptions('table'); $cb = static::persistenceLoad(); $op = static::persistenceOptions(); // Use standard persistence on DB layer return ( false == is_callable($cb) ) ? static::persistenceLoadDefault($pk,$table,$op) : $cb($pk,$table,$op); }
Load the model from the persistence layer @return mixed The retrieved object
private static function persistenceLoadDefault($pk, $table, $options){ if ( $data = SQL::single("SELECT * FROM $table WHERE {$options['key']}=? LIMIT 1",[$pk]) ){ $obj = new static; foreach ((array)$data as $key => $value) { $obj->$key = $value; } if (is_callable(($c=get_called_class())."::trigger")) $c::trigger("load", $obj, $table, $options['key']); return $obj; } else { return null; } }
Private Standard Load Method
public function save(){ $table = static::persistenceOptions('table'); $op = static::persistenceOptions(); $cb = static::persistenceSave(); // Use standard persistence on DB layer $cb = $cb ? Closure::bind($cb, $this) : [$this,'persistenceSaveDefault']; return $cb($table,$op); }
Save the model to the persistence layer @return mixed The results from the save callback. (default: lastInsertID)
private function persistenceSaveDefault($table,$options){ if (is_callable(($c=get_called_class())."::trigger")) $c::trigger("save", $this, $table, $options['key']); $id = SQL::insertOrUpdate($table,array_filter((array)$this, function($var) { return !is_null($var); }),$options['key']); // Populate retrieved primary key in Models. if (null !== $id && is_a($this, 'Model')) $this->{$options['key']} = $id; return $id; }
Private Standard Save Method
public static function accept($key='type',$choices='') { if (null === static::$accepts) static::$accepts = [ 'type' => new Negotiation(isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : ''), 'language' => new Negotiation(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : ''), 'encoding' => new Negotiation(isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : ''), 'charset' => new Negotiation(isset($_SERVER['HTTP_ACCEPT_CHARSET']) ? $_SERVER['HTTP_ACCEPT_CHARSET'] : ''), ]; return empty(static::$accepts[$key]) ? false : ( empty($choices) ? static::$accepts[$key]->preferred() : static::$accepts[$key]->best($choices) ); }
Handle Content Negotiation requests @param string $key The name of the negotiation subject @param string $choices A query string for the negotiation choices (See RFC 7231) @return Object The preferred content if $choices is empty else return best match
public static function input($key=null,$default=null){ return $key ? (isset($_REQUEST[$key]) ? new Structure($_REQUEST[$key]) : (is_callable($default)?call_user_func($default):$default)) : new Structure($_REQUEST[$key]); }
Retrive a value from generic input (from the $_REQUEST array) Returns all elements if you pass `null` as $key @param string $key The name of the input value @return Structure The returned value or $default.
public static function env($key=null,$default=null){ return $key ? (filter_input(INPUT_ENV,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_ENV; }
Retrive a value from environment (from the $_ENV array) Returns all elements if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function server($key=null,$default=null){ return $key ? (isset($_SERVER[$key]) ? $_SERVER[$key] : (is_callable($default)?call_user_func($default):$default)) : $_SERVER; }
Retrive a value from server (from the $_SERVER array) Returns all elements if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function post($key=null,$default=null){ return $key ? (filter_input(INPUT_POST,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_POST; }
Retrive a value from generic input (from the $_POST array) Returns all elements if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function get($key=null,$default=null){ return $key ? (filter_input(INPUT_GET,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_GET; }
Retrive a value from generic input (from the $_GET array) Returns all elements if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function files($key=null,$default=null){ return $key ? (isset($_FILES[$key]) ? $_FILES[$key] : (is_callable($default)?call_user_func($default):$default)) : $_FILES; }
Retrive uploaded file (from the $_FILES array) Returns all uploaded files if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function cookie($key=null,$default=null){ return $key ? (filter_input(INPUT_COOKIE,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_COOKIE; }
Retrive cookie (from the $_COOKIE array) Returns all cookies if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or $default.
public static function host($with_protocol=true){ switch(true){ case !empty($_SERVER['HTTP_X_FORWARDED_HOST']) : $host = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_HOST'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_HOST']); break; case !empty($_SERVER['HTTP_HOST']) : $host = $_SERVER['HTTP_HOST']; break; case !empty($_SERVER['SERVER_NAME']) : $host = $_SERVER['SERVER_NAME']; break; case !empty($_SERVER['HOSTNAME']) : $host = $_SERVER['HOSTNAME']; break; default : $host = 'localhost'; break; } $host = explode(':',$host,2); $port = isset($host[1]) ? (int)$host[1] : (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80); $host = $host[0] . (($port && $port != 80) ? ":$port" : ''); if ($port == 80) $port = ''; return ($with_protocol ? 'http' . (!empty($_SERVER['HTTPS'])&&(strtolower($_SERVER['HTTPS'])!=='off')?'s':'') . '://' : '') . Filter::with('core.request.host',$host); }
Returns the current host and port (omitted if port 80). @param bool $with_protocol Pass true to prepend protocol to hostname @return string
public static function header($key=null,$default=null){ if ($key) $key = 'HTTP_'.strtr(strtoupper($key),'-','_'); return $key ? (isset($_SERVER[$key])? $_SERVER[$key] : (is_callable($default)?call_user_func($default):$default)) : array_filter($_SERVER, function($k) { return strrpos($k, "HTTP_") === 0; }, ARRAY_FILTER_USE_KEY); }
Retrive header Returns all headers if you pass `null` as $key @param string $key The name of the input value @return Object The returned value or null.
public static function URI(){ switch(true){ case !empty($_SERVER['REQUEST_URI']): $serv_uri = $_SERVER['REQUEST_URI']; break; case !empty($_SERVER['ORIG_PATH_INFO']): $serv_uri = $_SERVER['ORIG_PATH_INFO']; break; case !empty($_SERVER['PATH_INFO']): $serv_uri = $_SERVER['PATH_INFO']; break; default: $serv_uri = '/'; break; } $uri = rtrim(strtok($serv_uri,'?'),'/') ?: '/'; return Filter::with('core.request.URI', $uri) ?: '/'; }
Returns the current request URI. @return string
public static function IP(){ switch(true){ case !empty($_SERVER['HTTP_X_FORWARDED_FOR']): $ip = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_FOR'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_FOR']); break; case !empty($_SERVER['HTTP_X_FORWARDED_HOST']): $ip = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_HOST'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_HOST']); break; case !empty($_SERVER['REMOTE_ADDR']): $ip = $_SERVER['REMOTE_ADDR']; break; case !empty($_SERVER['HTTP_CLIENT_IP']): $ip = $_SERVER['HTTP_CLIENT_IP']; break; default: $ip = ''; break; } return Filter::with('core.request.IP',$ip); }
Returns the remote IP @return string
public static function data($key=null,$default=null){ if (null===static::$body){ $json = (false !== stripos(empty($_SERVER['HTTP_CONTENT_TYPE'])?'':$_SERVER['HTTP_CONTENT_TYPE'],'json')) || (false !== stripos(empty($_SERVER['CONTENT_TYPE'])?'':$_SERVER['CONTENT_TYPE'],'json')); if ($json) { static::$body = json_decode(file_get_contents("php://input")); } else { if (empty($_POST)) { static::$body = file_get_contents("php://input"); } else { static::$body = (object)$_POST; } } } return $key ? (isset(static::$body->$key) ? static::$body->$key : (is_callable($default)?call_user_func($default):$default)) : static::$body; }
Returns request body data, convert to object if content type is JSON Gives you all request data if you pass `null` as $key @param string $key The name of the key requested @return mixed The request body data
public function copy(BucketInterface $bucket, BucketInterface $destination, string $name): bool { return $this->put($destination, $name, $this->getStream($bucket, $name)); }
{@inheritdoc}
public function replace(BucketInterface $bucket, BucketInterface $destination, string $name): bool { if ($this->copy($bucket, $destination, $name)) { $this->delete($bucket, $name); return true; } throw new ServerException("Unable to copy '{$name}' to new bucket"); }
{@inheritdoc}
public static function verify($password, $hash){ // Pre PHP 5.5 support if (!defined('PASSWORD_DEFAULT') || substr($hash,0,4)=='$5h$') { return '$5h$'.hash('sha1',$password) == $hash; } else { return password_verify($password,$hash); } }
Verify if password match a given hash @param string $password The password to check @param string $hash The hash to match against @return bool Returns `true` if hash match password
public function exists(BucketInterface $bucket, string $name): bool { return $this->gridFS($bucket)->findOne(['filename' => $name]) !== null; }
{@inheritdoc}
public function size(BucketInterface $bucket, string $name): ?int { if (!$this->exists($bucket, $name)) { return null; } return $this->gridFS($bucket)->findOne(['filename' => $name])->length; }
{@inheritdoc}
public function put(BucketInterface $bucket, string $name, StreamInterface $stream): bool { //No updates, only delete and re-upload if ($this->exists($bucket, $name)) { $this->delete($bucket, $name); } $resource = StreamWrapper::getResource($stream); try { $result = $this->gridFS($bucket)->uploadFromStream($name, $resource); } finally { StreamWrapper::release($resource); fclose($resource); } if (empty($result)) { throw new ServerException("Unable to store {$name} at GridFS server"); } return true; }
{@inheritdoc}
public function getStream(BucketInterface $bucket, string $name): StreamInterface { $file = $this->gridFS($bucket)->findOne(['filename' => $name]); if (empty($file)) { throw new ServerException( "Unable to create stream for '{$name}', object does not exists" ); } //We have to use temporary file now due to issues with seeking (should be fixed soon) $resource = fopen('php://memory', 'rw'); //Copying from non seekable to seekable stream stream_copy_to_stream($this->gridFS($bucket)->openDownloadStream($file->_id), $resource); //Working thought the memory, WILL FAIL on very huge files rewind($resource); //Ugly :/ return stream_for($resource); }
{@inheritdoc} This method must be improved in future versions! @see https://github.com/mongodb/mongo-php-library/issues/317 @see https://github.com/slimphp/Slim/issues/2112 @see https://jira.mongodb.org/browse/PHPLIB-213
public function delete(BucketInterface $bucket, string $name) { if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to delete object, file not found"); } $file = $this->gridFS($bucket)->findOne(['filename' => $name]); $this->gridFS($bucket)->delete($file->_id); }
{@inheritdoc}
public function rename(BucketInterface $bucket, string $oldName, string $newName): bool { $file = $this->gridFS($bucket)->findOne(['filename' => $oldName]); if (empty($file)) { return false; } $this->gridFS($bucket)->rename($file->_id, $newName); return true; }
{@inheritdoc}
protected function gridFS(BucketInterface $bucket): Bucket { if (empty($this->database)) { $this->database = new Database( new Manager($this->options['connection']), $this->options['database'] ); } return $this->database->selectGridFSBucket([ 'bucketName' => $bucket->getOption('bucket') ]); }
Get valid GridFS collection associated with bucket. @param BucketInterface $bucket Bucket instance. @return Bucket
protected static function install_shutdown(){ if (static::$inited_shutdown) return; // Disable time limit set_time_limit(0); // HHVM support if(function_exists('register_postsend_function')){ register_postsend_function(function(){ Event::trigger('core.shutdown'); }); } else if(function_exists('fastcgi_finish_request')) { register_shutdown_function(function(){ fastcgi_finish_request(); Event::trigger('core.shutdown'); }); } else { register_shutdown_function(function(){ Event::trigger('core.shutdown'); }); } static::$inited_shutdown = true; }
Single shot defer handeler install
protected function doHandleRequest(RequestInterface $request, callable $next, callable $first) { $method = strtoupper($request->getMethod()); // If the request not is cachable, move to $next if (!in_array($method, ['GET', 'HEAD'], true)) { return $next($request); } $cacheItem = $this->createCacheItem($request); if ($cacheItem->isHit() && ($etag = $this->getETag($cacheItem))) { $request = $request->withHeader('If-None-Match', $etag); } return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) { if (304 === $response->getStatusCode()) { if (!$cacheItem->isHit()) { // We do not have the item in cache. This plugin did not // add If-None-Match headers. Return the response. return $response; } // The cached response we have is still valid $cacheItem->set($cacheItem->get())->expiresAfter($this->lifetime); $this->pool->save($cacheItem); return $this->createResponseFromCacheItem($cacheItem); } if ($this->isCacheable($response)) { $bodyStream = $response->getBody(); $body = $bodyStream->__toString(); if ($bodyStream->isSeekable()) { $bodyStream->rewind(); } else { $response = $response->withBody($this->streamFactory->createStream($body)); } $cacheItem ->expiresAfter($this->lifetime) ->set([ 'response' => $response, 'body' => $body, 'etag' => $response->getHeader('ETag'), ]); $this->pool->save($cacheItem); } return $response; }); }
Handle the request and return the response coming from the next callable. @param \Psr\Http\Message\RequestInterface $request @param callable $next @param callable $first @return \Http\Promise\Promise
protected function createCacheItem(RequestInterface $request) { $key = sha1($this->generator->generate($request)); return $this->pool->getItem($key); }
Create a cache item for a request. @param \Psr\Http\Message\RequestInterface $request @return \Psr\Cache\CacheItemInterface
protected function isCacheable(ResponseInterface $response) { if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) { return false; } return !$this->getCacheControlDirective($response, 'no-cache'); }
Verify that we can cache this response. @param \Psr\Http\Message\ResponseInterface $response @return bool
protected function getCacheControlDirective(ResponseInterface $response, string $name) { foreach ($response->getHeader('Cache-Control') as $header) { if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) { // return the value for $name if it exists if (isset($matches[1])) { return $matches[1]; } return true; } } return false; }
Get the value of a parameter in the cache control header. @param \Psr\Http\Message\ResponseInterface $response @param string $name @return bool|string
protected function createResponseFromCacheItem(CacheItemInterface $cacheItem) { $data = $cacheItem->get(); $response = $data['response']; $stream = $this->streamFactory->createStream($data['body']); try { $stream->rewind(); } catch (Exception $e) { throw new RewindStreamException('Cannot rewind stream.', 0, $e); } $response = $response->withBody($stream); return $response; }
Create a response from a cache item. @param \Psr\Cache\CacheItemInterface $cacheItem @return \Psr\Http\Message\ResponseInterface
protected function getETag(CacheItemInterface $cacheItem) { $data = $cacheItem->get(); foreach ($data['etag'] as $etag) { if (!empty($etag)) { return $etag; } } }
Get the ETag from the cached response. @param \Psr\Cache\CacheItemInterface $cacheItem @return string|null
public function merge( array $attributes ) { foreach ( $attributes as $name => $value ) { $this->set_attribute( $name, $value ); } return $this; }
Merges the provided attributes with the provided array. @param array $attributes @return $this
public function get_changed_table_attributes() { $changed = array(); foreach ( $this->get_table_attributes() as $key => $value ) { if ( $value !== $this->get_original_attribute( $key ) ) { $changed[ $key ] = $value; } } return $changed; }
Retrieve an array of the attributes on the model that have changed compared to the model's original data. @return array
public function get_underlying_wp_object() { if ( isset( $this->attributes[ self::OBJECT_KEY ] ) ) { return $this->attributes[ self::OBJECT_KEY ]; } return false; }
Get the model's underlying post. Returns the underlying WP_Post object for the model, representing the data that will be save in the wp_posts table. @return false|WP_Post|WP_Term
public function get_changed_wp_object_attributes() { $changed = array(); foreach ( $this->get_wp_object_keys() as $key ) { if ( $this->get_attribute( $key ) !== $this->get_original_attribute( $key ) ) { $changed[ $key ] = $this->get_attribute( $key ); } } return $changed; }
Get the model attributes on the WordPress object that have changed compared to the model's original attributes. @return array
public function set_attribute( $name, $value ) { if ( self::OBJECT_KEY === $name ) { return $this->override_wp_object( $value ); } if ( self::TABLE_KEY === $name ) { return $this->override_table( $value ); } if ( ! $this->is_fillable( $name ) ) { throw new GuardedPropertyException; } if ( $method = $this->has_map_method( $name ) ) { $this->attributes[ self::OBJECT_KEY ]->{$this->{$method}()} = $value; } else { $this->attributes[ self::TABLE_KEY ][ $name ] = $value; } return $this; }
Sets the model attributes. Checks whether the model attribute can be set, check if it maps to the WP_Post property, otherwise, assigns it to the table attribute array. @param string $name @param mixed $value @return $this @throws GuardedPropertyException
public function get_attribute_keys() { if ( isset( self::$memo[ get_called_class() ][ __METHOD__ ] ) ) { return self::$memo[ get_called_class() ][ __METHOD__ ]; } return self::$memo[ get_called_class() ][ __METHOD__ ] = array_merge( $this->fillable, $this->guarded, $this->get_compute_methods() ); }
Retrieves all the attribute keys for the model. @return array
public function get_table_keys() { if ( isset( self::$memo[ get_called_class() ][ __METHOD__ ] ) ) { return self::$memo[ get_called_class() ][ __METHOD__ ]; } $keys = array(); foreach ( $this->get_attribute_keys() as $key ) { if ( ! $this->has_map_method( $key ) && ! $this->has_compute_method( $key ) ) { $keys[] = $key; } } return self::$memo[ get_called_class() ][ __METHOD__ ] = $keys; }
Retrieves the attribute keys that aren't mapped to a post. @return array
public function get_wp_object_keys() { if ( isset( self::$memo[ get_called_class() ][ __METHOD__ ] ) ) { return self::$memo[ get_called_class() ][ __METHOD__ ]; } $keys = array(); foreach ( $this->get_attribute_keys() as $key ) { if ( $this->has_map_method( $key ) ) { $keys[] = $key; } } return self::$memo[ get_called_class() ][ __METHOD__ ] = $keys; }
Retrieves the attribute keys that are mapped to a post. @return array
public function get_computed_keys() { if ( isset( self::$memo[ get_called_class() ][ __METHOD__ ] ) ) { return self::$memo[ get_called_class() ][ __METHOD__ ]; } $keys = array(); foreach ( $this->get_attribute_keys() as $key ) { if ( $this->has_compute_method( $key ) ) { $keys[] = $key; } } return self::$memo[ get_called_class() ][ __METHOD__ ] = $keys; }
Returns the model's keys that are computed at call time. @return array
public function serialize() { $attributes = array(); if ( $this->visible ) { // If visible attributes are set, we'll only reveal those. foreach ( $this->visible as $key ) { $attributes[ $key ] = $this->get_attribute( $key ); } } elseif ( $this->hidden ) { // If hidden attributes are set, we'll grab everything and hide those. foreach ( $this->get_attribute_keys() as $key ) { if ( ! in_array( $key, $this->hidden ) ) { $attributes[ $key ] = $this->get_attribute( $key ); } } } else { // If nothing is hidden/visible, we'll grab and reveal everything. foreach ( $this->get_attribute_keys() as $key ) { $attributes[ $key ] = $this->get_attribute( $key ); } } return array_map( function ( $attribute ) { if ( $attribute instanceof Serializes ) { return $attribute->serialize(); } return $attribute; }, $attributes ); }
Serializes the model's public data into an array. @return array