repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
PHPColibri/framework
Application/Application/API.php
API.getCacheKeyForCall
private static function getCacheKeyForCall(array $params) { static $domainLevel = null; $params += $_GET; $keyStr = ''; foreach ($params as $param) { $keyStr .= serialize($param); } $keyStr .= Request::domainPrefix( $domainLevel ?? $domainLevel = count(explode('.', Config::application('domain'))) ); return md5($keyStr); }
php
private static function getCacheKeyForCall(array $params) { static $domainLevel = null; $params += $_GET; $keyStr = ''; foreach ($params as $param) { $keyStr .= serialize($param); } $keyStr .= Request::domainPrefix( $domainLevel ?? $domainLevel = count(explode('.', Config::application('domain'))) ); return md5($keyStr); }
@param array $params @return string
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Application/Application/API.php#L50-L65
PHPColibri/framework
Application/Application/API.php
API.getModuleViewCached
public static function getModuleViewCached($division, $module, $method, ...$params) { if (Config::application('useCache') && ! DEBUG) { $key = self::getCacheKeyForCall(func_get_args()); $retValue = Cache::remember($key, function () use ($division, $module, $method, $params) { return self::getModuleView($division, $module, $method, ...$params); }); } else { $retValue = self::getModuleView($division, $module, $method, ...$params); } return $retValue; }
php
public static function getModuleViewCached($division, $module, $method, ...$params) { if (Config::application('useCache') && ! DEBUG) { $key = self::getCacheKeyForCall(func_get_args()); $retValue = Cache::remember($key, function () use ($division, $module, $method, $params) { return self::getModuleView($division, $module, $method, ...$params); }); } else { $retValue = self::getModuleView($division, $module, $method, ...$params); } return $retValue; }
@param string $division @param string $module @param string $method @param array $params @return string @throws \Colibri\Routing\Exception\NotFoundException @throws \Psr\SimpleCache\InvalidArgumentException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Application/Application/API.php#L78-L90
PHPColibri/framework
Application/Application/API.php
API.passed
protected static function passed($type, $key = null, $default = null) { return Session::get( $type . ($key !== null ? '.' . $key : ''), $key === null && $default === null ? [] : $default ); }
php
protected static function passed($type, $key = null, $default = null) { return Session::get( $type . ($key !== null ? '.' . $key : ''), $key === null && $default === null ? [] : $default ); }
@param string $type @param string|null $key @param array|mixed|null $default @return mixed
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Application/Application/API.php#L138-L144
PlatoCreative/silverstripe-sections
code/models/Section.php
Section.getCMSFields
public function getCMSFields() { $fields = $this->scaffoldFormFields( array( // Don't allow has_many/many_many relationship editing before the record is first saved 'includeRelations' => ($this->ID > 0), 'tabbed' => true, 'ajaxSafe' => true ) ); $fields->removeByName('MenuTitle'); $fields->addFieldsToTab( 'Root.Main', array( HiddenField::create('UniqueConfigTitle'), TextField::create( 'AdminTitle', 'Admin title' ) ->setDescription('This field is for adminisration use only and will not display on the site.'), CheckboxField::create( 'ShowInMenus', 'Show in menus', 0 ), DisplayLogicWrapper::create( TextField::create( 'MenuTitle', 'Navigation label' ) ) ->displayIf("ShowInMenus")->isChecked()->end() ) ); $fields->addFieldsToTab( 'Root.Settings', array( CheckboxField::create( 'Public', 'Public', 1 ) ->setDescription('Is this section publicly accessible?.'), DropdownField::create( 'Style', 'Select a style', $this->ConfigStyles ) ->setEmptyString('Default') ) ); $this->extend('updateCMSFields', $fields); return $fields; }
php
public function getCMSFields() { $fields = $this->scaffoldFormFields( array( // Don't allow has_many/many_many relationship editing before the record is first saved 'includeRelations' => ($this->ID > 0), 'tabbed' => true, 'ajaxSafe' => true ) ); $fields->removeByName('MenuTitle'); $fields->addFieldsToTab( 'Root.Main', array( HiddenField::create('UniqueConfigTitle'), TextField::create( 'AdminTitle', 'Admin title' ) ->setDescription('This field is for adminisration use only and will not display on the site.'), CheckboxField::create( 'ShowInMenus', 'Show in menus', 0 ), DisplayLogicWrapper::create( TextField::create( 'MenuTitle', 'Navigation label' ) ) ->displayIf("ShowInMenus")->isChecked()->end() ) ); $fields->addFieldsToTab( 'Root.Settings', array( CheckboxField::create( 'Public', 'Public', 1 ) ->setDescription('Is this section publicly accessible?.'), DropdownField::create( 'Style', 'Select a style', $this->ConfigStyles ) ->setEmptyString('Default') ) ); $this->extend('updateCMSFields', $fields); return $fields; }
CMS Fields @return FieldList
https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/models/Section.php#L63-L116
PlatoCreative/silverstripe-sections
code/models/Section.php
Section.Anchor
public function Anchor(){ if ($this->MenuTitle && $this->ShowInMenus) { return strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-',$this->MenuTitle), '-')); } return false; }
php
public function Anchor(){ if ($this->MenuTitle && $this->ShowInMenus) { return strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-',$this->MenuTitle), '-')); } return false; }
Applies anchor to section in template. @return string $classes
https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/models/Section.php#L245-L250
PlatoCreative/silverstripe-sections
code/models/Section.php
Section.Classes
public function Classes(){ $classes = array($this->config()->get('base_class')); if ($this->Style) { $classes[] = strtolower($this->Style).'-'.strtolower(preg_replace('/([a-z]+)([A-Z0-9])/', '$1-$2', get_called_class())); }else{ $classes[] = strtolower(preg_replace('/([a-z]+)([A-Z0-9])/', '$1-$2', get_called_class())); } return implode(' ',$classes); }
php
public function Classes(){ $classes = array($this->config()->get('base_class')); if ($this->Style) { $classes[] = strtolower($this->Style).'-'.strtolower(preg_replace('/([a-z]+)([A-Z0-9])/', '$1-$2', get_called_class())); }else{ $classes[] = strtolower(preg_replace('/([a-z]+)([A-Z0-9])/', '$1-$2', get_called_class())); } return implode(' ',$classes); }
Applies classes to section in template. @return string $classes
https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/models/Section.php#L269-L277
smalldb/libSmalldb
class/Utils/Utils.php
Utils.template_format
static function template_format($template, $values, $escaping_function = 'htmlspecialchars') { $available_functions = array( 'sprintf' => 'sprintf', 'strftime' => 'strftime', 'floor' => 'sprintf', 'ceil' => 'sprintf', 'frac' => 'sprintf', 'frac_str' => 'sprintf', 'intval' => 'sprintf', 'floatval' => 'sprintf', ); $tokens = preg_split('/(?:({)' ."(\\/?[a-zA-Z0-9_.-]+)" // symbol name .'(?:' .'([:%])([^:}\s]*)' // function name ."(?:([:])((?:[^}\\\\]|\\\\.)*))?" // format string .')?' .'(})' .'|(\\\\[{}\\\\]))/', $template, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $status = 0; // Current status of parser $append = 0; // Append value to result after token is processed ? $result = array(); $process_function = null; $format_function = null; $raw_values = array_slice(func_get_args(), 3); foreach($tokens as $token) { switch ($status) { // text around case 0: if ($token === '{') { $status = 10; $process_function = null; $format_function = null; $fmt = null; } else if ($token[0] === '\\') { $result[] = substr($token, 1); } else { $result[] = $token; } break; // first part case 10: $key = $token; $status = 20; break; // first separator case 20: if ($token === '}') { // end $append = true; $status = 0; } else if ($token === '%') { $process_function = null; $format_function = 'sprintf'; $status = 51; } else if ($token === ':') { $status = 30; } else { return FALSE; } break; // format function case 30: if (isset($available_functions[$token])) { $process_function = ($token != $available_functions[$token] ? $token : null); $format_function = $available_functions[$token]; } else { $process_function = null; $format_function = null; } $status = 40; break; // second separator case 40: if ($token === ':') { $status = 50; } else if ($token === '}') { $append = true; $status = 0; } else { return FALSE; } break; // format string case 50: $fmt = preg_replace("/\\\\(.)/", "\\1", $token); $status = 90; break; // format string, prepend % case 51: $fmt = '%'.str_replace(array('\\\\', '\:', '\}'), array('\\', ':', '}'), $token); $status = 90; break; // end case 90: if ($token === '}') { $append = true; $status = 0; } else { return FALSE; } break; } if ($append) { $append = false; $raw = null; // get value foreach ($raw_values as $rv) { if (isset($rv[$key])) { $v = $rv[$key]; $raw = true; break; } } if ($raw === null) { if (isset($values[$key])) { $v = $values[$key]; $raw = false; } else { // key not found, do not append it $result[] = '{?'.$key.'?}'; continue; } } // apply $process_function if ($process_function !== null) { $v = $process_function($v); } // apply $format_function if ($format_function !== null && $fmt !== null) { $v = $format_function($fmt, $v); } // apply $escaping_function if ($escaping_function && !$raw) { $v = $escaping_function($v); } $result[] = $v; } } return join('', $result); }
php
static function template_format($template, $values, $escaping_function = 'htmlspecialchars') { $available_functions = array( 'sprintf' => 'sprintf', 'strftime' => 'strftime', 'floor' => 'sprintf', 'ceil' => 'sprintf', 'frac' => 'sprintf', 'frac_str' => 'sprintf', 'intval' => 'sprintf', 'floatval' => 'sprintf', ); $tokens = preg_split('/(?:({)' ."(\\/?[a-zA-Z0-9_.-]+)" // symbol name .'(?:' .'([:%])([^:}\s]*)' // function name ."(?:([:])((?:[^}\\\\]|\\\\.)*))?" // format string .')?' .'(})' .'|(\\\\[{}\\\\]))/', $template, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $status = 0; // Current status of parser $append = 0; // Append value to result after token is processed ? $result = array(); $process_function = null; $format_function = null; $raw_values = array_slice(func_get_args(), 3); foreach($tokens as $token) { switch ($status) { // text around case 0: if ($token === '{') { $status = 10; $process_function = null; $format_function = null; $fmt = null; } else if ($token[0] === '\\') { $result[] = substr($token, 1); } else { $result[] = $token; } break; // first part case 10: $key = $token; $status = 20; break; // first separator case 20: if ($token === '}') { // end $append = true; $status = 0; } else if ($token === '%') { $process_function = null; $format_function = 'sprintf'; $status = 51; } else if ($token === ':') { $status = 30; } else { return FALSE; } break; // format function case 30: if (isset($available_functions[$token])) { $process_function = ($token != $available_functions[$token] ? $token : null); $format_function = $available_functions[$token]; } else { $process_function = null; $format_function = null; } $status = 40; break; // second separator case 40: if ($token === ':') { $status = 50; } else if ($token === '}') { $append = true; $status = 0; } else { return FALSE; } break; // format string case 50: $fmt = preg_replace("/\\\\(.)/", "\\1", $token); $status = 90; break; // format string, prepend % case 51: $fmt = '%'.str_replace(array('\\\\', '\:', '\}'), array('\\', ':', '}'), $token); $status = 90; break; // end case 90: if ($token === '}') { $append = true; $status = 0; } else { return FALSE; } break; } if ($append) { $append = false; $raw = null; // get value foreach ($raw_values as $rv) { if (isset($rv[$key])) { $v = $rv[$key]; $raw = true; break; } } if ($raw === null) { if (isset($values[$key])) { $v = $values[$key]; $raw = false; } else { // key not found, do not append it $result[] = '{?'.$key.'?}'; continue; } } // apply $process_function if ($process_function !== null) { $v = $process_function($v); } // apply $format_function if ($format_function !== null && $fmt !== null) { $v = $format_function($fmt, $v); } // apply $escaping_function if ($escaping_function && !$raw) { $v = $escaping_function($v); } $result[] = $v; } } return join('', $result); }
Format data using template string with placeholders. The placeholders to replace are in the following format: `{name}` or `{name:function}` or `{name:function:format_string}`. The function is formatting function (like `sprintf`) and format string is the first parameter of the formatting function. Available formatting functions: - `sprintf` - `strftime` - `floor` - `ceil` - `frac` - `frac_str` - `intval` - `floatval` All except `strftime` accept same formatting string as `sprintf`. The `strftime` accepts `strftime` format string. @par Example of the template: Hello {user}, now is {time:strftime:%H} o'clock and the temperature is {temp:sprintf:%0.2f} degree Celsius.
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/Utils.php#L61-L220
smalldb/libSmalldb
class/Utils/Utils.php
Utils.filename_format
static function filename_format($template, $values) { static $constants = false; if ($constants === false) { // Fixme: How to invalidate this cache? $constants = get_defined_constants(); } $args = func_get_args(); array_splice($args, 2, 0, array(null, $constants)); //return template_format($template, $values, null, $constants); return call_user_func_array(__NAMESPACE__ . '\Utils::template_format', $args); }
php
static function filename_format($template, $values) { static $constants = false; if ($constants === false) { // Fixme: How to invalidate this cache? $constants = get_defined_constants(); } $args = func_get_args(); array_splice($args, 2, 0, array(null, $constants)); //return template_format($template, $values, null, $constants); return call_user_func_array(__NAMESPACE__ . '\Utils::template_format', $args); }
Helper method to invoke template_format() without HTML escaping.
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/Utils.php#L226-L238
smalldb/libSmalldb
class/Utils/Utils.php
Utils.write_json_file
static function write_json_file($filename, $json_array, array $whitelist = null, $json_options = null) { $stop_snippet = "<?php printf('_%c%c}%c',34,10,10);__halt_compiler();?>"; if ($whitelist === null) { // Put stop snippet on begin. $result = array_merge(array('_' => null), $json_array); } else { // Whitelisted keys first (if they exist in $json_array), then stop snippet, then rest. $header = array_intersect_key(array_flip($whitelist), $json_array); $header['_'] = null; $result = array_merge($header, $json_array); // Replace '<?' with '<_?' in all whitelisted values, so injected PHP will not execute. foreach ($whitelist as $k) { if (array_key_exists($k, $result) && is_string($result[$k])) { $result[$k] = str_replace('<?', '<_?', $result[$k]); } } } // Put stop snipped at marked position (it is here to prevent // overwriting from $json_array). $result['_'] = $stop_snippet; $json_str = json_encode($result, $json_options === null ? (defined('JSON_PRETTY_PRINT') ? JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : JSON_NUMERIC_CHECK) : $json_options & ~(JSON_HEX_TAG | JSON_HEX_APOS)); if ($filename === null) { return $json_str; } else { return file_put_contents($filename, $json_str); } }
php
static function write_json_file($filename, $json_array, array $whitelist = null, $json_options = null) { $stop_snippet = "<?php printf('_%c%c}%c',34,10,10);__halt_compiler();?>"; if ($whitelist === null) { // Put stop snippet on begin. $result = array_merge(array('_' => null), $json_array); } else { // Whitelisted keys first (if they exist in $json_array), then stop snippet, then rest. $header = array_intersect_key(array_flip($whitelist), $json_array); $header['_'] = null; $result = array_merge($header, $json_array); // Replace '<?' with '<_?' in all whitelisted values, so injected PHP will not execute. foreach ($whitelist as $k) { if (array_key_exists($k, $result) && is_string($result[$k])) { $result[$k] = str_replace('<?', '<_?', $result[$k]); } } } // Put stop snipped at marked position (it is here to prevent // overwriting from $json_array). $result['_'] = $stop_snippet; $json_str = json_encode($result, $json_options === null ? (defined('JSON_PRETTY_PRINT') ? JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : JSON_NUMERIC_CHECK) : $json_options & ~(JSON_HEX_TAG | JSON_HEX_APOS)); if ($filename === null) { return $json_str; } else { return file_put_contents($filename, $json_str); } }
Encode array to JSON using json_encode, but insert PHP snippet to protect sensitive data. If $filename is set, JSON will be written to given file. Otherwise you are expected to store returned string into *.json.php file. Stop snippet: When JSON file is evaluated as PHP, stop snippet will interrupt evaluation without breaking JSON syntax, only underscore key is appended (and overwritten if exists). To make sure that whitelisted keys does not contain PHP tags, all occurrences of '<?' are replaced with '<_?' in whitelisted values. Default $json_options are: - PHP >= 5.4: JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE - PHP < 5.4: JSON_NUMERIC_CHECK Options JSON_HEX_TAG and JSON_HEX_APOS are disabled, becouse they break PHP snippet.
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/Utils.php#L262-L297
smalldb/libSmalldb
class/Utils/Utils.php
Utils.parse_json_file
static function parse_json_file($filename) { $json_str = file_get_contents($filename); if ($json_str === FALSE) { // FIXME: Use different exception ? throw new JsonException("Failed to read file: ".$filename); } return static::parse_json_string($json_str); }
php
static function parse_json_file($filename) { $json_str = file_get_contents($filename); if ($json_str === FALSE) { // FIXME: Use different exception ? throw new JsonException("Failed to read file: ".$filename); } return static::parse_json_string($json_str); }
JSON version of parse_ini_file(). Throws JsonException on error.
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/Utils.php#L305-L314
smalldb/libSmalldb
class/Utils/Utils.php
Utils.parse_json_string
static function parse_json_string($json_str, $filename = null) { $data = json_decode($json_str, TRUE, 512, JSON_BIGINT_AS_STRING); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { throw new JsonException($filename !== null ? json_last_error_msg().' ('.$filename.')' : json_last_error_msg(), $error); } return $data; }
php
static function parse_json_string($json_str, $filename = null) { $data = json_decode($json_str, TRUE, 512, JSON_BIGINT_AS_STRING); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { throw new JsonException($filename !== null ? json_last_error_msg().' ('.$filename.')' : json_last_error_msg(), $error); } return $data; }
Decode JSON string. @param $json_str String to parse. @param $filename If set the exception message will contain $filename.
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/Utils.php#L323-L331
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.setupFontAwesome
protected function setupFontAwesome(array $imports) { if (!$this->config->getUseFontAwesome()) { return $imports; } $this->lessFilter->addLoadPath($this->config->getFontAwesomePath() . '/less'); if (false !== ($key = array_search('sprites.less', $imports))) { $imports[$key] = 'font-awesome.less'; } else { $imports[] = 'font-awesome.less'; } return $imports; }
php
protected function setupFontAwesome(array $imports) { if (!$this->config->getUseFontAwesome()) { return $imports; } $this->lessFilter->addLoadPath($this->config->getFontAwesomePath() . '/less'); if (false !== ($key = array_search('sprites.less', $imports))) { $imports[$key] = 'font-awesome.less'; } else { $imports[] = 'font-awesome.less'; } return $imports; }
@param array $imports @return array
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L49-L64
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.filterLoad
public function filterLoad(AssetInterface $asset) { $assetRoot = $asset->getSourceRoot(); $assetPath = $asset->getSourcePath(); $assetImportDir = dirname($assetRoot . '/' . $assetPath); $importDir = $this->config->getBootstrapPath() . '/less'; $this->setupLoadPaths($assetImportDir); // Make sure we _always_ have the bootstrap import dir. if ($importDir !== $assetImportDir) { $this->lessFilter->addLoadPath($importDir); } $variables = array_merge( $this->extractVariables($importDir . '/variables.less'), $this->config->getVariables() ); $variablesString = ''; foreach ($variables as $key => $value) { $variablesString .= "@$key:$value;" . PHP_EOL; } if ('bootstrap.less' === $assetPath) { $imports = $this->filterImportFiles(array_unique(array_merge( $this->extractImports($importDir . '/bootstrap.less'), $this->extractImports($importDir . '/responsive.less'), $this->config->getCustomComponents() ))); $assetContent = $variablesString . $imports; $asset->setContent($assetContent); } else { $asset->setContent($variablesString . $asset->getContent()); } $this->lessFilter->filterLoad($asset); }
php
public function filterLoad(AssetInterface $asset) { $assetRoot = $asset->getSourceRoot(); $assetPath = $asset->getSourcePath(); $assetImportDir = dirname($assetRoot . '/' . $assetPath); $importDir = $this->config->getBootstrapPath() . '/less'; $this->setupLoadPaths($assetImportDir); // Make sure we _always_ have the bootstrap import dir. if ($importDir !== $assetImportDir) { $this->lessFilter->addLoadPath($importDir); } $variables = array_merge( $this->extractVariables($importDir . '/variables.less'), $this->config->getVariables() ); $variablesString = ''; foreach ($variables as $key => $value) { $variablesString .= "@$key:$value;" . PHP_EOL; } if ('bootstrap.less' === $assetPath) { $imports = $this->filterImportFiles(array_unique(array_merge( $this->extractImports($importDir . '/bootstrap.less'), $this->extractImports($importDir . '/responsive.less'), $this->config->getCustomComponents() ))); $assetContent = $variablesString . $imports; $asset->setContent($assetContent); } else { $asset->setContent($variablesString . $asset->getContent()); } $this->lessFilter->filterLoad($asset); }
Sets the by-config generated imports on the asset. {@inheritDoc}
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L86-L127
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.extractImports
protected function extractImports($importsFile) { $str = file_get_contents($importsFile); preg_match_all('/@import "(?!variables)(?<imports>[\w-_\.]+)";/', $str, $matches); return array_map('trim', $matches['imports']); }
php
protected function extractImports($importsFile) { $str = file_get_contents($importsFile); preg_match_all('/@import "(?!variables)(?<imports>[\w-_\.]+)";/', $str, $matches); return array_map('trim', $matches['imports']); }
Extract the imports from the import file. @param string $importsFile @return array The extracted imports
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L136-L143
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.extractVariables
protected function extractVariables($variablesFile) { $str = file_get_contents($variablesFile); $parts = explode(';', preg_replace('/(\/\/.*?\n|\s\n|\s{2,})/', '', $str)); $vars = array(); foreach ($parts as $part) { $varMeta = explode(':', $part); if (empty($varMeta[0]) || empty($varMeta[1])) { continue; } $vars[substr(trim($varMeta[0]), 1)] = trim($varMeta[1]); } return $vars; }
php
protected function extractVariables($variablesFile) { $str = file_get_contents($variablesFile); $parts = explode(';', preg_replace('/(\/\/.*?\n|\s\n|\s{2,})/', '', $str)); $vars = array(); foreach ($parts as $part) { $varMeta = explode(':', $part); if (empty($varMeta[0]) || empty($varMeta[1])) { continue; } $vars[substr(trim($varMeta[0]), 1)] = trim($varMeta[1]); } return $vars; }
Extract the variables from the less file. @param string $variablesFile The path to the less file @return array The extracted variables
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L152-L167
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.filterImportFiles
protected function filterImportFiles(array $imports) { $config = $this->config; $excludedComponents = $config->getExcludedComponents(); $includedComponents = $config->getIncludedComponents(); if (!empty($excludedComponents) && !empty($includedComponents)) { throw new Exception\RuntimeException( 'You may not set both excluded and included components.' ); } if (!empty($excludedComponents)) { $imports = $this->removeImportFiles($imports, $excludedComponents); } elseif (!empty($includedComponents)) { $imports = $this->addImportFiles($imports, $includedComponents); } $imports = $this->setupFontAwesome($imports); array_walk($imports, function (&$val) { $val = "@import \"$val\";"; }); return implode(PHP_EOL, $imports); }
php
protected function filterImportFiles(array $imports) { $config = $this->config; $excludedComponents = $config->getExcludedComponents(); $includedComponents = $config->getIncludedComponents(); if (!empty($excludedComponents) && !empty($includedComponents)) { throw new Exception\RuntimeException( 'You may not set both excluded and included components.' ); } if (!empty($excludedComponents)) { $imports = $this->removeImportFiles($imports, $excludedComponents); } elseif (!empty($includedComponents)) { $imports = $this->addImportFiles($imports, $includedComponents); } $imports = $this->setupFontAwesome($imports); array_walk($imports, function (&$val) { $val = "@import \"$val\";"; }); return implode(PHP_EOL, $imports); }
Filter the import files needed. @param array $imports @throws \SxBootstrap\Exception\RuntimeException @return array
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L177-L202
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.removeImportFiles
protected function removeImportFiles(array $importFiles, array $config) { foreach ($config as $item) { if (in_array($item, $importFiles)) { unset($importFiles[array_search($item, $importFiles)]); } } return $importFiles; }
php
protected function removeImportFiles(array $importFiles, array $config) { foreach ($config as $item) { if (in_array($item, $importFiles)) { unset($importFiles[array_search($item, $importFiles)]); } } return $importFiles; }
Remove import files from the import config. @param array $importFiles @param array $config @return array
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L212-L221
SpoonX/SxBootstrap
src/SxBootstrap/Service/BootstrapFilter.php
BootstrapFilter.addImportFiles
protected function addImportFiles(array $importFiles, array $config) { foreach ($importFiles as $key => $if) { if (!in_array($if, $config)) { unset($importFiles[$key]); } } return $importFiles; }
php
protected function addImportFiles(array $importFiles, array $config) { foreach ($importFiles as $key => $if) { if (!in_array($if, $config)) { unset($importFiles[$key]); } } return $importFiles; }
Remove everything from the import config except for the values in $config @param array $importFiles @param array $config @return array
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/Service/BootstrapFilter.php#L231-L240
soliphp/web
src/Web/Session.php
Session.get
public function get($key, $default = null, $remove = false) { if (isset($_SESSION[$key])) { return $remove ? $this->remove($key) : $_SESSION[$key]; } return $default; }
php
public function get($key, $default = null, $remove = false) { if (isset($_SESSION[$key])) { return $remove ? $this->remove($key) : $_SESSION[$key]; } return $default; }
获取一个 session 变量 @param string $key @param mixed $default @param bool $remove 是否获取完就删除掉 @return mixed
https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Session.php#L79-L86
soliphp/web
src/Web/Session.php
Session.remove
public function remove($key) { $value = null; if (isset($_SESSION[$key])) { $value = $_SESSION[$key]; unset($_SESSION[$key]); } return $value; }
php
public function remove($key) { $value = null; if (isset($_SESSION[$key])) { $value = $_SESSION[$key]; unset($_SESSION[$key]); } return $value; }
移除一个 session 变量 @param string $key @return mixed
https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Session.php#L116-L124
ideil/laravel-generic-file
src/LaravelGenericFileServiceProvider.php
LaravelGenericFileServiceProvider.boot
public function boot() { $configurations = [ 'handlers-base', 'handlers-filters', 'http', 'store', ]; $configDir = __DIR__.'/config'; foreach ($configurations as $configName) { $this->publishes(["{$configDir}/{$configName}.php" => config_path("generic-file/{$configName}.php")]); $this->mergeConfigFrom("{$configDir}/{$configName}.php", 'generic-file.' . $configName); } }
php
public function boot() { $configurations = [ 'handlers-base', 'handlers-filters', 'http', 'store', ]; $configDir = __DIR__.'/config'; foreach ($configurations as $configName) { $this->publishes(["{$configDir}/{$configName}.php" => config_path("generic-file/{$configName}.php")]); $this->mergeConfigFrom("{$configDir}/{$configName}.php", 'generic-file.' . $configName); } }
Bootstrap the application events.
https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/LaravelGenericFileServiceProvider.php#L20-L35
ideil/laravel-generic-file
src/LaravelGenericFileServiceProvider.php
LaravelGenericFileServiceProvider.register
public function register() { $this->app->singleton('generic-file', function ($app) { $config = config('generic-file'); if (empty($config)) { throw new Exception('LaravelGenericFile not configured. Please run "php artisan vendor:publish"'); } return new GenericFile($config); }); }
php
public function register() { $this->app->singleton('generic-file', function ($app) { $config = config('generic-file'); if (empty($config)) { throw new Exception('LaravelGenericFile not configured. Please run "php artisan vendor:publish"'); } return new GenericFile($config); }); }
Register the service provider.
https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/LaravelGenericFileServiceProvider.php#L40-L51
phramework/phramework
src/Models/Request.php
Request.checkPermission
public static function checkPermission($userId = false) { $user = \Phramework\Phramework::getUser(); //If user is not authenticated throw an \Exception if (!$user) { throw new \Phramework\Exceptions\UnauthorizedException(); } //Check if speficied user is same as current user if ($userId !== false && $user->id != $userId) { throw new PermissionException( 'Insufficient permissions' ); } return $user; }
php
public static function checkPermission($userId = false) { $user = \Phramework\Phramework::getUser(); //If user is not authenticated throw an \Exception if (!$user) { throw new \Phramework\Exceptions\UnauthorizedException(); } //Check if speficied user is same as current user if ($userId !== false && $user->id != $userId) { throw new PermissionException( 'Insufficient permissions' ); } return $user; }
Check if current request is authenticated Optionaly it checks the authenticated user has a specific user_id @param integer $userId *[Optional]* Check if current user has the same id with $userId @return object Returns the user object @throws \Phramework\Exceptions\PermissionException @throws \Phramework\Exceptions\UnauthorizedException
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Request.php#L46-L63
phramework/phramework
src/Models/Request.php
Request.requireParameters
public static function requireParameters($parameters, $required) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } $missing = []; if (!is_array($required)) { $required = [$required]; } foreach ($required as $key) { if (!isset($parameters[$key])) { array_push($missing, $key); } } if (count($missing)) { throw new MissingParametersException($missing); } }
php
public static function requireParameters($parameters, $required) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } $missing = []; if (!is_array($required)) { $required = [$required]; } foreach ($required as $key) { if (!isset($parameters[$key])) { array_push($missing, $key); } } if (count($missing)) { throw new MissingParametersException($missing); } }
Check if required parameters are set @param array|object $parameters Request's parameters @param string|array $required The required parameters @throws \Phramework\Exceptions\MissingParametersException
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Request.php#L71-L93
phramework/phramework
src/Models/Request.php
Request.resourceId
public static function resourceId($parameters, $UINTEGER = true) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } //Check if is set AND validate if (isset($parameters['resource_id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['resource_id']) !== false ) { if ($UINTEGER) { return UnsignedIntegerValidator::parseStatic($parameters['resource_id']); } return $parameters['resource_id']; } if (isset($parameters['id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['id']) !== false ) { if ($UINTEGER) { return UnsignedIntegerValidator::parseStatic($parameters['id']); } return $parameters['id']; } return false; }
php
public static function resourceId($parameters, $UINTEGER = true) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } //Check if is set AND validate if (isset($parameters['resource_id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['resource_id']) !== false ) { if ($UINTEGER) { return UnsignedIntegerValidator::parseStatic($parameters['resource_id']); } return $parameters['resource_id']; } if (isset($parameters['id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['id']) !== false ) { if ($UINTEGER) { return UnsignedIntegerValidator::parseStatic($parameters['id']); } return $parameters['id']; } return false; }
Require id parameter if it's set else return NULL, it uses `resource_id` or `id` parameter if available @param array|object $parameters The request parameters @param boolean $UINTEGER *[Optional]*, Check id's type to be unsigned integer @throws \Phramework\Exceptions\IncorrectParameters When value is not correct @return string|integer Returns the id or NULL if not set, if $UINTEGER the returned value will be converted to unsigned integer
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Request.php#L103-L129
phramework/phramework
src/Models/Request.php
Request.requireId
public static function requireId($parameters, $UINTEGER = true) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } if (isset($parameters['resource_id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['resource_id']) !== false ) { $parameters['id'] = $parameters['resource_id']; } if (!isset($parameters['id'])) { throw new MissingParametersException(['id']); } //Validate as unsigned integer if ($UINTEGER && filter_var($parameters['id'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) === false ) { throw new IncorrectParametersException(['id']); } elseif (!$UINTEGER && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['id']) === false ) { //Validate as alphanumeric throw new IncorrectParametersException(['id']); } return ($UINTEGER ? intval($parameters['id']) : $parameters['id']); }
php
public static function requireId($parameters, $UINTEGER = true) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } if (isset($parameters['resource_id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['resource_id']) !== false ) { $parameters['id'] = $parameters['resource_id']; } if (!isset($parameters['id'])) { throw new MissingParametersException(['id']); } //Validate as unsigned integer if ($UINTEGER && filter_var($parameters['id'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) === false ) { throw new IncorrectParametersException(['id']); } elseif (!$UINTEGER && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['id']) === false ) { //Validate as alphanumeric throw new IncorrectParametersException(['id']); } return ($UINTEGER ? intval($parameters['id']) : $parameters['id']); }
Require id parameter, it uses `resource_id` or `id` parameter if available @param array|object $parameters The request paramters @param boolean $UINTEGER *[Optional]*, Check id's type to be unsigned integer, default is true @throws \Phramework\Exceptions\IncorrectParameters When value is not correct @throws \Phramework\Exceptions\MissingParametersException When id is missing if $UINTEGER the returned value will be converted to unsigned integer
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Request.php#L139-L167
phramework/phramework
src/Models/Request.php
Request.parseModel
public static function parseModel($parameters, $model) { if (is_object($parameters)) { $parameters = (array)$parameters; } $required_fields = []; foreach ($model as $key => $value) { if (in_array('required', $value, true) === true || in_array('required', $value, true) == true) { $required_fields[] = $key; } } Request::requireParameters($parameters, $required_fields); \Phramework\Validate\Validate::model($parameters, $model); $keys_values = []; foreach ($model as $key => $value) { if (isset($parameters[$key])) { if (in_array('nullable', $value) && $parameters[$key] == '0') { $keys_values[$key] = null; continue; } //Set value as null if (in_array('nullable', $value) && !$parameters[$key]) { $keys_values[$key] = null; continue; } /* if ($value['type'] == 'select' && !$parameters[$key]) { $keys_values[$key] = NULL; } else {*/ $keys_values[$key] = $parameters[$key]; /*}*/ } elseif (($value['type'] == 'boolean' || in_array('boolean', $value)) && (!isset($parameters[$key]) || !$parameters[$key])) { $keys_values[$key] = false; } } return $keys_values; }
php
public static function parseModel($parameters, $model) { if (is_object($parameters)) { $parameters = (array)$parameters; } $required_fields = []; foreach ($model as $key => $value) { if (in_array('required', $value, true) === true || in_array('required', $value, true) == true) { $required_fields[] = $key; } } Request::requireParameters($parameters, $required_fields); \Phramework\Validate\Validate::model($parameters, $model); $keys_values = []; foreach ($model as $key => $value) { if (isset($parameters[$key])) { if (in_array('nullable', $value) && $parameters[$key] == '0') { $keys_values[$key] = null; continue; } //Set value as null if (in_array('nullable', $value) && !$parameters[$key]) { $keys_values[$key] = null; continue; } /* if ($value['type'] == 'select' && !$parameters[$key]) { $keys_values[$key] = NULL; } else {*/ $keys_values[$key] = $parameters[$key]; /*}*/ } elseif (($value['type'] == 'boolean' || in_array('boolean', $value)) && (!isset($parameters[$key]) || !$parameters[$key])) { $keys_values[$key] = false; } } return $keys_values; }
Required required values and parse provided parameters into an array Validate the provided request model and return the @uses \Phramework\Models\Request::requireParameters @param array|object $parameters @param array $model @return array Return the keys => values collection @deprecated since 1.0.0
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Request.php#L178-L220
keeko/framework
src/utils/NameUtils.php
NameUtils.toStudlyCase
public static function toStudlyCase($input) { $input = trim($input, '-_'); return ucfirst(preg_replace_callback('/([A-Z-_][a-z]+)/', function($matches) { return ucfirst(str_replace(['-','_'], '',$matches[0])); }, $input)); }
php
public static function toStudlyCase($input) { $input = trim($input, '-_'); return ucfirst(preg_replace_callback('/([A-Z-_][a-z]+)/', function($matches) { return ucfirst(str_replace(['-','_'], '',$matches[0])); }, $input)); }
Transforms a given input into StudlyCase @param string $input @return string
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/utils/NameUtils.php#L14-L19
keeko/framework
src/utils/NameUtils.php
NameUtils.pluralize
public static function pluralize($input) { if (self::$pluralizer === null) { self::$pluralizer = new StandardEnglishSingularizer(); } return self::$pluralizer->getPluralForm($input); }
php
public static function pluralize($input) { if (self::$pluralizer === null) { self::$pluralizer = new StandardEnglishSingularizer(); } return self::$pluralizer->getPluralForm($input); }
Returns the plural form of the input @param string $input @return string
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/utils/NameUtils.php#L67-L73
keeko/framework
src/utils/NameUtils.php
NameUtils.singularize
public static function singularize($input) { if (self::$pluralizer === null) { self::$pluralizer = new StandardEnglishSingularizer(); } return self::$pluralizer->getSingularForm($input); }
php
public static function singularize($input) { if (self::$pluralizer === null) { self::$pluralizer = new StandardEnglishSingularizer(); } return self::$pluralizer->getSingularForm($input); }
Returns the singular form of the input @param string $input @return string
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/utils/NameUtils.php#L81-L87
znframework/package-pagination
Paginator.php
Paginator.linkNames
public function linkNames(String $prev, String $next, String $first, String $last) : Paginator { $this->settings['prevName'] = $prev; $this->settings['nextName'] = $next; $this->settings['firstName'] = $first; $this->settings['lastName'] = $last; return $this; }
php
public function linkNames(String $prev, String $next, String $first, String $last) : Paginator { $this->settings['prevName'] = $prev; $this->settings['nextName'] = $next; $this->settings['firstName'] = $first; $this->settings['lastName'] = $last; return $this; }
Change the names of links. @param string $prev @param string $next @param string $first @param string $last @return Paginator
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L237-L245
znframework/package-pagination
Paginator.php
Paginator.settings
public function settings(Array $config = []) : Paginator { foreach( $config as $key => $value ) { $this->$key = $value; } $this->class = array_merge($this->config['class'], $this->class ?? []); $this->style = array_merge($this->config['style'], $this->style ?? []); if( isset($config['url']) && $this->type !== 'ajax' ) { $this->url = Base::suffix(URL::site($config['url'])); } elseif( $this->type === 'ajax' ) { $this->url = 'javascript:;'; } else { $this->url = CURRENT_CFURL; } return $this; }
php
public function settings(Array $config = []) : Paginator { foreach( $config as $key => $value ) { $this->$key = $value; } $this->class = array_merge($this->config['class'], $this->class ?? []); $this->style = array_merge($this->config['style'], $this->style ?? []); if( isset($config['url']) && $this->type !== 'ajax' ) { $this->url = Base::suffix(URL::site($config['url'])); } elseif( $this->type === 'ajax' ) { $this->url = 'javascript:;'; } else { $this->url = CURRENT_CFURL; } return $this; }
Configures all settings of the page. @param array $cofig = [] @return Paginator
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L308-L332
znframework/package-pagination
Paginator.php
Paginator.create
public function create($start = NULL, Array $settings = []) : String { # The configuration arrays are merge. $settings = array_merge($this->config, $this->settings, $settings); # If the configuration is present, it is rearranged. if( ! empty($settings) ) { $this->settings($settings); } # Gets information about which recording to start the paging process. $startRowNumber = $this->getStartRowNumber($start); # If the limit is set to 0, 1 is accepted. $this->limit = $this->limit === 0 ? 1 : $this->limit; # Generate pagination bar. if( $this->isPaginationBar() ) { return $this->isBasicPaginationBar() ? $this->createBasicPaginationBar($startRowNumber) : $this->createAdvancedPaginationBar($startRowNumber); } return false; }
php
public function create($start = NULL, Array $settings = []) : String { # The configuration arrays are merge. $settings = array_merge($this->config, $this->settings, $settings); # If the configuration is present, it is rearranged. if( ! empty($settings) ) { $this->settings($settings); } # Gets information about which recording to start the paging process. $startRowNumber = $this->getStartRowNumber($start); # If the limit is set to 0, 1 is accepted. $this->limit = $this->limit === 0 ? 1 : $this->limit; # Generate pagination bar. if( $this->isPaginationBar() ) { return $this->isBasicPaginationBar() ? $this->createBasicPaginationBar($startRowNumber) : $this->createAdvancedPaginationBar($startRowNumber); } return false; }
Creates the pagination. @param mixed $start @param array $settings = [] @return string
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L342-L366
znframework/package-pagination
Paginator.php
Paginator.createBasicPaginationBar
protected function createBasicPaginationBar($startRowNumber) { # Add prev link. if( $this->isPrevLink($startRowNumber) ) { $this->addPrevLink($startRowNumber, $prevLink); } # Remove prev link. else { $this->removeLinkFromPagingationBar($prevLink); } # Add next link. if( $this->isNextLink($this->getPerPage(), $startRowNumber) ) { $this->addNextLink($startRowNumber, $nextLink); } # Remove next link. else { $this->removeLinkFromPagingationBar($nextLink); } # Generate pagination bar. return $this->generatePaginationBar($prevLink, $this->getNumberLinks($this->getPerPage(), $startRowNumber), $nextLink); }
php
protected function createBasicPaginationBar($startRowNumber) { # Add prev link. if( $this->isPrevLink($startRowNumber) ) { $this->addPrevLink($startRowNumber, $prevLink); } # Remove prev link. else { $this->removeLinkFromPagingationBar($prevLink); } # Add next link. if( $this->isNextLink($this->getPerPage(), $startRowNumber) ) { $this->addNextLink($startRowNumber, $nextLink); } # Remove next link. else { $this->removeLinkFromPagingationBar($nextLink); } # Generate pagination bar. return $this->generatePaginationBar($prevLink, $this->getNumberLinks($this->getPerPage(), $startRowNumber), $nextLink); }
Protected create basic pagination bar
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L371-L397
znframework/package-pagination
Paginator.php
Paginator.createAdvancedPaginationBar
protected function createAdvancedPaginationBar($startRowNumber) { # Add prev link. if( $this->isAdvancedPrevLink($startRowNumber) ) { $this->addPrevLink($startRowNumber, $prevLink); } # Remove prev link. else { $this->removeLinkFromPagingationBar($prevLink); } # Add first, next, last links. if( $this->isAdvancedNextLink($startRowNumber) ) { $this->addNextLink($startRowNumber, $nextLink); $this->addLastLink($lastLink); $pageIndex = $this->getPageIndex($startRowNumber); } # Remove next, last links. else { $this->removeLinkFromPagingationBar($nextLink); $this->removeLinkFromPagingationBar($lastLink); $pageIndex = $this->getPageIndexWithoutNextLinks(); } # On the first page, remove the first link. if( $this->isFirstLink($startRowNumber, $pageIndex) ) { $this->removeLinkFromPagingationBar($firstLink); } else { $this->addFirstLink($firstLink); } $advancedPerPage = $this->getAdvancedPerPage($pageIndex, $nextLink, $lastLink); return $this->generatePaginationBar($firstLink, $prevLink, $this->getNumberLinks($advancedPerPage, $startRowNumber, $pageIndex), $nextLink, $lastLink); }
php
protected function createAdvancedPaginationBar($startRowNumber) { # Add prev link. if( $this->isAdvancedPrevLink($startRowNumber) ) { $this->addPrevLink($startRowNumber, $prevLink); } # Remove prev link. else { $this->removeLinkFromPagingationBar($prevLink); } # Add first, next, last links. if( $this->isAdvancedNextLink($startRowNumber) ) { $this->addNextLink($startRowNumber, $nextLink); $this->addLastLink($lastLink); $pageIndex = $this->getPageIndex($startRowNumber); } # Remove next, last links. else { $this->removeLinkFromPagingationBar($nextLink); $this->removeLinkFromPagingationBar($lastLink); $pageIndex = $this->getPageIndexWithoutNextLinks(); } # On the first page, remove the first link. if( $this->isFirstLink($startRowNumber, $pageIndex) ) { $this->removeLinkFromPagingationBar($firstLink); } else { $this->addFirstLink($firstLink); } $advancedPerPage = $this->getAdvancedPerPage($pageIndex, $nextLink, $lastLink); return $this->generatePaginationBar($firstLink, $prevLink, $this->getNumberLinks($advancedPerPage, $startRowNumber, $pageIndex), $nextLink, $lastLink); }
Protected create advanced pagination bar
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L402-L445
znframework/package-pagination
Paginator.php
Paginator.addLastLink
protected function addLastLink(&$lastLink) { $lastLink = $this->getLink($this->calculatePageRowNumberForLastLink(), $this->getStyleClassAttributes('last'), $this->lastName); }
php
protected function addLastLink(&$lastLink) { $lastLink = $this->getLink($this->calculatePageRowNumberForLastLink(), $this->getStyleClassAttributes('last'), $this->lastName); }
Protected get last link
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L487-L490
znframework/package-pagination
Paginator.php
Paginator.addPrevLink
protected function addPrevLink($startRowNumber, &$prevLink) { $prevLink = $this->getLink($this->decrementPageRowNumber($startRowNumber), $this->getStyleClassAttributes('prev'), $this->prevName); }
php
protected function addPrevLink($startRowNumber, &$prevLink) { $prevLink = $this->getLink($this->decrementPageRowNumber($startRowNumber), $this->getStyleClassAttributes('prev'), $this->prevName); }
Protected get prev link
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L495-L498
znframework/package-pagination
Paginator.php
Paginator.addNextLink
protected function addNextLink($startRowNumber, &$nextLink) { $nextLink = $this->getLink($this->incrementPageRowNumber($startRowNumber), $this->getStyleClassAttributes('next'), $this->nextName); }
php
protected function addNextLink($startRowNumber, &$nextLink) { $nextLink = $this->getLink($this->incrementPageRowNumber($startRowNumber), $this->getStyleClassAttributes('next'), $this->nextName); }
Protected get advanced next link
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L503-L506
znframework/package-pagination
Paginator.php
Paginator.getStartRowNumber
protected function getStartRowNumber($start) { if( $this->start !== NULL ) { $start = (int) $this->start; } if( empty($start) && ! is_numeric($start) ) { return ! is_numeric($segment = URI::segment(-1)) ? 0 : $segment; } return ! is_numeric($start) ? 0 : $start; }
php
protected function getStartRowNumber($start) { if( $this->start !== NULL ) { $start = (int) $this->start; } if( empty($start) && ! is_numeric($start) ) { return ! is_numeric($segment = URI::segment(-1)) ? 0 : $segment; } return ! is_numeric($start) ? 0 : $start; }
Protected get start row number
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L511-L524
znframework/package-pagination
Paginator.php
Paginator.getAdvancedPerPage
protected function getAdvancedPerPage($pageIndex, &$nextLink, &$lastLink) { $perPage = $this->countLinks + $pageIndex - 1; if( $perPage >= ($getPerPage = $this->getPerPage()) ) { $this->removeLinkFromPagingationBar($nextLink); $this->removeLinkFromPagingationBar($lastLink); $perPage = $getPerPage; } return $perPage; }
php
protected function getAdvancedPerPage($pageIndex, &$nextLink, &$lastLink) { $perPage = $this->countLinks + $pageIndex - 1; if( $perPage >= ($getPerPage = $this->getPerPage()) ) { $this->removeLinkFromPagingationBar($nextLink); $this->removeLinkFromPagingationBar($lastLink); $perPage = $getPerPage; } return $perPage; }
Protected advanced per page.
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L545-L558
znframework/package-pagination
Paginator.php
Paginator.getNumberLinks
protected function getNumberLinks($perPage, $startRowNumber, $startIndexNumber = 1) { $numberLinks = NULL; for( $i = $startIndexNumber; $i <= $perPage; $i++ ) { $page = ($i - 1) * $this->limit; if( $i - 1 == floor((int) $startRowNumber / $this->limit) ) { $currentLink = $this->getStyleClassAttributes('current'); } else { $currentLink = $this->getStyleClassLinkAttributes('links');; } $numberLinks .= $this->getLink($page, $currentLink, $i); } return $numberLinks; }
php
protected function getNumberLinks($perPage, $startRowNumber, $startIndexNumber = 1) { $numberLinks = NULL; for( $i = $startIndexNumber; $i <= $perPage; $i++ ) { $page = ($i - 1) * $this->limit; if( $i - 1 == floor((int) $startRowNumber / $this->limit) ) { $currentLink = $this->getStyleClassAttributes('current'); } else { $currentLink = $this->getStyleClassLinkAttributes('links');; } $numberLinks .= $this->getLink($page, $currentLink, $i); } return $numberLinks; }
Protected get number links
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L611-L632
znframework/package-pagination
Paginator.php
Paginator.calculatePageRowNumberForLastLink
protected function calculatePageRowNumberForLastLink() { $mod = $this->totalRows % $this->limit; return ($this->totalRows - $mod ) - ($mod == 0 ? $this->limit : 0); }
php
protected function calculatePageRowNumberForLastLink() { $mod = $this->totalRows % $this->limit; return ($this->totalRows - $mod ) - ($mod == 0 ? $this->limit : 0); }
Protected page row number for last link
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L653-L658
znframework/package-pagination
Paginator.php
Paginator.checkGetRequest
protected function checkGetRequest($page) { $this->url .= $this->explodeRequestGetValue(); if( strstr($this->url, '?') ) { $urlEx = explode('?', $this->url); return Base::suffix($urlEx[0]) . $page . '?' . rtrim($urlEx[1], '/'); } return $this->type === 'ajax' ? $this->url : Base::suffix($this->url) . $page; }
php
protected function checkGetRequest($page) { $this->url .= $this->explodeRequestGetValue(); if( strstr($this->url, '?') ) { $urlEx = explode('?', $this->url); return Base::suffix($urlEx[0]) . $page . '?' . rtrim($urlEx[1], '/'); } return $this->type === 'ajax' ? $this->url : Base::suffix($this->url) . $page; }
Protected check get request
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L697-L709
znframework/package-pagination
Paginator.php
Paginator.getLink
protected function getLink($var, $fix, $val) { return $this->getHtmlLiElement($this->getHtmlAnchorElement($var, $fix, $val), $fix); }
php
protected function getLink($var, $fix, $val) { return $this->getHtmlLiElement($this->getHtmlAnchorElement($var, $fix, $val), $fix); }
Protected get link
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L714-L717
znframework/package-pagination
Paginator.php
Paginator.getHtmlAnchorElement
protected function getHtmlAnchorElement($var, $attr, $val) { if( $this->output === 'bootstrap' ) { $attr = NULL; } return '<a href="'.$this->checkGetRequest($var).'"'.$this->getAttributesForAjaxProcess($var).$attr.'>'.$val.'</a>'; }
php
protected function getHtmlAnchorElement($var, $attr, $val) { if( $this->output === 'bootstrap' ) { $attr = NULL; } return '<a href="'.$this->checkGetRequest($var).'"'.$this->getAttributesForAjaxProcess($var).$attr.'>'.$val.'</a>'; }
Protected get html anchor element
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L722-L730
znframework/package-pagination
Paginator.php
Paginator.generatePaginationBar
protected function generatePaginationBar(...$numberLinks) { $links = $this->implodeLinks(...$numberLinks); if( $this->output === 'bootstrap' ) { return '<ul class="pagination">' . $links . '</ul>'; } return $links; }
php
protected function generatePaginationBar(...$numberLinks) { $links = $this->implodeLinks(...$numberLinks); if( $this->output === 'bootstrap' ) { return '<ul class="pagination">' . $links . '</ul>'; } return $links; }
Protected get html ul element
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L748-L758
znframework/package-pagination
Paginator.php
Paginator.getStyleLinkAttribute
protected function getStyleLinkAttribute($var, $type = 'style') { $getAttribute = ( ! empty($this->{$type}[$var]) ) ? $this->{$type}[$var] . ' ' : ''; if( $type === 'class' ) { $this->classAttribute = $getAttribute; } else { $this->styleAttribute = $getAttribute; } return $this->createAttribute($getAttribute, $type); }
php
protected function getStyleLinkAttribute($var, $type = 'style') { $getAttribute = ( ! empty($this->{$type}[$var]) ) ? $this->{$type}[$var] . ' ' : ''; if( $type === 'class' ) { $this->classAttribute = $getAttribute; } else { $this->styleAttribute = $getAttribute; } return $this->createAttribute($getAttribute, $type); }
Protected get style link attribute
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L763-L777
znframework/package-pagination
Paginator.php
Paginator.getClassAttribute
protected function getClassAttribute($var, $type = 'class') { $status = trim(( $type === 'class' ? $this->classAttribute : $this->styleAttribute) . $this->{$type}[$var]); return $this->createAttribute($status, $type); }
php
protected function getClassAttribute($var, $type = 'class') { $status = trim(( $type === 'class' ? $this->classAttribute : $this->styleAttribute) . $this->{$type}[$var]); return $this->createAttribute($status, $type); }
Protected get class attribute
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L790-L795
znframework/package-pagination
Paginator.php
Paginator.createAttribute
protected function createAttribute($condition, $key, $value = NULL) { return ! empty($condition) ? ' ' . $key . '="' . trim($value ?? $condition) . '"' : ''; }
php
protected function createAttribute($condition, $key, $value = NULL) { return ! empty($condition) ? ' ' . $key . '="' . trim($value ?? $condition) . '"' : ''; }
Protcted create attribute
https://github.com/znframework/package-pagination/blob/43549d3c7d1783d0d92195384f0cc2b0f73c1693/Paginator.php#L800-L803
phavour/phavour
Phavour/Runnable.php
Runnable.finalise
final public function finalise() { if ($this->view->isEnabled()) { $this->view->setResponse($this->response); $this->view->render(); } return true; }
php
final public function finalise() { if ($this->view->isEnabled()) { $this->view->setResponse($this->response); $this->view->render(); } return true; }
Called at the end of the process. @return boolean
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable.php#L199-L206
phavour/phavour
Phavour/Runnable.php
Runnable.urlFor
final public function urlFor($routeName, array $params = array()) { if (null === $this->router) { return ''; } return $this->router->urlFor($routeName, $params); }
php
final public function urlFor($routeName, array $params = array()) { if (null === $this->router) { return ''; } return $this->router->urlFor($routeName, $params); }
Get a route path by a given name @param string $routeName @param array $params (optional) @return string
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable.php#L214-L221
phavour/phavour
Phavour/Runnable.php
Runnable.notFound
public function notFound($package = 'DefaultPackage', $class = 'Error', $method = 'notFound') { $this->response->setStatus(404); $this->view->setPackage($package); $this->view->setClass($class); $this->view->setScriptName($method); return; }
php
public function notFound($package = 'DefaultPackage', $class = 'Error', $method = 'notFound') { $this->response->setStatus(404); $this->view->setPackage($package); $this->view->setClass($class); $this->view->setScriptName($method); return; }
When you need to send a not found in your runnable, you can call this directly. Optionally, you can specify the package name, class name, and method name to render accordingly. @param sring $package (optional) default 'DefaultPackage' @param sring $class (optional) default 'Error' @param sring $method (optional) default 'notFound' @return void
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable.php#L233-L240
weew/error-handler
src/Weew/ErrorHandler/Handlers/NativeErrorHandler.php
NativeErrorHandler.handle
public function handle(IError $error) { $handled = $this->invokeHandler($this->getHandler(), $error); return $handled === true ? true : false; }
php
public function handle(IError $error) { $handled = $this->invokeHandler($this->getHandler(), $error); return $handled === true ? true : false; }
@param IError $error @return bool
https://github.com/weew/error-handler/blob/883ac0b2cb6c83f177abdd61dfa33eaaa7b23043/src/Weew/ErrorHandler/Handlers/NativeErrorHandler.php#L53-L57
liufee/cms-core
backend/widgets/ueditor/Uploader.php
Uploader.upFile
private function upFile() { $file = $this->file = $_FILES[$this->fileField]; if (! $file) { $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND"); return; } if ($this->file['error']) { $this->stateInfo = $this->getStateInfo($file['error']); return; } else { if (! file_exists($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND"); return; } else { if (! is_uploaded_file($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE"); return; } } } $this->oriName = $file['name']; $this->fileSize = $file['size']; $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //检查是否不允许的文件格式 if (! $this->checkType()) { $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
php
private function upFile() { $file = $this->file = $_FILES[$this->fileField]; if (! $file) { $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND"); return; } if ($this->file['error']) { $this->stateInfo = $this->getStateInfo($file['error']); return; } else { if (! file_exists($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND"); return; } else { if (! is_uploaded_file($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE"); return; } } } $this->oriName = $file['name']; $this->fileSize = $file['size']; $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //检查是否不允许的文件格式 if (! $this->checkType()) { $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
上传文件的主处理方法 @return mixed
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/Uploader.php#L94-L153
liufee/cms-core
backend/widgets/ueditor/Uploader.php
Uploader.upBase64
private function upBase64() { $base64Data = $_POST[$this->fileField]; $img = base64_decode($base64Data); $this->oriName = $this->config['oriName']; $this->fileSize = strlen($img); $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
php
private function upBase64() { $base64Data = $_POST[$this->fileField]; $img = base64_decode($base64Data); $this->oriName = $this->config['oriName']; $this->fileSize = strlen($img); $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
处理base64编码的图片上传 @return mixed
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/Uploader.php#L160-L197
liufee/cms-core
backend/widgets/ueditor/Uploader.php
Uploader.saveRemote
private function saveRemote() { $imgUrl = htmlspecialchars($this->fileField); $imgUrl = str_replace("&amp;", "&", $imgUrl); //http开头验证 if (strpos($imgUrl, "http") !== 0) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK"); return; } preg_match('/(^https?:\/\/[^:\/]+)/', $imgUrl, $matches); $host_with_protocol = count($matches) > 1 ? $matches[1] : ''; // 判断是否是合法 url if (! filter_var($host_with_protocol, FILTER_VALIDATE_URL)) { $this->stateInfo = $this->getStateInfo("INVALID_URL"); return; } preg_match('/^https?:\/\/(.+)/', $host_with_protocol, $matches); $host_without_protocol = count($matches) > 1 ? $matches[1] : ''; // 此时提取出来的可能是 IP 也有可能是域名,先获取 IP $ip = gethostbyname($host_without_protocol); // 判断是否允许私有 IP if (! $this->allowIntranet && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { $this->stateInfo = $this->getStateInfo("INVALID_IP"); return; } //获取请求头并检测死链 $heads = get_headers($imgUrl, 1); if (! (stristr($heads[0], "200") && stristr($heads[0], "OK"))) { $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK"); return; } //格式验证(扩展名验证和Content-Type验证) $fileType = strtolower(strrchr($imgUrl, '.')); if (! in_array($fileType, $this->config['allowFiles']) || ! isset($heads['Content-Type']) || ! stristr($heads['Content-Type'], "image")) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE"); return; } //打开输出缓冲区并获取远程图片 ob_start(); $context = stream_context_create([ 'http' => [ 'follow_location' => false // don't follow redirects ] ]); readfile($imgUrl, false, $context); $img = ob_get_contents(); ob_end_clean(); preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m); $this->oriName = $m ? $m[1] : ""; $this->fileSize = strlen($img); $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
php
private function saveRemote() { $imgUrl = htmlspecialchars($this->fileField); $imgUrl = str_replace("&amp;", "&", $imgUrl); //http开头验证 if (strpos($imgUrl, "http") !== 0) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK"); return; } preg_match('/(^https?:\/\/[^:\/]+)/', $imgUrl, $matches); $host_with_protocol = count($matches) > 1 ? $matches[1] : ''; // 判断是否是合法 url if (! filter_var($host_with_protocol, FILTER_VALIDATE_URL)) { $this->stateInfo = $this->getStateInfo("INVALID_URL"); return; } preg_match('/^https?:\/\/(.+)/', $host_with_protocol, $matches); $host_without_protocol = count($matches) > 1 ? $matches[1] : ''; // 此时提取出来的可能是 IP 也有可能是域名,先获取 IP $ip = gethostbyname($host_without_protocol); // 判断是否允许私有 IP if (! $this->allowIntranet && ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { $this->stateInfo = $this->getStateInfo("INVALID_IP"); return; } //获取请求头并检测死链 $heads = get_headers($imgUrl, 1); if (! (stristr($heads[0], "200") && stristr($heads[0], "OK"))) { $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK"); return; } //格式验证(扩展名验证和Content-Type验证) $fileType = strtolower(strrchr($imgUrl, '.')); if (! in_array($fileType, $this->config['allowFiles']) || ! isset($heads['Content-Type']) || ! stristr($heads['Content-Type'], "image")) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE"); return; } //打开输出缓冲区并获取远程图片 ob_start(); $context = stream_context_create([ 'http' => [ 'follow_location' => false // don't follow redirects ] ]); readfile($imgUrl, false, $context); $img = ob_get_contents(); ob_end_clean(); preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m); $this->oriName = $m ? $m[1] : ""; $this->fileSize = strlen($img); $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (! $this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //创建目录失败 if (! file_exists($dirname) && ! mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else { if (! is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } } //移动文件 if (! (file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
拉取远程图片 @return mixed
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/Uploader.php#L204-L294
liufee/cms-core
backend/widgets/ueditor/Uploader.php
Uploader.getFileInfo
public function getFileInfo() { $prefix = str_replace(yii::getAlias(yii::getAlias('@frontend/web')), '', yii::getAlias('@ueditor')); return array( "state" => $this->stateInfo, "url" => $prefix . $this->fullName, "title" => $this->fileName, "original" => $this->oriName, "type" => $this->fileType, "size" => $this->fileSize ); }
php
public function getFileInfo() { $prefix = str_replace(yii::getAlias(yii::getAlias('@frontend/web')), '', yii::getAlias('@ueditor')); return array( "state" => $this->stateInfo, "url" => $prefix . $this->fullName, "title" => $this->fileName, "original" => $this->oriName, "type" => $this->fileType, "size" => $this->fileSize ); }
获取当前上传成功文件的各项信息 @return array
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/Uploader.php#L406-L417
tanmotop/laravel-api
src/Http/Response.php
Response.toResponse
public function toResponse($request) { if (!empty($this->resource)) { return $this->resource->response($request)->setStatusCode($this->status())->withHeaders($this->headers); } /// $data = [ 'status_code' => $this->getStatusCode(), 'message' => $this->getContent(), ]; if (!empty($this->meta)) { $data['meta'] = $this->meta; } if ($this->debug && !empty($this->debugData)) { $data['debug'] = $this->debugData; } return response()->json($data, $this->status())->withHeaders($this->headers); }
php
public function toResponse($request) { if (!empty($this->resource)) { return $this->resource->response($request)->setStatusCode($this->status())->withHeaders($this->headers); } /// $data = [ 'status_code' => $this->getStatusCode(), 'message' => $this->getContent(), ]; if (!empty($this->meta)) { $data['meta'] = $this->meta; } if ($this->debug && !empty($this->debugData)) { $data['debug'] = $this->debugData; } return response()->json($data, $this->status())->withHeaders($this->headers); }
Create an HTTP response that represents the object. @param \Illuminate\Http\Request $request @return $this|\Illuminate\Http\JsonResponse
https://github.com/tanmotop/laravel-api/blob/dc0f00e61c52744acdaf1a013e62500156f75828/src/Http/Response.php#L84-L105
brainexe/core
src/Middleware/Gentime.php
Gentime.processResponse
public function processResponse(Request $request, Response $response) { $startTime = $request->server->get('REQUEST_TIME_FLOAT'); $user = $request->attributes->get('user'); $username = $this->getUsername($user); $diff = microtime(true) - $startTime; $this->logger->info( sprintf( '%0.2fms - %s', $diff * 1000, $request->getRequestUri() ), [ 'channel' => 'gentime', 'time' => round($diff * 1000, 2), 'route' => $request->attributes->get('_route'), 'userName' => $username, 'userId' => $request->attributes->get('user_id') ] ); }
php
public function processResponse(Request $request, Response $response) { $startTime = $request->server->get('REQUEST_TIME_FLOAT'); $user = $request->attributes->get('user'); $username = $this->getUsername($user); $diff = microtime(true) - $startTime; $this->logger->info( sprintf( '%0.2fms - %s', $diff * 1000, $request->getRequestUri() ), [ 'channel' => 'gentime', 'time' => round($diff * 1000, 2), 'route' => $request->attributes->get('_route'), 'userName' => $username, 'userId' => $request->attributes->get('user_id') ] ); }
{@inheritdoc}
https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Middleware/Gentime.php#L36-L57
morrislaptop/error-tracker-adapter
src/Group/Chain.php
Chain.report
public function report(Exception $e, array $extra = []) { $exceptions = []; foreach ($this->trackers as $tracker) { try { return $tracker->report($e, $extra); } catch (Exception $exception) { $exceptions[] = $exception; } } throw new GroupNotReported(sprintf('Could not report: "%s".', $e->getMessage()), $exceptions); }
php
public function report(Exception $e, array $extra = []) { $exceptions = []; foreach ($this->trackers as $tracker) { try { return $tracker->report($e, $extra); } catch (Exception $exception) { $exceptions[] = $exception; } } throw new GroupNotReported(sprintf('Could not report: "%s".', $e->getMessage()), $exceptions); }
Reports the exception to the SaaS platform @param Exception $e @param array $extra @return mixed @throws ChainNoResult
https://github.com/morrislaptop/error-tracker-adapter/blob/955aea67c45892da2b8813517600f338bada6a01/src/Group/Chain.php#L17-L29
Boolive/Core
data/Entity.php
Entity.rule
protected function rule() { return Rule::arrays([ 'name' => Rule::string()->regexp('|^[^/@:#\\\\]*$|')->min(IS_INSTALL?1:0)->max(100)->required(), // Имя объекта без символов /@:#\ 'parent' => Rule::any(Rule::uri(), Rule::null()), // URI родителя 'proto' => Rule::any(Rule::uri(), Rule::null()), // URI прототипа 'author' => Rule::any(Rule::uri(), Rule::null()), // Автор (идентификатор объекта-пользователя) 'order' => Rule::int()->max(Entity::MAX_ORDER), // Порядковый номер. Уникален в рамках родителя 'created' => Rule::int(), // Дата создания в секундах 'updated' => Rule::int(), // Дата обновления в секундах 'value' => Rule::string()->max(65535), // Значение до 65535 сиволов //'is_file' => Rule::bool(), // Признак, привязан ли файл? 'is_draft' => Rule::bool(), // Признак, в черновике или нет? 'is_hidden' => Rule::bool(), // Признак, скрытый или нет? 'is_mandatory' => Rule::bool(), // Признак, обязательный или дополненый? 'is_property' => Rule::bool(), // Признак, свойство или самостоятельный объект? 'is_relative' => Rule::bool(), // Прототип относительный или нет? // 'is_completed' => Rule::bool(), // Признак, дополнен объект свойствами прототипа или нет? 'is_link' => Rule::bool(), // Ссылка или нет? 'is_default_value' => Rule::bool(), // Признак, используется значение прототипа или своё? 'is_default_file' => Rule::bool(), // Признак, используется файл прототипа или свой? 'is_default_logic' => Rule::bool(), // Признак, используется класс прототипа или свой? // Имя файла или сведения о загружаемом файле 'file' => Rule::any([ Rule::null(), Rule::string()->regexp('/[^\\/\\\\]+/ui'), // имя файла Rule::arrays([ 'tmp_name' => Rule::string(), // Путь на связываемый файл 'name' => Rule::lowercase()->ospatterns('*.*')->ignore('lowercase')->required(), // Имя файла, из которого будет взято расширение 'size' => Rule::int(), // Размер в байтах 'error' => Rule::int()->eq(0, true), // Код ошибки. Если 0, то ошибки нет 'type' => Rule::string(), // MIME тип файла //'content' => Rule::string() ]) ]), // // Сведения о классе объекта (загружаемый файл или программный код). Не является атрибутом объекта // 'logic' => Rule::arrays([ // 'content' => Rule::string(), // Программный код класса // 'tmp_name' => Rule::string(), // Путь на файл, если класс загржается в виде файла // 'size' => Rule::int(), // Размер в байтах // 'error' => Rule::int()->eq(0, true), // Код ошибки. Если 0, то ошибки нет // 'type' => Rule::string() // MIME тип файла // ]) ]); }
php
protected function rule() { return Rule::arrays([ 'name' => Rule::string()->regexp('|^[^/@:#\\\\]*$|')->min(IS_INSTALL?1:0)->max(100)->required(), // Имя объекта без символов /@:#\ 'parent' => Rule::any(Rule::uri(), Rule::null()), // URI родителя 'proto' => Rule::any(Rule::uri(), Rule::null()), // URI прототипа 'author' => Rule::any(Rule::uri(), Rule::null()), // Автор (идентификатор объекта-пользователя) 'order' => Rule::int()->max(Entity::MAX_ORDER), // Порядковый номер. Уникален в рамках родителя 'created' => Rule::int(), // Дата создания в секундах 'updated' => Rule::int(), // Дата обновления в секундах 'value' => Rule::string()->max(65535), // Значение до 65535 сиволов //'is_file' => Rule::bool(), // Признак, привязан ли файл? 'is_draft' => Rule::bool(), // Признак, в черновике или нет? 'is_hidden' => Rule::bool(), // Признак, скрытый или нет? 'is_mandatory' => Rule::bool(), // Признак, обязательный или дополненый? 'is_property' => Rule::bool(), // Признак, свойство или самостоятельный объект? 'is_relative' => Rule::bool(), // Прототип относительный или нет? // 'is_completed' => Rule::bool(), // Признак, дополнен объект свойствами прототипа или нет? 'is_link' => Rule::bool(), // Ссылка или нет? 'is_default_value' => Rule::bool(), // Признак, используется значение прототипа или своё? 'is_default_file' => Rule::bool(), // Признак, используется файл прототипа или свой? 'is_default_logic' => Rule::bool(), // Признак, используется класс прототипа или свой? // Имя файла или сведения о загружаемом файле 'file' => Rule::any([ Rule::null(), Rule::string()->regexp('/[^\\/\\\\]+/ui'), // имя файла Rule::arrays([ 'tmp_name' => Rule::string(), // Путь на связываемый файл 'name' => Rule::lowercase()->ospatterns('*.*')->ignore('lowercase')->required(), // Имя файла, из которого будет взято расширение 'size' => Rule::int(), // Размер в байтах 'error' => Rule::int()->eq(0, true), // Код ошибки. Если 0, то ошибки нет 'type' => Rule::string(), // MIME тип файла //'content' => Rule::string() ]) ]), // // Сведения о классе объекта (загружаемый файл или программный код). Не является атрибутом объекта // 'logic' => Rule::arrays([ // 'content' => Rule::string(), // Программный код класса // 'tmp_name' => Rule::string(), // Путь на файл, если класс загржается в виде файла // 'size' => Rule::int(), // Размер в байтах // 'error' => Rule::int()->eq(0, true), // Код ошибки. Если 0, то ошибки нет // 'type' => Rule::string() // MIME тип файла // ]) ]); }
Правило на атрибуты @return Rule
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L139-L183
Boolive/Core
data/Entity.php
Entity.uri
function uri($current = false) { if ($current && $this->is_changed('uri')){ return $this->changes('uri'); } return $this->_attributes['uri']; }
php
function uri($current = false) { if ($current && $this->is_changed('uri')){ return $this->changes('uri'); } return $this->_attributes['uri']; }
URI объекта @param bool $current Возвращать новый или текущий uri? @return string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L215-L221
Boolive/Core
data/Entity.php
Entity.name
function name($new = null, $choose_unique = false) { if (!isset($new) && $choose_unique) $new = $this->_attributes['name']; if (isset($new) && ($this->_attributes['name'] != $new || $choose_unique)){ // Фильтр имени $new = preg_replace('/\s/ui','_',$new); $this->change('name', $new); $this->change('uri', $this->parent().'/'.$new); $this->_auto_naming = $choose_unique; } return $this->_attributes['name']; }
php
function name($new = null, $choose_unique = false) { if (!isset($new) && $choose_unique) $new = $this->_attributes['name']; if (isset($new) && ($this->_attributes['name'] != $new || $choose_unique)){ // Фильтр имени $new = preg_replace('/\s/ui','_',$new); $this->change('name', $new); $this->change('uri', $this->parent().'/'.$new); $this->_auto_naming = $choose_unique; } return $this->_attributes['name']; }
Имя объекта @param null|string $new Новое имя @param bool $choose_unique Признак, подобрать ли уникальное имя. Если $new не указан, то будет подбираться постфик к текущему имени @return string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L229-L240
Boolive/Core
data/Entity.php
Entity.parent
function parent($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_parent = $new; $new = $new->uri(); }else{ $this->_parent = null; // for reloading } if ($new != $this->_attributes['parent']){ $this->change('parent', $new); $this->change('order', Entity::MAX_ORDER); $this->change('uri', $new.'/'.$this->_attributes['name']); } } if ($return_entity){ if (!isset($this->_parent)){ if (isset($this->_attributes['parent'])){ $this->_parent = Data::read($this->_attributes['parent']); }else{ $this->_parent = false; } } return $this->_parent; } return $this->_attributes['parent']; }
php
function parent($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_parent = $new; $new = $new->uri(); }else{ $this->_parent = null; // for reloading } if ($new != $this->_attributes['parent']){ $this->change('parent', $new); $this->change('order', Entity::MAX_ORDER); $this->change('uri', $new.'/'.$this->_attributes['name']); } } if ($return_entity){ if (!isset($this->_parent)){ if (isset($this->_attributes['parent'])){ $this->_parent = Data::read($this->_attributes['parent']); }else{ $this->_parent = false; } } return $this->_parent; } return $this->_attributes['parent']; }
Parent of this object @param null|string|Entity $new New parent. URI or object @param bool $return_entity Признак, возвращать объект вместо uri @return string|Entity|false
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L248-L274
Boolive/Core
data/Entity.php
Entity.proto
function proto($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_proto = $new; $new = $new->uri(); }else{ $this->_proto = null; // for reloading } if ($new != $this->_attributes['proto']){ $this->change('proto', $new); } } if ($return_entity){ if (!isset($this->_proto)){ if (isset($this->_attributes['proto'])){ $this->_proto = Data::read($this->_attributes['proto']); }else{ $this->_proto = false; } } return $this->_proto; } return $this->_attributes['proto']; }
php
function proto($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_proto = $new; $new = $new->uri(); }else{ $this->_proto = null; // for reloading } if ($new != $this->_attributes['proto']){ $this->change('proto', $new); } } if ($return_entity){ if (!isset($this->_proto)){ if (isset($this->_attributes['proto'])){ $this->_proto = Data::read($this->_attributes['proto']); }else{ $this->_proto = false; } } return $this->_proto; } return $this->_attributes['proto']; }
Prototype of this object @param null|string|Entity $new Новый прототип. URI или объект @param bool $return_entity Признак, возвращать объект вместо uri @return string|Entity|false
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L282-L306
Boolive/Core
data/Entity.php
Entity.author
function author($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_author = $new; $new = $new->uri(); }else{ $this->_author = null; // for reloading } if ($new != $this->_attributes['author']){ $this->change('author', $new); } } if ($return_entity){ if (!isset($this->_author)){ if (isset($this->_attributes['author'])){ $this->_author = Data::read($this->_attributes['author']); }else{ $this->_author = false; } } return $this->_author; } return $this->_attributes['author']; }
php
function author($new = null, $return_entity = false) { if (isset($new)){ if ($new instanceof Entity){ $this->_author = $new; $new = $new->uri(); }else{ $this->_author = null; // for reloading } if ($new != $this->_attributes['author']){ $this->change('author', $new); } } if ($return_entity){ if (!isset($this->_author)){ if (isset($this->_attributes['author'])){ $this->_author = Data::read($this->_attributes['author']); }else{ $this->_author = false; } } return $this->_author; } return $this->_attributes['author']; }
Author of this object @param null|string|Entity $new Новый автор. URI или объект @param bool $return_entity Признак, возвращать объект вместо uri @return mixed
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L314-L338
Boolive/Core
data/Entity.php
Entity.order
function order($new = null) { if (isset($new) && ($this->_attributes['order'] != $new)){ $this->change('order', (int)$new); } return $this->_attributes['order']; }
php
function order($new = null) { if (isset($new) && ($this->_attributes['order'] != $new)){ $this->change('order', (int)$new); } return $this->_attributes['order']; }
Порядковый номер @param int $new Новое порядковое значение @return int
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L345-L351
Boolive/Core
data/Entity.php
Entity.created
function created($new = null) { if (isset($new) && ($this->_attributes['created'] != $new)){ $this->change('created', (int)$new); } return $this->_attributes['created']; }
php
function created($new = null) { if (isset($new) && ($this->_attributes['created'] != $new)){ $this->change('created', (int)$new); } return $this->_attributes['created']; }
Дата создания в TIMESTAMP @param int $new Новая дата создания @return int
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L358-L364
Boolive/Core
data/Entity.php
Entity.updated
function updated($new = null) { if (isset($new) && ($this->_attributes['updated'] != $new)){ $this->change('updated', (int)$new); } return $this->_attributes['updated']; }
php
function updated($new = null) { if (isset($new) && ($this->_attributes['updated'] != $new)){ $this->change('updated', (int)$new); } return $this->_attributes['updated']; }
Дата последнего изменения в TIMESTAMP @param int $new Новая дата изменения @return int
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L371-L377
Boolive/Core
data/Entity.php
Entity.value
function value($new = null) { if (isset($new) && ((string)$this->_attributes['value'] != (string)$new)){ $this->change('value', $new); $this->change('is_default_value', false); $this->_def_value = null; } if (($proto = $this->is_default_value(null, true)) && $proto->is_exists()){ return $proto->value(); } return $this->_attributes['value']; }
php
function value($new = null) { if (isset($new) && ((string)$this->_attributes['value'] != (string)$new)){ $this->change('value', $new); $this->change('is_default_value', false); $this->_def_value = null; } if (($proto = $this->is_default_value(null, true)) && $proto->is_exists()){ return $proto->value(); } return $this->_attributes['value']; }
Значение @param mixed $new Новое значение. Если привязан файл, то имя файла без пути @return mixed
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L384-L395
Boolive/Core
data/Entity.php
Entity.file
function file($new = null, $root = false) { // Установка нового файла if (isset($new)){ if (empty($new)){ $this->change('file', ''); }else{ if (is_string($new)){ $new = [ 'tmp_name' => $new, 'name' => basename($new), 'size' => @filesize($new), 'error' => is_file($new)? 0 : true ]; } if (empty($new['name']) && $this->is_file()){ $new['name'] = $this->name().'.'.File::fileExtention($this->file()); } $this->change('file', $new); } $this->change('is_default_file', false); $this->_def_file = null; } // Возврат пути к текущему файлу, если есть if ($this->is_file()){ if (($proto = $this->is_default_file(null, true)) && $proto->is_exists()){ return $proto->file(null, $root); }else{ if (is_array($this->_attributes['file'])){ return $this->_attributes['file']; } return $this->dir($root).$this->_attributes['file']; } } return null; }
php
function file($new = null, $root = false) { // Установка нового файла if (isset($new)){ if (empty($new)){ $this->change('file', ''); }else{ if (is_string($new)){ $new = [ 'tmp_name' => $new, 'name' => basename($new), 'size' => @filesize($new), 'error' => is_file($new)? 0 : true ]; } if (empty($new['name']) && $this->is_file()){ $new['name'] = $this->name().'.'.File::fileExtention($this->file()); } $this->change('file', $new); } $this->change('is_default_file', false); $this->_def_file = null; } // Возврат пути к текущему файлу, если есть if ($this->is_file()){ if (($proto = $this->is_default_file(null, true)) && $proto->is_exists()){ return $proto->file(null, $root); }else{ if (is_array($this->_attributes['file'])){ return $this->_attributes['file']; } return $this->dir($root).$this->_attributes['file']; } } return null; }
Файл, ассоциированный с объектом @param null|array|string $new Информация о новом файле. Полный путь к новому файлу или сведения из $_FILES @param bool $root Возвращать полный путь или от директории сайта @return null|string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L403-L438
Boolive/Core
data/Entity.php
Entity.logic
function logic($new = null, $root = false) { if (isset($new)){ if (is_string($new)){ $new = array( 'tmp_name' => $new, 'size' => @filesize($new), 'error' => is_file($new)? 0 : true ); } $this->change('logic', $new); $this->change('is_default_logic', false); } if ($proto = $this->is_default_logic(null, true)){ $path = $proto->logic(null, $root); }else if ($this->_attributes['is_default_logic']) { $path = ($root ? DIR : '/').'vendor/boolive/core/data/Entity.php'; }else{ $path = $this->dir($root).$this->name().'.php'; } return $path; }
php
function logic($new = null, $root = false) { if (isset($new)){ if (is_string($new)){ $new = array( 'tmp_name' => $new, 'size' => @filesize($new), 'error' => is_file($new)? 0 : true ); } $this->change('logic', $new); $this->change('is_default_logic', false); } if ($proto = $this->is_default_logic(null, true)){ $path = $proto->logic(null, $root); }else if ($this->_attributes['is_default_logic']) { $path = ($root ? DIR : '/').'vendor/boolive/core/data/Entity.php'; }else{ $path = $this->dir($root).$this->name().'.php'; } return $path; }
Путь на файл используемого класса (логики) @param null $new Установка своего класса. Сведения о загружаемом файле или его программный код @param bool $root Возвращать полный путь или от директории сайта? @return string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L446-L468
Boolive/Core
data/Entity.php
Entity.dir
function dir($root = false, $current = false) { $dir = $this->uri($current); if ($root){ return DIR.trim($dir,'/').'/'; }else{ return $dir.'/'; } }
php
function dir($root = false, $current = false) { $dir = $this->uri($current); if ($root){ return DIR.trim($dir,'/').'/'; }else{ return $dir.'/'; } }
Директория объекта @param bool $root Признак, возвращать путь от корня сервера или от web директории (www) @param bool $current Возвращать с учётом исходного uri (true) или нового (false) @return string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L476-L484
Boolive/Core
data/Entity.php
Entity.is_file
function is_file() { if (!empty($this->_attributes['file'])){ return true; } if (($proto = $this->is_default_file(null, true)) && $proto->is_exists()){ return $proto->is_file(); } return false; }
php
function is_file() { if (!empty($this->_attributes['file'])){ return true; } if (($proto = $this->is_default_file(null, true)) && $proto->is_exists()){ return $proto->is_file(); } return false; }
Признак, привязан ли файл @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L491-L500
Boolive/Core
data/Entity.php
Entity.is_draft
function is_draft($new = null) { if (isset($new) && ($this->_attributes['is_draft'] != $new)){ $this->change('is_draft', (bool)$new); } return $this->_attributes['is_draft']; }
php
function is_draft($new = null) { if (isset($new) && ($this->_attributes['is_draft'] != $new)){ $this->change('is_draft', (bool)$new); } return $this->_attributes['is_draft']; }
Признак, в черновике ли оъект? @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L507-L513
Boolive/Core
data/Entity.php
Entity.is_hidden
function is_hidden($new = null) { if (isset($new) && ($this->_attributes['is_hidden'] != $new)){ $this->change('is_hidden', (bool)$new); } return $this->_attributes['is_hidden']; }
php
function is_hidden($new = null) { if (isset($new) && ($this->_attributes['is_hidden'] != $new)){ $this->change('is_hidden', (bool)$new); } return $this->_attributes['is_hidden']; }
Признак, скрытый ли оъект? @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L520-L526
Boolive/Core
data/Entity.php
Entity.is_mandatory
function is_mandatory($new = null) { if (isset($new) && ($this->_attributes['is_mandatory'] != $new)){ $this->change('is_mandatory', (bool)$new); } return $this->_attributes['is_mandatory']; }
php
function is_mandatory($new = null) { if (isset($new) && ($this->_attributes['is_mandatory'] != $new)){ $this->change('is_mandatory', (bool)$new); } return $this->_attributes['is_mandatory']; }
Признак, обязательный ли оъект для наследования? @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L533-L539
Boolive/Core
data/Entity.php
Entity.is_property
function is_property($new = null) { if (isset($new) && ($this->_attributes['is_property'] != $new)){ $this->change('is_property', (bool)$new); } return $this->_attributes['is_property']; }
php
function is_property($new = null) { if (isset($new) && ($this->_attributes['is_property'] != $new)){ $this->change('is_property', (bool)$new); } return $this->_attributes['is_property']; }
Признак, является ли оъект свойством? @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L546-L552
Boolive/Core
data/Entity.php
Entity.is_relative
function is_relative($new = null) { if (isset($new) && ($this->_attributes['is_relative'] != $new)){ $this->change('is_relative', (bool)$new); } return $this->_attributes['is_relative']; }
php
function is_relative($new = null) { if (isset($new) && ($this->_attributes['is_relative'] != $new)){ $this->change('is_relative', (bool)$new); } return $this->_attributes['is_relative']; }
Признак, является ли прототип относительным? Используется при прототипировании родительского объекта @param bool $new Новое значение признака @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L560-L566
Boolive/Core
data/Entity.php
Entity.is_link
function is_link($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_link'] != $new)){ $this->change('is_link', (bool)$new); } if ($return_entity){ if (!isset($this->_link)){ if (empty($this->_attributes['is_link'])){ $this->_link = false; }else if (($this->_link = $this->proto(null, true))){ if ($p = $this->_link->is_link(null, true)) $this->_link = $p; } } return $this->_link; } return $this->_attributes['is_link']; }
php
function is_link($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_link'] != $new)){ $this->change('is_link', (bool)$new); } if ($return_entity){ if (!isset($this->_link)){ if (empty($this->_attributes['is_link'])){ $this->_link = false; }else if (($this->_link = $this->proto(null, true))){ if ($p = $this->_link->is_link(null, true)) $this->_link = $p; } } return $this->_link; } return $this->_attributes['is_link']; }
Object referenced by this object @param null|bool $new Новое значение признака @param bool $return_entity Признак, возвращать объект вместо uri @return bool|Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L574-L591
Boolive/Core
data/Entity.php
Entity.is_default_value
function is_default_value($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_value'] != $new)){ $this->change('is_default_value', (bool)$new); if ($this->_attributes['is_default_value']){ $this->change('value', null); } } if ($return_entity){ if (!isset($this->_def_value)){ if (empty($this->_attributes['is_default_value'])){ $this->_def_value = false; }else if (($this->_def_value = $this->proto(null, true))){ if ($p = $this->_def_value->is_default_value(null, true)) $this->_def_value = $p; } } return $this->_def_value; } return $this->_attributes['is_default_value']; }
php
function is_default_value($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_value'] != $new)){ $this->change('is_default_value', (bool)$new); if ($this->_attributes['is_default_value']){ $this->change('value', null); } } if ($return_entity){ if (!isset($this->_def_value)){ if (empty($this->_attributes['is_default_value'])){ $this->_def_value = false; }else if (($this->_def_value = $this->proto(null, true))){ if ($p = $this->_def_value->is_default_value(null, true)) $this->_def_value = $p; } } return $this->_def_value; } return $this->_attributes['is_default_value']; }
Признак, значение наследуется от прототипа? @param bool $new Новое значение признака @param bool $return_entity Признак, возвращать объект вместо uri @return bool|Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L599-L619
Boolive/Core
data/Entity.php
Entity.is_default_file
function is_default_file($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_file'] != $new)){ $this->change('is_default_file', (bool)$new); if ($this->_attributes['is_default_file']){ $this->change('file', ''); } } if ($return_entity){ if (!isset($this->_def_file)){ if (empty($this->_attributes['is_default_file'])){ $this->_def_file = false; }else if (($this->_def_file = $this->proto(null, true))){ if ($p = $this->_def_file->is_default_file(null, true)) $this->_def_file = $p; } } return $this->_def_file; } return $this->_attributes['is_default_file']; }
php
function is_default_file($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_file'] != $new)){ $this->change('is_default_file', (bool)$new); if ($this->_attributes['is_default_file']){ $this->change('file', ''); } } if ($return_entity){ if (!isset($this->_def_file)){ if (empty($this->_attributes['is_default_file'])){ $this->_def_file = false; }else if (($this->_def_file = $this->proto(null, true))){ if ($p = $this->_def_file->is_default_file(null, true)) $this->_def_file = $p; } } return $this->_def_file; } return $this->_attributes['is_default_file']; }
Признак, файл наследуется от прототипа? @param bool $new Новое значение признака @param bool $return_entity Признак, возвращать объект вместо uri @return bool|Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L627-L647
Boolive/Core
data/Entity.php
Entity.is_default_logic
function is_default_logic($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_logic'] != $new)){ $this->change('is_default_logic', (bool)$new); } if ($return_entity){ if (!isset($this->_def_logic)){ if (empty($this->_attributes['is_default_logic'])){ $this->_def_logic = false; }else if (($this->_def_logic = $this->proto(null, true))){ if ($p = $this->_def_logic->is_default_logic(null, true)) $this->_def_logic = $p; } } return $this->_def_logic; } return $this->_attributes['is_default_logic']; }
php
function is_default_logic($new = null, $return_entity = false) { if (isset($new) && ($this->_attributes['is_default_logic'] != $new)){ $this->change('is_default_logic', (bool)$new); } if ($return_entity){ if (!isset($this->_def_logic)){ if (empty($this->_attributes['is_default_logic'])){ $this->_def_logic = false; }else if (($this->_def_logic = $this->proto(null, true))){ if ($p = $this->_def_logic->is_default_logic(null, true)) $this->_def_logic = $p; } } return $this->_def_logic; } return $this->_attributes['is_default_logic']; }
Признак, класс (которым определяется логика объекта) наследуется от прототипа? @param bool $new Новое значение признака @param bool $return_entity Признак, возвращать объект вместо uri @return bool|Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L655-L672
Boolive/Core
data/Entity.php
Entity.is_changed
function is_changed($attr_name = null) { if (isset($attr_name)){ return array_key_exists($attr_name, $this->_changes); } return !empty($this->_changes); }
php
function is_changed($attr_name = null) { if (isset($attr_name)){ return array_key_exists($attr_name, $this->_changes); } return !empty($this->_changes); }
Есть ли изменения? Если не указан атрибут, то проверяется изменение в любом атрибуте @param null|string $attr_name Атрибут, изменения в котором проверяются. @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L703-L709
Boolive/Core
data/Entity.php
Entity.change
function change($attr_name, $new_value) { if (!$this->is_changed($attr_name)){ $this->_changes[$attr_name] = $this->_attributes[$attr_name]; }else if ($this->_changes[$attr_name] === $new_value){ unset($this->_attributes[$attr_name]); } $this->_attributes[$attr_name] = $new_value; }
php
function change($attr_name, $new_value) { if (!$this->is_changed($attr_name)){ $this->_changes[$attr_name] = $this->_attributes[$attr_name]; }else if ($this->_changes[$attr_name] === $new_value){ unset($this->_attributes[$attr_name]); } $this->_attributes[$attr_name] = $new_value; }
Зафиксировать изменение атрибута Если новое значение эквиалентно исходному, то признак изменения убирается @param string $attr_name Названия атрибута @param mixed $new_value Новое значение
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L717-L726
Boolive/Core
data/Entity.php
Entity.changes
function changes($attr_name = null) { if (isset($attr_name)){ return $this->_changes[$attr_name]; } return $this->_changes; }
php
function changes($attr_name = null) { if (isset($attr_name)){ return $this->_changes[$attr_name]; } return $this->_changes; }
Возвращается первоначальное значение атрибута (или всех измененных атрибуты) @param null|string $attr_name Атрибут, исходное значение которого вернуть @return array
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L733-L739
Boolive/Core
data/Entity.php
Entity.updateChildrenUri
function updateChildrenUri() { foreach ($this->_children as $child_name => $child){ /* @var Entity $child */ $child->_attributes['uri'] = $this->_attributes['uri'].'/'.$child_name; $child->_attributes['parent'] = $this->_attributes['uri']; $child->updateChildrenUri(); } }
php
function updateChildrenUri() { foreach ($this->_children as $child_name => $child){ /* @var Entity $child */ $child->_attributes['uri'] = $this->_attributes['uri'].'/'.$child_name; $child->_attributes['parent'] = $this->_attributes['uri']; $child->updateChildrenUri(); } }
Каскадное обновление URI подчиненных на основании своего uri Обновляются uri только выгруженных/присоединенных на данный момент подчиенных
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L745-L753
Boolive/Core
data/Entity.php
Entity.child
public function child($name, $load = false) { if (!isset($this->_children[$name])){ if ($load){ $this->_children[$name] = Data::read($this->uri().'/'.$name); }else{ return false; } } return $this->_children[$name]; }
php
public function child($name, $load = false) { if (!isset($this->_children[$name])){ if ($load){ $this->_children[$name] = Data::read($this->uri().'/'.$name); }else{ return false; } } return $this->_children[$name]; }
Подчиненный по имени @param string $name @param bool $load @return Entity|bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L825-L835
Boolive/Core
data/Entity.php
Entity.check
function check($children = true) { // "Контейнер" для ошибок по атрибутам и подчиненным объектам //$errors = new Error('Неверный объект', $this->uri()); if ($this->_checked) return true; // Проверка и фильтр атрибутов $attribs = new Values($this->_attributes); $filtered = array_replace($this->_attributes, $attribs->get($this->rule(), $error)); /** @var $error Error */ if ($error){ //$errors->_attributes->add($error->children()); $this->errors()->_attributes->add($error->children()); }else{ $this->_attributes = $filtered; } // Проверка подчиненных if ($children){ foreach ($this->_children as $child){ $error = null; /** @var Entity $child */ if (!$child->check()){ //$errors->_children->add($error); $this->errors()->_children->add($child->errors()); } } } // Проверка родителем. if ($p = $this->parent(null,true)){ $p->checkChild($this); } // Если ошибок нет, то удаляем контейнер для них if (!$this->errors()->isExist()){ //$errors = null; return $this->_checked = true; } return false; }
php
function check($children = true) { // "Контейнер" для ошибок по атрибутам и подчиненным объектам //$errors = new Error('Неверный объект', $this->uri()); if ($this->_checked) return true; // Проверка и фильтр атрибутов $attribs = new Values($this->_attributes); $filtered = array_replace($this->_attributes, $attribs->get($this->rule(), $error)); /** @var $error Error */ if ($error){ //$errors->_attributes->add($error->children()); $this->errors()->_attributes->add($error->children()); }else{ $this->_attributes = $filtered; } // Проверка подчиненных if ($children){ foreach ($this->_children as $child){ $error = null; /** @var Entity $child */ if (!$child->check()){ //$errors->_children->add($error); $this->errors()->_children->add($child->errors()); } } } // Проверка родителем. if ($p = $this->parent(null,true)){ $p->checkChild($this); } // Если ошибок нет, то удаляем контейнер для них if (!$this->errors()->isExist()){ //$errors = null; return $this->_checked = true; } return false; }
Проверка корректности объекта по внутренним правилам объекта Используется перед сохранением @param bool $children Признак, проверять или нет подчиненных @return bool Признак, корректен объект (true) или нет (false)
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L850-L887
Boolive/Core
data/Entity.php
Entity.verify
function verify($cond) { if (empty($cond)) return true; if (is_string($cond)) $cond = Data::condStringToArray($cond); if (count($cond)==1 && is_array($cond[0])){ $cond = $cond[0]; } if (is_array($cond[0])) $cond = array('all', $cond); switch (strtolower($cond[0])){ case 'all': if (count($cond)>2){ unset($cond[0]); $cond[1] = $cond; } foreach ($cond[1] as $c){ if (!$this->verify($c)) return false; } return true; case 'any': if (count($cond)>2){ unset($cond[0]); $cond[1] = $cond; } foreach ($cond[1] as $c){ if ($this->verify($c)) return true; } return !sizeof($cond[1]); case 'not': return !$this->verify($cond[1]); // Проверка подчиненного case 'child': $child = $this->{$cond[1]}; if ($child->is_exists()){ if (isset($cond[2])){ return $child->verify($cond[2]); } return true; } return false; // Проверка наследника // case 'heir': // $heir = $this->{$cond[1]}; // if ($heir->is_exists()){ // if (isset($cond[2])){ // return $heir->verify($cond[2]); // } // return true; // } // return false; // Эквивалентность указанному объекту case 'eq': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->eq($proto)) return true; } return false; // Является ли подчиенным для указанного объекта или eq() case 'in': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $parent){ if ($this->in($parent)) return true; } return false; // Является ли наследником указзаного объекта или eq() case 'is': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->is($proto)) return true; } return false; // in || is case 'of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $obj){ if ($this->of($obj)) return true; } return false; case 'child_of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $parent){ if ($this->child_of($parent)) return true; } return false; case 'heir_of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->heir_of($proto)) return true; } return false; case 'is_my': return $this->is_my(); case 'access': return $this->is_accessible($cond[1]); // Остальные параметры считать условиями на атрибут default: if ($cond[0] == 'attr') array_shift($cond); if (sizeof($cond) < 2){ $cond[1] = '!='; $cond[2] = 0; } if (isset($this->_attributes[$cond[0]]) || array_key_exists($cond[0], $this->_attributes)){ $value = $this->_attributes[$cond[0]]; }else{ $value = null; } switch ($cond[1]){ case '=': return $value == $cond[2]; case '<': return $value < $cond[2]; case '>': return $value > $cond[2]; case '>=': return $value >= $cond[2]; case '<=': return $value <= $cond[2]; case '!=': case '<>': return $value != $cond[2]; case 'like': $pattern = strtr($cond[2], array('%' => '*', '_' => '?')); return fnmatch($pattern, $value); case 'in': if (!is_array($cond[2])) $cond[2] = array($cond[2]); return in_array($value, $cond[2]); } return false; } }
php
function verify($cond) { if (empty($cond)) return true; if (is_string($cond)) $cond = Data::condStringToArray($cond); if (count($cond)==1 && is_array($cond[0])){ $cond = $cond[0]; } if (is_array($cond[0])) $cond = array('all', $cond); switch (strtolower($cond[0])){ case 'all': if (count($cond)>2){ unset($cond[0]); $cond[1] = $cond; } foreach ($cond[1] as $c){ if (!$this->verify($c)) return false; } return true; case 'any': if (count($cond)>2){ unset($cond[0]); $cond[1] = $cond; } foreach ($cond[1] as $c){ if ($this->verify($c)) return true; } return !sizeof($cond[1]); case 'not': return !$this->verify($cond[1]); // Проверка подчиненного case 'child': $child = $this->{$cond[1]}; if ($child->is_exists()){ if (isset($cond[2])){ return $child->verify($cond[2]); } return true; } return false; // Проверка наследника // case 'heir': // $heir = $this->{$cond[1]}; // if ($heir->is_exists()){ // if (isset($cond[2])){ // return $heir->verify($cond[2]); // } // return true; // } // return false; // Эквивалентность указанному объекту case 'eq': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->eq($proto)) return true; } return false; // Является ли подчиенным для указанного объекта или eq() case 'in': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $parent){ if ($this->in($parent)) return true; } return false; // Является ли наследником указзаного объекта или eq() case 'is': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->is($proto)) return true; } return false; // in || is case 'of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $obj){ if ($this->of($obj)) return true; } return false; case 'child_of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $parent){ if ($this->child_of($parent)) return true; } return false; case 'heir_of': if (is_array($cond[1])){ $cond = $cond[1]; }else{ unset($cond[0]); } foreach ($cond as $proto){ if ($this->heir_of($proto)) return true; } return false; case 'is_my': return $this->is_my(); case 'access': return $this->is_accessible($cond[1]); // Остальные параметры считать условиями на атрибут default: if ($cond[0] == 'attr') array_shift($cond); if (sizeof($cond) < 2){ $cond[1] = '!='; $cond[2] = 0; } if (isset($this->_attributes[$cond[0]]) || array_key_exists($cond[0], $this->_attributes)){ $value = $this->_attributes[$cond[0]]; }else{ $value = null; } switch ($cond[1]){ case '=': return $value == $cond[2]; case '<': return $value < $cond[2]; case '>': return $value > $cond[2]; case '>=': return $value >= $cond[2]; case '<=': return $value <= $cond[2]; case '!=': case '<>': return $value != $cond[2]; case 'like': $pattern = strtr($cond[2], array('%' => '*', '_' => '?')); return fnmatch($pattern, $value); case 'in': if (!is_array($cond[2])) $cond[2] = array($cond[2]); return in_array($value, $cond[2]); } return false; } }
Проверка объекта соответствию указанному условию <code> [ // услвоия поиска объединенные логическим AND ['uri', '=', '?'], // сравнение атрибута ['not', [ // отрицание всех вложенных условий (в примере одно) ['value', 'like', '%?%'] // сравнение атрибута value с шаблоном %?% ]], ['any', [ // условия объединенные логическим OR ['child', [ // проверка подчиенного объекта ['name', '=', 'price'], // имя подчиненного объекта (атрибут name) ['value', '<', 100], ]] ]], ['is', '/library/object'] // кем объект является? проверка наследования ) @param array|string $cond Условие как для поиска @throws \Exception @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L920-L1066
Boolive/Core
data/Entity.php
Entity.eq
function eq($object) { if ($object instanceof Entity){ return $this->uri() === $object->uri(); } return isset($object) && ($this->uri() === $object); }
php
function eq($object) { if ($object instanceof Entity){ return $this->uri() === $object->uri(); } return isset($object) && ($this->uri() === $object); }
Сравнение с дргуим объектом (экземпляром) по uri @param Entity $object @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1073-L1079
Boolive/Core
data/Entity.php
Entity.in
function in($parent) { if (!$this->is_exists() || ($parent instanceof Entity && !$parent->is_exists())) return false; if ($this->eq($parent)) return true; return $this->child_of($parent); }
php
function in($parent) { if (!$this->is_exists() || ($parent instanceof Entity && !$parent->is_exists())) return false; if ($this->eq($parent)) return true; return $this->child_of($parent); }
Проверка, является ли подчиненным для указанного родителя? @param string|Entity $parent Экземпляр родителя или его идентификатор @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1086-L1091
Boolive/Core
data/Entity.php
Entity.is
function is($proto) { if ($proto == 'all') return true; if ($this->eq($proto)) return true; return $this->heir_of($proto); }
php
function is($proto) { if ($proto == 'all') return true; if ($this->eq($proto)) return true; return $this->heir_of($proto); }
Проверка, являектся наследником указанного прототипа? @param string|Entity $proto Экземпляр прототипа или его идентификатор @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1098-L1103
Boolive/Core
data/Entity.php
Entity.child_of
function child_of($object) { if ($object instanceof Entity){ $object = $object->uri(); } return $object.'/' == mb_substr($this->uri(),0,mb_strlen($object)+1); }
php
function child_of($object) { if ($object instanceof Entity){ $object = $object->uri(); } return $object.'/' == mb_substr($this->uri(),0,mb_strlen($object)+1); }
Провкра, является ли подчиненным для указанного объекта? @param $object @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1120-L1126
Boolive/Core
data/Entity.php
Entity.heir_of
function heir_of($object) { return ($p = $this->proto(null, true)) ? $p->is($object) : false; }
php
function heir_of($object) { return ($p = $this->proto(null, true)) ? $p->is($object) : false; }
Провкра, является ли наследником для указанного объекта? @param $object @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1133-L1136
Boolive/Core
data/Entity.php
Entity.errors
function errors() { if (!$this->_errors){ $this->_errors = new Error('Ошибки', $this->name(), null, true); // Связывание с ошибками родительского объекта. Образуется целостная иерархия ошибок if ($this->_parent){ $this->_parent->errors()->_children->add($this->_errors, '', true); } } return $this->_errors; }
php
function errors() { if (!$this->_errors){ $this->_errors = new Error('Ошибки', $this->name(), null, true); // Связывание с ошибками родительского объекта. Образуется целостная иерархия ошибок if ($this->_parent){ $this->_parent->errors()->_children->add($this->_errors, '', true); } } return $this->_errors; }
Ошибки объекта @return Error|null
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1154-L1164
Boolive/Core
data/Entity.php
Entity.linked
function linked($clone = false) { if (!empty($this->_attributes['is_link']) && ($link = $this->is_link(null, true))){ if ($clone) $link = clone $link; return $link; } return $this; }
php
function linked($clone = false) { if (!empty($this->_attributes['is_link']) && ($link = $this->is_link(null, true))){ if ($clone) $link = clone $link; return $link; } return $this; }
Объект, на которого ссылется данный, если является ссылкой Если данный объект не является ссылкой, то возарщается $this, иначе возвращается первый из прототипов, не являющейся ссылкой @param bool $clone Клонировать, если объект является ссылкой? @return Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1173-L1180
Boolive/Core
data/Entity.php
Entity.inner
function inner() { if (!$this->is_exists() && /*!$this->_attributes['proto'] && */($p = $this->parent(null, true))){ // У прототипов родителя найти свойство с именем $this->name() $find = false; $name = $this->name(); $protos = array($this); $parents = array($p); while (($p = $p->proto(null, true)) && !$find){ $propertry = $p->{$name}; $find = $propertry->is_exists(); $protos[] = $propertry; $parents[] = $p; } for ($i = sizeof($protos)-1; $i>0; $i--){ $protos[$i-1] = Data::create($protos[$i], $parents[$i-1]); $protos[$i-1]->_is_inner = true; } return $protos[0]; } return $this; }
php
function inner() { if (!$this->is_exists() && /*!$this->_attributes['proto'] && */($p = $this->parent(null, true))){ // У прототипов родителя найти свойство с именем $this->name() $find = false; $name = $this->name(); $protos = array($this); $parents = array($p); while (($p = $p->proto(null, true)) && !$find){ $propertry = $p->{$name}; $find = $propertry->is_exists(); $protos[] = $propertry; $parents[] = $p; } for ($i = sizeof($protos)-1; $i>0; $i--){ $protos[$i-1] = Data::create($protos[$i], $parents[$i-1]); $protos[$i-1]->_is_inner = true; } return $protos[0]; } return $this; }
Внутреннй. Доступ к внутренему объекту, который скрыт в (одном из) прототипе родителя Объеты не создаются автоматически из-за скрытости их прототипов, но к ним можно получить доступ. @return $this | Entity Текущий или новый объект, если текущий не существует, но у него есть скрытый прототип
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1188-L1209
Boolive/Core
data/Entity.php
Entity.complete
function complete($only_mandatory = true, $only_property = true) { // Выбор подчиненных объектов $proto = $this->proto(null, true); $cond = [ 'from' => $proto, 'select' => 'properties', 'key' => 'name' ]; if ($only_mandatory){ $cond['where'] = [['is_mandatory','=',true]]; } $props_children = Data::find($cond); if (!$only_property){ // Выбор подчиненных объектов $cond['select'] = 'children'; $props_children = array_merge($props_children, Data::find($cond)); } // Прототипирование отсутствующих подчиненных foreach ($props_children as $name => $child){ $this->{$name}->complete($only_mandatory, $only_property); if ($this->{$name}->order() == Entity::MAX_ORDER){ $this->{$name}->order($props_children[$name]->order()); } } }
php
function complete($only_mandatory = true, $only_property = true) { // Выбор подчиненных объектов $proto = $this->proto(null, true); $cond = [ 'from' => $proto, 'select' => 'properties', 'key' => 'name' ]; if ($only_mandatory){ $cond['where'] = [['is_mandatory','=',true]]; } $props_children = Data::find($cond); if (!$only_property){ // Выбор подчиненных объектов $cond['select'] = 'children'; $props_children = array_merge($props_children, Data::find($cond)); } // Прототипирование отсутствующих подчиненных foreach ($props_children as $name => $child){ $this->{$name}->complete($only_mandatory, $only_property); if ($this->{$name}->order() == Entity::MAX_ORDER){ $this->{$name}->order($props_children[$name]->order()); } } }
Дополнить объект свойствами прототипа Используется для создания полного объекта или его обновления @param bool $only_mandatory Дополнять только обязательными или всеми свойствами? @param bool $only_property Дополнять только свойствами или всеми объектами?
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1227-L1252
Boolive/Core
data/Entity.php
Entity.__trace
public function __trace() { $info['_attributes'] = $this->_attributes; $info['_changes'] = $this->_changes; $info['_checked'] = $this->_checked; // $info['_proto'] = $this->_proto; // $info['_parent'] = $this->_parent; $info['_children'] = $this->_children; // if ($this->_errors) $info['_errors'] = $this->_errors->toArrayCompact(false); return $info; }
php
public function __trace() { $info['_attributes'] = $this->_attributes; $info['_changes'] = $this->_changes; $info['_checked'] = $this->_checked; // $info['_proto'] = $this->_proto; // $info['_parent'] = $this->_parent; $info['_children'] = $this->_children; // if ($this->_errors) $info['_errors'] = $this->_errors->toArrayCompact(false); return $info; }
Информация для var_dump() и trace() @return mixed
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Entity.php#L1338-L1349