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
|
---|---|---|---|---|---|---|---|
soliphp/web | src/Web/Response.php | Response.setCookie | public function setCookie(array $cookie)
{
$default = [
'name' => '__cookieDefault',
'value' => '',
'expire' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => true
];
$cookie = array_merge($default, $cookie);
$this->cookies[$cookie['name']] = $cookie;
return $this;
} | php | public function setCookie(array $cookie)
{
$default = [
'name' => '__cookieDefault',
'value' => '',
'expire' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => true
];
$cookie = array_merge($default, $cookie);
$this->cookies[$cookie['name']] = $cookie;
return $this;
} | 设置响应的 cookie 信息
@param array $cookie 单个 cookie 信息
@return $this | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Response.php#L176-L192 |
soliphp/web | src/Web/Response.php | Response.setHeader | public function setHeader($header, $value = null)
{
if (is_string($header)) {
$this->headers[$header] = $value;
}
return $this;
} | php | public function setHeader($header, $value = null)
{
if (is_string($header)) {
$this->headers[$header] = $value;
}
return $this;
} | 设置响应头信息
@param string $header
@param string $value
@return $this | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Response.php#L212-L219 |
soliphp/web | src/Web/Response.php | Response.send | public function send()
{
$this->sendHeaders();
$this->sendCookies();
$this->sendContent();
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
// 重置响应信息,terminate 的时候有可能需要收集响应信息
$this->reset();
return $this;
} | php | public function send()
{
$this->sendHeaders();
$this->sendCookies();
$this->sendContent();
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
// 重置响应信息,terminate 的时候有可能需要收集响应信息
$this->reset();
return $this;
} | 发送响应数据
@return $this | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Response.php#L226-L240 |
soliphp/web | src/Web/Response.php | Response.sendCookies | public function sendCookies()
{
foreach ($this->cookies as $name => $c) {
setcookie(
$name,
$c['value'], // encryptValue
$c['expire'],
$c['path'],
$c['domain'],
$c['secure'],
$c['httpOnly']
);
}
return $this;
} | php | public function sendCookies()
{
foreach ($this->cookies as $name => $c) {
setcookie(
$name,
$c['value'], // encryptValue
$c['expire'],
$c['path'],
$c['domain'],
$c['secure'],
$c['httpOnly']
);
}
return $this;
} | 发送响应 cookie
@return $this | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Response.php#L259-L274 |
soliphp/web | src/Web/Response.php | Response.sendHeaders | public function sendHeaders()
{
if (headers_sent()) {
return $this;
}
if (isset($this->headers['Location']) && $this->code === 200) {
$this->setStatusCode(302);
}
// 发送状态码
http_response_code($this->code);
// 发送自定义响应头
foreach ($this->headers as $header => $value) {
if (empty($value)) {
header($header, true);
} else {
header("$header: $value", true);
}
}
return $this;
} | php | public function sendHeaders()
{
if (headers_sent()) {
return $this;
}
if (isset($this->headers['Location']) && $this->code === 200) {
$this->setStatusCode(302);
}
// 发送状态码
http_response_code($this->code);
// 发送自定义响应头
foreach ($this->headers as $header => $value) {
if (empty($value)) {
header($header, true);
} else {
header("$header: $value", true);
}
}
return $this;
} | 发送响应头
@return $this | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/Response.php#L281-L304 |
as3io/modlr | src/Metadata/EmbedMetadata.php | EmbedMetadata.applyMixinProperties | protected function applyMixinProperties(MixinMetadata $mixin)
{
foreach ($mixin->getAttributes() as $attribute) {
if (true === $this->hasAttribute($attribute->key)) {
throw MetadataException::mixinPropertyExists($this->name, $mixin->name, 'attribute', $attribute->key);
}
$this->addAttribute($attribute);
}
foreach ($mixin->getEmbeds() as $embed) {
if (true === $this->hasEmbed($embed->key)) {
throw MetadataException::mixinPropertyExists($this->name, $mixin->name, 'embed', $embed->key);
}
$this->addEmbed($embed);
}
} | php | protected function applyMixinProperties(MixinMetadata $mixin)
{
foreach ($mixin->getAttributes() as $attribute) {
if (true === $this->hasAttribute($attribute->key)) {
throw MetadataException::mixinPropertyExists($this->name, $mixin->name, 'attribute', $attribute->key);
}
$this->addAttribute($attribute);
}
foreach ($mixin->getEmbeds() as $embed) {
if (true === $this->hasEmbed($embed->key)) {
throw MetadataException::mixinPropertyExists($this->name, $mixin->name, 'embed', $embed->key);
}
$this->addEmbed($embed);
}
} | {@inheritdoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbedMetadata.php#L63-L77 |
as3io/modlr | src/Metadata/EmbedMetadata.php | EmbedMetadata.validateAttribute | protected function validateAttribute(AttributeMetadata $attribute)
{
if (true === $this->hasEmbed($attribute->getKey())) {
throw MetadataException::fieldKeyInUse('attribute', 'embed', $attribute->getKey(), $this->name);
}
} | php | protected function validateAttribute(AttributeMetadata $attribute)
{
if (true === $this->hasEmbed($attribute->getKey())) {
throw MetadataException::fieldKeyInUse('attribute', 'embed', $attribute->getKey(), $this->name);
}
} | {@inheritdoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbedMetadata.php#L82-L87 |
as3io/modlr | src/Metadata/EmbedMetadata.php | EmbedMetadata.validateEmbed | protected function validateEmbed(EmbeddedPropMetadata $embed)
{
if (true === $this->hasAttribute($embed->getKey())) {
throw MetadataException::fieldKeyInUse('embed', 'attribute', $embed->getKey(), $this->name);
}
} | php | protected function validateEmbed(EmbeddedPropMetadata $embed)
{
if (true === $this->hasAttribute($embed->getKey())) {
throw MetadataException::fieldKeyInUse('embed', 'attribute', $embed->getKey(), $this->name);
}
} | {@inheritdoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbedMetadata.php#L92-L97 |
deweller/php-cliopts | src/CLIOpts/Help/ConsoleFormat.php | ConsoleFormat.applyformatToText | public static function applyformatToText() {
$args = func_get_args();
$count = func_num_args();
$text = $args[$count - 1];
if ($count == 1) { return $text; }
$mode_texts = array_slice($args, 0, $count - 1);
return self::buildEscapeCodes($mode_texts).$text.self::buildEscapeCodes('plain');
} | php | public static function applyformatToText() {
$args = func_get_args();
$count = func_num_args();
$text = $args[$count - 1];
if ($count == 1) { return $text; }
$mode_texts = array_slice($args, 0, $count - 1);
return self::buildEscapeCodes($mode_texts).$text.self::buildEscapeCodes('plain');
} | Applies one or more console formatting codes to text
@param string $mode A mode like bold or black. This can be repeated numerous times.
@param string $text the text to be formatted
@return string a formatted version of $text | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/ConsoleFormat.php#L57-L67 |
deweller/php-cliopts | src/CLIOpts/Help/ConsoleFormat.php | ConsoleFormat.buildEscapeCodes | protected static function buildEscapeCodes($mode_texts) {
if (!is_array($mode_texts)) { $mode_texts = array($mode_texts); }
$code_text = '';
foreach ($mode_texts as $mode) {
$constant_name = 'self::CONSOLE_'.strtoupper($mode);
if (defined($constant_name)) {
$code_text .= (strlen($code_text) ? ';': '').constant($constant_name);
}
}
return chr(27)."[0;".$code_text."m";
} | php | protected static function buildEscapeCodes($mode_texts) {
if (!is_array($mode_texts)) { $mode_texts = array($mode_texts); }
$code_text = '';
foreach ($mode_texts as $mode) {
$constant_name = 'self::CONSOLE_'.strtoupper($mode);
if (defined($constant_name)) {
$code_text .= (strlen($code_text) ? ';': '').constant($constant_name);
}
}
return chr(27)."[0;".$code_text."m";
} | builds ANSI escape codes
@param mixed $mode_texts An array of mode texts like bold or white. Can also be a single string.
@return string ANSI escape code to activate the modes | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/ConsoleFormat.php#L82-L94 |
newestindustry/ginger-rest | src/Ginger/Url.php | Url.getParameter | public function getParameter($key)
{
if(isset($this->queryParts[$key])) {
return $this->queryParts[$key];
} else {
return false;
}
} | php | public function getParameter($key)
{
if(isset($this->queryParts[$key])) {
return $this->queryParts[$key];
} else {
return false;
}
} | getParameter function.
@access public
@param mixed $key
@return void | https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/Url.php#L127-L134 |
newup/core | src/Filesystem/Generators/PathTreeArrayFormat.php | PathTreeArrayFormat.getPathForTreeGenerator | private function getPathForTreeGenerator($pathKey, $path)
{
// If the $path is an array, it most likely already contains
// the information we need, such as if the target is a file or directory.
if (is_array($path) && array_key_exists('type', $path) && array_key_exists('path', $path)) {
return $path;
}
// At this point, the key should contain at least one ']' character.
if (!Str::contains($pathKey, ']')) {
throw new InvalidArgumentException('Missing key options. Supplied key was ' . $pathKey);
}
// Since we did not get handed the information we wanted, we have to figure it out
// by looking at the path key.
$keyParts = explode(']', $pathKey);
$formattingOptions = array_pop($keyParts);
$type = 'file';
if (Str::contains('d', $formattingOptions)) {
$type = 'dir';
}
return [
'path' => $path,
'type' => $type
];
} | php | private function getPathForTreeGenerator($pathKey, $path)
{
// If the $path is an array, it most likely already contains
// the information we need, such as if the target is a file or directory.
if (is_array($path) && array_key_exists('type', $path) && array_key_exists('path', $path)) {
return $path;
}
// At this point, the key should contain at least one ']' character.
if (!Str::contains($pathKey, ']')) {
throw new InvalidArgumentException('Missing key options. Supplied key was ' . $pathKey);
}
// Since we did not get handed the information we wanted, we have to figure it out
// by looking at the path key.
$keyParts = explode(']', $pathKey);
$formattingOptions = array_pop($keyParts);
$type = 'file';
if (Str::contains('d', $formattingOptions)) {
$type = 'dir';
}
return [
'path' => $path,
'type' => $type
];
} | Converts the key and path into an array that various tree
generators expect.
This function does NOT process the path using any renderers.
@param $pathKey
@param $path
@return mixed
@throws InvalidArgumentException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Filesystem/Generators/PathTreeArrayFormat.php#L22-L49 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php | ServiceBuilder.build | public function build($serviceConfig) {
//“服务配置”可以是一个匿名函数
if ($serviceConfig instanceof Closure) {
$callback = $serviceConfig;
$refFunc = new ReflectionFunction($callback);
return $refFunc->getNumberOfParameters() == 1 ? $callback($this->serviceContainer) : $callback();
}
/*
* 以下是数组形式的服务配置
*/
$refClass = new ReflectionClass($serviceConfig['class']);
//实例化
$constructorArgs = isset($serviceConfig['constructor-args']) ? $serviceConfig['constructor-args'] : [];
$parsedArgs = $this->parseArgs($constructorArgs);
$serviceInstance = $refClass->newInstanceArgs($parsedArgs);
//如果需要调用实例方法
if (isset($serviceConfig['calls'])) {
foreach ($serviceConfig['calls'] as $methodName => $methodArgs) {
$refMethod = $refClass->getMethod($methodName);
$refMethod->invokeArgs($serviceInstance, $this->parseArgs($methodArgs));
}
}
return $serviceInstance;
} | php | public function build($serviceConfig) {
//“服务配置”可以是一个匿名函数
if ($serviceConfig instanceof Closure) {
$callback = $serviceConfig;
$refFunc = new ReflectionFunction($callback);
return $refFunc->getNumberOfParameters() == 1 ? $callback($this->serviceContainer) : $callback();
}
/*
* 以下是数组形式的服务配置
*/
$refClass = new ReflectionClass($serviceConfig['class']);
//实例化
$constructorArgs = isset($serviceConfig['constructor-args']) ? $serviceConfig['constructor-args'] : [];
$parsedArgs = $this->parseArgs($constructorArgs);
$serviceInstance = $refClass->newInstanceArgs($parsedArgs);
//如果需要调用实例方法
if (isset($serviceConfig['calls'])) {
foreach ($serviceConfig['calls'] as $methodName => $methodArgs) {
$refMethod = $refClass->getMethod($methodName);
$refMethod->invokeArgs($serviceInstance, $this->parseArgs($methodArgs));
}
}
return $serviceInstance;
} | 构造服务对象实例
@param array|callable $serviceConfig 服务配置
@return mixed 服务对象实例 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php#L30-L58 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php | ServiceBuilder.parseArgs | private function parseArgs($rawArgs) {
if (!is_array($rawArgs)) {
throw new ServiceContainerException('constructor-args or call argument must be array!');
}
if (empty($rawArgs)) {
return [];
}
$args = [];
foreach ($rawArgs as $rawArg) {
$args[] = $this->parseArg($rawArg);
}
return $args;
} | php | private function parseArgs($rawArgs) {
if (!is_array($rawArgs)) {
throw new ServiceContainerException('constructor-args or call argument must be array!');
}
if (empty($rawArgs)) {
return [];
}
$args = [];
foreach ($rawArgs as $rawArg) {
$args[] = $this->parseArg($rawArg);
}
return $args;
} | 解析参数列表
@param array $rawArgs 未经处理的参数列表,必须为数组。
@return null|array | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php#L65-L79 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php | ServiceBuilder.parseArg | private function parseArg($rawArg) {
//如果不是字符串,则传入原值
if (!is_string($rawArg)) {
return $rawArg;
}
$rawArgLen = strlen($rawArg);
if ($rawArgLen <= 1) {
return $rawArg;
}
//以 @ 开头,则表示引用一个服务对象。例如 @bar,表示引用一个名称为 bar 的服务对象
if ($rawArg[0] == '@') {
$serviceName = substr($rawArg, 1, $rawArgLen - 1);
return $this->serviceContainer->get($serviceName);
}
//以 \@ 开头,则表示传入一个以@开头的字符串,反斜杠作为转义符
//例如 \@bar,则实际传入的是 @bar
if ($rawArg[0] == '\\' && $rawArg[1] == '@') {
return substr($rawArg, 1, $rawArgLen - 1);
}
//其他字符串
return $rawArg;
} | php | private function parseArg($rawArg) {
//如果不是字符串,则传入原值
if (!is_string($rawArg)) {
return $rawArg;
}
$rawArgLen = strlen($rawArg);
if ($rawArgLen <= 1) {
return $rawArg;
}
//以 @ 开头,则表示引用一个服务对象。例如 @bar,表示引用一个名称为 bar 的服务对象
if ($rawArg[0] == '@') {
$serviceName = substr($rawArg, 1, $rawArgLen - 1);
return $this->serviceContainer->get($serviceName);
}
//以 \@ 开头,则表示传入一个以@开头的字符串,反斜杠作为转义符
//例如 \@bar,则实际传入的是 @bar
if ($rawArg[0] == '\\' && $rawArg[1] == '@') {
return substr($rawArg, 1, $rawArgLen - 1);
}
//其他字符串
return $rawArg;
} | 解析单个参数
@param mixed $rawArg <br/>
参数示例:
<ul>
<li>0、null、对象、长度小于或等于1的字符串,etc 返回原参数</li>
<li>@bar 则表示传入一个名称为 bar 的服务对象</li>
<li>\@bar 则实际传入的是字符串 @bar</dd>
<li>其他任何字符串 返回原参数</li>
</ul>
@return mixed 可能的返回值:服务对象、字符串、其他类型的值,etc | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/DependencyInjection/ServiceBuilder.php#L93-L118 |
cwd/datamolino-client | Model/Document/AbstractCompany.php | AbstractCompany.setId | public function setId($id): AbstractCompany
{
if ('' == $id) {
return $this;
}
$this->id = intval($id);
return $this;
} | php | public function setId($id): AbstractCompany
{
if ('' == $id) {
return $this;
}
$this->id = intval($id);
return $this;
} | @param mixed $id
@return AbstractCompany | https://github.com/cwd/datamolino-client/blob/9054fdf06055b6618f3746120f5689e23868dd3f/Model/Document/AbstractCompany.php#L55-L63 |
prokki/theaigames-bot-engine | src/Util/Debugger.php | Debugger.Init | public static function Init($path = '')
{
if( !is_null(self::$_Instance) )
{
// TODO error
}
self::$_Instance = new static($path);
return self::$_Instance;
} | php | public static function Init($path = '')
{
if( !is_null(self::$_Instance) )
{
// TODO error
}
self::$_Instance = new static($path);
return self::$_Instance;
} | @param string $path
@return Debugger | https://github.com/prokki/theaigames-bot-engine/blob/82c8360569a13ce79f0623d730388b613645c6ce/src/Util/Debugger.php#L26-L36 |
andyburton/Sonic-Framework | src/Memcached.php | Memcached.create | public function create ($exclude = array (), $cache = FALSE)
{
// If we're not caching or there is no memcached object just call parent
if ($cache === FALSE || !($this->memcached instanceof \Memcached))
{
return parent::create ($exclude);
}
// Call parent method
$parent = parent::create ($exclude);
if ($parent === FALSE)
{
return FALSE;
}
// Cache
$this->memcached->set ($this->getMemcachedID (), $this->getCacheAttributes (), $cache);
// Return
return $parent;
} | php | public function create ($exclude = array (), $cache = FALSE)
{
// If we're not caching or there is no memcached object just call parent
if ($cache === FALSE || !($this->memcached instanceof \Memcached))
{
return parent::create ($exclude);
}
// Call parent method
$parent = parent::create ($exclude);
if ($parent === FALSE)
{
return FALSE;
}
// Cache
$this->memcached->set ($this->getMemcachedID (), $this->getCacheAttributes (), $cache);
// Return
return $parent;
} | Create object in the database and set in memcached
@param array $exclude Attributes not to set
@param integer|boolean $cache Number of seconds to cache the object for
0 = cache never expires, FALSE = do not cache
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Memcached.php#L28-L55 |
andyburton/Sonic-Framework | src/Memcached.php | Memcached.read | public function read ($pkValue = FALSE, $cache = FALSE)
{
// If we're not caching or there is no memcached object just call parent
if ($cache === FALSE || !($this->memcached instanceof \Memcached))
{
return parent::read ($pkValue);
}
// If there is a key value passed set it
if ($pkValue !== FALSE)
{
$this->iset (static::$pk, $pkValue);
}
// Load memcached object attributres
$obj = $this->memcached->get ($this->getMemcachedID ());
// If the object is not cached, load and cache it
if ($obj === FALSE)
{
// Read object
if (parent::read ($pkValue) === FALSE)
{
return FALSE;
}
// Cache object attributes
$this->memcached->set ($this->getMemcachedID (), $this->getCacheAttributes (), $cache);
}
// Set object attributes from the cache
else
{
$this->setCacheAttributes ($obj);
}
// Return
return TRUE;
} | php | public function read ($pkValue = FALSE, $cache = FALSE)
{
// If we're not caching or there is no memcached object just call parent
if ($cache === FALSE || !($this->memcached instanceof \Memcached))
{
return parent::read ($pkValue);
}
// If there is a key value passed set it
if ($pkValue !== FALSE)
{
$this->iset (static::$pk, $pkValue);
}
// Load memcached object attributres
$obj = $this->memcached->get ($this->getMemcachedID ());
// If the object is not cached, load and cache it
if ($obj === FALSE)
{
// Read object
if (parent::read ($pkValue) === FALSE)
{
return FALSE;
}
// Cache object attributes
$this->memcached->set ($this->getMemcachedID (), $this->getCacheAttributes (), $cache);
}
// Set object attributes from the cache
else
{
$this->setCacheAttributes ($obj);
}
// Return
return TRUE;
} | Read an object from memcached if it exists,
otherwise load the object from the database and then cache it
@param mixed $pkValue Primary key value
@param integer|boolean $cache Number of seconds to cache the object for
0 = cache never expires, FALSE = do not cache
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Memcached.php#L67-L117 |
andyburton/Sonic-Framework | src/Memcached.php | Memcached.delete | public function delete ($pkValue = FALSE)
{
// If there is no key value passed set it
if ($pkValue === FALSE)
{
$pkValue = $this->iget (static::$pk);
}
// Call parent method
$parent = parent::delete ($pkValue);
if ($parent === FALSE)
{
return FALSE;
}
// If there is a memcached object delete from the cache
if ($this->memcached instanceof \Memcached)
{
$this->memcached->delete (static::_getMemcachedID ($pkValue));
}
// Return
return $parent;
} | php | public function delete ($pkValue = FALSE)
{
// If there is no key value passed set it
if ($pkValue === FALSE)
{
$pkValue = $this->iget (static::$pk);
}
// Call parent method
$parent = parent::delete ($pkValue);
if ($parent === FALSE)
{
return FALSE;
}
// If there is a memcached object delete from the cache
if ($this->memcached instanceof \Memcached)
{
$this->memcached->delete (static::_getMemcachedID ($pkValue));
}
// Return
return $parent;
} | Delete an object in the database and memcached
@param mixed $pkValue Primary key value
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Memcached.php#L165-L195 |
andyburton/Sonic-Framework | src/Memcached.php | Memcached.getCacheAttributes | private function getCacheAttributes ()
{
$attributes = array ();
foreach (array_keys (self::$attributes) as $name)
{
$attributes[$name] = $this->iget ($name);
}
return $attributes;
} | php | private function getCacheAttributes ()
{
$attributes = array ();
foreach (array_keys (self::$attributes) as $name)
{
$attributes[$name] = $this->iget ($name);
}
return $attributes;
} | Return object attributes to cache
@return array | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Memcached.php#L225-L237 |
andyburton/Sonic-Framework | src/Memcached.php | Memcached.setCacheAttributes | private function setCacheAttributes ($arr)
{
foreach ($arr as $name => $val)
{
$this->iset ($name, $val, FALSE);
}
} | php | private function setCacheAttributes ($arr)
{
foreach ($arr as $name => $val)
{
$this->iset ($name, $val, FALSE);
}
} | Set object attributes from cache
@return array | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Memcached.php#L245-L253 |
kmfk/slowdb | src/Database.php | Database.getCollection | public function getCollection($name)
{
$name = strtolower($name);
if ($this->collections->containsKey($name)) {
return $this->collections->get($name);
}
$this->collections->set($name, $this->createCollection($name));
return $this->collections->get($name);
} | php | public function getCollection($name)
{
$name = strtolower($name);
if ($this->collections->containsKey($name)) {
return $this->collections->get($name);
}
$this->collections->set($name, $this->createCollection($name));
return $this->collections->get($name);
} | Gets a Collection by name
Collections are idempotent, we create a collection if it does not exist
or return existing collections
@param string $name The name of the Collection
@return Collection | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Database.php#L67-L78 |
kmfk/slowdb | src/Database.php | Database.all | public function all()
{
$results = [];
foreach ($this->collections as $collection) {
$results[] = array_merge(['name' => $collection->name], $collection->info());
}
return $results;
} | php | public function all()
{
$results = [];
foreach ($this->collections as $collection) {
$results[] = array_merge(['name' => $collection->name], $collection->info());
}
return $results;
} | Lists the available Collections by name
@return array | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Database.php#L85-L93 |
kmfk/slowdb | src/Database.php | Database.drop | public function drop($collection)
{
if (!$this->collections->containsKey($collection)) {
return false;
}
$this->collections->get($collection)->drop();
$this->collections->remove($collection);
return true;
} | php | public function drop($collection)
{
if (!$this->collections->containsKey($collection)) {
return false;
}
$this->collections->get($collection)->drop();
$this->collections->remove($collection);
return true;
} | Drops a Collection - removing all data
@param string $collection The name of the Collection to drop | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Database.php#L100-L110 |
kmfk/slowdb | src/Database.php | Database.loadCollections | private function loadCollections()
{
$collections = new ArrayCollection();
$finder = new Finder();
$finder->files()->name('*.dat')->in($this->filepath);
foreach ($finder as $file) {
$name = $file->getBasename('.dat');
$collections->set($name, $this->createCollection($name));
}
return $collections;
} | php | private function loadCollections()
{
$collections = new ArrayCollection();
$finder = new Finder();
$finder->files()->name('*.dat')->in($this->filepath);
foreach ($finder as $file) {
$name = $file->getBasename('.dat');
$collections->set($name, $this->createCollection($name));
}
return $collections;
} | Loads the collections for the Database
@return ArrayCollection | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Database.php#L127-L140 |
matryoshka-model/matryoshka | library/Object/ActiveRecord/AbstractActiveRecord.php | AbstractActiveRecord.save | public function save()
{
if (!$this->activeRecordCriteriaPrototype) {
throw new Exception\RuntimeException(sprintf(
'An Active Record Criteria Prototype must be set prior to calling %s',
__FUNCTION__
));
}
if (!$this->getModel()) {
throw new Exception\RuntimeException(sprintf('A Model must be set prior to calling %s', __FUNCTION__));
}
$criteria = $this->activeRecordCriteriaPrototype;
$criteria->setId($this->getId());
$result = $this->getModel()->save($criteria, $this);
return $result;
} | php | public function save()
{
if (!$this->activeRecordCriteriaPrototype) {
throw new Exception\RuntimeException(sprintf(
'An Active Record Criteria Prototype must be set prior to calling %s',
__FUNCTION__
));
}
if (!$this->getModel()) {
throw new Exception\RuntimeException(sprintf('A Model must be set prior to calling %s', __FUNCTION__));
}
$criteria = $this->activeRecordCriteriaPrototype;
$criteria->setId($this->getId());
$result = $this->getModel()->save($criteria, $this);
return $result;
} | Save
@return null|int
@throws Exception\RuntimeException | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/ActiveRecord/AbstractActiveRecord.php#L78-L95 |
syzygypl/remote-media-bundle | src/DependencyInjection/RemoteMediaExtension.php | RemoteMediaExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$data = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('remote_media.yml');
$container->setParameter('remote_media.cdn.s3.bucket', $data['cdn']['s3']['bucket']);
$container->setParameter('remote_media.cdn.s3.region', $data['cdn']['s3']['region']);
$container->setParameter('remote_media.cdn.s3.access_key', $data['cdn']['s3']['access_key']);
$container->setParameter('remote_media.cdn.s3.access_secret', $data['cdn']['s3']['access_secret']);
$mediaUrl = $data['cdn']['media_url'];
if (null === $mediaUrl) {
$mediaUrl = sprintf('https://%s.s3-%s.amazonaws.com', $data['cdn']['s3']['bucket'], $data['cdn']['s3']['region']);
}
$container->setParameter('remote_media.cdn.media_url', $mediaUrl);
$cachePrefix = $data['cdn']['cache_prefix'];
if (null === $cachePrefix) {
$env = $container->getParameter('kernel.environment');
$cachePrefix = ("prod" === $env) ? "" : "$env/";
}
$container->setParameter('remote_media.cdn.cache_prefix', $cachePrefix);
if (isset($data['cdn']['cache_provider'])) {
$this->setupCacheProvider($data['cdn']['cache_provider'], $container);
}
} | php | public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$data = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('remote_media.yml');
$container->setParameter('remote_media.cdn.s3.bucket', $data['cdn']['s3']['bucket']);
$container->setParameter('remote_media.cdn.s3.region', $data['cdn']['s3']['region']);
$container->setParameter('remote_media.cdn.s3.access_key', $data['cdn']['s3']['access_key']);
$container->setParameter('remote_media.cdn.s3.access_secret', $data['cdn']['s3']['access_secret']);
$mediaUrl = $data['cdn']['media_url'];
if (null === $mediaUrl) {
$mediaUrl = sprintf('https://%s.s3-%s.amazonaws.com', $data['cdn']['s3']['bucket'], $data['cdn']['s3']['region']);
}
$container->setParameter('remote_media.cdn.media_url', $mediaUrl);
$cachePrefix = $data['cdn']['cache_prefix'];
if (null === $cachePrefix) {
$env = $container->getParameter('kernel.environment');
$cachePrefix = ("prod" === $env) ? "" : "$env/";
}
$container->setParameter('remote_media.cdn.cache_prefix', $cachePrefix);
if (isset($data['cdn']['cache_provider'])) {
$this->setupCacheProvider($data['cdn']['cache_provider'], $container);
}
} | {@inheritDoc} | https://github.com/syzygypl/remote-media-bundle/blob/2be3284d5baf8a12220ecbaf63043eb105eb87ef/src/DependencyInjection/RemoteMediaExtension.php#L23-L54 |
samsonos/php_core | src/loader/ContainerManager.php | ContainerManager.collectXmlMetadata | public function collectXmlMetadata(array $metadataCollection) : array
{
// If config path is exists
if (file_exists($this->configPath)) {
// Init resolver
$xmlConfigurator = new XmlResolver(new CollectionClassResolver([
Scope::class,
Name::class,
ClassName::class,
\samsonframework\containercollection\attribute\Service::class
]), new CollectionPropertyResolver([
ClassName::class,
Value::class
]), new CollectionMethodResolver([], new CollectionParameterResolver([
ClassName::class,
Value::class,
ArrayValue::class,
\samsonframework\containercollection\attribute\Service::class
])));
// Collect new metadata
$xmlCollector = new XmlMetadataCollector($xmlConfigurator);
return $xmlCollector->collect(file_get_contents($this->configPath), $metadataCollection);
}
return $metadataCollection;
} | php | public function collectXmlMetadata(array $metadataCollection) : array
{
// If config path is exists
if (file_exists($this->configPath)) {
// Init resolver
$xmlConfigurator = new XmlResolver(new CollectionClassResolver([
Scope::class,
Name::class,
ClassName::class,
\samsonframework\containercollection\attribute\Service::class
]), new CollectionPropertyResolver([
ClassName::class,
Value::class
]), new CollectionMethodResolver([], new CollectionParameterResolver([
ClassName::class,
Value::class,
ArrayValue::class,
\samsonframework\containercollection\attribute\Service::class
])));
// Collect new metadata
$xmlCollector = new XmlMetadataCollector($xmlConfigurator);
return $xmlCollector->collect(file_get_contents($this->configPath), $metadataCollection);
}
return $metadataCollection;
} | Get xml metadata collection
@param array $metadataCollection
@return array
@throws \Exception | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/loader/ContainerManager.php#L79-L103 |
samsonos/php_core | src/loader/ContainerManager.php | ContainerManager.getDefaultPropertyValue | public function getDefaultPropertyValue($className, $propertyName)
{
$reflection = new \ReflectionClass($className);
$values = $reflection->getDefaultProperties();
return $values[$propertyName] ?? null;
} | php | public function getDefaultPropertyValue($className, $propertyName)
{
$reflection = new \ReflectionClass($className);
$values = $reflection->getDefaultProperties();
return $values[$propertyName] ?? null;
} | Get default property value by property name
@param $className
@param $propertyName
@return null | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/loader/ContainerManager.php#L112-L117 |
samsonos/php_core | src/loader/ContainerManager.php | ContainerManager.createMetadata | public function createMetadata($class, $name, $path, $scope = 'module') : ClassMetadata
{
$metadata = new ClassMetadata();
$class = ltrim($class, '\\');
$name = strtolower(ltrim($name, '\\'));
$metadata->className = $class;
$metadata->name = str_replace(['\\', '/'], '_', $name ?? $class);
$metadata->scopes[] = Builder::SCOPE_SERVICES;
$metadata->scopes[] = $scope;
// TODO: Now we need to remove and change constructors
$metadata->methodsMetadata['__construct'] = new MethodMetadata($metadata);
// Iterate constructor arguments to preserve arguments order and inject dependencies
foreach ((new \ReflectionMethod($class, '__construct'))->getParameters() as $parameter) {
if ($parameter->getName() === 'path') {
$metadata->methodsMetadata['__construct']->dependencies['path'] = $path;
} elseif ($parameter->getName() === 'resources') {
$metadata->methodsMetadata['__construct']->dependencies['resources'] = ResourceMap::class;
} elseif ($parameter->getName() === 'system') {
$metadata->methodsMetadata['__construct']->dependencies['system'] = Core::class;
} elseif (!$parameter->isOptional()) {
$metadata->methodsMetadata['__construct']->dependencies[$parameter->getName()] = '';
}
}
return $metadata;
} | php | public function createMetadata($class, $name, $path, $scope = 'module') : ClassMetadata
{
$metadata = new ClassMetadata();
$class = ltrim($class, '\\');
$name = strtolower(ltrim($name, '\\'));
$metadata->className = $class;
$metadata->name = str_replace(['\\', '/'], '_', $name ?? $class);
$metadata->scopes[] = Builder::SCOPE_SERVICES;
$metadata->scopes[] = $scope;
// TODO: Now we need to remove and change constructors
$metadata->methodsMetadata['__construct'] = new MethodMetadata($metadata);
// Iterate constructor arguments to preserve arguments order and inject dependencies
foreach ((new \ReflectionMethod($class, '__construct'))->getParameters() as $parameter) {
if ($parameter->getName() === 'path') {
$metadata->methodsMetadata['__construct']->dependencies['path'] = $path;
} elseif ($parameter->getName() === 'resources') {
$metadata->methodsMetadata['__construct']->dependencies['resources'] = ResourceMap::class;
} elseif ($parameter->getName() === 'system') {
$metadata->methodsMetadata['__construct']->dependencies['system'] = Core::class;
} elseif (!$parameter->isOptional()) {
$metadata->methodsMetadata['__construct']->dependencies[$parameter->getName()] = '';
}
}
return $metadata;
} | Create metadata for module
@param $class
@param $name
@param $path
@param string $scope
@return ClassMetadata | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/loader/ContainerManager.php#L128-L154 |
samsonos/php_core | src/loader/ContainerManager.php | ContainerManager.replaceInterfaceDependencies | public function replaceInterfaceDependencies(array $metadataCollection) {
$list = [];
$listPath = [];
/** @var ClassMetadata $classMetadata */
foreach ($metadataCollection as $classPath => $classMetadata) {
$list[$classMetadata->className] = $classMetadata;
$listPath[$classMetadata->name ?? $classMetadata->className] = $classPath;
}
$metadataCollection = $list;
// Gather all interface implementations
$implementsByAlias = $implementsByAlias ?? [];
foreach (get_declared_classes() as $class) {
$classImplements = class_implements($class);
foreach (get_declared_interfaces() as $interface) {
if (in_array($interface, $classImplements, true)) {
if (array_key_exists($class, $metadataCollection)) {
$implementsByAlias[$interface][] = $metadataCollection[$class]->name;
}
}
}
}
// Gather all class implementations
$serviceAliasesByClass = $serviceAliasesByClass ?? [];
foreach (get_declared_classes() as $class) {
if (array_key_exists($class, $metadataCollection)) {
$serviceAliasesByClass[$class][] = $metadataCollection[$class]->name;
}
}
/**
* TODO: now we need to implement not forcing to load fixed dependencies into modules
* to give ability to change constructors and inject old variable into properties
* and them after refactoring remove them. With this we can only specify needed dependencies
* in new modules, and still have old ones working.
*/
foreach ($metadataCollection as $alias => $metadata) {
foreach ($metadata->propertiesMetadata as $property => $propertyMetadata) {
if (is_string($propertyMetadata->dependency)) {
$dependency = $propertyMetadata->dependency;
if (array_key_exists($dependency, $implementsByAlias)) {
$propertyMetadata->dependency = $implementsByAlias[$dependency][0];
} elseif (array_key_exists($dependency, $serviceAliasesByClass)) {
$propertyMetadata->dependency = $serviceAliasesByClass[$dependency][0];
} else {
}
}
}
// Iterate constructor arguments to preserve arguments order and inject dependencies
$reflectionClass = new \ReflectionClass($metadata->className);
// Check if instance has a constructor or it instance of external module
if ($reflectionClass->hasMethod('__construct') && is_subclass_of($metadata->className, ExternalModule::class)) {
foreach ((new \ReflectionMethod($metadata->className, '__construct'))->getParameters() as $parameter) {
if ($parameter->getName() === 'path') {
$metadata->methodsMetadata['__construct']->dependencies['path'] = dirname($listPath[$metadata->name ?? $metadata->className]);
} elseif ($parameter->getName() === 'resources') {
$metadata->methodsMetadata['__construct']->dependencies['resources'] = ResourceMap::class;
} elseif ($parameter->getName() === 'system') {
$metadata->methodsMetadata['__construct']->dependencies['system'] = 'core';
}
}
}
foreach ($metadata->methodsMetadata as $method => $methodMetadata) {
foreach ($methodMetadata->dependencies as $argument => $dependency) {
if (is_string($dependency)) {
if (array_key_exists($dependency, $implementsByAlias)) {
$methodMetadata->dependencies[$argument] = $implementsByAlias[$dependency][0];
//$methodMetadata->parametersMetadata[$argument]->dependency = $implementsByAlias[$dependency][0];
} elseif (array_key_exists($dependency, $serviceAliasesByClass)) {
$methodMetadata->dependencies[$argument] = $serviceAliasesByClass[$dependency][0];
//$methodMetadata->parametersMetadata[$argument]->dependency = $serviceAliasesByClass[$dependency][0];
} else {
}
}
}
}
}
} | php | public function replaceInterfaceDependencies(array $metadataCollection) {
$list = [];
$listPath = [];
/** @var ClassMetadata $classMetadata */
foreach ($metadataCollection as $classPath => $classMetadata) {
$list[$classMetadata->className] = $classMetadata;
$listPath[$classMetadata->name ?? $classMetadata->className] = $classPath;
}
$metadataCollection = $list;
// Gather all interface implementations
$implementsByAlias = $implementsByAlias ?? [];
foreach (get_declared_classes() as $class) {
$classImplements = class_implements($class);
foreach (get_declared_interfaces() as $interface) {
if (in_array($interface, $classImplements, true)) {
if (array_key_exists($class, $metadataCollection)) {
$implementsByAlias[$interface][] = $metadataCollection[$class]->name;
}
}
}
}
// Gather all class implementations
$serviceAliasesByClass = $serviceAliasesByClass ?? [];
foreach (get_declared_classes() as $class) {
if (array_key_exists($class, $metadataCollection)) {
$serviceAliasesByClass[$class][] = $metadataCollection[$class]->name;
}
}
/**
* TODO: now we need to implement not forcing to load fixed dependencies into modules
* to give ability to change constructors and inject old variable into properties
* and them after refactoring remove them. With this we can only specify needed dependencies
* in new modules, and still have old ones working.
*/
foreach ($metadataCollection as $alias => $metadata) {
foreach ($metadata->propertiesMetadata as $property => $propertyMetadata) {
if (is_string($propertyMetadata->dependency)) {
$dependency = $propertyMetadata->dependency;
if (array_key_exists($dependency, $implementsByAlias)) {
$propertyMetadata->dependency = $implementsByAlias[$dependency][0];
} elseif (array_key_exists($dependency, $serviceAliasesByClass)) {
$propertyMetadata->dependency = $serviceAliasesByClass[$dependency][0];
} else {
}
}
}
// Iterate constructor arguments to preserve arguments order and inject dependencies
$reflectionClass = new \ReflectionClass($metadata->className);
// Check if instance has a constructor or it instance of external module
if ($reflectionClass->hasMethod('__construct') && is_subclass_of($metadata->className, ExternalModule::class)) {
foreach ((new \ReflectionMethod($metadata->className, '__construct'))->getParameters() as $parameter) {
if ($parameter->getName() === 'path') {
$metadata->methodsMetadata['__construct']->dependencies['path'] = dirname($listPath[$metadata->name ?? $metadata->className]);
} elseif ($parameter->getName() === 'resources') {
$metadata->methodsMetadata['__construct']->dependencies['resources'] = ResourceMap::class;
} elseif ($parameter->getName() === 'system') {
$metadata->methodsMetadata['__construct']->dependencies['system'] = 'core';
}
}
}
foreach ($metadata->methodsMetadata as $method => $methodMetadata) {
foreach ($methodMetadata->dependencies as $argument => $dependency) {
if (is_string($dependency)) {
if (array_key_exists($dependency, $implementsByAlias)) {
$methodMetadata->dependencies[$argument] = $implementsByAlias[$dependency][0];
//$methodMetadata->parametersMetadata[$argument]->dependency = $implementsByAlias[$dependency][0];
} elseif (array_key_exists($dependency, $serviceAliasesByClass)) {
$methodMetadata->dependencies[$argument] = $serviceAliasesByClass[$dependency][0];
//$methodMetadata->parametersMetadata[$argument]->dependency = $serviceAliasesByClass[$dependency][0];
} else {
}
}
}
}
}
} | Replace interface dependency on their implementation
@param array $metadataCollection | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/loader/ContainerManager.php#L161-L245 |
samsonos/php_core | src/loader/ContainerManager.php | ContainerManager.collectAnnotationMetadata | public function collectAnnotationMetadata($classes, $metadataCollection)
{
// Load annotation and parse classes
new Injectable();
new InjectArgument(['var' => 'type']);
new Service(['value' => '']);
$reader = new AnnotationReader();
$resolver = new AnnotationResolver(
new AnnotationClassResolver($reader),
new AnnotationPropertyResolver($reader),
new AnnotationMethodResolver($reader)
);
$annotationCollector = new AnnotationMetadataCollector($resolver);
// Rewrite collection by entity name
return $annotationCollector->collect($classes, $metadataCollection);
} | php | public function collectAnnotationMetadata($classes, $metadataCollection)
{
// Load annotation and parse classes
new Injectable();
new InjectArgument(['var' => 'type']);
new Service(['value' => '']);
$reader = new AnnotationReader();
$resolver = new AnnotationResolver(
new AnnotationClassResolver($reader),
new AnnotationPropertyResolver($reader),
new AnnotationMethodResolver($reader)
);
$annotationCollector = new AnnotationMetadataCollector($resolver);
// Rewrite collection by entity name
return $annotationCollector->collect($classes, $metadataCollection);
} | Get annotation metadata
@param $classes
@param $metadataCollection
@return array|\samsonframework\container\metadata\ClassMetadata[] | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/loader/ContainerManager.php#L269-L287 |
danhanly/signalert | src/Signalert/Resolver.php | Resolver.getRenderer | public function getRenderer()
{
// Attempt to retrieve the renderer config
$config = new Config($this->configDirectory);
$rendererClass = $config->getRenderer();
// Validate Renderer Class
$reflection = new ReflectionClass($rendererClass);
// Ensure class is built with the correct interface
if (false === $reflection->implementsInterface('Signalert\Renderer\RendererInterface')) {
throw new SignalertResolverException;
}
// If it all checks out, resolve the class and instantiate
return $reflection->newInstance();
} | php | public function getRenderer()
{
// Attempt to retrieve the renderer config
$config = new Config($this->configDirectory);
$rendererClass = $config->getRenderer();
// Validate Renderer Class
$reflection = new ReflectionClass($rendererClass);
// Ensure class is built with the correct interface
if (false === $reflection->implementsInterface('Signalert\Renderer\RendererInterface')) {
throw new SignalertResolverException;
}
// If it all checks out, resolve the class and instantiate
return $reflection->newInstance();
} | Returns a valid renderer class
@return RendererInterface
@throws Exception\SignalertInvalidRendererException
@throws SignalertResolverException | https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Resolver.php#L32-L45 |
danhanly/signalert | src/Signalert/Resolver.php | Resolver.getDriver | public function getDriver()
{
// Attempt to retrieve the driver config
$config = new Config($this->configDirectory);
$driverClass = $config->getDriver();
// Validate Driver Class
$reflection = new ReflectionClass($driverClass);
// Ensure class is built with the correct interface
if (false === $reflection->implementsInterface('Signalert\Storage\DriverInterface')) {
throw new SignalertResolverException;
}
// If it all checks out, resolve the class and instantiate
return $reflection->newInstance();
} | php | public function getDriver()
{
// Attempt to retrieve the driver config
$config = new Config($this->configDirectory);
$driverClass = $config->getDriver();
// Validate Driver Class
$reflection = new ReflectionClass($driverClass);
// Ensure class is built with the correct interface
if (false === $reflection->implementsInterface('Signalert\Storage\DriverInterface')) {
throw new SignalertResolverException;
}
// If it all checks out, resolve the class and instantiate
return $reflection->newInstance();
} | Returns a valid driver class
@return DriverInterface
@throws SignalertResolverException | https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Resolver.php#L53-L67 |
ruvents/ruwork-synchronizer | SynchronizerFactory.php | SynchronizerFactory.createSynchronizer | public function createSynchronizer(string $type, array $attributes = []): SynchronizerInterface
{
return $this->createContextBuilder()
->setAttributes($attributes)
->createContext()
->getSynchronizer($type);
} | php | public function createSynchronizer(string $type, array $attributes = []): SynchronizerInterface
{
return $this->createContextBuilder()
->setAttributes($attributes)
->createContext()
->getSynchronizer($type);
} | {@inheritdoc} | https://github.com/ruvents/ruwork-synchronizer/blob/68aa35d48f04634828e76eb2a49e504985da92a9/SynchronizerFactory.php#L26-L32 |
greg-md/php-view | src/Viewer.php | Viewer.getCompiler | public function getCompiler(string $extension): CompilerStrategy
{
if (!$this->hasCompiler($extension)) {
throw new ViewException('View compiler for extension `' . $extension . '` not found.');
}
$compiler = &$this->compilers[$extension];
if (is_callable($compiler)) {
$compiler = call_user_func_array($compiler, [$this]);
}
if (!($compiler instanceof CompilerStrategy)) {
throw new ViewException('View compiler for extension `' . $extension . '` should be an instance of `' . CompilerStrategy::class . '`.');
}
return $compiler;
} | php | public function getCompiler(string $extension): CompilerStrategy
{
if (!$this->hasCompiler($extension)) {
throw new ViewException('View compiler for extension `' . $extension . '` not found.');
}
$compiler = &$this->compilers[$extension];
if (is_callable($compiler)) {
$compiler = call_user_func_array($compiler, [$this]);
}
if (!($compiler instanceof CompilerStrategy)) {
throw new ViewException('View compiler for extension `' . $extension . '` should be an instance of `' . CompilerStrategy::class . '`.');
}
return $compiler;
} | @param $extension
@throws ViewException
@return CompilerStrategy | https://github.com/greg-md/php-view/blob/1343928d951f236895afdff6afc240995db67afe/src/Viewer.php#L207-L224 |
rackberg/para | src/Para.php | Para.getVersion | public function getVersion()
{
$version = 'unknown';
/** @var \Para\Factory\ProcessFactoryInterface $processFactory */
$processFactory = $this->container->get('para.factory.process_factory');
$process = $processFactory->getProcess(
'git describe --tags --always',
__DIR__ . '/../'
);
$process->run();
if ($process->isSuccessful()) {
$version = trim($process->getOutput());
}
return $version;
} | php | public function getVersion()
{
$version = 'unknown';
/** @var \Para\Factory\ProcessFactoryInterface $processFactory */
$processFactory = $this->container->get('para.factory.process_factory');
$process = $processFactory->getProcess(
'git describe --tags --always',
__DIR__ . '/../'
);
$process->run();
if ($process->isSuccessful()) {
$version = trim($process->getOutput());
}
return $version;
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Para.php#L41-L58 |
skillberto/SonataExtendedAdminBundle | Controller/CRUDController.php | CRUDController.activateAction | public function activateAction()
{
$object = $this->getObject();
if (method_exists($object, 'setActive') && method_exists($object, 'getActive')) {
$object->setActive(($object->getActive()==1) ? 0 : 1);
}
$this->admin->update($object);
return new RedirectResponse($this->admin->generateUrl('list'));
} | php | public function activateAction()
{
$object = $this->getObject();
if (method_exists($object, 'setActive') && method_exists($object, 'getActive')) {
$object->setActive(($object->getActive()==1) ? 0 : 1);
}
$this->admin->update($object);
return new RedirectResponse($this->admin->generateUrl('list'));
} | Activate or inactivate the object
@throws Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@return Symfony\Component\HttpFoundation\RedirectResponse | https://github.com/skillberto/SonataExtendedAdminBundle/blob/5ca04cab25181e78b7ee4e866ae0567bd074fa41/Controller/CRUDController.php#L23-L34 |
dermatthes/html-template | src/Template/Opt/GoOrderedList.php | GoOrderedList.each | public function each(callable $fn) {
$this->_build();
foreach ($this->list as $curListItem) {
$prio = $curListItem[0];
$alias = $curListItem[1];
if ( ! isset ($this->item[$alias]))
continue;
$what = $this->item[$alias];
if ($fn($what, $prio, $alias) === false)
return false;
}
} | php | public function each(callable $fn) {
$this->_build();
foreach ($this->list as $curListItem) {
$prio = $curListItem[0];
$alias = $curListItem[1];
if ( ! isset ($this->item[$alias]))
continue;
$what = $this->item[$alias];
if ($fn($what, $prio, $alias) === false)
return false;
}
} | <example>
$c->each(function ($what, $prio, $alias) {
});
</example>
@param callable $fn | https://github.com/dermatthes/html-template/blob/e301fa669f9847f31af878e0a8929f6f880a5567/src/Template/Opt/GoOrderedList.php#L66-L78 |
oliwierptak/Everon1 | src/Everon/Helper/Asserts/IsArray.php | IsArray.assertIsArray | public function assertIsArray($value, $message='%s must be an Array', $exception='Asserts')
{
if (isset($value) === false || is_array($value) === false) {
$this->throwException($exception, $message, $value);
}
} | php | public function assertIsArray($value, $message='%s must be an Array', $exception='Asserts')
{
if (isset($value) === false || is_array($value) === false) {
$this->throwException($exception, $message, $value);
}
} | Verifies that the specified condition is array.
The assertion fails if the condition is not array.
@param mixed $value
@param string $message
@param string $exception
@throws \Everon\Exception\Asserts | https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/Asserts/IsArray.php#L23-L28 |
RowlandOti/ooglee-blogmodule | src/OoGlee/Application/Entities/Post/Category/CategoryResponse.php | PostResponse.make | public function make(ICategory $category)
{
//$category->setResponse($this->response->view('admin.categorys.view', compact('category')));
$category->setResponse($this->response->view(\OogleeBConfig::get('config.category_view.view'), compact('category')));
} | php | public function make(ICategory $category)
{
//$category->setResponse($this->response->view('admin.categorys.view', compact('category')));
$category->setResponse($this->response->view(\OogleeBConfig::get('config.category_view.view'), compact('category')));
} | Make the category response.
@param ICategory $category | https://github.com/RowlandOti/ooglee-blogmodule/blob/d9c0fe4745bb09f8b94047b0cda4fd7438cde16a/src/OoGlee/Application/Entities/Post/Category/CategoryResponse.php#L40-L44 |
alphacomm/alpharpc | src/AlphaRPC/Manager/WorkerHandler/Worker.php | Worker.addAction | public function addAction($action)
{
if ($action instanceof Action) {
$action = $action->getName();
}
$this->actionList[] = $action;
$this->valid = null;
return $this;
} | php | public function addAction($action)
{
if ($action instanceof Action) {
$action = $action->getName();
}
$this->actionList[] = $action;
$this->valid = null;
return $this;
} | Adds a action name to the list of actions the worker listens to.
@param Action $action
@return Worker | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Worker.php#L126-L135 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/Image/Entity/Image.php | Image.getFormattedImage | public function getFormattedImage($format)
{
$formatName = $format instanceof FormatInterface
? $format->getName()
: $format
;
return $this->formattedImages
->filter(function (FormattedImageInterface $formattedImage) use ($formatName) {
return ($format = $formattedImage->getFormat())
&& $format->getName() == $formatName
;
})
->first() ?: null // first() returns "false" if collection empty
;
} | php | public function getFormattedImage($format)
{
$formatName = $format instanceof FormatInterface
? $format->getName()
: $format
;
return $this->formattedImages
->filter(function (FormattedImageInterface $formattedImage) use ($formatName) {
return ($format = $formattedImage->getFormat())
&& $format->getName() == $formatName
;
})
->first() ?: null // first() returns "false" if collection empty
;
} | Returns image formatted for given format name or FormatInterface object.
@param string|FormatInterface $format
@return FormattedImageInterface|null | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/Image/Entity/Image.php#L213-L228 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/Image/Entity/Image.php | Image.getFormatWebPath | public function getFormatWebPath($format = null)
{
if (!$format = $format ?: $this->defaultFormat) {
return $this->getWebPath();
}
return ($formattedImage = $this->getFormattedImage($format))
? $formattedImage->getWebPath()
: $this->getWebPath()
;
} | php | public function getFormatWebPath($format = null)
{
if (!$format = $format ?: $this->defaultFormat) {
return $this->getWebPath();
}
return ($formattedImage = $this->getFormattedImage($format))
? $formattedImage->getWebPath()
: $this->getWebPath()
;
} | Returns requested format web path, or original one, if format doesnt exists.
@param string|FormatInterface $format
@return string | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/Image/Entity/Image.php#L237-L247 |
DimNS/MFLPHP | src/Init.php | Init.start | public function start()
{
//
// ,,
// mm mm db
// MM MM
// ,pP"Ybd .gP"Ya mmMMmm mmMMmm `7MM `7MMpMMMb. .P"Ybmmm ,pP"Ybd
// 8I `" ,M' Yb MM MM MM MM MM :MI I8 8I `"
// `YMMMa. 8M"""""" MM MM MM MM MM WmmmP" `YMMMa.
// L. I8 YM. , MM MM MM MM MM 8M L. I8
// M9mmmP' `Mbmmd' `Mbmo `Mbmo.JMML..JMML JMML.YMMMMMb M9mmmP'
// 6' dP
// Ybmmmd'
// Устанавливаем временные настройки
date_default_timezone_set(Settings::TIMEZONE);
setlocale(LC_TIME, 'ru_RU.UTF-8');
// Где будут хранится php сессии (в файлах или в БД)
if (Settings::PHP_SESSION === 'DB') {
new \Zebra_Session(
mysqli_connect(
Settings::DB_HOST,
Settings::DB_USER,
Settings::DB_PASSWORD,
Settings::DB_DATABASE,
Settings::DB_PORT
), 'AVuVqYR6uwgEuhV79tln0tlKk'
);
} else {
session_start();
}
// Включим страницу с ошибками, если включен режим DEBUG
if (Settings::DEBUG === true) {
$whoops = new Run;
$whoops->pushHandler(new PrettyPageHandler);
if (Misc::isAjaxRequest()) {
$jsonHandler = new JsonResponseHandler();
$jsonHandler->setJsonApi(true);
$whoops->pushHandler($jsonHandler);
}
$whoops->register();
}
// Настраиваем соединение с БД
\ORM::configure([
'connection_string' => 'mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE,
'username' => Settings::DB_USER,
'password' => Settings::DB_PASSWORD,
'logging' => Settings::DEBUG,
'driver_options' => [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
],
]);
// Инициализируем CSRF-токен
$csrf = new \DimNS\SimpleCSRF();
$this->csrf_token = $csrf->getToken();
// Определим корневую папку, если переменная не пустая
if (Settings::PATH_SHORT_ROOT != '/') {
$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen(Settings::PATH_SHORT_ROOT));
}
// Инициируем роутер
$klein = new \Klein\Klein();
//
//
// `7MM"""Yb. `7MMF'
// MM `Yb. MM
// MM `Mb MM
// MM MM MM
// MM ,MP MM
// MM ,dP' MM
// .JMMmmmdP' .JMML.
//
//
// Создаем DI
$klein->respond(function ($request, $response, $service, $di) use ($csrf) {
// Регистрируем доступ к Carbon
$di->register('carbon', function () {
return Carbon::now(Settings::TIMEZONE);
});
// Регистрируем доступ к настройкам
$di->register('cfg', function () {
return new \MFLPHP\Configs\Config();
});
// Регистрируем доступ к управлению пользователем
$di->register('auth', function () {
$dbh = new \PDO('mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE,
Settings::DB_USER,
Settings::DB_PASSWORD,
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]
);
return new Auth($dbh, new Config($dbh, 'phpauth_config'), 'ru_RU');
});
// Регистрируем доступ к информации о пользователе
$di->register('userinfo', function () use ($di) {
if ($di->auth->isLogged()) {
$user_id = $di->auth->getSessionUID($di->auth->getSessionHash());
$user_info = \ORM::for_table('users')
->join('users_info', ['users.id', '=', 'users_info.uid'])
->where_equal('id', $user_id)
->find_one();
if (is_object($user_info)) {
return $user_info;
}
}
return false;
});
// Регистрируем доступ к PHPMailer
$di->register('phpmailer', function () use ($di) {
$phpmailer = new \PHPMailer();
$phpmailer->setLanguage('ru', $di->cfg->abs_root_path . 'vendor/phpmailer/phpmailer/language/');
$phpmailer->IsHTML(true);
$phpmailer->CharSet = 'windows-1251';
$phpmailer->From = $di->auth->config->site_email;
$phpmailer->FromName = iconv('utf-8', 'windows-1251', $di->auth->config->site_name);
if ('1' == $di->auth->config->smtp) {
$phpmailer->IsSMTP();
$phpmailer->SMTPDebug = 0;
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = $di->auth->config->smtp_security;
$phpmailer->Host = $di->auth->config->smtp_host;
$phpmailer->Port = $di->auth->config->smtp_port;
$phpmailer->Username = $di->auth->config->smtp_username;
$phpmailer->Password = $di->auth->config->smtp_password;
}
return $phpmailer;
});
// Регистрируем доступ к отправке почты
$di->register('mail', function () use ($di) {
return new EmailSender($di);
});
// Регистрируем доступ к логгеру Monolog
$di->register('log', function () use ($di) {
$log = new Logger('MainLog');
$log->pushHandler(new StreamHandler($di->cfg->abs_root_path . 'errors.log', Logger::DEBUG));
return $log;
});
// Регистрируем доступ к проверке CSRF-токена
$di->register('csrf', function () use ($csrf) {
return $csrf;
});
$views_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Views/';
$service->layout($views_path . 'layout-default.php');
$service->csrf_token = $this->csrf_token;
$service->path = Settings::PATH_SHORT_ROOT;
$service->app_root_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app';
$service->uri = $request->uri();
$service->di = $di;
});
//
//
// mm
// MM
// `7Mb,od8 ,pW"Wq.`7MM `7MM mmMMmm .gP"Ya ,pP"Ybd
// MM' "'6W' `Wb MM MM MM ,M' Yb 8I `"
// MM 8M M8 MM MM MM 8M"""""" `YMMMa.
// MM YA. ,A9 MM MM MM YM. , L. I8
// .JMML. `Ybmd9' `Mbod"YML. `Mbmo`Mbmmd' M9mmmP'
//
//
require_once $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Routes.php';
//
//
//
//
// `7Mb,od8 `7MM `7MM `7MMpMMMb.
// MM' "' MM MM MM MM
// MM MM MM MM MM
// MM MM MM MM MM
// .JMML. `Mbod"YML..JMML JMML.
//
//
$klein->dispatch();
} | php | public function start()
{
//
// ,,
// mm mm db
// MM MM
// ,pP"Ybd .gP"Ya mmMMmm mmMMmm `7MM `7MMpMMMb. .P"Ybmmm ,pP"Ybd
// 8I `" ,M' Yb MM MM MM MM MM :MI I8 8I `"
// `YMMMa. 8M"""""" MM MM MM MM MM WmmmP" `YMMMa.
// L. I8 YM. , MM MM MM MM MM 8M L. I8
// M9mmmP' `Mbmmd' `Mbmo `Mbmo.JMML..JMML JMML.YMMMMMb M9mmmP'
// 6' dP
// Ybmmmd'
// Устанавливаем временные настройки
date_default_timezone_set(Settings::TIMEZONE);
setlocale(LC_TIME, 'ru_RU.UTF-8');
// Где будут хранится php сессии (в файлах или в БД)
if (Settings::PHP_SESSION === 'DB') {
new \Zebra_Session(
mysqli_connect(
Settings::DB_HOST,
Settings::DB_USER,
Settings::DB_PASSWORD,
Settings::DB_DATABASE,
Settings::DB_PORT
), 'AVuVqYR6uwgEuhV79tln0tlKk'
);
} else {
session_start();
}
// Включим страницу с ошибками, если включен режим DEBUG
if (Settings::DEBUG === true) {
$whoops = new Run;
$whoops->pushHandler(new PrettyPageHandler);
if (Misc::isAjaxRequest()) {
$jsonHandler = new JsonResponseHandler();
$jsonHandler->setJsonApi(true);
$whoops->pushHandler($jsonHandler);
}
$whoops->register();
}
// Настраиваем соединение с БД
\ORM::configure([
'connection_string' => 'mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE,
'username' => Settings::DB_USER,
'password' => Settings::DB_PASSWORD,
'logging' => Settings::DEBUG,
'driver_options' => [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
],
]);
// Инициализируем CSRF-токен
$csrf = new \DimNS\SimpleCSRF();
$this->csrf_token = $csrf->getToken();
// Определим корневую папку, если переменная не пустая
if (Settings::PATH_SHORT_ROOT != '/') {
$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen(Settings::PATH_SHORT_ROOT));
}
// Инициируем роутер
$klein = new \Klein\Klein();
//
//
// `7MM"""Yb. `7MMF'
// MM `Yb. MM
// MM `Mb MM
// MM MM MM
// MM ,MP MM
// MM ,dP' MM
// .JMMmmmdP' .JMML.
//
//
// Создаем DI
$klein->respond(function ($request, $response, $service, $di) use ($csrf) {
// Регистрируем доступ к Carbon
$di->register('carbon', function () {
return Carbon::now(Settings::TIMEZONE);
});
// Регистрируем доступ к настройкам
$di->register('cfg', function () {
return new \MFLPHP\Configs\Config();
});
// Регистрируем доступ к управлению пользователем
$di->register('auth', function () {
$dbh = new \PDO('mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE,
Settings::DB_USER,
Settings::DB_PASSWORD,
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]
);
return new Auth($dbh, new Config($dbh, 'phpauth_config'), 'ru_RU');
});
// Регистрируем доступ к информации о пользователе
$di->register('userinfo', function () use ($di) {
if ($di->auth->isLogged()) {
$user_id = $di->auth->getSessionUID($di->auth->getSessionHash());
$user_info = \ORM::for_table('users')
->join('users_info', ['users.id', '=', 'users_info.uid'])
->where_equal('id', $user_id)
->find_one();
if (is_object($user_info)) {
return $user_info;
}
}
return false;
});
// Регистрируем доступ к PHPMailer
$di->register('phpmailer', function () use ($di) {
$phpmailer = new \PHPMailer();
$phpmailer->setLanguage('ru', $di->cfg->abs_root_path . 'vendor/phpmailer/phpmailer/language/');
$phpmailer->IsHTML(true);
$phpmailer->CharSet = 'windows-1251';
$phpmailer->From = $di->auth->config->site_email;
$phpmailer->FromName = iconv('utf-8', 'windows-1251', $di->auth->config->site_name);
if ('1' == $di->auth->config->smtp) {
$phpmailer->IsSMTP();
$phpmailer->SMTPDebug = 0;
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = $di->auth->config->smtp_security;
$phpmailer->Host = $di->auth->config->smtp_host;
$phpmailer->Port = $di->auth->config->smtp_port;
$phpmailer->Username = $di->auth->config->smtp_username;
$phpmailer->Password = $di->auth->config->smtp_password;
}
return $phpmailer;
});
// Регистрируем доступ к отправке почты
$di->register('mail', function () use ($di) {
return new EmailSender($di);
});
// Регистрируем доступ к логгеру Monolog
$di->register('log', function () use ($di) {
$log = new Logger('MainLog');
$log->pushHandler(new StreamHandler($di->cfg->abs_root_path . 'errors.log', Logger::DEBUG));
return $log;
});
// Регистрируем доступ к проверке CSRF-токена
$di->register('csrf', function () use ($csrf) {
return $csrf;
});
$views_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Views/';
$service->layout($views_path . 'layout-default.php');
$service->csrf_token = $this->csrf_token;
$service->path = Settings::PATH_SHORT_ROOT;
$service->app_root_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app';
$service->uri = $request->uri();
$service->di = $di;
});
//
//
// mm
// MM
// `7Mb,od8 ,pW"Wq.`7MM `7MM mmMMmm .gP"Ya ,pP"Ybd
// MM' "'6W' `Wb MM MM MM ,M' Yb 8I `"
// MM 8M M8 MM MM MM 8M"""""" `YMMMa.
// MM YA. ,A9 MM MM MM YM. , L. I8
// .JMML. `Ybmd9' `Mbod"YML. `Mbmo`Mbmmd' M9mmmP'
//
//
require_once $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Routes.php';
//
//
//
//
// `7Mb,od8 `7MM `7MM `7MMpMMMb.
// MM' "' MM MM MM MM
// MM MM MM MM MM
// MM MM MM MM MM
// .JMML. `Mbod"YML..JMML JMML.
//
//
$klein->dispatch();
} | Старт приложения
@version 27.04.2017
@author Дмитрий Щербаков <[email protected]> | https://github.com/DimNS/MFLPHP/blob/8da06f3f9aabf1da5796f9a3cea97425b30af201/src/Init.php#L52-L259 |
nasumilu/geometry | src/MultiSurface.php | MultiSurface.getArea | public function getArea(): float {
$event = new MeasurementOpEvent($this);
$this->fireOperationEvent(MeasurementOpEvent::AREA_EVENT, $event);
return $event->getResults();
} | php | public function getArea(): float {
$event = new MeasurementOpEvent($this);
$this->fireOperationEvent(MeasurementOpEvent::AREA_EVENT, $event);
return $event->getResults();
} | Gets the area of this MultiSurface, as measured in the spatial reference
system of this Surface.
@return float | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/MultiSurface.php#L65-L69 |
nasumilu/geometry | src/MultiSurface.php | MultiSurface.getPointOnSurface | public function getPointOnSurface(): Point {
$event = new ProcessOpEvent($this);
$this->fireOperationEvent(ProcessOpEvent::POINT_ON_SURFACE_EVENT, $event);
return $event->getResults();
} | php | public function getPointOnSurface(): Point {
$event = new ProcessOpEvent($this);
$this->fireOperationEvent(ProcessOpEvent::POINT_ON_SURFACE_EVENT, $event);
return $event->getResults();
} | Gets a Point guaranteed to be on the MultiSurface.
@return \Nasumilu\Geometry\Geometry | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/MultiSurface.php#L88-L92 |
siriusphp/filtration | src/Filtrator.php | Filtrator.add | function add($selector, $callbackOrFilterName = null, $options = null, $recursive = false, $priority = 0)
{
/**
* $selector is actually an array with filters
*
* @example $filtrator->add(array(
* 'title' => array('trim', array('truncate', '{"limit":100}'))
* 'description' => array('trim')
* ));
*/
if (is_array($selector)) {
foreach ($selector as $key => $filters) {
$this->add($key, $filters);
}
return $this;
}
if (! is_string($selector)) {
throw new \InvalidArgumentException('The data selector for filtering must be a string');
}
if (is_string($callbackOrFilterName)) {
// rule was supplied like 'trim' or 'trim | nullify'
if (strpos($callbackOrFilterName, ' | ') !== false) {
return $this->add($selector, explode(' | ', $callbackOrFilterName));
}
// rule was supplied like this 'trim(limit=10)(true)(10)'
if (strpos($callbackOrFilterName, '(') !== false) {
list ($callbackOrFilterName, $options, $recursive, $priority) = $this->parseRule($callbackOrFilterName);
}
}
/**
* The $callbackOrFilterName is an array of filters
*
* @example $filtrator->add('title', array(
* 'trim',
* array('truncate', '{"limit":100}')
* ));
*/
if (is_array($callbackOrFilterName) && ! is_callable($callbackOrFilterName)) {
foreach ($callbackOrFilterName as $filter) {
// $filter is something like array('truncate', '{"limit":100}')
if (is_array($filter) && ! is_callable($filter)) {
$args = $filter;
array_unshift($args, $selector);
call_user_func_array(array(
$this,
'add'
), $args);
} elseif (is_string($filter) || is_callable($filter)) {
$this->add($selector, $filter);
}
}
return $this;
}
$filter = $this->filterFactory->createFilter($callbackOrFilterName, $options, $recursive);
if (! array_key_exists($selector, $this->filters)) {
$this->filters[$selector] = new FilterSet();
}
/* @var $filterSet FilterSet */
$filterSet = $this->filters[$selector];
$filterSet->insert($filter, $priority);
return $this;
} | php | function add($selector, $callbackOrFilterName = null, $options = null, $recursive = false, $priority = 0)
{
/**
* $selector is actually an array with filters
*
* @example $filtrator->add(array(
* 'title' => array('trim', array('truncate', '{"limit":100}'))
* 'description' => array('trim')
* ));
*/
if (is_array($selector)) {
foreach ($selector as $key => $filters) {
$this->add($key, $filters);
}
return $this;
}
if (! is_string($selector)) {
throw new \InvalidArgumentException('The data selector for filtering must be a string');
}
if (is_string($callbackOrFilterName)) {
// rule was supplied like 'trim' or 'trim | nullify'
if (strpos($callbackOrFilterName, ' | ') !== false) {
return $this->add($selector, explode(' | ', $callbackOrFilterName));
}
// rule was supplied like this 'trim(limit=10)(true)(10)'
if (strpos($callbackOrFilterName, '(') !== false) {
list ($callbackOrFilterName, $options, $recursive, $priority) = $this->parseRule($callbackOrFilterName);
}
}
/**
* The $callbackOrFilterName is an array of filters
*
* @example $filtrator->add('title', array(
* 'trim',
* array('truncate', '{"limit":100}')
* ));
*/
if (is_array($callbackOrFilterName) && ! is_callable($callbackOrFilterName)) {
foreach ($callbackOrFilterName as $filter) {
// $filter is something like array('truncate', '{"limit":100}')
if (is_array($filter) && ! is_callable($filter)) {
$args = $filter;
array_unshift($args, $selector);
call_user_func_array(array(
$this,
'add'
), $args);
} elseif (is_string($filter) || is_callable($filter)) {
$this->add($selector, $filter);
}
}
return $this;
}
$filter = $this->filterFactory->createFilter($callbackOrFilterName, $options, $recursive);
if (! array_key_exists($selector, $this->filters)) {
$this->filters[$selector] = new FilterSet();
}
/* @var $filterSet FilterSet */
$filterSet = $this->filters[$selector];
$filterSet->insert($filter, $priority);
return $this;
} | Add a filter to the filters stack
@example // normal callback
$filtrator->add('title', '\strip_tags');
// anonymous function
$filtrator->add('title', function($value){ return $value . '!!!'; });
// filter class from the library registered on the $filtersMap
$filtrator->add('title', 'normalizedate', array('format' => 'm/d/Y'));
// custom class
$filtrator->add('title', '\MyApp\Filters\CustomFilter');
// multiple filters as once with different ways to pass options
$filtrator->add('title', array(
array('truncate', 'limit=10', true, 10),
array('censor', array('words' => array('faggy', 'idiot'))
));
// multiple fitlers as a single string
$filtrator->add('title', 'stringtrim(side=left)(true)(10) | truncate(limit=100)');
@param string|array $selector
@param mixed $callbackOrFilterName
@param array|null $options
@param bool $recursive
@param integer $priority
@throws \InvalidArgumentException
@internal param $ callable|filter class name|\Sirius\Filtration\Filter\AbstractFilter $callbackOrFilterName* callable|filter class name|\Sirius\Filtration\Filter\AbstractFilter $callbackOrFilterName
@internal param array|string $params
@return self | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L58-L124 |
siriusphp/filtration | src/Filtrator.php | Filtrator.parseRule | protected function parseRule($ruleAsString)
{
$ruleAsString = trim($ruleAsString);
$options = array();
$recursive = false;
$priority = 0;
$name = substr($ruleAsString, 0, strpos($ruleAsString, '('));
$ruleAsString = substr($ruleAsString, strpos($ruleAsString, '('));
$matches = array();
preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches);
if (isset($matches[1])) {
if (isset($matches[1][0]) && $matches[1][0]) {
$options = $matches[1][0];
}
if (isset($matches[1][1]) && $matches[1][1]) {
$recursive = (in_array($matches[1][1], array(true, 'TRUE', 'true', 1))) ? true : false;
}
if (isset($matches[1][2]) && $matches[1][2]) {
$priority = (int)$matches[1][2];
}
}
return array(
$name,
$options,
$recursive,
$priority
);
} | php | protected function parseRule($ruleAsString)
{
$ruleAsString = trim($ruleAsString);
$options = array();
$recursive = false;
$priority = 0;
$name = substr($ruleAsString, 0, strpos($ruleAsString, '('));
$ruleAsString = substr($ruleAsString, strpos($ruleAsString, '('));
$matches = array();
preg_match_all('/\(([^\)]*)\)/', $ruleAsString, $matches);
if (isset($matches[1])) {
if (isset($matches[1][0]) && $matches[1][0]) {
$options = $matches[1][0];
}
if (isset($matches[1][1]) && $matches[1][1]) {
$recursive = (in_array($matches[1][1], array(true, 'TRUE', 'true', 1))) ? true : false;
}
if (isset($matches[1][2]) && $matches[1][2]) {
$priority = (int)$matches[1][2];
}
}
return array(
$name,
$options,
$recursive,
$priority
);
} | Converts a rule that was supplied as string into a set of options that define the rule
@example 'minLength({"min":2})(true)(10)'
will be converted into
array(
'minLength', // validator name
array('min' => 2'), // validator options
true, // recursive
10 // priority
)
@param string $ruleAsString
@return array | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L142-L173 |
siriusphp/filtration | src/Filtrator.php | Filtrator.remove | function remove($selector, $callbackOrName = true)
{
if (array_key_exists($selector, $this->filters)) {
if ($callbackOrName === true) {
unset($this->filters[$selector]);
} else {
if (! is_object($callbackOrName)) {
$filter = $this->filterFactory->createFilter($callbackOrName);
} else {
$filter = $callbackOrName;
}
/* @var $filterSet FilterSet */
$filterSet = $this->filters[$selector];
$filterSet->remove($filter);
}
}
return $this;
} | php | function remove($selector, $callbackOrName = true)
{
if (array_key_exists($selector, $this->filters)) {
if ($callbackOrName === true) {
unset($this->filters[$selector]);
} else {
if (! is_object($callbackOrName)) {
$filter = $this->filterFactory->createFilter($callbackOrName);
} else {
$filter = $callbackOrName;
}
/* @var $filterSet FilterSet */
$filterSet = $this->filters[$selector];
$filterSet->remove($filter);
}
}
return $this;
} | Remove a filter from the stack
@param string $selector
@param bool|callable|string|TRUE $callbackOrName
@throws \InvalidArgumentException
@return \Sirius\Filtration\Filtrator | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L183-L200 |
siriusphp/filtration | src/Filtrator.php | Filtrator.filter | function filter($data = array())
{
if (! is_array($data)) {
return $data;
}
// first apply the filters to the ROOT
if (isset($this->filters[self::SELECTOR_ROOT])) {
/* @var $rootFilters FilterSet */
$rootFilters = $this->filters[self::SELECTOR_ROOT];
$data = $rootFilters->applyFilters($data);
}
foreach ($data as $key => $value) {
$data[$key] = $this->filterItem($data, $key);
}
return $data;
} | php | function filter($data = array())
{
if (! is_array($data)) {
return $data;
}
// first apply the filters to the ROOT
if (isset($this->filters[self::SELECTOR_ROOT])) {
/* @var $rootFilters FilterSet */
$rootFilters = $this->filters[self::SELECTOR_ROOT];
$data = $rootFilters->applyFilters($data);
}
foreach ($data as $key => $value) {
$data[$key] = $this->filterItem($data, $key);
}
return $data;
} | Apply filters to an array
@param array $data
@return array | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L218-L233 |
siriusphp/filtration | src/Filtrator.php | Filtrator.filterItem | function filterItem($data, $valueIdentifier)
{
$value = Utils::arrayGetByPath($data, $valueIdentifier);
$value = $this->applyFilters($value, $valueIdentifier, $data);
if (is_array($value)) {
foreach (array_keys($value) as $k) {
$value[$k] = $this->filterItem($data, "{$valueIdentifier}[{$k}]");
}
}
return $value;
} | php | function filterItem($data, $valueIdentifier)
{
$value = Utils::arrayGetByPath($data, $valueIdentifier);
$value = $this->applyFilters($value, $valueIdentifier, $data);
if (is_array($value)) {
foreach (array_keys($value) as $k) {
$value[$k] = $this->filterItem($data, "{$valueIdentifier}[{$k}]");
}
}
return $value;
} | Apply filters on a single item in the array
@param array $data
@param string $valueIdentifier
@return mixed | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L242-L252 |
siriusphp/filtration | src/Filtrator.php | Filtrator.applyFilters | function applyFilters($value, $valueIdentifier, $context)
{
foreach ($this->filters as $selector => $filterSet) {
/* @var $filterSet FilterSet */
if ($selector != self::SELECTOR_ROOT && $this->itemMatchesSelector($valueIdentifier, $selector)) {
$value = $filterSet->applyFilters($value, $valueIdentifier, $context);
}
}
return $value;
} | php | function applyFilters($value, $valueIdentifier, $context)
{
foreach ($this->filters as $selector => $filterSet) {
/* @var $filterSet FilterSet */
if ($selector != self::SELECTOR_ROOT && $this->itemMatchesSelector($valueIdentifier, $selector)) {
$value = $filterSet->applyFilters($value, $valueIdentifier, $context);
}
}
return $value;
} | Apply filters to a single value
@param mixed $value
value of the item
@param string $valueIdentifier
array element path (eg: 'key' or 'key[0][subkey]')
@param mixed $context
@return mixed | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L264-L273 |
siriusphp/filtration | src/Filtrator.php | Filtrator.itemMatchesSelector | protected function itemMatchesSelector($item, $selector)
{
// the selector is a simple path identifier
// NOT something like key[*][subkey]
if (strpos($selector, '*') === false) {
return $item === $selector;
}
$regex = '/' . str_replace('*', '[^\]]+', str_replace(array(
'[',
']'
), array(
'\[',
'\]'
), $selector)) . '/';
return preg_match($regex, $item);
} | php | protected function itemMatchesSelector($item, $selector)
{
// the selector is a simple path identifier
// NOT something like key[*][subkey]
if (strpos($selector, '*') === false) {
return $item === $selector;
}
$regex = '/' . str_replace('*', '[^\]]+', str_replace(array(
'[',
']'
), array(
'\[',
'\]'
), $selector)) . '/';
return preg_match($regex, $item);
} | Checks if an item matches a selector
@example $this->('key[subkey]', 'key[*]') -> true;
$this->('key[subkey]', 'subkey') -> false;
@param string $item
@param string $selector
@return boolean number | https://github.com/siriusphp/filtration/blob/9f96592484f6d326e8bb8d5957be604a1622d08f/src/Filtrator.php#L285-L300 |
temp/media-converter | src/Converter/DelegatingConverter.php | DelegatingConverter.accept | public function accept(Specification $spec)
{
$converter = $this->resolver->resolve($spec);
if (!$converter) {
return false;
}
return true;
} | php | public function accept(Specification $spec)
{
$converter = $this->resolver->resolve($spec);
if (!$converter) {
return false;
}
return true;
} | {@inheritdoc} | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/DelegatingConverter.php#L37-L46 |
temp/media-converter | src/Converter/DelegatingConverter.php | DelegatingConverter.convert | public function convert($inFilename, Specification $spec, $outFilename)
{
$converter = $this->resolver->resolve($spec);
if (!$converter) {
throw new \Exception("No converter found for specification " . get_class($spec));
}
return $converter->convert($inFilename, $spec, $outFilename);
} | php | public function convert($inFilename, Specification $spec, $outFilename)
{
$converter = $this->resolver->resolve($spec);
if (!$converter) {
throw new \Exception("No converter found for specification " . get_class($spec));
}
return $converter->convert($inFilename, $spec, $outFilename);
} | @param string $inFilename
@param Specification $spec
@param string $outFilename
@return string
@throws \Exception | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/DelegatingConverter.php#L56-L65 |
scarwu/Pack | src/Pack/HTML.php | HTML.get | public function get($html = null)
{
if (null === $html) {
if (file_exists($this->_path)) {
$html = file_get_contents($this->_path);
}
}
$this->_path = null;
return $this->parse($html);
} | php | public function get($html = null)
{
if (null === $html) {
if (file_exists($this->_path)) {
$html = file_get_contents($this->_path);
}
}
$this->_path = null;
return $this->parse($html);
} | Get Packed HTML
@param string
@param string | https://github.com/scarwu/Pack/blob/284e3273b18ac963f597893059c0b0d34fa15695/src/Pack/HTML.php#L41-L52 |
scarwu/Pack | src/Pack/HTML.php | HTML.parse | private function parse($input)
{
$in_tag = false;
$in_quote = false;
$in_script_tag = false;
$in_style_tag = false;
$in_style_attribute = false;
$text = '';
$js_pack = new JS();
$css_pack = new CSS();
$input = str_replace(["\r\n", "\r"], "\n", $input);
$output = '';
for ($i = 0;$i < strlen($input);$i++) {
$char = substr($input, $i, 1);
$pre_input_char = $i != 0 ? substr($input, $i - 1, 1) : null;
$pre_output_char = substr($output, -1);
if ($in_tag && !$in_quote) {
if ('"' === $char) {
// ' "'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_quote = true;
$output .= $char;
continue;
}
if ('>' === $char) {
// ' >'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_tag = false;
$output .= $char;
continue;
}
if ("\n" === $char || "\t" === $char) {
continue;
}
// ' '
if (' ' === $pre_output_char && ' ' === $char) {
continue;
}
// '< '
if ('<' === $pre_output_char && ' ' === $char) {
continue;
}
// ' ='
if (' ' === $pre_output_char && '=' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
// ' /'
if (' ' === $pre_output_char && '/' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
$output .= $char;
continue;
}
if ($in_tag && $in_quote) {
if ('"' === $char) {
$in_quote = false;
}
$output .= $char;
continue;
}
if (!$in_tag && !$in_quote) {
if ('<' === $char) {
// ' <'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_tag = true;
$output .= $char;
continue;
}
if ("\n" === $char || "\t" === $char) {
continue;
}
// ' '
if (' ' === $pre_output_char && ' ' === $char) {
continue;
}
// '> '
if ('>' === $pre_output_char && ' ' === $char) {
continue;
}
// ' <'
if (' ' === $pre_output_char && '<' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
$output .= $char;
continue;
}
}
return trim($output);
} | php | private function parse($input)
{
$in_tag = false;
$in_quote = false;
$in_script_tag = false;
$in_style_tag = false;
$in_style_attribute = false;
$text = '';
$js_pack = new JS();
$css_pack = new CSS();
$input = str_replace(["\r\n", "\r"], "\n", $input);
$output = '';
for ($i = 0;$i < strlen($input);$i++) {
$char = substr($input, $i, 1);
$pre_input_char = $i != 0 ? substr($input, $i - 1, 1) : null;
$pre_output_char = substr($output, -1);
if ($in_tag && !$in_quote) {
if ('"' === $char) {
// ' "'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_quote = true;
$output .= $char;
continue;
}
if ('>' === $char) {
// ' >'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_tag = false;
$output .= $char;
continue;
}
if ("\n" === $char || "\t" === $char) {
continue;
}
// ' '
if (' ' === $pre_output_char && ' ' === $char) {
continue;
}
// '< '
if ('<' === $pre_output_char && ' ' === $char) {
continue;
}
// ' ='
if (' ' === $pre_output_char && '=' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
// ' /'
if (' ' === $pre_output_char && '/' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
$output .= $char;
continue;
}
if ($in_tag && $in_quote) {
if ('"' === $char) {
$in_quote = false;
}
$output .= $char;
continue;
}
if (!$in_tag && !$in_quote) {
if ('<' === $char) {
// ' <'
if (' ' === $pre_output_char) {
$output = substr($output, 0, strlen($output) - 1);
}
$in_tag = true;
$output .= $char;
continue;
}
if ("\n" === $char || "\t" === $char) {
continue;
}
// ' '
if (' ' === $pre_output_char && ' ' === $char) {
continue;
}
// '> '
if ('>' === $pre_output_char && ' ' === $char) {
continue;
}
// ' <'
if (' ' === $pre_output_char && '<' === $char) {
$output = substr($output, 0, strlen($output) - 1);
}
$output .= $char;
continue;
}
}
return trim($output);
} | Parse HTML | https://github.com/scarwu/Pack/blob/284e3273b18ac963f597893059c0b0d34fa15695/src/Pack/HTML.php#L71-L194 |
Etenil/assegai | src/assegai/modules/mail/services/ses/utilities/hadoopstep.class.php | CFHadoopStep.run_hive_script | public static function run_hive_script($script, $args = null)
{
if (!$args) $args = array();
$args = is_array($args) ? $args : array($args);
$args = array_merge(array('--run-hive-script', '--args', '-f', $script), $args);
return self::hive_pig_script('hive', $args);
} | php | public static function run_hive_script($script, $args = null)
{
if (!$args) $args = array();
$args = is_array($args) ? $args : array($args);
$args = array_merge(array('--run-hive-script', '--args', '-f', $script), $args);
return self::hive_pig_script('hive', $args);
} | Step that runs a Hive script on your job flow.
@param string $script (Required) The script to run with `script-runner.jar`.
@param array $args (Optional) An indexed array of arguments to pass to the script.
@return array A standard array that is intended to be passed into a <CFStepConfig> object.
@link http://hive.apache.org Apache Hive | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/utilities/hadoopstep.class.php#L62-L69 |
Etenil/assegai | src/assegai/modules/mail/services/ses/utilities/hadoopstep.class.php | CFHadoopStep.run_pig_script | public static function run_pig_script($script, $args = null)
{
if (!$args) $args = array();
$args = is_array($args) ? $args : array($args);
$args = array_merge(array('--run-pig-script', '--args', '-f', $script), $args);
return self::hive_pig_script('pig', $args);
} | php | public static function run_pig_script($script, $args = null)
{
if (!$args) $args = array();
$args = is_array($args) ? $args : array($args);
$args = array_merge(array('--run-pig-script', '--args', '-f', $script), $args);
return self::hive_pig_script('pig', $args);
} | Step that runs a Pig script on your job flow.
@param string $script (Required) The script to run with `script-runner.jar`.
@param array $args (Optional) An indexed array of arguments to pass to the script.
@return array A standard array that is intended to be passed into a <CFStepConfig> object.
@link http://pig.apache.org Apache Pig | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/utilities/hadoopstep.class.php#L90-L97 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Reflection.php | Reflection.normalizeProperty | public static function normalizeProperty($property)
{
//Remove an underscore, so you can do get_date()
if(substr($property,0,1) == '_')
{
$property = substr($property, 1);
}
$property = lcfirst($property);
// //Deal with famil-'ies', make it 'family'
// if ('ies' == substr($property, -3)) {
// $property = substr($property, 0, -3) . 'y';
// }
//
// //Deal with 'friends', make it 'friend'
// if (preg_match('/[^s]s$/', $property))
// {
// $property = substr($property, 0, -1);
// }
return $property;
} | php | public static function normalizeProperty($property)
{
//Remove an underscore, so you can do get_date()
if(substr($property,0,1) == '_')
{
$property = substr($property, 1);
}
$property = lcfirst($property);
// //Deal with famil-'ies', make it 'family'
// if ('ies' == substr($property, -3)) {
// $property = substr($property, 0, -3) . 'y';
// }
//
// //Deal with 'friends', make it 'friend'
// if (preg_match('/[^s]s$/', $property))
// {
// $property = substr($property, 0, -1);
// }
return $property;
} | Normalizes a property name, by making it lowercase and stripping off "ies" or "s"
@param string $property Property name to sigularize.
@return string Singularized property name. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Reflection.php#L38-L60 |
composer-synchronizer/composer-synchronizer | src/Helpers.php | Helpers.appendToFile | public static function appendToFile(string $filePath, string $content, bool $withoutDuplicates = true): void
{
if ($withoutDuplicates && self::fileContains($filePath, $content)) {
return;
}
self::insertIntoFile($filePath, $content, FILE_APPEND);
} | php | public static function appendToFile(string $filePath, string $content, bool $withoutDuplicates = true): void
{
if ($withoutDuplicates && self::fileContains($filePath, $content)) {
return;
}
self::insertIntoFile($filePath, $content, FILE_APPEND);
} | ************************* Files ************************** | https://github.com/composer-synchronizer/composer-synchronizer/blob/ca1c2f4dd05e0142148c030dba63b5081edb2bc3/src/Helpers.php#L65-L72 |
composer-synchronizer/composer-synchronizer | src/Helpers.php | Helpers.copy | public static function copy(string $source, string $dest, bool $override = false): void
{
if (is_file($source)) {
self::copyFile($source, $dest, $override);
return;
}
if ( ! is_dir($source)) {
Helpers::consoleMessage("File or directory '%s' not found.", [$source]);
return;
}
$sourceHandle = opendir($source);
if ( ! $sourceHandle) {
throw new SynchronizerException('Failed to copy directory: failed to open source ' . $source);
}
while ($file = readdir($sourceHandle)) {
if (in_array($file, ['.', '..'], true)) {
continue;
}
if (is_dir($source . '/' . $file)) {
if ( ! file_exists($dest . '/' . $file)) {
self::createDirectory($dest);
}
$file .= '/';
self::copy($source . $file, $dest . $file, $override);
} else {
$dest = rtrim($dest, '/') . '/';
$source = rtrim($source, '/') . '/';
self::copyFile($source . $file, $dest . $file, $override);
}
}
} | php | public static function copy(string $source, string $dest, bool $override = false): void
{
if (is_file($source)) {
self::copyFile($source, $dest, $override);
return;
}
if ( ! is_dir($source)) {
Helpers::consoleMessage("File or directory '%s' not found.", [$source]);
return;
}
$sourceHandle = opendir($source);
if ( ! $sourceHandle) {
throw new SynchronizerException('Failed to copy directory: failed to open source ' . $source);
}
while ($file = readdir($sourceHandle)) {
if (in_array($file, ['.', '..'], true)) {
continue;
}
if (is_dir($source . '/' . $file)) {
if ( ! file_exists($dest . '/' . $file)) {
self::createDirectory($dest);
}
$file .= '/';
self::copy($source . $file, $dest . $file, $override);
} else {
$dest = rtrim($dest, '/') . '/';
$source = rtrim($source, '/') . '/';
self::copyFile($source . $file, $dest . $file, $override);
}
}
} | Copies files recursively and automatically creates nested directories | https://github.com/composer-synchronizer/composer-synchronizer/blob/ca1c2f4dd05e0142148c030dba63b5081edb2bc3/src/Helpers.php#L78-L115 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/Run.php | Run.handle | public function handle()
{
$port = $this->input->getOption('port');
if($port) {
$this->info("Planet Framework built-in server started on http://localhost:{$port}");
exec("php -S localhost:{$port} -t public");
}
$this->info("Planet Framework built-in server started on http://localhost:8000");
exec("php -S localhost:8000 -t public");
} | php | public function handle()
{
$port = $this->input->getOption('port');
if($port) {
$this->info("Planet Framework built-in server started on http://localhost:{$port}");
exec("php -S localhost:{$port} -t public");
}
$this->info("Planet Framework built-in server started on http://localhost:8000");
exec("php -S localhost:8000 -t public");
} | To handle console command | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/Run.php#L42-L54 |
Dhii/output-renderer-abstract | src/CaptureOutputCapableTrait.php | CaptureOutputCapableTrait._captureOutput | protected function _captureOutput(callable $callable, $args = null)
{
// Default
if (is_null($args)) {
$args = [];
}
ob_start();
$this->_invokeCallable($callable, $args);
$output = ob_get_clean();
return $output;
} | php | protected function _captureOutput(callable $callable, $args = null)
{
// Default
if (is_null($args)) {
$args = [];
}
ob_start();
$this->_invokeCallable($callable, $args);
$output = ob_get_clean();
return $output;
} | Invokes the given callable, and returns the output as a string.
@since [*next-version*]
@param callable $callable The callable that may produce output.
@param array|stdClass|Traversable|null $args The arguments to invoke the callable with. Defaults to empty array.
@throws InvalidArgumentException If the callable or the args list are invalid.
@throws RootException If a problem occurs.
@return string The output. | https://github.com/Dhii/output-renderer-abstract/blob/0f6e5eed940025332dd1986d6c771e10f7197b1a/src/CaptureOutputCapableTrait.php#L32-L44 |
diasbruno/stc | lib/stc/DataValidator.php | DataValidator.walker | private function walker($keys, &$arr)
{
if (count($keys) == 0) {
return true;
}
$current = array_shift($keys);
return (is_array($arr) ?
array_key_exists($current, $arr) :
false)
&& ((is_array($arr[$current])) ?
$this->walker($keys, $arr[$current]) :
(count($keys) > 0 ? false : true));
} | php | private function walker($keys, &$arr)
{
if (count($keys) == 0) {
return true;
}
$current = array_shift($keys);
return (is_array($arr) ?
array_key_exists($current, $arr) :
false)
&& ((is_array($arr[$current])) ?
$this->walker($keys, $arr[$current]) :
(count($keys) > 0 ? false : true));
} | Recursive walker to check.
@param $keys array | List of keys.
@param $arr array | A hash list to check.
@return bool | https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataValidator.php#L33-L47 |
diasbruno/stc | lib/stc/DataValidator.php | DataValidator.validate | public function validate(&$arr)
{
if (count($this->list) == 0) {
return true;
}
$ok = true;
foreach ($this->list as $key => $value) {
$list = explode('.', $value);
$ok = $ok && $this->walker($list, $arr);
}
return $ok;
} | php | public function validate(&$arr)
{
if (count($this->list) == 0) {
return true;
}
$ok = true;
foreach ($this->list as $key => $value) {
$list = explode('.', $value);
$ok = $ok && $this->walker($list, $arr);
}
return $ok;
} | Tries to validate a hash list.
@param $arr array | The array to check.
@return bool | https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataValidator.php#L54-L68 |
kleijnweb/php-api-middleware | src/ParameterAssembler.php | ParameterAssembler.process | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$operation = $this->getOperation($request);
foreach ($this->parameterAssembler->getRequestParameters($request, $operation) as $name => $value) {
$request = $request->withAttribute($name, $value);
}
return $delegate->process($request);
} | php | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$operation = $this->getOperation($request);
foreach ($this->parameterAssembler->getRequestParameters($request, $operation) as $name => $value) {
$request = $request->withAttribute($name, $value);
}
return $delegate->process($request);
} | Process a server request and return a response.
@param ServerRequestInterface $request
@param DelegateInterface $delegate
@return ResponseInterface | https://github.com/kleijnweb/php-api-middleware/blob/e9e74706c3b30a0e06c7f0f7e2a3a43ef17e6df4/src/ParameterAssembler.php#L39-L48 |
tofex/logging | Logger/Wrapper.php | Wrapper.emergency | public function emergency($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->emergency($message, $context);
}
} | php | public function emergency($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->emergency($message, $context);
}
} | System is unusable.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L69-L76 |
tofex/logging | Logger/Wrapper.php | Wrapper.alert | public function alert($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->alert($message, $context);
}
} | php | public function alert($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->alert($message, $context);
}
} | Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should
trigger the SMS alerts and wake you up.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L88-L95 |
tofex/logging | Logger/Wrapper.php | Wrapper.critical | public function critical($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->critical($message, $context);
}
} | php | public function critical($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->critical($message, $context);
}
} | Critical conditions.
Example: Application component unavailable, unexpected exception.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L106-L113 |
tofex/logging | Logger/Wrapper.php | Wrapper.error | public function error($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->error($message, $context);
}
} | php | public function error($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->error($message, $context);
}
} | Runtime errors that do not require immediate action but should typically
be logged and monitored.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L124-L131 |
tofex/logging | Logger/Wrapper.php | Wrapper.warning | public function warning($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->warning($message, $context);
}
} | php | public function warning($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->warning($message, $context);
}
} | Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things
that are not necessarily wrong.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L143-L150 |
tofex/logging | Logger/Wrapper.php | Wrapper.notice | public function notice($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->notice($message, $context);
}
} | php | public function notice($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->notice($message, $context);
}
} | Normal but significant events.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L160-L167 |
tofex/logging | Logger/Wrapper.php | Wrapper.info | public function info($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->info($message, $context);
}
} | php | public function info($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->info($message, $context);
}
} | Interesting events.
Example: User logs in, SQL logs.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L178-L185 |
tofex/logging | Logger/Wrapper.php | Wrapper.debug | public function debug($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->debug($message, $context);
}
} | php | public function debug($message, array $context = [])
{
$this->checkInitialized();
foreach ($this->loggers as $logger) {
$logger->debug($message, $context);
}
} | Detailed debug information.
@param string $message
@param array $context
@return void | https://github.com/tofex/logging/blob/57cec5546c6315b5a219b9df3c5dda5c925a5f03/Logger/Wrapper.php#L195-L202 |
opis/events | src/EventDispatcher.php | EventDispatcher.handle | public function handle(string $event, callable $callback, int $priority = 0): Route
{
return $this->collection->createRoute($event, $callback)->set('priority', $priority);
} | php | public function handle(string $event, callable $callback, int $priority = 0): Route
{
return $this->collection->createRoute($event, $callback)->set('priority', $priority);
} | Handle an event
@param string $event Event's name
@param callable $callback Callback
@param int $priority (optional) Event's priority
@return Route | https://github.com/opis/events/blob/97f34bd0334975580ee915661c79880061c1bf1a/src/EventDispatcher.php#L54-L57 |
opis/events | src/EventDispatcher.php | EventDispatcher.emit | public function emit(string $name, bool $cancelable = false): Event
{
return $this->dispatch(new Event($name, $cancelable));
} | php | public function emit(string $name, bool $cancelable = false): Event
{
return $this->dispatch(new Event($name, $cancelable));
} | Emits an event
@param string $name Event's name
@param boolean $cancelable (optional) Cancelable event
@return Event | https://github.com/opis/events/blob/97f34bd0334975580ee915661c79880061c1bf1a/src/EventDispatcher.php#L67-L70 |
opis/events | src/EventDispatcher.php | EventDispatcher.dispatch | public function dispatch(Event $event): Event
{
return $this->getRouter()->route(new Context($event->name(), $event));
} | php | public function dispatch(Event $event): Event
{
return $this->getRouter()->route(new Context($event->name(), $event));
} | Dispatch an event
@param Event $event Event
@return Event | https://github.com/opis/events/blob/97f34bd0334975580ee915661c79880061c1bf1a/src/EventDispatcher.php#L79-L82 |
schpill/thin | src/Facebook.php | Facebook.getFacebookHelper | public function getFacebookHelper()
{
$redirectHelper = new FacebookRedirectLoginHelper(
$this->getRedirectUrl(),
$this->appId,
$this->appSecret
);
$redirectHelper->disableSessionStatusCheck();
return $redirectHelper;
} | php | public function getFacebookHelper()
{
$redirectHelper = new FacebookRedirectLoginHelper(
$this->getRedirectUrl(),
$this->appId,
$this->appSecret
);
$redirectHelper->disableSessionStatusCheck();
return $redirectHelper;
} | Get Facebook Redirect Login Helper.
@return FacebookRedirectLoginHelper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L114-L125 |
schpill/thin | src/Facebook.php | Facebook.getLoginUrl | public function getLoginUrl($scope = array(), $version = null)
{
$scope = $this->getScope($scope);
return $this->getFacebookHelper()->getLoginUrl($scope, $version);
} | php | public function getLoginUrl($scope = array(), $version = null)
{
$scope = $this->getScope($scope);
return $this->getFacebookHelper()->getLoginUrl($scope, $version);
} | Get Login Url.
@param array $scope
@param null $version
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L207-L212 |
schpill/thin | src/Facebook.php | Facebook.getSessionFromRedirect | public function getSessionFromRedirect()
{
$session = $this->getFacebookHelper()->getSessionFromRedirect();
$this->session->put('session', $session);
return $session;
} | php | public function getSessionFromRedirect()
{
$session = $this->getFacebookHelper()->getSessionFromRedirect();
$this->session->put('session', $session);
return $session;
} | Get the facebook session (access token) when redirected back.
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L231-L238 |
schpill/thin | src/Facebook.php | Facebook.getCallback | public function getCallback()
{
$token = $this->getAccessToken();
if ( ! empty($token))
{
$this->putSessionToken($token);
return true;
}
return false;
} | php | public function getCallback()
{
$token = $this->getAccessToken();
if ( ! empty($token))
{
$this->putSessionToken($token);
return true;
}
return false;
} | Get callback from facebook.
@return boolean | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L304-L314 |
schpill/thin | src/Facebook.php | Facebook.api | public function api($method, $path, $parameters = null, $version = null, $etag = null)
{
$session = new FacebookSession($this->getAccessToken());
$request = with(new FacebookRequest($session, $method, $path, $parameters, $version, $etag))
->execute()
->getGraphObject(GraphUser::className());
return $request;
} | php | public function api($method, $path, $parameters = null, $version = null, $etag = null)
{
$session = new FacebookSession($this->getAccessToken());
$request = with(new FacebookRequest($session, $method, $path, $parameters, $version, $etag))
->execute()
->getGraphObject(GraphUser::className());
return $request;
} | Facebook API Call.
@param string $method The request method.
@param string $path The end points path.
@param mixed $parameters Parameters.
@param string $version The specified version of Api.
@param mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L357-L366 |
schpill/thin | src/Facebook.php | Facebook.get | public function get($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('GET', $path, $parameters, $version, $etag);
} | php | public function get($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('GET', $path, $parameters, $version, $etag);
} | Facebook API Request with "GET" method.
@param string $path
@param string|null|mixed $parameters
@param string|null|mixed $version
@param string|null|mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L377-L380 |
schpill/thin | src/Facebook.php | Facebook.post | public function post($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('POST', $path, $parameters, $version, $etag);
} | php | public function post($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('POST', $path, $parameters, $version, $etag);
} | Facebook API Request with "POST" method.
@param string $path
@param string|null|mixed $parameters
@param string|null|mixed $version
@param string|null|mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L391-L394 |
schpill/thin | src/Facebook.php | Facebook.delete | public function delete($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('DELETE', $path, $parameters, $version, $etag);
} | php | public function delete($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('DELETE', $path, $parameters, $version, $etag);
} | Facebook API Request with "DELETE" method.
@param string $path
@param string|null|mixed $parameters
@param string|null|mixed $version
@param string|null|mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L405-L408 |
schpill/thin | src/Facebook.php | Facebook.put | public function put($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('PUT', $path, $parameters, $version, $etag);
} | php | public function put($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('PUT', $path, $parameters, $version, $etag);
} | Facebook API Request with "PUT" method.
@param string $path
@param string|null|mixed $parameters
@param string|null|mixed $version
@param string|null|mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L419-L422 |
schpill/thin | src/Facebook.php | Facebook.patch | public function patch($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('PATCH', $path, $parameters, $version, $etag);
} | php | public function patch($path, $parameters = null, $version = null, $etag = null)
{
return $this->api('PATCH', $path, $parameters, $version, $etag);
} | Facebook API Request with "PATCH" method.
@param string $path
@param string|null|mixed $parameters
@param string|null|mixed $version
@param string|null|mixed $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L433-L436 |
schpill/thin | src/Facebook.php | Facebook.getProfile | public function getProfile($parameters = [], $version = null, $etag = null)
{
return $this->get('/me', $parameters, $version, $etag);
} | php | public function getProfile($parameters = [], $version = null, $etag = null)
{
return $this->get('/me', $parameters, $version, $etag);
} | Get user profile.
@param array $parameters
@param null $version
@param null $etag
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Facebook.php#L446-L449 |
fnayou/instapush-php | src/Transformer/ModelTransformer.php | ModelTransformer.transform | public function transform(ResponseInterface $response, string $class)
{
$body = $response->getBody()->__toString();
$data = \json_decode($body, true);
if (JSON_ERROR_NONE !== \json_last_error()) {
throw new TransformerException(
\sprintf(
'Invalid json response format : Error %d when trying to \json_decode response',
\json_last_error()
)
);
}
$reflection = new \ReflectionClass($class);
if (true === $reflection->implementsInterface(FromArrayInterface::class)) {
$object = \call_user_func($class.'::fromArray', $data);
} else {
$object = new $class($data);
}
return $object;
} | php | public function transform(ResponseInterface $response, string $class)
{
$body = $response->getBody()->__toString();
$data = \json_decode($body, true);
if (JSON_ERROR_NONE !== \json_last_error()) {
throw new TransformerException(
\sprintf(
'Invalid json response format : Error %d when trying to \json_decode response',
\json_last_error()
)
);
}
$reflection = new \ReflectionClass($class);
if (true === $reflection->implementsInterface(FromArrayInterface::class)) {
$object = \call_user_func($class.'::fromArray', $data);
} else {
$object = new $class($data);
}
return $object;
} | {@inheritdoc} | https://github.com/fnayou/instapush-php/blob/fa7bd9091cf4dee767449412dc10911f4afbdf24/src/Transformer/ModelTransformer.php#L25-L47 |
Elephant418/Staq | src/Staq/Core/View/Stack/Controller/Error.php | Error.actionView | public function actionView($code)
{
parent::actionView($code);
$message = '';
$exception = \Staq::App()->getLastException();
if ($exception && \Staq::App()->settings->getAsBoolean('error.display_errors')) {
$message = $exception->getMessage() . HTML_EOL . $exception->getTraceAsString();
}
$page = new \Stack\View\Error;
$page['code'] = $code;
$page['message'] = $message;
return $page;
} | php | public function actionView($code)
{
parent::actionView($code);
$message = '';
$exception = \Staq::App()->getLastException();
if ($exception && \Staq::App()->settings->getAsBoolean('error.display_errors')) {
$message = $exception->getMessage() . HTML_EOL . $exception->getTraceAsString();
}
$page = new \Stack\View\Error;
$page['code'] = $code;
$page['message'] = $message;
return $page;
} | /* ACTION METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/View/Stack/Controller/Error.php#L14-L26 |
infusephp/auth | src/Libs/Strategy/TraditionalStrategy.php | TraditionalStrategy.login | public function login($username, $password, $remember = false)
{
$rateLimiter = $this->getRateLimiter();
if (!$rateLimiter->canLogin($username)) {
$window = $rateLimiter->getLockoutWindow($username);
throw new AuthException("This account has been locked due to too many failed sign in attempts. The lock is only temporary. Please try again after $window.");
}
try {
$user = $this->getUserWithCredentials($username, $password);
} catch (AuthException $e) {
// record user's failed login attempt and rethrow the exception
$rateLimiter->recordFailedLogin($username);
// throw a special message on the final failed attempt
$remaining = $rateLimiter->getRemainingAttempts($username);
if ($remaining === 0) {
$window = $rateLimiter->getLockoutWindow($username);
$message = $e->getMessage();
$message .= " This account has been locked due to too many failed sign in attempts. The lock is only temporary. Please try again after $window.";
throw new AuthException($message);
}
throw $e;
}
$this->signInUser($user, $this->getId(), $remember);
return true;
} | php | public function login($username, $password, $remember = false)
{
$rateLimiter = $this->getRateLimiter();
if (!$rateLimiter->canLogin($username)) {
$window = $rateLimiter->getLockoutWindow($username);
throw new AuthException("This account has been locked due to too many failed sign in attempts. The lock is only temporary. Please try again after $window.");
}
try {
$user = $this->getUserWithCredentials($username, $password);
} catch (AuthException $e) {
// record user's failed login attempt and rethrow the exception
$rateLimiter->recordFailedLogin($username);
// throw a special message on the final failed attempt
$remaining = $rateLimiter->getRemainingAttempts($username);
if ($remaining === 0) {
$window = $rateLimiter->getLockoutWindow($username);
$message = $e->getMessage();
$message .= " This account has been locked due to too many failed sign in attempts. The lock is only temporary. Please try again after $window.";
throw new AuthException($message);
}
throw $e;
}
$this->signInUser($user, $this->getId(), $remember);
return true;
} | Performs a traditional username/password login and
creates a signed in user.
@param string $username username
@param string $password password
@param bool $remember makes the session persistent
@throws AuthException when the user cannot be signed in.
@return bool success | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Strategy/TraditionalStrategy.php#L53-L82 |
infusephp/auth | src/Libs/Strategy/TraditionalStrategy.php | TraditionalStrategy.getUserWithCredentials | public function getUserWithCredentials($username, $password)
{
if (empty($username)) {
throw new AuthException('Please enter a valid username.');
}
if (empty($password)) {
throw new AuthException('Please enter a valid password.');
}
// look the user up with the given username
$usernameWhere = $this->buildUsernameWhere($username);
$userClass = $this->auth->getUserClass();
$user = $userClass::where($usernameWhere)
->first();
if (!$user) {
throw new AuthException('We could not find a match for that email address and password.');
}
if (!$this->verifyPassword($user, $password)) {
throw new AuthException('We could not find a match for that email address and password.');
}
if ($user->isTemporary()) {
throw new AuthException('It looks like your account has not been setup yet. Please go to the sign up page to finish creating your account.');
}
if (!$user->isEnabled()) {
throw new AuthException('Sorry, your account has been disabled.');
}
if (!$user->isVerified()) {
throw new AuthException('You must verify your account with the email that was sent to you before you can log in.');
}
// success!
return $user;
} | php | public function getUserWithCredentials($username, $password)
{
if (empty($username)) {
throw new AuthException('Please enter a valid username.');
}
if (empty($password)) {
throw new AuthException('Please enter a valid password.');
}
// look the user up with the given username
$usernameWhere = $this->buildUsernameWhere($username);
$userClass = $this->auth->getUserClass();
$user = $userClass::where($usernameWhere)
->first();
if (!$user) {
throw new AuthException('We could not find a match for that email address and password.');
}
if (!$this->verifyPassword($user, $password)) {
throw new AuthException('We could not find a match for that email address and password.');
}
if ($user->isTemporary()) {
throw new AuthException('It looks like your account has not been setup yet. Please go to the sign up page to finish creating your account.');
}
if (!$user->isEnabled()) {
throw new AuthException('Sorry, your account has been disabled.');
}
if (!$user->isVerified()) {
throw new AuthException('You must verify your account with the email that was sent to you before you can log in.');
}
// success!
return $user;
} | Fetches the user for a given username/password combination.
@param string $username username
@param string $password password
@throws AuthException when a matching user cannot be found.
@return UserInterface matching user | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Strategy/TraditionalStrategy.php#L94-L132 |
infusephp/auth | src/Libs/Strategy/TraditionalStrategy.php | TraditionalStrategy.verifyPassword | public function verifyPassword(UserInterface $user, $password)
{
if (!$password) {
return false;
}
$hashedPassword = $user->getHashedPassword();
if (!$hashedPassword) {
return false;
}
return password_verify($password, $hashedPassword);
} | php | public function verifyPassword(UserInterface $user, $password)
{
if (!$password) {
return false;
}
$hashedPassword = $user->getHashedPassword();
if (!$hashedPassword) {
return false;
}
return password_verify($password, $hashedPassword);
} | Checks if a given password matches the user's password.
@param UserInterface $user
@param string $password
@return bool | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Strategy/TraditionalStrategy.php#L142-L154 |
infusephp/auth | src/Libs/Strategy/TraditionalStrategy.php | TraditionalStrategy.getRateLimiter | function getRateLimiter()
{
if ($this->rateLimiter) {
return $this->rateLimiter;
}
$app = $this->auth->getApp();
$class = $app['config']->get('auth.loginRateLimiter', NullRateLimiter::class);
$this->rateLimiter = new $class();
if (method_exists($this->rateLimiter, 'setApp')) {
$this->rateLimiter->setApp($app);
}
return $this->rateLimiter;
} | php | function getRateLimiter()
{
if ($this->rateLimiter) {
return $this->rateLimiter;
}
$app = $this->auth->getApp();
$class = $app['config']->get('auth.loginRateLimiter', NullRateLimiter::class);
$this->rateLimiter = new $class();
if (method_exists($this->rateLimiter, 'setApp')) {
$this->rateLimiter->setApp($app);
}
return $this->rateLimiter;
} | Gets the login rate limiter.
@return \Infuse\Auth\Interfaces\LoginRateLimiterInterface | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Strategy/TraditionalStrategy.php#L161-L176 |
infusephp/auth | src/Libs/Strategy/TraditionalStrategy.php | TraditionalStrategy.buildUsernameWhere | private function buildUsernameWhere($username)
{
$userClass = $this->auth->getUserClass();
$conditions = array_map(
function ($prop, $username) { return $prop." = '".$username."'"; },
$userClass::$usernameProperties,
array_fill(0, count($userClass::$usernameProperties),
addslashes($username)));
return '('.implode(' OR ', $conditions).')';
} | php | private function buildUsernameWhere($username)
{
$userClass = $this->auth->getUserClass();
$conditions = array_map(
function ($prop, $username) { return $prop." = '".$username."'"; },
$userClass::$usernameProperties,
array_fill(0, count($userClass::$usernameProperties),
addslashes($username)));
return '('.implode(' OR ', $conditions).')';
} | Builds a query string for matching the username.
@param string $username username to match
@return string | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Strategy/TraditionalStrategy.php#L185-L196 |
ShaoZeMing/lumen-pgApi | app/Providers/AuthServiceProvider.php | AuthServiceProvider.boot | public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
// return true;
if ($request->input('lbs_token')) {
return ($request->input('lbs_token')== env('LBS_TOKEN'))?1:null;
}
});
} | php | public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
// return true;
if ($request->input('lbs_token')) {
return ($request->input('lbs_token')== env('LBS_TOKEN'))?1:null;
}
});
} | Boot the authentication services for the application.
@return void | https://github.com/ShaoZeMing/lumen-pgApi/blob/f5ef140ef8d2f6ec9f1d1a6dc61292913e4e7271/app/Providers/AuthServiceProvider.php#L26-L46 |
simpleapisecurity/php | src/Encryption.php | Encryption.encryptMessage | public static function encryptMessage($message, $key, $hashKey = '')
{
// Test the key for string validity.
Helpers::isString($message, 'Encryption', 'encryptMessage');
Helpers::isString($key, 'Encryption', 'encryptMessage');
Helpers::isString($hashKey, 'Encryption', 'encryptMessage');
// Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::SECRETBOX_KEYBYTES);
// Generate a nonce for the communication.
$nonce = Entropy::generateNonce();
// Serialize and encrypt the message object
$ciphertext = \Sodium\crypto_secretbox(serialize($message), $nonce, $key);
$nonce = base64_encode($nonce);
$ciphertext = base64_encode($ciphertext);
$json = json_encode(compact('nonce', 'ciphertext'));
if (! is_string($json)) {
throw new Exceptions\EncryptionException('Failed to encrypt message using key');
}
return base64_encode($json);
} | php | public static function encryptMessage($message, $key, $hashKey = '')
{
// Test the key for string validity.
Helpers::isString($message, 'Encryption', 'encryptMessage');
Helpers::isString($key, 'Encryption', 'encryptMessage');
Helpers::isString($hashKey, 'Encryption', 'encryptMessage');
// Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::SECRETBOX_KEYBYTES);
// Generate a nonce for the communication.
$nonce = Entropy::generateNonce();
// Serialize and encrypt the message object
$ciphertext = \Sodium\crypto_secretbox(serialize($message), $nonce, $key);
$nonce = base64_encode($nonce);
$ciphertext = base64_encode($ciphertext);
$json = json_encode(compact('nonce', 'ciphertext'));
if (! is_string($json)) {
throw new Exceptions\EncryptionException('Failed to encrypt message using key');
}
return base64_encode($json);
} | Returns an encrypted message in the form of a JSON string.
@param string $message The message to be encrypted.
@param string $key The key to encrypt the message with.
@param string $hashKey The key to hash the key with.
@return string The JSON string for the encrypted message.
@throws Exceptions\EncryptionException
@throws Exceptions\InvalidTypeException
@throws Exceptions\OutOfRangeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L38-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.