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
IStranger/yii2-resource-smart-load
base/Helper.php
Helper.createByFn
public static function createByFn($array, callable $callback, $data = null) { $handler = function (&$array, $key, $item, $result) { list($newKey, $newValue) = $result; $array[$newKey] = $newValue; return $result; }; return self::_execute($array, $callback, $handler, $data, true); }
php
public static function createByFn($array, callable $callback, $data = null) { $handler = function (&$array, $key, $item, $result) { list($newKey, $newValue) = $result; $array[$newKey] = $newValue; return $result; }; return self::_execute($array, $callback, $handler, $data, true); }
Returns a new array built using a callback. <code> $array = A::createByFn($array, function($key,$item) { // array return [$key.' '.count($item), $item]; }); // Result: $array = ['key1 cnt1'=>$item1,'key1 cnt2'=>$item2,...]; $objects = A::createByFn($objects, function() { // if array of objects return [$this->name.'-'.$this->id, $this]; }); </code> @param array $array @param callable $callback @param array $data @return array @uses execute()
https://github.com/IStranger/yii2-resource-smart-load/blob/a4f203745d9a02fd97853b49c55b287aea6d7e6d/base/Helper.php#L132-L140
IStranger/yii2-resource-smart-load
base/Helper.php
Helper._execute
private static function _execute($array, callable $callback, callable $handler, $data = null, $bind = false) { $resultValue = array(); foreach ($array as $key => $item) { if (is_object($item)) { $item = clone $item; if ($callback instanceof \Closure and $bind) { $callback = \Closure::bind($callback, $item); } } $result = call_user_func_array($callback, array($key, &$item, $data)); if (call_user_func_array($handler, array(&$resultValue, $key, $item, $result)) === false) { break; } } return $resultValue; }
php
private static function _execute($array, callable $callback, callable $handler, $data = null, $bind = false) { $resultValue = array(); foreach ($array as $key => $item) { if (is_object($item)) { $item = clone $item; if ($callback instanceof \Closure and $bind) { $callback = \Closure::bind($callback, $item); } } $result = call_user_func_array($callback, array($key, &$item, $data)); if (call_user_func_array($handler, array(&$resultValue, $key, $item, $result)) === false) { break; } } return $resultValue; }
Returns result execute a $callback over each item of array. Result prepare with execute $handler. @param array $array @param callable $callback @param callable $handler @param mixed $data @param boolean $bind @return array
https://github.com/IStranger/yii2-resource-smart-load/blob/a4f203745d9a02fd97853b49c55b287aea6d7e6d/base/Helper.php#L153-L169
fxpio/fxp-doctrine-console
Adapter/ResourceAdapter.php
ResourceAdapter.create
public function create($instance) { $res = $this->domain->create($instance); $this->validateResource($res); }
php
public function create($instance) { $res = $this->domain->create($instance); $this->validateResource($res); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ResourceAdapter.php#L51-L55
fxpio/fxp-doctrine-console
Adapter/ResourceAdapter.php
ResourceAdapter.update
public function update($instance) { $res = $this->domain->update($instance); $this->validateResource($res); }
php
public function update($instance) { $res = $this->domain->update($instance); $this->validateResource($res); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ResourceAdapter.php#L68-L72
fxpio/fxp-doctrine-console
Adapter/ResourceAdapter.php
ResourceAdapter.delete
public function delete($instance) { $res = $this->domain->delete($instance); $this->validateResource($res); }
php
public function delete($instance) { $res = $this->domain->delete($instance); $this->validateResource($res); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ResourceAdapter.php#L77-L81
fxpio/fxp-doctrine-console
Adapter/ResourceAdapter.php
ResourceAdapter.undelete
public function undelete($identifier) { $res = $this->domain->undelete($identifier); $this->validateResource($res); return $res->getRealData(); }
php
public function undelete($identifier) { $res = $this->domain->undelete($identifier); $this->validateResource($res); return $res->getRealData(); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ResourceAdapter.php#L86-L92
buse974/Dal
src/Dal/AbstractFactory/ModelAbstractFactory.php
ModelAbstractFactory.canCreate
public function canCreate(ContainerInterface $container, $requestedName) { $namespace = $this->getConfig($container)['namespace']; $ar = explode('_', $requestedName); return (count($ar) >= 2 && array_key_exists($ar[0], $namespace) && $ar[1] === 'model'); }
php
public function canCreate(ContainerInterface $container, $requestedName) { $namespace = $this->getConfig($container)['namespace']; $ar = explode('_', $requestedName); return (count($ar) >= 2 && array_key_exists($ar[0], $namespace) && $ar[1] === 'model'); }
Determine if we can create a Model with name {@inheritDoc} @see \Zend\ServiceManager\Factory\AbstractFactoryInterface::canCreate()
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/AbstractFactory/ModelAbstractFactory.php#L25-L31
internetofvoice/libvoice
src/Alexa/Request/CertificateValidator.php
CertificateValidator.validateRequestSignature
public function validateRequestSignature($requestData) { $certKey = openssl_pkey_get_public($this->certificateContent); $valid = openssl_verify($requestData, base64_decode($this->requestSignature), $certKey, self::ENCRYPT_METHOD); if (!$valid) { throw new InvalidArgumentException('Request signature could not be verified'); } return true; }
php
public function validateRequestSignature($requestData) { $certKey = openssl_pkey_get_public($this->certificateContent); $valid = openssl_verify($requestData, base64_decode($this->requestSignature), $certKey, self::ENCRYPT_METHOD); if (!$valid) { throw new InvalidArgumentException('Request signature could not be verified'); } return true; }
/* @params string $requestData @return bool @throws InvalidArgumentException
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Request/CertificateValidator.php#L109-L117
jasny/entity
src/Traits/ToJsonTrait.php
ToJsonTrait.jsonSerialize
public function jsonSerialize(): stdClass { $object = (object)object_get_properties($this, $this instanceof DynamicEntity); /** @var Event\ToJson $event */ $event = $this->dispatchEvent(new Event\ToJson($this, $object)); $data = i\type_check($event->getPayload(), stdClass::class, new UnexpectedValueException()); return $data; }
php
public function jsonSerialize(): stdClass { $object = (object)object_get_properties($this, $this instanceof DynamicEntity); /** @var Event\ToJson $event */ $event = $this->dispatchEvent(new Event\ToJson($this, $object)); $data = i\type_check($event->getPayload(), stdClass::class, new UnexpectedValueException()); return $data; }
Prepare entity for JsonSerialize encoding @return stdClass
https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/Traits/ToJsonTrait.php#L32-L41
Phpillip/phpillip
src/EventListener/TemplateListener.php
TemplateListener.onKernelController
public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); if ($template = $this->getTemplate($request, $event->getController())) { $request->attributes->set('_template', $template); } }
php
public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); if ($template = $this->getTemplate($request, $event->getController())) { $request->attributes->set('_template', $template); } }
Handles Kernel Controller events @param FilterControllerEvent $event
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/TemplateListener.php#L55-L62
Phpillip/phpillip
src/EventListener/TemplateListener.php
TemplateListener.onKernelView
public function onKernelView(GetResponseForControllerResultEvent $event) { $request = $event->getRequest(); $response = $event->getResponse(); $parameters = $event->getControllerResult(); if (!$response instanceof Response && $template = $request->attributes->get('_template')) { return $event->setControllerResult($this->templating->render($template, $parameters)); } }
php
public function onKernelView(GetResponseForControllerResultEvent $event) { $request = $event->getRequest(); $response = $event->getResponse(); $parameters = $event->getControllerResult(); if (!$response instanceof Response && $template = $request->attributes->get('_template')) { return $event->setControllerResult($this->templating->render($template, $parameters)); } }
Handles Kernel View events @param GetResponseForControllerResultEvent $event
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/TemplateListener.php#L69-L78
Phpillip/phpillip
src/EventListener/TemplateListener.php
TemplateListener.getTemplate
protected function getTemplate(Request $request, $controller) { if ($request->attributes->has('_template')) { return null; } $format = $request->attributes->get('_format', 'html'); $templates = []; if ($controllerInfo = $this->parseController($controller)) { $template = sprintf('%s/%s.%s.twig', $controllerInfo['name'], $controllerInfo['action'], $format); if ($this->templateExists($template)) { return $template; } else { $templates[] = $template; } } $route = $this->routes->get($request->attributes->get('_route')); if ($route && $route->hasContent()) { $template = sprintf('%s/%s.%s.twig', $route->getContent(), $route->isList() ? 'list' : 'show', $format); if ($this->templateExists($template)) { return $template; } else { $templates[] = $template; } } return array_pop($templates); }
php
protected function getTemplate(Request $request, $controller) { if ($request->attributes->has('_template')) { return null; } $format = $request->attributes->get('_format', 'html'); $templates = []; if ($controllerInfo = $this->parseController($controller)) { $template = sprintf('%s/%s.%s.twig', $controllerInfo['name'], $controllerInfo['action'], $format); if ($this->templateExists($template)) { return $template; } else { $templates[] = $template; } } $route = $this->routes->get($request->attributes->get('_route')); if ($route && $route->hasContent()) { $template = sprintf('%s/%s.%s.twig', $route->getContent(), $route->isList() ? 'list' : 'show', $format); if ($this->templateExists($template)) { return $template; } else { $templates[] = $template; } } return array_pop($templates); }
Get template from the given request and controller @param Request $request @param mixed $controller @return string|null
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/TemplateListener.php#L88-L120
Phpillip/phpillip
src/EventListener/TemplateListener.php
TemplateListener.parseController
protected function parseController($controller) { if (!is_array($controller) || !is_object($controller[0]) || !isset($controller[1])) { return null; } if (!preg_match('#Controller\\\(.+)Controller$#', get_class($controller[0]), $matches)) { return null; } return ['name' => $matches[1], 'action' => $controller[1]]; }
php
protected function parseController($controller) { if (!is_array($controller) || !is_object($controller[0]) || !isset($controller[1])) { return null; } if (!preg_match('#Controller\\\(.+)Controller$#', get_class($controller[0]), $matches)) { return null; } return ['name' => $matches[1], 'action' => $controller[1]]; }
Parse controller to extract its name @param mixed $controller @return string
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/TemplateListener.php#L129-L140
Phpillip/phpillip
src/EventListener/TemplateListener.php
TemplateListener.templateExists
protected function templateExists($template) { try { $class = $this->templating->getTemplateClass($template); } catch (Twig_Error_Loader $e) { return false; } return $template; }
php
protected function templateExists($template) { try { $class = $this->templating->getTemplateClass($template); } catch (Twig_Error_Loader $e) { return false; } return $template; }
Does the given template exists? @param string $template @return boolean
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/TemplateListener.php#L149-L158
Dhii/output-renderer-abstract
src/RenderCapableTemplateBlockTrait.php
RenderCapableTemplateBlockTrait._render
protected function _render() { try { $template = $this->_getTemplate(); $context = $this->_getContextFor($template); return $this->_renderTemplate($template, $context); } catch (RootException $e) { throw $this->_throwCouldNotRenderException($this->__('Could not render template'), null, $e); } }
php
protected function _render() { try { $template = $this->_getTemplate(); $context = $this->_getContextFor($template); return $this->_renderTemplate($template, $context); } catch (RootException $e) { throw $this->_throwCouldNotRenderException($this->__('Could not render template'), null, $e); } }
Renders an internal template. @since [*next-version*] @throws CouldNotRenderExceptionInterface If the template could not be rendered. @throws RendererExceptionInterface If a problem related to a renderer occurs.
https://github.com/Dhii/output-renderer-abstract/blob/0f6e5eed940025332dd1986d6c771e10f7197b1a/src/RenderCapableTemplateBlockTrait.php#L27-L37
schpill/thin
src/Html/Doctype.php
Doctype.doctype
public function doctype($doctype = null) { if (null !== $doctype) { switch ($doctype) { case static::XHTML11: case static::XHTML1_STRICT: case static::XHTML1_TRANSITIONAL: case static::XHTML1_FRAMESET: case static::XHTML_BASIC1: case static::XHTML1_RDFA: case static::XHTML1_RDFA11: case static::XHTML5: case static::HTML4_STRICT: case static::HTML4_LOOSE: case static::HTML4_FRAMESET: case static::HTML5: $this->setDoctype($doctype); break; default: if (substr($doctype, 0, 9) != '<!DOCTYPE') { $e = new Exception('The specified doctype is malformed'); throw $e; } if (stristr($doctype, 'xhtml')) { $type = static::CUSTOM_XHTML; } else { $type = static::CUSTOM; } $this->setDoctype($type); $this->_registry['doctypes'][$type] = $doctype; break; } } return $this; }
php
public function doctype($doctype = null) { if (null !== $doctype) { switch ($doctype) { case static::XHTML11: case static::XHTML1_STRICT: case static::XHTML1_TRANSITIONAL: case static::XHTML1_FRAMESET: case static::XHTML_BASIC1: case static::XHTML1_RDFA: case static::XHTML1_RDFA11: case static::XHTML5: case static::HTML4_STRICT: case static::HTML4_LOOSE: case static::HTML4_FRAMESET: case static::HTML5: $this->setDoctype($doctype); break; default: if (substr($doctype, 0, 9) != '<!DOCTYPE') { $e = new Exception('The specified doctype is malformed'); throw $e; } if (stristr($doctype, 'xhtml')) { $type = static::CUSTOM_XHTML; } else { $type = static::CUSTOM; } $this->setDoctype($type); $this->_registry['doctypes'][$type] = $doctype; break; } } return $this; }
Set or retrieve doctype @param string $doctype @return FTV_Html_Doctype
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Doctype.php#L84-L119
ShaoZeMing/lumen-pgApi
app/Http/Middleware/Authenticate.php
Authenticate.handle
public function handle($request, Closure $next, $guard = null) { if ($this->auth->guard($guard)->guest()) { return response()->json([ 'error' => 1, 'msg' => "没有权限,请确认是否传入有效的lbs_token!", 'data' => [], ], 401); } return $next($request); }
php
public function handle($request, Closure $next, $guard = null) { if ($this->auth->guard($guard)->guest()) { return response()->json([ 'error' => 1, 'msg' => "没有权限,请确认是否传入有效的lbs_token!", 'data' => [], ], 401); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param string|null $guard @return mixed
https://github.com/ShaoZeMing/lumen-pgApi/blob/f5ef140ef8d2f6ec9f1d1a6dc61292913e4e7271/app/Http/Middleware/Authenticate.php#L36-L47
zeyon/rest
src/localizer.php
Localizer.getInstance
public static function getInstance($arrAccepted=array(), $strDefault='de') { if (self::$instance === NULL) self::$instance = new self($arrAccepted, $strDefault); return self::$instance; }
php
public static function getInstance($arrAccepted=array(), $strDefault='de') { if (self::$instance === NULL) self::$instance = new self($arrAccepted, $strDefault); return self::$instance; }
Return the current instance @param array $arrAccepted All accepted languages @param string $strDefault Default language code @return Localizer
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L54-L58
zeyon/rest
src/localizer.php
Localizer.fileFormatDir
private function fileFormatDir($strDirectory, $strSlash=DIRECTORY_SEPARATOR) { return substr($strDirectory, -1) != $strSlash ? $strDirectory.$strSlash : $strDirectory; }
php
private function fileFormatDir($strDirectory, $strSlash=DIRECTORY_SEPARATOR) { return substr($strDirectory, -1) != $strSlash ? $strDirectory.$strSlash : $strDirectory; }
Makes sure the directory ends with a slash @param string $strDirectory @return string
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L66-L68
zeyon/rest
src/localizer.php
Localizer.load
public function load($strSourcePath, $strCachePath=false, $bolStore=true) { $strSourcePath = $this->fileFormatDir($strSourcePath); $strLang = self::init($this->arrAccepted, $this->strDefault, $bolStore); $this->strCurrent = $strLang; if ($strCachePath) { $strCachePath = $this->fileFormatDir($strCachePath); if (file_exists($strCachePath.$strLang.'.php')) { include $strCachePath.$strLang.'.php'; if (isset($LANGVAR)) { $this->setData($LANGVAR); return $LANGVAR; } } } $strFilename = $strSourcePath.$strLang.'.'.$this->strFileFormat; if (!file_exists($strFilename)) throw new \Exception('Locale file not found: '.$strFilename); switch ($this->strFileFormat) { case 'yml': if (!class_exists('\\Spyc')) throw new \Exception('Spyc YAML parser not loaded!'); $LANGVAR = \Spyc::YAMLLoad($strFilename); break; case 'ini': $LANGVAR = parse_ini_file($strFilename, true); break; default: $LANGVAR = json_decode(file_get_contents($strFilename, true)); break; } $this->setData($LANGVAR); if ($strCachePath) $this->writeCacheFile($strCachePath, $strLang); return $LANGVAR; }
php
public function load($strSourcePath, $strCachePath=false, $bolStore=true) { $strSourcePath = $this->fileFormatDir($strSourcePath); $strLang = self::init($this->arrAccepted, $this->strDefault, $bolStore); $this->strCurrent = $strLang; if ($strCachePath) { $strCachePath = $this->fileFormatDir($strCachePath); if (file_exists($strCachePath.$strLang.'.php')) { include $strCachePath.$strLang.'.php'; if (isset($LANGVAR)) { $this->setData($LANGVAR); return $LANGVAR; } } } $strFilename = $strSourcePath.$strLang.'.'.$this->strFileFormat; if (!file_exists($strFilename)) throw new \Exception('Locale file not found: '.$strFilename); switch ($this->strFileFormat) { case 'yml': if (!class_exists('\\Spyc')) throw new \Exception('Spyc YAML parser not loaded!'); $LANGVAR = \Spyc::YAMLLoad($strFilename); break; case 'ini': $LANGVAR = parse_ini_file($strFilename, true); break; default: $LANGVAR = json_decode(file_get_contents($strFilename, true)); break; } $this->setData($LANGVAR); if ($strCachePath) $this->writeCacheFile($strCachePath, $strLang); return $LANGVAR; }
Initialized the language variable @param string $strSourcePath The source path for all localization files (.yml) @param string $strCachePath The caching path; if specified, cache files will be enabled @param bool $bolStore Switch to store language in the current session @return array The language variable array
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L78-L122
zeyon/rest
src/localizer.php
Localizer.writeCacheFile
public function writeCacheFile($strCachePath, $strLang) { if (file_exists($strCachePath) && is_dir($strCachePath)) { file_put_contents($strCachePath.$strLang.'.php', '<?php '."\n\n" .'/* Language file "'.$strLang.'; Generated '.date('Y-m-d H:i').' */'."\n\n".'$LANG = '.var_export($this->arrData, true).';'."\n".'?>'); return true; } return false; }
php
public function writeCacheFile($strCachePath, $strLang) { if (file_exists($strCachePath) && is_dir($strCachePath)) { file_put_contents($strCachePath.$strLang.'.php', '<?php '."\n\n" .'/* Language file "'.$strLang.'; Generated '.date('Y-m-d H:i').' */'."\n\n".'$LANG = '.var_export($this->arrData, true).';'."\n".'?>'); return true; } return false; }
Write the cache file @param string $strCachePath The caching path @param string $strLang @return bool
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L131-L140
zeyon/rest
src/localizer.php
Localizer.get
public function get($strKey, $bolReturnPath=true) { $data = $this->arrData; foreach (explode('.', $strKey) as $p) { if (isset($data[$p])) $data = $data[$p]; else return $bolReturnPath ? $this->returnKey($strKey) : false; } // if key was not resolved completely if ( is_array($data) ) return $bolReturnPath ? $this->returnKey($strKey) : false; return (string) $data; }
php
public function get($strKey, $bolReturnPath=true) { $data = $this->arrData; foreach (explode('.', $strKey) as $p) { if (isset($data[$p])) $data = $data[$p]; else return $bolReturnPath ? $this->returnKey($strKey) : false; } // if key was not resolved completely if ( is_array($data) ) return $bolReturnPath ? $this->returnKey($strKey) : false; return (string) $data; }
Gets a variable value @param string $strKey The path for the language variable (e.g. "messages.error.single") @param bool $bolReturnPath If set the function will return the variable path, instead of FALSE @return string If the path could not be resolved, the path will be returned instead
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L177-L192
zeyon/rest
src/localizer.php
Localizer.getDateFormat
public function getDateFormat($strKey) { $format = $this->get($strKey, false); return $format ? preg_replace('/%([A-Za-z%])/', '$1', $format) : 'Y-m-d H:i'; }
php
public function getDateFormat($strKey) { $format = $this->get($strKey, false); return $format ? preg_replace('/%([A-Za-z%])/', '$1', $format) : 'Y-m-d H:i'; }
Returns a date string without "%" for PHP compatibiltiy @param string $strKey The path for the language variable (e.g. "messages.error.single") @return string The date format string
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L210-L213
zeyon/rest
src/localizer.php
Localizer.insert
public function insert($strKey, $arrReplace) { $data = $this->arrData; foreach (explode('.', $strKey) as $p) { if (isset($data[$p])) $data = $data[$p]; else return $this->returnKey($strKey).'('.json_encode($arrReplace).')'; } $arrSearch = array(); $arrValues = array(); foreach ($arrReplace as $key => $value) { $arrSearch[] = '{'.$key.'}'; $arrValues[] = $value; } return str_replace($arrSearch, $arrValues, (string) $data); }
php
public function insert($strKey, $arrReplace) { $data = $this->arrData; foreach (explode('.', $strKey) as $p) { if (isset($data[$p])) $data = $data[$p]; else return $this->returnKey($strKey).'('.json_encode($arrReplace).')'; } $arrSearch = array(); $arrValues = array(); foreach ($arrReplace as $key => $value) { $arrSearch[] = '{'.$key.'}'; $arrValues[] = $value; } return str_replace($arrSearch, $arrValues, (string) $data); }
Gets a variable value and replaces placeholders contained in it @param string $strKey The path for the language variable (e.g. "messages.error.single") @param array $arrReplace Associative array containing the placeholder variables @return string If the path could not be resolved, the path will be returned instead
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L222-L239
zeyon/rest
src/localizer.php
Localizer.replace
public function replace($strTemplate) { preg_match_all($this->regex, $strTemplate, $matches); $arrReplace = array(); foreach ($matches[1] as $match) { $arrReplace[] = $this->get($match); } return str_replace($matches[0], $arrReplace, $strTemplate); }
php
public function replace($strTemplate) { preg_match_all($this->regex, $strTemplate, $matches); $arrReplace = array(); foreach ($matches[1] as $match) { $arrReplace[] = $this->get($match); } return str_replace($matches[0], $arrReplace, $strTemplate); }
Insert placeholders into a string @param string $strTemplate @return $strTemplate
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L247-L255
zeyon/rest
src/localizer.php
Localizer.init
public function init($arrAccepted, $strDefault, $bolStore=true) { $strLang = isset($_GET['lang']) ? $_GET['lang'] : (isset($_SESSION['lang']) ? $_SESSION['lang'] : (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : false)); if (!$strLang || !in_array($strLang, $arrAccepted)) { $browser = self::askBrowser($arrAccepted, $strDefault); $strLang = $browser['lang']; } if ($bolStore) { $_SESSION['lang'] = $strLang; setcookie('lang', $strLang, time() + 315885600); } $this->strCurrent = $strLang; return $strLang; }
php
public function init($arrAccepted, $strDefault, $bolStore=true) { $strLang = isset($_GET['lang']) ? $_GET['lang'] : (isset($_SESSION['lang']) ? $_SESSION['lang'] : (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : false)); if (!$strLang || !in_array($strLang, $arrAccepted)) { $browser = self::askBrowser($arrAccepted, $strDefault); $strLang = $browser['lang']; } if ($bolStore) { $_SESSION['lang'] = $strLang; setcookie('lang', $strLang, time() + 315885600); } $this->strCurrent = $strLang; return $strLang; }
Initialized the language variable and stores it in the session @param array $arrAccepted All accepted languages @param string $strDefault Default language code @param bool $bolStore Switch to store language in the current session
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L264-L278
zeyon/rest
src/localizer.php
Localizer.askBrowser
public static function askBrowser($arrAccepted, $strDefault='de') { $res = array('lang' => $strDefault, 'other' => array()); try { $lang_variable = ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null ); if ( empty($lang_variable) ) return $res; $accepted_languages = preg_split('/,\s*/', $lang_variable); $current_lang = $strDefault; $current_q = 0; $other = array(); foreach ($accepted_languages as $accepted_language) { $res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'. '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches); if (!$res) continue; $lang_code = explode('-', $matches[1]); if (isset($matches[2])) $lang_quality = (float) $matches[2]; else $lang_quality = 1.0; while (count($lang_code)) { $full_code = strtolower(join ('-', $lang_code)); if (in_array($full_code, $arrAccepted)) { if ($lang_quality > $current_q) { if ($current_lang) $other[] = $current_lang; $current_lang = $full_code; $current_q = $lang_quality; break; } else $other[] = $full_code; } else $other[] = $full_code; array_pop($lang_code); } } return array('lang' => $current_lang, 'other' => $other);; } catch (\Exception $e) { return $res; } }
php
public static function askBrowser($arrAccepted, $strDefault='de') { $res = array('lang' => $strDefault, 'other' => array()); try { $lang_variable = ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null ); if ( empty($lang_variable) ) return $res; $accepted_languages = preg_split('/,\s*/', $lang_variable); $current_lang = $strDefault; $current_q = 0; $other = array(); foreach ($accepted_languages as $accepted_language) { $res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'. '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches); if (!$res) continue; $lang_code = explode('-', $matches[1]); if (isset($matches[2])) $lang_quality = (float) $matches[2]; else $lang_quality = 1.0; while (count($lang_code)) { $full_code = strtolower(join ('-', $lang_code)); if (in_array($full_code, $arrAccepted)) { if ($lang_quality > $current_q) { if ($current_lang) $other[] = $current_lang; $current_lang = $full_code; $current_q = $lang_quality; break; } else $other[] = $full_code; } else $other[] = $full_code; array_pop($lang_code); } } return array('lang' => $current_lang, 'other' => $other);; } catch (\Exception $e) { return $res; } }
Returns the accepted browser language @param array $arrAccepted @param string $strDefault @return array {'lang': PRIMARY LANGUAGE, 'other': ADDITIONAL LANGUAGES}
https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L287-L338
cityware/city-format
src/Cpu.php
Cpu.loadAverage
public static function loadAverage($load) { $loadReturn = Array(); if($load > 1){ $loadReturn['utilized'] = 100; $loadReturn['overload'] = ($load - 1) * 100; } else { $loadReturn['utilized'] = ($load * 100); $loadReturn['overload'] = 0; } return $loadReturn; }
php
public static function loadAverage($load) { $loadReturn = Array(); if($load > 1){ $loadReturn['utilized'] = 100; $loadReturn['overload'] = ($load - 1) * 100; } else { $loadReturn['utilized'] = ($load * 100); $loadReturn['overload'] = 0; } return $loadReturn; }
Formata os dados de Carga Média de CPU do servidor @param double $load @return array
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Cpu.php#L23-L35
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.getWebSrvUser
public function getWebSrvUser() { $result = ''; if ($this->isOsWindows()) { return $result; } $cmd = "ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 2>/dev/null"; $output = []; $exitCode = -1; exec($cmd, $output, $exitCode); if (($exitCode !== 0) || (count($output) < 1)) { return $result; } $result = array_shift($output); return $result; }
php
public function getWebSrvUser() { $result = ''; if ($this->isOsWindows()) { return $result; } $cmd = "ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 2>/dev/null"; $output = []; $exitCode = -1; exec($cmd, $output, $exitCode); if (($exitCode !== 0) || (count($output) < 1)) { return $result; } $result = array_shift($output); return $result; }
Return WEB server user. @return string Return user name of WEB server
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L102-L119
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.getWebSrvUserGroup
public function getWebSrvUserGroup($username = null) { $result = ''; if ($this->isOsWindows() || empty($username)) { return $result; } $cmd = 'groups ' . $username . ' | head -1 | cut -d\ -f1 2>/dev/null'; $output = []; $exitCode = -1; exec($cmd, $output, $exitCode); if (($exitCode !== 0) || (count($output) < 1)) { return $result; } $result = array_shift($output); return $result; }
php
public function getWebSrvUserGroup($username = null) { $result = ''; if ($this->isOsWindows() || empty($username)) { return $result; } $cmd = 'groups ' . $username . ' | head -1 | cut -d\ -f1 2>/dev/null'; $output = []; $exitCode = -1; exec($cmd, $output, $exitCode); if (($exitCode !== 0) || (count($output) < 1)) { return $result; } $result = array_shift($output); return $result; }
Return group of user. @param string $username Username for retrieving group. @return string Return group of user
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L127-L144
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.isAppInstalled
public function isAppInstalled($configKey = null, $createMarkerFile = true) { $pathMarkerFileIsInstalled = $this->getPathMarkerFileIsInstalled(); if ($this->_checkMarkerFile($pathMarkerFileIsInstalled)) { return true; } $installTasks = $this->_modelConfigInstaller->getListInstallerTasks(); if (empty($installTasks)) { return false; } if (in_array('check', $installTasks) && ($this->checkPhpVersion() === false)) { return false; } if (in_array('check', $installTasks) && ($this->checkPhpExtensions(true) === false)) { return false; } if (in_array('configdb', $installTasks) && ($this->checkConnectDb(null, true) === false)) { return false; } if (in_array('createdb', $installTasks) && !$this->checkDbTableExists()) { return false; } if (in_array('createsymlinks', $installTasks) && !$this->checkSymLinksExists()) { return false; } if (in_array('createcronjobs', $installTasks) && !$this->checkCronJobsExists()) { return false; } if (!empty($configKey) && !Configure::check($configKey)) { return false; } if (!$createMarkerFile) { return true; } return $this->_createMarkerFile($pathMarkerFileIsInstalled); }
php
public function isAppInstalled($configKey = null, $createMarkerFile = true) { $pathMarkerFileIsInstalled = $this->getPathMarkerFileIsInstalled(); if ($this->_checkMarkerFile($pathMarkerFileIsInstalled)) { return true; } $installTasks = $this->_modelConfigInstaller->getListInstallerTasks(); if (empty($installTasks)) { return false; } if (in_array('check', $installTasks) && ($this->checkPhpVersion() === false)) { return false; } if (in_array('check', $installTasks) && ($this->checkPhpExtensions(true) === false)) { return false; } if (in_array('configdb', $installTasks) && ($this->checkConnectDb(null, true) === false)) { return false; } if (in_array('createdb', $installTasks) && !$this->checkDbTableExists()) { return false; } if (in_array('createsymlinks', $installTasks) && !$this->checkSymLinksExists()) { return false; } if (in_array('createcronjobs', $installTasks) && !$this->checkCronJobsExists()) { return false; } if (!empty($configKey) && !Configure::check($configKey)) { return false; } if (!$createMarkerFile) { return true; } return $this->_createMarkerFile($pathMarkerFileIsInstalled); }
Check application is installed successfully @param string $configKey The identifier to check configuration for application. @param bool $createMarkerFile If True, create marker file, if application is installed successfully. @return bool True, if application is installed successfully. False otherwise.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L170-L214
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.isAppReadyToInstall
public function isAppReadyToInstall() { $checkPHPversion = $this->checkPhpVersion(); if ($checkPHPversion === false) { return false; } $checkPHPextensions = $this->checkPhpExtensions(true); if ($checkPHPextensions === false) { return false; } return true; }
php
public function isAppReadyToInstall() { $checkPHPversion = $this->checkPhpVersion(); if ($checkPHPversion === false) { return false; } $checkPHPextensions = $this->checkPhpExtensions(true); if ($checkPHPextensions === false) { return false; } return true; }
Check application is ready to install @return bool True, if application is ready to install. False otherwise.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L222-L234
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkPhpVersion
public function checkPhpVersion() { $phpVesion = $this->_modelConfigInstaller->getPhpVersionConfig(); if (empty($phpVesion)) { return null; } $result = true; foreach ($phpVesion as $phpVesionItem) { if (!is_array($phpVesionItem)) { continue; } $phpVesionItem += ['', null]; list($version, $operator) = $phpVesionItem; if (empty($operator)) { $operator = '=='; } $checkResult = false; if (!empty($version)) { $checkResult = version_compare(PHP_VERSION, $version, $operator); } if (!$checkResult) { $result = false; } } return $result; }
php
public function checkPhpVersion() { $phpVesion = $this->_modelConfigInstaller->getPhpVersionConfig(); if (empty($phpVesion)) { return null; } $result = true; foreach ($phpVesion as $phpVesionItem) { if (!is_array($phpVesionItem)) { continue; } $phpVesionItem += ['', null]; list($version, $operator) = $phpVesionItem; if (empty($operator)) { $operator = '=='; } $checkResult = false; if (!empty($version)) { $checkResult = version_compare(PHP_VERSION, $version, $operator); } if (!$checkResult) { $result = false; } } return $result; }
Check version of PHP @return null|bool Return Null, if checking is not configured. True, if PHP version is compatible. False otherwise.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L242-L270
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkPhpExtensions
public function checkPhpExtensions($returnBool = false) { $modules = $this->_modelConfigInstaller->getPhpExtensionsConfig(); if (empty($modules)) { return null; } $result = []; $resultBool = true; foreach ($modules as $module) { if (empty($module) || !is_array($module)) { continue; } $module += ['', true]; list($moduleName, $critical) = $module; $checkResult = false; if (!empty($moduleName)) { $checkResult = extension_loaded($moduleName); } if ($checkResult) { $result[$moduleName] = 2; } else { if (!$critical) { $result[$moduleName] = 1; } else { $result[$moduleName] = 0; $resultBool = false; } } } if ($returnBool) { return $resultBool; } return $result; }
php
public function checkPhpExtensions($returnBool = false) { $modules = $this->_modelConfigInstaller->getPhpExtensionsConfig(); if (empty($modules)) { return null; } $result = []; $resultBool = true; foreach ($modules as $module) { if (empty($module) || !is_array($module)) { continue; } $module += ['', true]; list($moduleName, $critical) = $module; $checkResult = false; if (!empty($moduleName)) { $checkResult = extension_loaded($moduleName); } if ($checkResult) { $result[$moduleName] = 2; } else { if (!$critical) { $result[$moduleName] = 1; } else { $result[$moduleName] = 0; $resultBool = false; } } } if ($returnBool) { return $resultBool; } return $result; }
Check extension of PHP @param bool $returnBool If True, return boolean. Otherwise, return array otherwise in format: - key - PHP extension name; - value - check result in format: - 0 - Bad; - 1 - Ok - Warning; - 2 - Ok - Success. @return null|bool|array Return Null, if checking is not configured.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L284-L320
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkFilesWritable
public function checkFilesWritable($returnBool = false) { $targetFiles = $this->_getFilesForCheckingWritable(); if (empty($targetFiles)) { return null; } $result = []; $resultBool = true; foreach ($targetFiles as $targetFile) { if (!file_exists($targetFile)) { $state = false; } else { $state = is_writable($targetFile); } $resultBool = $resultBool && $state; $result[$targetFile] = $state; } if ($returnBool) { return $resultBool; } return $result; }
php
public function checkFilesWritable($returnBool = false) { $targetFiles = $this->_getFilesForCheckingWritable(); if (empty($targetFiles)) { return null; } $result = []; $resultBool = true; foreach ($targetFiles as $targetFile) { if (!file_exists($targetFile)) { $state = false; } else { $state = is_writable($targetFile); } $resultBool = $resultBool && $state; $result[$targetFile] = $state; } if ($returnBool) { return $resultBool; } return $result; }
Check extension of PHP @param bool $returnBool If True, return boolean. Otherwise, return array otherwise in format: - key - PHP extension name; - value - check result in format: - 0 - Bad; - 1 - Ok - Warning; - 2 - Ok - Success. @return null|bool|array Return Null, if checking is not configured.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L348-L370
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.getListDbConn
public function getListDbConn($path = null) { if (empty($path)) { $path = APP; } $configFile = $path . 'Config' . DS . 'database.php'; $connections = []; if (file_exists($configFile)) { $connections = array_keys(ConnectionManager::enumConnectionObjects()); } return $connections; }
php
public function getListDbConn($path = null) { if (empty($path)) { $path = APP; } $configFile = $path . 'Config' . DS . 'database.php'; $connections = []; if (file_exists($configFile)) { $connections = array_keys(ConnectionManager::enumConnectionObjects()); } return $connections; }
Return list of configured database connection. @param string $path Path to database connection configuration file. @return array List of configured database connection.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L378-L390
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkConnectDb
public function checkConnectDb($path = null, $returnBool = false) { $connections = $this->getListDbConn($path); if (empty($connections)) { return null; } $cfgConnections = $this->_modelConfigInstaller->getListDbConnConfigs(); if (empty($cfgConnections)) { return null; } $connections = array_intersect($connections, $cfgConnections); $notCfgConnections = array_diff($cfgConnections, $connections); $result = []; $resultBool = true; foreach ($connections as $connectionName) { try { //@codingStandardsIgnoreStart $ds = @ConnectionManager::getDataSource($connectionName); //@codingStandardsIgnoreEnd $checkResult = $ds->isConnected(); } catch (Exception $exception) { $checkResult = [$exception->getMessage()]; $attributes = $exception->getAttributes(); if (isset($attributes['message'])) { $checkResult[] = $attributes['message']; } $resultBool = false; } if (!$checkResult) { $resultBool = false; } $result[$connectionName] = $checkResult; } foreach ($notCfgConnections as $connectionName) { $result[$connectionName] = false; $resultBool = false; } if ($returnBool) { return $resultBool; } return $result; }
php
public function checkConnectDb($path = null, $returnBool = false) { $connections = $this->getListDbConn($path); if (empty($connections)) { return null; } $cfgConnections = $this->_modelConfigInstaller->getListDbConnConfigs(); if (empty($cfgConnections)) { return null; } $connections = array_intersect($connections, $cfgConnections); $notCfgConnections = array_diff($cfgConnections, $connections); $result = []; $resultBool = true; foreach ($connections as $connectionName) { try { //@codingStandardsIgnoreStart $ds = @ConnectionManager::getDataSource($connectionName); //@codingStandardsIgnoreEnd $checkResult = $ds->isConnected(); } catch (Exception $exception) { $checkResult = [$exception->getMessage()]; $attributes = $exception->getAttributes(); if (isset($attributes['message'])) { $checkResult[] = $attributes['message']; } $resultBool = false; } if (!$checkResult) { $resultBool = false; } $result[$connectionName] = $checkResult; } foreach ($notCfgConnections as $connectionName) { $result[$connectionName] = false; $resultBool = false; } if ($returnBool) { return $resultBool; } return $result; }
Check connections to database @param string $path Path to database connection configuration file. @param bool $returnBool If True, return boolean. Otherwise, return array otherwise in format: - key - database connection name; - value - True, if connection success. Otherwise False or Array or error messages. @return null|bool|array Return Null, if checking is not configured.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L403-L446
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkDbTableExists
public function checkDbTableExists() { $ds = $this->getDataSource(); $existsTables = $ds->listSources(); if (empty($existsTables)) { return false; } $schemaList = []; $schemaCheckingList = ['']; $schemaCheckingListCfg = $this->_modelConfigInstaller->getListSchemaChecking(); if (!empty($schemaCheckingList)) { $schemaCheckingList = array_merge($schemaCheckingList, $schemaCheckingListCfg); } foreach ($schemaCheckingList as $schemaCheckingListItem) { $name = null; $path = null; $file = null; $connection = null; $plugin = null; if (preg_match('/[\s\b]?\-\-name\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { list($plugin, $name) = pluginSplit($matches[1]); } elseif (preg_match('/^(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $name = $matches[1]; } if (preg_match('/[\s\b]?(?:\-p|\-\-plugin)\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $plugin = $matches[1]; } if (preg_match('/[\s\b]?(?:\-c|\-\-connection)\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $connection = $matches[1]; } if (preg_match('/[\s\b]?\-\-path\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $path = $matches[1]; } if (preg_match('/[\s\b]?\-\-file\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $file = $matches[1]; } if (!empty($name)) { $file = Inflector::underscore($name); } elseif (empty($file)) { $file = 'schema.php'; } if (strpos($file, '.php') === false) { $file .= '.php'; } if (!empty($plugin) && empty($name)) { $name = $plugin; } $name = Inflector::camelize($name); $schemaList[] = compact('name', 'path', 'file', 'connection', 'plugin'); } $existsTables = array_flip($existsTables); foreach ($schemaList as $schemaListItem) { $Schema = new CakeSchema($schemaListItem); $oldSchema = $Schema->load(); if (!$oldSchema) { return false; } $diffTables = array_diff_key($oldSchema->tables, $existsTables); if (!empty($diffTables)) { return false; } unset($Schema); } return true; }
php
public function checkDbTableExists() { $ds = $this->getDataSource(); $existsTables = $ds->listSources(); if (empty($existsTables)) { return false; } $schemaList = []; $schemaCheckingList = ['']; $schemaCheckingListCfg = $this->_modelConfigInstaller->getListSchemaChecking(); if (!empty($schemaCheckingList)) { $schemaCheckingList = array_merge($schemaCheckingList, $schemaCheckingListCfg); } foreach ($schemaCheckingList as $schemaCheckingListItem) { $name = null; $path = null; $file = null; $connection = null; $plugin = null; if (preg_match('/[\s\b]?\-\-name\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { list($plugin, $name) = pluginSplit($matches[1]); } elseif (preg_match('/^(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $name = $matches[1]; } if (preg_match('/[\s\b]?(?:\-p|\-\-plugin)\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $plugin = $matches[1]; } if (preg_match('/[\s\b]?(?:\-c|\-\-connection)\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $connection = $matches[1]; } if (preg_match('/[\s\b]?\-\-path\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $path = $matches[1]; } if (preg_match('/[\s\b]?\-\-file\s+(\w+)/', $schemaCheckingListItem, $matches) && (count($matches) == 2)) { $file = $matches[1]; } if (!empty($name)) { $file = Inflector::underscore($name); } elseif (empty($file)) { $file = 'schema.php'; } if (strpos($file, '.php') === false) { $file .= '.php'; } if (!empty($plugin) && empty($name)) { $name = $plugin; } $name = Inflector::camelize($name); $schemaList[] = compact('name', 'path', 'file', 'connection', 'plugin'); } $existsTables = array_flip($existsTables); foreach ($schemaList as $schemaListItem) { $Schema = new CakeSchema($schemaListItem); $oldSchema = $Schema->load(); if (!$oldSchema) { return false; } $diffTables = array_diff_key($oldSchema->tables, $existsTables); if (!empty($diffTables)) { return false; } unset($Schema); } return true; }
Check database tables exists @return bool Success
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L453-L529
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkSymLinksExists
public function checkSymLinksExists() { $symlinksList = $this->_modelConfigInstaller->getListSymlinksCreation(); if (empty($symlinksList)) { return true; } foreach ($symlinksList as $link => $target) { if (empty($link)) { continue; } if (!file_exists($link) || (!is_link($link) && (DS !== '\\'))) { return false; } if (stripos(readlink($link), $target) !== 0) { return false; } } return true; }
php
public function checkSymLinksExists() { $symlinksList = $this->_modelConfigInstaller->getListSymlinksCreation(); if (empty($symlinksList)) { return true; } foreach ($symlinksList as $link => $target) { if (empty($link)) { continue; } if (!file_exists($link) || (!is_link($link) && (DS !== '\\'))) { return false; } if (stripos(readlink($link), $target) !== 0) { return false; } } return true; }
Check symbolic links exists @return bool Success
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L536-L557
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck.checkCronJobsExists
public function checkCronJobsExists() { if ($this->isOsWindows()) { return true; } $apacheUser = $this->getWebSrvUser(); if (empty($apacheUser)) { return false; } $cronjobsList = $this->_modelConfigInstaller->getListCronJobsCreation(); if (empty($cronjobsList)) { return true; } $output = []; $exitCode = -1; $cmd = 'crontab -u ' . $apacheUser . ' -l 2>/dev/null'; exec($cmd, $output, $exitCode); if ($exitCode !== 0) { return false; } if (empty($output)) { return false; } foreach ($cronjobsList as $cmd => $time) { if (empty($cmd)) { continue; } if (count(preg_grep('/^[^#]+' . preg_quote($cmd, '/') . '$/', $output)) == 0) { return false; } } return true; }
php
public function checkCronJobsExists() { if ($this->isOsWindows()) { return true; } $apacheUser = $this->getWebSrvUser(); if (empty($apacheUser)) { return false; } $cronjobsList = $this->_modelConfigInstaller->getListCronJobsCreation(); if (empty($cronjobsList)) { return true; } $output = []; $exitCode = -1; $cmd = 'crontab -u ' . $apacheUser . ' -l 2>/dev/null'; exec($cmd, $output, $exitCode); if ($exitCode !== 0) { return false; } if (empty($output)) { return false; } foreach ($cronjobsList as $cmd => $time) { if (empty($cmd)) { continue; } if (count(preg_grep('/^[^#]+' . preg_quote($cmd, '/') . '$/', $output)) == 0) { return false; } } return true; }
Check cron jobs exists @return bool Success
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L564-L602
anklimsk/cakephp-console-installer
Model/InstallerCheck.php
InstallerCheck._removeMarkerFile
protected function _removeMarkerFile($path) { if (empty($path)) { return false; } $oFile = new File($path, false); if (!$oFile->exists()) { return false; } return $oFile->delete(); }
php
protected function _removeMarkerFile($path) { if (empty($path)) { return false; } $oFile = new File($path, false); if (!$oFile->exists()) { return false; } return $oFile->delete(); }
Remove marker file @param string $path Path to marker file. @return bool True, if file removed successful. False otherwise.
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L668-L679
phpextra/event-manager-silex-provider
src/PHPExtra/EventManager/Silex/ProxyMapper.php
ProxyMapper.createProxyEvent
public function createProxyEvent(Event $event) { if ($event instanceof GetResponseForControllerResultEvent) { $silexEvent = new PostDispatchEvent($event); } elseif ($event instanceof GetResponseEvent) { $silexEvent = new RequestEvent($event); } elseif ($event instanceof FilterControllerEvent) { $silexEvent = new PreDispatchEvent($event); } elseif ($event instanceof FilterResponseEvent) { $silexEvent = new ResponseEvent($event); } elseif ($event instanceof SfPostResponseEvent) { $silexEvent = new PostResponseEvent($event); } elseif ($event instanceof FinishRequestEvent) { $silexEvent = new PostRequestEvent($event); } elseif ($event instanceof KernelEvent) { $silexEvent = new SilexKernelEvent($event); } elseif ($event instanceof Event) { $silexEvent = new SilexEvent($event); } else { $silexEvent = null; // unknown event } return $silexEvent; }
php
public function createProxyEvent(Event $event) { if ($event instanceof GetResponseForControllerResultEvent) { $silexEvent = new PostDispatchEvent($event); } elseif ($event instanceof GetResponseEvent) { $silexEvent = new RequestEvent($event); } elseif ($event instanceof FilterControllerEvent) { $silexEvent = new PreDispatchEvent($event); } elseif ($event instanceof FilterResponseEvent) { $silexEvent = new ResponseEvent($event); } elseif ($event instanceof SfPostResponseEvent) { $silexEvent = new PostResponseEvent($event); } elseif ($event instanceof FinishRequestEvent) { $silexEvent = new PostRequestEvent($event); } elseif ($event instanceof KernelEvent) { $silexEvent = new SilexKernelEvent($event); } elseif ($event instanceof Event) { $silexEvent = new SilexEvent($event); } else { $silexEvent = null; // unknown event } return $silexEvent; }
Create proxy event for given Symfony dispatcher event @param Event $event @return EventInterface
https://github.com/phpextra/event-manager-silex-provider/blob/9952b237feffa5a469dd2976317736a570526249/src/PHPExtra/EventManager/Silex/ProxyMapper.php#L37-L68
pilipinews/common
src/Converters/TableRowConverter.php
TableRowConverter.convert
public function convert(ElementInterface $element) { $children = array(); foreach ($element->getChildren() as $item) { $value = str_replace("\n", ' ', $item->getValue()); $null = $value === ' ' || empty($value); $null === false && array_push($children, $value); } return implode(' - ', $children) . "\n"; }
php
public function convert(ElementInterface $element) { $children = array(); foreach ($element->getChildren() as $item) { $value = str_replace("\n", ' ', $item->getValue()); $null = $value === ' ' || empty($value); $null === false && array_push($children, $value); } return implode(' - ', $children) . "\n"; }
Converts the specified element into a parsed string. @param \League\HTMLToMarkdown\ElementInterface $element @return string
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Converters/TableRowConverter.php#L16-L30
thienhungho/yii2-media-management
src/modules/MediaConfiguration/controllers/MediaController.php
MediaController.actionIndex
public function actionIndex() { $model = new MediaConfigurationForm(); $model->thumbnail_size_width = Media::getConfigurationThumbnailSizeWidth(); $model->thumbnail_size_height = Media::getConfigurationThumbnailSizeHeight(); $model->medium_size_width = Media::getConfigurationMediumSizeWidth(); $model->medium_size_height = Media::getConfigurationMediumSizeHeight(); $model->large_size_width = Media::getConfigurationLargeSizeWidth(); $model->large_size_height = Media::getConfigurationLargeSizeHeight(); $model->quality = Media::getConfigurationQuality(); if ($model->load(\request()->post())) { if ($model->config()) { set_flash_has_been_saved(); return $this->redirect(Url::to(['index'])); } else { set_flash_has_not_been_saved(); return $this->render('index', ['model' => $model]); } } else { return $this->render('index', ['model' => $model]); } }
php
public function actionIndex() { $model = new MediaConfigurationForm(); $model->thumbnail_size_width = Media::getConfigurationThumbnailSizeWidth(); $model->thumbnail_size_height = Media::getConfigurationThumbnailSizeHeight(); $model->medium_size_width = Media::getConfigurationMediumSizeWidth(); $model->medium_size_height = Media::getConfigurationMediumSizeHeight(); $model->large_size_width = Media::getConfigurationLargeSizeWidth(); $model->large_size_height = Media::getConfigurationLargeSizeHeight(); $model->quality = Media::getConfigurationQuality(); if ($model->load(\request()->post())) { if ($model->config()) { set_flash_has_been_saved(); return $this->redirect(Url::to(['index'])); } else { set_flash_has_not_been_saved(); return $this->render('index', ['model' => $model]); } } else { return $this->render('index', ['model' => $model]); } }
Renders the index view for the module @return string
https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/MediaConfiguration/controllers/MediaController.php#L19-L42
comodojo/extender.framework
src/Comodojo/Extender/Utils/Checks.php
Checks.database
final public static function database(Configuration $configuration) { try { $dbh = Database::init($configuration); $dbh->connect(); $manager = $dbh->getSchemaManager(); $manager->getTable($configuration->get('database-jobs-table')); $manager->getTable($configuration->get('database-worklogs-table')); $manager->getTable($configuration->get('database-queue-table')); } catch (Exception $e) { return false; } finally { $dhb->close(); } return true; }
php
final public static function database(Configuration $configuration) { try { $dbh = Database::init($configuration); $dbh->connect(); $manager = $dbh->getSchemaManager(); $manager->getTable($configuration->get('database-jobs-table')); $manager->getTable($configuration->get('database-worklogs-table')); $manager->getTable($configuration->get('database-queue-table')); } catch (Exception $e) { return false; } finally { $dhb->close(); } return true; }
Check if database is available and initialized correctly @return bool
https://github.com/comodojo/extender.framework/blob/cc9a4fbd29fe0e80965ce4535091c956aad70b27/src/Comodojo/Extender/Utils/Checks.php#L63-L89
fxpio/fxp-gluon
Block/Type/PanelListType.php
PanelListType.addChild
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, PanelType::class)) { $panels = $block->getAttribute('panels', []); $block->remove($child->getName()); $panels[$child->getName()] = $child; $block->setAttribute('panels', $panels); } elseif (!BlockUtil::isBlockType($child, PanelHeaderType::class)) { throw new InvalidConfigurationException('Only "panel" type child must be added into the panel list type'); } }
php
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, PanelType::class)) { $panels = $block->getAttribute('panels', []); $block->remove($child->getName()); $panels[$child->getName()] = $child; $block->setAttribute('panels', $panels); } elseif (!BlockUtil::isBlockType($child, PanelHeaderType::class)) { throw new InvalidConfigurationException('Only "panel" type child must be added into the panel list type'); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelListType.php#L40-L52
matryoshka-model/matryoshka
library/Object/Service/ObjectAbstractServiceFactory.php
ObjectAbstractServiceFactory.createServiceWithName
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if ($serviceLocator instanceof AbstractPluginManager && $serviceLocator->getServiceLocator()) { $serviceLocator = $serviceLocator->getServiceLocator(); } $config = $this->getConfig($serviceLocator)[$requestedName]; //Create an object instance $class = $config['type']; if (!class_exists($class)) { throw new Exception\RuntimeException(sprintf( 'ObjectAbstractServiceFactory expects the "type" to be a valid class; received "%s"', $class )); } $object = new $class; //Setup Hydrator $hydrator = null; if ($object instanceof HydratorAwareInterface && isset($config['hydrator']) && is_string($config['hydrator']) && !empty($config['hydrator']) ) { $object->setHydrator($this->getHydratorByName($serviceLocator, $config['hydrator'])); } //Setup InputFilter if ($object instanceof InputFilterAwareInterface && isset($config['input_filter']) && is_string($config['input_filter']) && !empty($config['input_filter']) ) { $object->setInputFilter($this->getInputFilterByName($serviceLocator, $config['input_filter'])); } //Setup ActiveRecord if ($object instanceof AbstractActiveRecord && isset($config['active_record_criteria']) && is_string($config['active_record_criteria']) && !empty($config['active_record_criteria']) ) { $object->setActiveRecordCriteriaPrototype($this->getActiveRecordCriteriaByName( $serviceLocator, $config['active_record_criteria'] )); } return $object; }
php
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if ($serviceLocator instanceof AbstractPluginManager && $serviceLocator->getServiceLocator()) { $serviceLocator = $serviceLocator->getServiceLocator(); } $config = $this->getConfig($serviceLocator)[$requestedName]; //Create an object instance $class = $config['type']; if (!class_exists($class)) { throw new Exception\RuntimeException(sprintf( 'ObjectAbstractServiceFactory expects the "type" to be a valid class; received "%s"', $class )); } $object = new $class; //Setup Hydrator $hydrator = null; if ($object instanceof HydratorAwareInterface && isset($config['hydrator']) && is_string($config['hydrator']) && !empty($config['hydrator']) ) { $object->setHydrator($this->getHydratorByName($serviceLocator, $config['hydrator'])); } //Setup InputFilter if ($object instanceof InputFilterAwareInterface && isset($config['input_filter']) && is_string($config['input_filter']) && !empty($config['input_filter']) ) { $object->setInputFilter($this->getInputFilterByName($serviceLocator, $config['input_filter'])); } //Setup ActiveRecord if ($object instanceof AbstractActiveRecord && isset($config['active_record_criteria']) && is_string($config['active_record_criteria']) && !empty($config['active_record_criteria']) ) { $object->setActiveRecordCriteriaPrototype($this->getActiveRecordCriteriaByName( $serviceLocator, $config['active_record_criteria'] )); } return $object; }
Create service with name @param ServiceLocatorInterface $serviceLocator @param $name @param $requestedName @return mixed @throws Exception\RuntimeException
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/Service/ObjectAbstractServiceFactory.php#L77-L127
matryoshka-model/matryoshka
library/Object/Service/ObjectAbstractServiceFactory.php
ObjectAbstractServiceFactory.getActiveRecordCriteriaByName
protected function getActiveRecordCriteriaByName($serviceLocator, $name) { $criteria = $serviceLocator->get($name); if (!$criteria instanceof AbstractCriteria) { throw new Exception\ServiceNotCreatedException(sprintf( 'Instance of type %s is invalid; must implement %s', (is_object($criteria) ? get_class($criteria) : gettype($criteria)), AbstractCriteria::class )); } return $criteria; }
php
protected function getActiveRecordCriteriaByName($serviceLocator, $name) { $criteria = $serviceLocator->get($name); if (!$criteria instanceof AbstractCriteria) { throw new Exception\ServiceNotCreatedException(sprintf( 'Instance of type %s is invalid; must implement %s', (is_object($criteria) ? get_class($criteria) : gettype($criteria)), AbstractCriteria::class )); } return $criteria; }
Retrieve PaginableCriteriaInterface object from config @param ServiceLocatorInterface $serviceLocator @param $name @return AbstractCriteria @throws Exception\ServiceNotCreatedException
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/Service/ObjectAbstractServiceFactory.php#L137-L148
davin-bao/php-git
src/Middleware/CatchException.php
CatchException.handle
public function handle($request, Closure $next) { try { return $next($request); } catch(Exception $exception){ $code =$exception->getCode(); if($code< 100 || $code >= 600){ $code = 512; //运行时异常 } $errors = ['msg'=>$exception->getMessage(), 'code'=>$code]; if ($request->ajax() || $request->wantsJson()) { //输出 JSON 字符串 return new JsonResponse($errors, $code); } //输出异常信息, 跳转回 GET 页 \Html::error($exception->getMessage(), $code); return redirect()->back() ->withInput($request->input()) ->withErrors($errors, $exception->getMessage()); } }
php
public function handle($request, Closure $next) { try { return $next($request); } catch(Exception $exception){ $code =$exception->getCode(); if($code< 100 || $code >= 600){ $code = 512; //运行时异常 } $errors = ['msg'=>$exception->getMessage(), 'code'=>$code]; if ($request->ajax() || $request->wantsJson()) { //输出 JSON 字符串 return new JsonResponse($errors, $code); } //输出异常信息, 跳转回 GET 页 \Html::error($exception->getMessage(), $code); return redirect()->back() ->withInput($request->input()) ->withErrors($errors, $exception->getMessage()); } }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Middleware/CatchException.php#L30-L53
digipolisgent/robo-digipolis-deploy
src/ClearOpCache.php
ClearOpCache.run
public function run() { if (!class_exists('\\CacheTool\\CacheTool')) { return Result::errorMissingPackage($this, '\\CacheTool\\CacheTool', 'gordalina/cachetool'); } $adapter = null; switch ($this->environment) { case static::ENV_CLI: $adapter = new \CacheTool\Adapter\Cli(); break; case static::ENV_FCGI: default: $adapter = new \CacheTool\Adapter\FastCGI($this->host); break; } $this->printTaskInfo(sprintf('Resetting opcache for %s.', $this->environment)); $cachetool = \CacheTool\CacheTool::factory($adapter); $cachetool->opcache_reset(); return Result::success($this); }
php
public function run() { if (!class_exists('\\CacheTool\\CacheTool')) { return Result::errorMissingPackage($this, '\\CacheTool\\CacheTool', 'gordalina/cachetool'); } $adapter = null; switch ($this->environment) { case static::ENV_CLI: $adapter = new \CacheTool\Adapter\Cli(); break; case static::ENV_FCGI: default: $adapter = new \CacheTool\Adapter\FastCGI($this->host); break; } $this->printTaskInfo(sprintf('Resetting opcache for %s.', $this->environment)); $cachetool = \CacheTool\CacheTool::factory($adapter); $cachetool->opcache_reset(); return Result::success($this); }
{@inheritdoc}
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/ClearOpCache.php#L47-L68
digipolisgent/robo-digipolis-deploy
src/ClearOpCache.php
ClearOpCache.getCommand
public function getCommand() { $tool = $this->findExecutable('cachetool'); $cmd = $tool . ' opcache:reset --' . $this->environment; if ($this->environment === static::ENV_FCGI && $this->host) { $cmd .= '=' . $this->host; } return $cmd; }
php
public function getCommand() { $tool = $this->findExecutable('cachetool'); $cmd = $tool . ' opcache:reset --' . $this->environment; if ($this->environment === static::ENV_FCGI && $this->host) { $cmd .= '=' . $this->host; } return $cmd; }
{@inheritdoc}
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/ClearOpCache.php#L73-L81
digipolisgent/robo-digipolis-deploy
src/Ssh/Adapter/SshPhpseclibAdapter.php
SshPhpseclibAdapter.read
public function read($expect = '', $mode = self::READ_SIMPLE) { return $this->ssh->read($expect, $mode); }
php
public function read($expect = '', $mode = self::READ_SIMPLE) { return $this->ssh->read($expect, $mode); }
{@inheritdoc}
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh/Adapter/SshPhpseclibAdapter.php#L293-L296
Elephant418/Staq
src/Staq/Core/Data/Stack/Controller/Model.php
Model.actionList
public function actionList() { $models = $this->getNewEntity()->fetchAll(); $view = $this->createView('list'); $view['content'] = $models; return $view; }
php
public function actionList() { $models = $this->getNewEntity()->fetchAll(); $view = $this->createView('list'); $view['content'] = $models; return $view; }
/* ACTION METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Controller/Model.php#L11-L17
Elephant418/Staq
src/Staq/Core/Data/Stack/Controller/Model.php
Model.getRouteAttributes
public function getRouteAttributes($model) { $attributes = []; $attributes['id'] = $model->id; $attributes['name'] = \Staq\Util::smartUrlEncode($model->name()); return $attributes; }
php
public function getRouteAttributes($model) { $attributes = []; $attributes['id'] = $model->id; $attributes['name'] = \Staq\Util::smartUrlEncode($model->name()); return $attributes; }
/* PUBLIC METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Controller/Model.php#L32-L38
Elephant418/Staq
src/Staq/Core/Data/Stack/Controller/Model.php
Model.createView
protected function createView($action='view') { $view = (new \Stack\View)->byName($this->getModelName(), 'Model_' . ucfirst($action)); $view['controller'] = $this->getModelName(); $view['controllerAction'] = $action; return $view; }
php
protected function createView($action='view') { $view = (new \Stack\View)->byName($this->getModelName(), 'Model_' . ucfirst($action)); $view['controller'] = $this->getModelName(); $view['controllerAction'] = $action; return $view; }
/* PRIVATE METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Controller/Model.php#L43-L49
xiewulong/yii2-wechat
models/WechatMessage.php
WechatMessage.autoReply
public function autoReply($messageClass = null) { if($messageClass) { return ($message = static::findOne($messageClass::reply($this->id))) && $message->pid == $this->id ? $message->replyFormat : null; } $reply = []; switch($this->msg_type) { case 'text': $reply = WechatMessageRule::keywords($this->appid, $this->content); break; case 'event': switch($this->event) { case 'unsubscribe': break; case 'subscribe': $reply = WechatMessageRule::beAdded($this->appid); break; } break; } if($reply) { $message = new static; foreach($reply as $k => $v) { $message[$k] = $v; } $message->appid = $this->appid; $message->type = 2; $message->pid = $this->id; $message->to_user_name = $this->from_user_name; $message->from_user_name = $this->to_user_name; if($message->save()) { return $message->replyFormat; } } return null; }
php
public function autoReply($messageClass = null) { if($messageClass) { return ($message = static::findOne($messageClass::reply($this->id))) && $message->pid == $this->id ? $message->replyFormat : null; } $reply = []; switch($this->msg_type) { case 'text': $reply = WechatMessageRule::keywords($this->appid, $this->content); break; case 'event': switch($this->event) { case 'unsubscribe': break; case 'subscribe': $reply = WechatMessageRule::beAdded($this->appid); break; } break; } if($reply) { $message = new static; foreach($reply as $k => $v) { $message[$k] = $v; } $message->appid = $this->appid; $message->type = 2; $message->pid = $this->id; $message->to_user_name = $this->from_user_name; $message->from_user_name = $this->to_user_name; if($message->save()) { return $message->replyFormat; } } return null; }
获取自动回复消息 @method autoReply @since 0.0.1 @param {string} [$messageClass] 调用公众号消息类回复(优先级最高), 否则默认规则回复 @return {array} @example $this->autoReply($messageClass);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatMessage.php#L30-L67
xiewulong/yii2-wechat
models/WechatMessage.php
WechatMessage.getReplyFormat
public function getReplyFormat() { if($this->type != 2) { return null; } $reply = [ 'ToUserName' => $this->to_user_name, 'FromUserName' => $this->from_user_name, 'CreateTime' => $this->created_at, 'MsgType' => $this->msg_type, ]; switch($this->msg_type) { case 'text': $reply['Content'] = $this->content; break; case 'image': $reply['Image']['MediaId'] = $this->media_id; break; case 'voice': $reply['Voice']['MediaId'] = $this->media_id; break; case 'video': $reply['Video'] = [ 'MediaId' => $this->media_id, 'Title' => $this->title, 'Description' => $this->description, ]; break; case 'music': $reply['Music'] = [ 'Title' => $this->title, 'Description' => $this->description, 'MusicUrl' => $this->music_url, 'HQMusicUrl' => $this->hq_music_url, 'ThumbMediaId' => $this->thumb_media_id, ]; break; case 'news': $articles = $this->articleList; $reply['ArticleCount'] = count($articles); $reply['Articles'] = []; foreach($articles as $article) { $reply['Articles'][] = [ 'Title' => $article['title'], 'Description' => $article['description'], 'PicUrl' => $article['pic_url'], 'Url' => $article['url'], ]; } break; default: return null; break; } return $reply; }
php
public function getReplyFormat() { if($this->type != 2) { return null; } $reply = [ 'ToUserName' => $this->to_user_name, 'FromUserName' => $this->from_user_name, 'CreateTime' => $this->created_at, 'MsgType' => $this->msg_type, ]; switch($this->msg_type) { case 'text': $reply['Content'] = $this->content; break; case 'image': $reply['Image']['MediaId'] = $this->media_id; break; case 'voice': $reply['Voice']['MediaId'] = $this->media_id; break; case 'video': $reply['Video'] = [ 'MediaId' => $this->media_id, 'Title' => $this->title, 'Description' => $this->description, ]; break; case 'music': $reply['Music'] = [ 'Title' => $this->title, 'Description' => $this->description, 'MusicUrl' => $this->music_url, 'HQMusicUrl' => $this->hq_music_url, 'ThumbMediaId' => $this->thumb_media_id, ]; break; case 'news': $articles = $this->articleList; $reply['ArticleCount'] = count($articles); $reply['Articles'] = []; foreach($articles as $article) { $reply['Articles'][] = [ 'Title' => $article['title'], 'Description' => $article['description'], 'PicUrl' => $article['pic_url'], 'Url' => $article['url'], ]; } break; default: return null; break; } return $reply; }
获取回复格式 @method getReplyFormat @since 0.0.1 @return {array} @example $this->getReplyFormat();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatMessage.php#L76-L132
prooph/processing
examples/ProcessingExample/Plugin/SetUpEventStore.php
SetUpEventStore.registerOn
public function registerOn(Environment $workflowEnv) { $es = $workflowEnv->getEventStore(); $es->beginTransaction(); $es->create( new \Prooph\EventStore\Stream\Stream( new \Prooph\EventStore\Stream\StreamName('prooph_processing_stream'), [] ) ); $es->commit(); }
php
public function registerOn(Environment $workflowEnv) { $es = $workflowEnv->getEventStore(); $es->beginTransaction(); $es->create( new \Prooph\EventStore\Stream\Stream( new \Prooph\EventStore\Stream\StreamName('prooph_processing_stream'), [] ) ); $es->commit(); }
Register the plugin on the workflow environment @param Environment $workflowEnv @return void
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/examples/ProcessingExample/Plugin/SetUpEventStore.php#L42-L56
fxpio/fxp-doctrine-console
Command/Create.php
Create.execute
protected function execute(InputInterface $input, OutputInterface $output) { $instance = $this->adapter->newInstance([]); $this->validateInstance($instance); $this->helper->injectNewValues($input, $instance); $this->adapter->create($instance); $this->showMessage($output, $instance, 'The %s <info>%s</info> was created with successfully'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $instance = $this->adapter->newInstance([]); $this->validateInstance($instance); $this->helper->injectNewValues($input, $instance); $this->adapter->create($instance); $this->showMessage($output, $instance, 'The %s <info>%s</info> was created with successfully'); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Create.php#L35-L44
gbprod/doctrine-specification
src/DoctrineSpecification/QueryFactory/NotFactory.php
NotFactory.create
public function create(Specification $spec, QueryBuilder $qb) { if (!$spec instanceof Not) { throw new \InvalidArgumentException(); } $factory = $this->registry->getFactory($spec->getWrappedSpecification()); return $qb->expr()->not( $factory->create($spec->getWrappedSpecification(), $qb) ); }
php
public function create(Specification $spec, QueryBuilder $qb) { if (!$spec instanceof Not) { throw new \InvalidArgumentException(); } $factory = $this->registry->getFactory($spec->getWrappedSpecification()); return $qb->expr()->not( $factory->create($spec->getWrappedSpecification(), $qb) ); }
{inheritdoc}
https://github.com/gbprod/doctrine-specification/blob/348e8ec31547f4949a193d21b3a1d5cdb48b23cb/src/DoctrineSpecification/QueryFactory/NotFactory.php#L35-L46
andyburton/Sonic-Framework
src/Controller/JSON/Session.php
Session.checkAuthenticated
protected function checkAuthenticated ($session_id = FALSE) { // Create user if (!$this->user) { $this->user = new \Sonic\Model\User ($session_id); } // Check authenticated $auth = $this->user->initSession (); if ($auth !== TRUE) { return $this->authFail ($auth); } // Return return TRUE; }
php
protected function checkAuthenticated ($session_id = FALSE) { // Create user if (!$this->user) { $this->user = new \Sonic\Model\User ($session_id); } // Check authenticated $auth = $this->user->initSession (); if ($auth !== TRUE) { return $this->authFail ($auth); } // Return return TRUE; }
Check the user is authenticated @param string $session_id Session ID @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/JSON/Session.php#L57-L80
andyburton/Sonic-Framework
src/Controller/JSON/Session.php
Session.authFail
protected function authFail ($message = null) { $this->error ($message); $this->view->response['auth_fail'] = TRUE; return FALSE; }
php
protected function authFail ($message = null) { $this->error ($message); $this->view->response['auth_fail'] = TRUE; return FALSE; }
Set response for an authentication failure @param string $message Error message @return false
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/JSON/Session.php#L89-L94
matryoshka-model/matryoshka
library/Hydrator/Strategy/HasManyStrategy.php
HasManyStrategy.extract
public function extract($value) { if ($this->nullable && $value === null) { return null; } $return = []; if (is_array($value) || $value instanceof \Traversable) { foreach ($value as $key => $object) { $return[$key] = $this->hasOneStrategy->extract($object); } } else { throw new Exception\InvalidArgumentException(sprintf( 'Value must be null (only if nullable option is enabled), or an array, or a Traversable: "%s" given', is_object($value) ? get_class($value) : gettype($value) )); } return $return; }
php
public function extract($value) { if ($this->nullable && $value === null) { return null; } $return = []; if (is_array($value) || $value instanceof \Traversable) { foreach ($value as $key => $object) { $return[$key] = $this->hasOneStrategy->extract($object); } } else { throw new Exception\InvalidArgumentException(sprintf( 'Value must be null (only if nullable option is enabled), or an array, or a Traversable: "%s" given', is_object($value) ? get_class($value) : gettype($value) )); } return $return; }
Converts the given value so that it can be extracted by the hydrator. @param array|\Traversable|null $value The original value. @return array|null Returns the value that should be extracted.
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Hydrator/Strategy/HasManyStrategy.php#L70-L89
matryoshka-model/matryoshka
library/Hydrator/Strategy/HasManyStrategy.php
HasManyStrategy.hydrate
public function hydrate($value) { if ($this->nullable && $value === null) { return null; } $this->hasOneStrategy->setPrototypeStrategy($this->getPrototypeStrategy()); $return = clone $this->arrayObjectPrototype; if (is_array($value) || $value instanceof \Traversable) { foreach ($value as $key => $data) { $return[$key] = $this->hasOneStrategy->hydrate($data); } } else { throw new Exception\InvalidArgumentException(sprintf( 'Value must be null (only if nullable option is enabled), or an array, or a Traversable: "%s" given', is_object($value) ? get_class($value) : gettype($value) )); } return $return; }
php
public function hydrate($value) { if ($this->nullable && $value === null) { return null; } $this->hasOneStrategy->setPrototypeStrategy($this->getPrototypeStrategy()); $return = clone $this->arrayObjectPrototype; if (is_array($value) || $value instanceof \Traversable) { foreach ($value as $key => $data) { $return[$key] = $this->hasOneStrategy->hydrate($data); } } else { throw new Exception\InvalidArgumentException(sprintf( 'Value must be null (only if nullable option is enabled), or an array, or a Traversable: "%s" given', is_object($value) ? get_class($value) : gettype($value) )); } return $return; }
Converts the given value so that it can be hydrated by the hydrator. @param array|\Traversable|null $value The original value. @return \ArrayAccess|null Returns the value that should be hydrated.
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Hydrator/Strategy/HasManyStrategy.php#L97-L117
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.create
public function create($template = false) { $this->addDefaultGeoFields($template); $this->useTemplate($template); return parent::create(); }
php
public function create($template = false) { $this->addDefaultGeoFields($template); $this->useTemplate($template); return parent::create(); }
Overwrites the CrudController create() method to add template usage.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L63-L69
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.store
public function store(StoreRequest $request) { $this->addDefaultGeoFields(\Request::input('template')); $this->useTemplate(\Request::input('template')); return parent::storeCrud(); }
php
public function store(StoreRequest $request) { $this->addDefaultGeoFields(\Request::input('template')); $this->useTemplate(\Request::input('template')); return parent::storeCrud(); }
Overwrites the CrudController store() method to add template usage.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L72-L78
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.edit
public function edit($id, $template = false) { // if the template in the GET parameter is missing, figure it out from the db if ($template == false) { $model = $this->crud->model; $this->data['entry'] = $model::findOrFail($id); $template = $this->data['entry']->template; } $this->addDefaultGeoFields($template); $this->useTemplate($template); return parent::edit($id); }
php
public function edit($id, $template = false) { // if the template in the GET parameter is missing, figure it out from the db if ($template == false) { $model = $this->crud->model; $this->data['entry'] = $model::findOrFail($id); $template = $this->data['entry']->template; } $this->addDefaultGeoFields($template); $this->useTemplate($template); return parent::edit($id); }
Overwrites the CrudController edit() method to add template usage.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L81-L94
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.update
public function update(UpdateRequest $request) { $this->addDefaultGeoFields(\Request::input('template')); $this->useTemplate(\Request::input('template')); return parent::updateCrud(); }
php
public function update(UpdateRequest $request) { $this->addDefaultGeoFields(\Request::input('template')); $this->useTemplate(\Request::input('template')); return parent::updateCrud(); }
Overwrites the CrudController update() method to add template usage.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L97-L103
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.addDefaultGeoFields
public function addDefaultGeoFields($template = false) { $this->crud->addField([ 'name' => 'template', 'label' => 'Template', 'type' => 'select_geo_template', 'options' => $this->getTemplatesArray(), 'value' => $template, 'allows_null' => false, ]); $this->crud->addField([ 'name' => 'name', 'label' => 'Geo name (only seen by admins)', 'type' => 'text', // 'disabled' => 'disabled' ]); $this->crud->addField([ 'name' => 'title', 'label' => 'Geo Title', 'type' => 'text', // 'disabled' => 'disabled' ]); $this->crud->addField([ 'name' => 'slug', 'label' => 'Geo Slug (URL)', 'type' => 'text', 'hint' => 'Will be automatically generated from your title, if left empty.', // 'disabled' => 'disabled' ]); }
php
public function addDefaultGeoFields($template = false) { $this->crud->addField([ 'name' => 'template', 'label' => 'Template', 'type' => 'select_geo_template', 'options' => $this->getTemplatesArray(), 'value' => $template, 'allows_null' => false, ]); $this->crud->addField([ 'name' => 'name', 'label' => 'Geo name (only seen by admins)', 'type' => 'text', // 'disabled' => 'disabled' ]); $this->crud->addField([ 'name' => 'title', 'label' => 'Geo Title', 'type' => 'text', // 'disabled' => 'disabled' ]); $this->crud->addField([ 'name' => 'slug', 'label' => 'Geo Slug (URL)', 'type' => 'text', 'hint' => 'Will be automatically generated from your title, if left empty.', // 'disabled' => 'disabled' ]); }
Populate the create/update forms with basic fields, that all geos need. @param string $template The name of the template that should be used in the current form.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L114-L143
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.useTemplate
public function useTemplate($template_name = false) { $templates = $this->getTemplates(); // set the default template if ($template_name == false) { $template_name = $templates[0]->name; } // actually use the template if ($template_name) { $this->{$template_name}(); } }
php
public function useTemplate($template_name = false) { $templates = $this->getTemplates(); // set the default template if ($template_name == false) { $template_name = $templates[0]->name; } // actually use the template if ($template_name) { $this->{$template_name}(); } }
Add the fields defined for a specific template. @param string $template_name The name of the template that should be used in the current form.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L150-L163
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.getTemplates
public function getTemplates() { $templates_array = []; $templates_trait = new \ReflectionClass('App\GeoTemplates'); $templates = $templates_trait->getMethods(); if (! count($templates)) { abort('403', 'No templates have been found.'); } return $templates; }
php
public function getTemplates() { $templates_array = []; $templates_trait = new \ReflectionClass('App\GeoTemplates'); $templates = $templates_trait->getMethods(); if (! count($templates)) { abort('403', 'No templates have been found.'); } return $templates; }
Get all defined templates.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L168-L180
luismareze/geomanager
src/app/Http/Controllers/Admin/GeoCrudController.php
GeoCrudController.getTemplatesArray
public function getTemplatesArray() { $templates = $this->getTemplates(); foreach ($templates as $template) { $templates_array[$template->name] = $this->crud->makeLabel($template->name); } return $templates_array; }
php
public function getTemplatesArray() { $templates = $this->getTemplates(); foreach ($templates as $template) { $templates_array[$template->name] = $this->crud->makeLabel($template->name); } return $templates_array; }
Get all defined template as an array. Used to populate the template dropdown in the create/update forms.
https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L187-L196
as3io/modlr
src/Metadata/EmbeddedPropMetadata.php
EmbeddedPropMetadata.setEmbedType
public function setEmbedType($embedType) { $embedType = strtolower($embedType); $this->validateType($embedType); $this->embedType = $embedType; return $this; }
php
public function setEmbedType($embedType) { $embedType = strtolower($embedType); $this->validateType($embedType); $this->embedType = $embedType; return $this; }
Sets the embed type: one or many. @param string $embedType @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbeddedPropMetadata.php#L70-L76
as3io/modlr
src/Metadata/EmbeddedPropMetadata.php
EmbeddedPropMetadata.validateType
protected function validateType($embedType) { $valid = ['one', 'many']; if (!in_array($embedType, $valid)) { throw MetadataException::invalidRelType($embedType, $valid); } return true; }
php
protected function validateType($embedType) { $valid = ['one', 'many']; if (!in_array($embedType, $valid)) { throw MetadataException::invalidRelType($embedType, $valid); } return true; }
Validates the embed type. @param string $embedType @return bool @throws MetadataException
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbeddedPropMetadata.php#L85-L92
activecollab/databaseconnection
src/Record/ValueCaster.php
ValueCaster.castRowValues
public function castRowValues(array &$row) { foreach ($row as $field_name => $value) { $row[$field_name] = $this->castValue($field_name, $value); } }
php
public function castRowValues(array &$row) { foreach ($row as $field_name => $value) { $row[$field_name] = $this->castValue($field_name, $value); } }
Cast row value to native PHP types based on caster settings. @param array $row
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L43-L48
activecollab/databaseconnection
src/Record/ValueCaster.php
ValueCaster.castValue
public function castValue($field_name, $value) { if ($value === null) { return null; // NULL remains NULL } switch ($this->getTypeByFieldName($field_name)) { case self::CAST_INT: return (int) $value; case self::CAST_FLOAT: return (float) $value; case self::CAST_STRING: return (string) $value; case self::CAST_BOOL: return (bool) $value; case self::CAST_DATE: return new DateValue($value, 'UTC'); case self::CAST_DATETIME: return new DateTimeValue($value, 'UTC'); case self::CAST_JSON: if (empty($value)) { return null; } else { $result = json_decode($value, true); if (empty($result) && json_last_error()) { throw new RuntimeException('Failed to parse JSON. Reason: ' . json_last_error_msg(), json_last_error()); } return $result; } default: return (string) $value; } }
php
public function castValue($field_name, $value) { if ($value === null) { return null; // NULL remains NULL } switch ($this->getTypeByFieldName($field_name)) { case self::CAST_INT: return (int) $value; case self::CAST_FLOAT: return (float) $value; case self::CAST_STRING: return (string) $value; case self::CAST_BOOL: return (bool) $value; case self::CAST_DATE: return new DateValue($value, 'UTC'); case self::CAST_DATETIME: return new DateTimeValue($value, 'UTC'); case self::CAST_JSON: if (empty($value)) { return null; } else { $result = json_decode($value, true); if (empty($result) && json_last_error()) { throw new RuntimeException('Failed to parse JSON. Reason: ' . json_last_error_msg(), json_last_error()); } return $result; } default: return (string) $value; } }
Cast a single value. @param string $field_name @param mixed $value @return mixed
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L58-L92
activecollab/databaseconnection
src/Record/ValueCaster.php
ValueCaster.getTypeByFieldName
public function getTypeByFieldName($field_name) { if (isset($this->dictated[$field_name])) { return $this->dictated[$field_name]; } if (substr($field_name, 0, 3) === 'is_' || in_array(substr($field_name, 0, 4), ['has_', 'had_', 'was_']) || in_array(substr($field_name, 0, 5), ['were_', 'have_'])) { return self::CAST_BOOL; } $last_three = substr($field_name, -3); if ($last_three === '_id') { return self::CAST_INT; } if ($last_three === '_on') { return self::CAST_DATE; } if ($last_three === '_at') { return self::CAST_DATETIME; } return self::CAST_STRING; }
php
public function getTypeByFieldName($field_name) { if (isset($this->dictated[$field_name])) { return $this->dictated[$field_name]; } if (substr($field_name, 0, 3) === 'is_' || in_array(substr($field_name, 0, 4), ['has_', 'had_', 'was_']) || in_array(substr($field_name, 0, 5), ['were_', 'have_'])) { return self::CAST_BOOL; } $last_three = substr($field_name, -3); if ($last_three === '_id') { return self::CAST_INT; } if ($last_three === '_on') { return self::CAST_DATE; } if ($last_three === '_at') { return self::CAST_DATETIME; } return self::CAST_STRING; }
Return type by field name. @param string $field_name @return string
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L101-L126
PhoxPHP/Glider
src/Query/Builder/QueryBinder.php
QueryBinder.createBinding
public function createBinding(String $key, $queryPart, $params=[], $expr='', $with='', $addValue=true) { if (!array_key_exists($key, $this->bindings)) { return false; } if ($key == 'sql') { return $queryPart; } if ($addValue == true) { $this->bindings[$key] = $queryPart; } return $this->$key($queryPart, $params, $expr, $with, $addValue); }
php
public function createBinding(String $key, $queryPart, $params=[], $expr='', $with='', $addValue=true) { if (!array_key_exists($key, $this->bindings)) { return false; } if ($key == 'sql') { return $queryPart; } if ($addValue == true) { $this->bindings[$key] = $queryPart; } return $this->$key($queryPart, $params, $expr, $with, $addValue); }
This method bindings together queries created with the query builder. @param $key <String> @param $queryPart <Mixed> @param $params <Mixed> @param $expr <Mixed> @param $with <Mixed> @access public @return <Mixed>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Builder/QueryBinder.php#L90-L105
PhoxPHP/Glider
src/Query/Builder/QueryBinder.php
QueryBinder.alias
public function alias(String $column, String $alias) { // if (!$this->getBinding('select') || empty($this->getBinding('select'))) { // Since this method cannot be used without the SELECT statement, // we will throw an exception if `SELECT` binding is null or false. // throw new RuntimeException(sprintf('Cannot call aggregate function on empty select.')); // } $alias = str_replace($this->generator->getDisallowedChars(), '', $alias); return $this->attachSeparator($column . ' AS ' . $alias); }
php
public function alias(String $column, String $alias) { // if (!$this->getBinding('select') || empty($this->getBinding('select'))) { // Since this method cannot be used without the SELECT statement, // we will throw an exception if `SELECT` binding is null or false. // throw new RuntimeException(sprintf('Cannot call aggregate function on empty select.')); // } $alias = str_replace($this->generator->getDisallowedChars(), '', $alias); return $this->attachSeparator($column . ' AS ' . $alias); }
Create and return alias for a column. @param $column <String> @param $alias <String> @access public @return <String>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Builder/QueryBinder.php#L125-L134
infusephp/auth
src/Libs/UserRegistration.php
UserRegistration.registerUser
public function registerUser(array $values, $verifiedEmail = false) { $email = array_value($values, 'email'); $tempUser = $this->getTemporaryUser($email); // upgrade temporary account if ($tempUser && $this->upgradeTemporaryUser($tempUser, $values)) { return $tempUser; } $userClass = $this->auth->getUserClass(); $user = new $userClass(); if (!$user->create($values)) { throw new AuthException('Could not create user account: '.implode(', ', $user->getErrors()->all())); } if (!$verifiedEmail) { $this->auth->sendVerificationEmail($user); } else { // send the user a welcome message $user->sendEmail('welcome'); } return $user; }
php
public function registerUser(array $values, $verifiedEmail = false) { $email = array_value($values, 'email'); $tempUser = $this->getTemporaryUser($email); // upgrade temporary account if ($tempUser && $this->upgradeTemporaryUser($tempUser, $values)) { return $tempUser; } $userClass = $this->auth->getUserClass(); $user = new $userClass(); if (!$user->create($values)) { throw new AuthException('Could not create user account: '.implode(', ', $user->getErrors()->all())); } if (!$verifiedEmail) { $this->auth->sendVerificationEmail($user); } else { // send the user a welcome message $user->sendEmail('welcome'); } return $user; }
Registers a new user. @param array $values values to set on user account @param bool $verifiedEmail true if the email has been verified @throws AuthException when the user cannot be created. @return UserInterface newly created user
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L38-L63
infusephp/auth
src/Libs/UserRegistration.php
UserRegistration.getTemporaryUser
public function getTemporaryUser($email) { $email = trim(strtolower($email)); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $userClass = $this->auth->getUserClass(); $user = $userClass::where('email', $email)->first(); if (!$user) { return false; } if (!$user->isTemporary()) { return false; } return $user; }
php
public function getTemporaryUser($email) { $email = trim(strtolower($email)); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $userClass = $this->auth->getUserClass(); $user = $userClass::where('email', $email)->first(); if (!$user) { return false; } if (!$user->isTemporary()) { return false; } return $user; }
Gets a temporary user from an email address if one exists. @param string $email email address @return UserInterface|false
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L72-L91
infusephp/auth
src/Libs/UserRegistration.php
UserRegistration.createTemporaryUser
public function createTemporaryUser($parameters) { $email = trim(strtolower(array_value($parameters, 'email'))); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new AuthException('Invalid email address'); } $insertArray = array_replace($parameters, ['enabled' => false]); // create the temporary user $userClass = $this->auth->getUserClass(); $user = new $userClass(); $driver = $userClass::getDriver(); $created = $driver->createModel($user, $insertArray); if (!$created) { throw new AuthException('Could not create temporary user'); } // get the new user ID $id = []; foreach ($userClass::getIDProperties() as $k) { $id[] = $driver->getCreatedID($user, $k); } $user = $userClass::find($id); // create the temporary link $link = new UserLink(); $link->user_id = $user->id(); $link->type = UserLink::TEMPORARY; $link->saveOrFail(); $user->setTemporaryLink($link); return $user; }
php
public function createTemporaryUser($parameters) { $email = trim(strtolower(array_value($parameters, 'email'))); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new AuthException('Invalid email address'); } $insertArray = array_replace($parameters, ['enabled' => false]); // create the temporary user $userClass = $this->auth->getUserClass(); $user = new $userClass(); $driver = $userClass::getDriver(); $created = $driver->createModel($user, $insertArray); if (!$created) { throw new AuthException('Could not create temporary user'); } // get the new user ID $id = []; foreach ($userClass::getIDProperties() as $k) { $id[] = $driver->getCreatedID($user, $k); } $user = $userClass::find($id); // create the temporary link $link = new UserLink(); $link->user_id = $user->id(); $link->type = UserLink::TEMPORARY; $link->saveOrFail(); $user->setTemporaryLink($link); return $user; }
Creates a temporary user. Useful for creating invites. @param array $parameters user data @throws AuthException when the user cannot be created. @return UserInterface temporary user
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L102-L137
infusephp/auth
src/Libs/UserRegistration.php
UserRegistration.upgradeTemporaryUser
public function upgradeTemporaryUser(UserInterface $user, $values = []) { if (!$user->isTemporary()) { throw new AuthException('Cannot upgrade a non-temporary account'); } $values = array_replace($values, [ 'created_at' => Utility::unixToDb(time()), 'enabled' => true, ]); $user->grantAllPermissions(); if (!$user->set($values)) { $user->enforcePermissions(); throw new AuthException('Could not upgrade temporary account: '.implode($user->getErrors()->all())); } // remove temporary and unverified links $app = $user->getApp(); $app['database']->getDefault() ->delete('UserLinks') ->where('user_id', $user->id()) ->where(function ($query) { return $query->where('type', UserLink::TEMPORARY) ->orWhere('type', UserLink::VERIFY_EMAIL); }) ->execute(); $user->clearTemporaryLink(); // send the user a welcome message $user->sendEmail('welcome'); $user->enforcePermissions(); return $this; }
php
public function upgradeTemporaryUser(UserInterface $user, $values = []) { if (!$user->isTemporary()) { throw new AuthException('Cannot upgrade a non-temporary account'); } $values = array_replace($values, [ 'created_at' => Utility::unixToDb(time()), 'enabled' => true, ]); $user->grantAllPermissions(); if (!$user->set($values)) { $user->enforcePermissions(); throw new AuthException('Could not upgrade temporary account: '.implode($user->getErrors()->all())); } // remove temporary and unverified links $app = $user->getApp(); $app['database']->getDefault() ->delete('UserLinks') ->where('user_id', $user->id()) ->where(function ($query) { return $query->where('type', UserLink::TEMPORARY) ->orWhere('type', UserLink::VERIFY_EMAIL); }) ->execute(); $user->clearTemporaryLink(); // send the user a welcome message $user->sendEmail('welcome'); $user->enforcePermissions(); return $this; }
Upgrades the user from temporary to a fully registered account. @param UserInterface $user @param array $values properties to set on user model @throws AuthException when the upgrade fails. @return $this
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L149-L186
atelierdisko/cute_php
src/Worker.php
Worker.dispatch
public function dispatch() { while (true) { if ($this->_break) { break; } if ($this->_paused) { $this->_title('Paused, waiting'); $this->_log->debug('Paused, waiting.'); } while ($this->_paused) { pcntl_signal_dispatch(); sleep($this->_interval); } $this->_title('Waiting for job'); $this->_log->debug('Waiting for job.'); while (!$this->_job) { // FIXME Catch exception. but only handler exceptions. $this->_job = $this->_connection->reserve($this->_queues, 5); pcntl_signal_dispatch(); } $this->_title("Performing job {$this->_job}"); $this->_log->debug("Performing job {$this->_job}."); try { if ($this->_job->perform()) { $this->_job->succeed(); } else { $this->_job->fail(); } } catch (Exception $e) { $this->_log->notice(get_class($e) . ' while performing job: ' . $e->getMessage()); $this->_job->fail(); } $this->_job = null; } }
php
public function dispatch() { while (true) { if ($this->_break) { break; } if ($this->_paused) { $this->_title('Paused, waiting'); $this->_log->debug('Paused, waiting.'); } while ($this->_paused) { pcntl_signal_dispatch(); sleep($this->_interval); } $this->_title('Waiting for job'); $this->_log->debug('Waiting for job.'); while (!$this->_job) { // FIXME Catch exception. but only handler exceptions. $this->_job = $this->_connection->reserve($this->_queues, 5); pcntl_signal_dispatch(); } $this->_title("Performing job {$this->_job}"); $this->_log->debug("Performing job {$this->_job}."); try { if ($this->_job->perform()) { $this->_job->succeed(); } else { $this->_job->fail(); } } catch (Exception $e) { $this->_log->notice(get_class($e) . ' while performing job: ' . $e->getMessage()); $this->_job->fail(); } $this->_job = null; } }
Main method to start processing loop and dispatch jobs. @return boolean
https://github.com/atelierdisko/cute_php/blob/0302ed6f819794ed57a6663361ae4527aa05e183/src/Worker.php#L118-L155
atelierdisko/cute_php
src/Worker.php
Worker._trapSignals
protected function _trapSignals() { $this->_log->debug('Trapping signals.'); $handler = function($number) { switch ($number) { case SIGQUIT: $this->_log->debug('Received SIGQUIT, waiting and exiting.'); $this->_break = true; $this->_connection->disconnect(); exit(0); case SIGINT: case SIGTERM: $this->_log->debug('Received SIGTERM/SIGINT, killing exiting.'); $this->_connection->disconnect(); exit(1); case SIGUSR2: $this->_log->debug('Received SIGUSR2, pausing job processing.'); $this->_paused = true; $this->_interval = 10; break; case SIGCONT: $this->_log->debug('Received SIGCONT, continuing to process jobs.'); $this->_paused = false; $this->_interval = null; break; } }; pcntl_signal(SIGQUIT, $handler); pcntl_signal(SIGINT, $handler); pcntl_signal(SIGTERM, $handler); pcntl_signal(SIGUSR2, $handler); pcntl_signal(SIGCONT, $handler); }
php
protected function _trapSignals() { $this->_log->debug('Trapping signals.'); $handler = function($number) { switch ($number) { case SIGQUIT: $this->_log->debug('Received SIGQUIT, waiting and exiting.'); $this->_break = true; $this->_connection->disconnect(); exit(0); case SIGINT: case SIGTERM: $this->_log->debug('Received SIGTERM/SIGINT, killing exiting.'); $this->_connection->disconnect(); exit(1); case SIGUSR2: $this->_log->debug('Received SIGUSR2, pausing job processing.'); $this->_paused = true; $this->_interval = 10; break; case SIGCONT: $this->_log->debug('Received SIGCONT, continuing to process jobs.'); $this->_paused = false; $this->_interval = null; break; } }; pcntl_signal(SIGQUIT, $handler); pcntl_signal(SIGINT, $handler); pcntl_signal(SIGTERM, $handler); pcntl_signal(SIGUSR2, $handler); pcntl_signal(SIGCONT, $handler); }
Registers signal handlers and handles signals once received. Controls the current processing loop by setting object properties and using the process manager. @return void
https://github.com/atelierdisko/cute_php/blob/0302ed6f819794ed57a6663361ae4527aa05e183/src/Worker.php#L164-L199
phPoirot/Client-OAuth2
mod/Services/ServiceOAuthClient.php
ServiceOAuthClient.newService
function newService() { $baseUrl = $this->baseUrl; $clientID = $this->clientId; $clientSecret = $this->clientSecret; $scopes = ($this->scopes) ? $this->scopes : []; return new OAuth2Client\Client($baseUrl, $clientID, $clientSecret, $scopes); }
php
function newService() { $baseUrl = $this->baseUrl; $clientID = $this->clientId; $clientSecret = $this->clientSecret; $scopes = ($this->scopes) ? $this->scopes : []; return new OAuth2Client\Client($baseUrl, $clientID, $clientSecret, $scopes); }
Create Service @return iClientOfOAuth
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Services/ServiceOAuthClient.php#L24-L32
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.isVoidElement
public function isVoidElement($tag = null) { if (null === $tag) { $tag = $this->getTag(); } return in_array($tag, $this->voidElements); }
php
public function isVoidElement($tag = null) { if (null === $tag) { $tag = $this->getTag(); } return in_array($tag, $this->voidElements); }
@param string $tag @return boolean
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L102-L109
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.removeAttribute
public function removeAttribute($key) { if (!empty($this->attributes[$key])) { unset($this->attributes[$key]); } return $this; }
php
public function removeAttribute($key) { if (!empty($this->attributes[$key])) { unset($this->attributes[$key]); } return $this; }
@param string $key @return HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L217-L224
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.getAttribute
public function getAttribute($attribute) { return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null; }
php
public function getAttribute($attribute) { return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null; }
Get a specific attribute for this tag. @param string @attribute @return string|null
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L243-L246
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.setContent
public function setContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content = $content; return $this; }
php
public function setContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content = $content; return $this; }
Set the content. (Overwrites old content) @param string $content @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L272-L283
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.appendContent
public function appendContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content .= $content; return $this; }
php
public function appendContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content .= $content; return $this; }
Append content before other content @param string $content @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L293-L304
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.prependContent
public function prependContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content = $content . $this->content; return $this; }
php
public function prependContent($content) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t contain content.' ); } $this->content = $content . $this->content; return $this; }
Prepend content before other content @param string $content @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L314-L325
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.spawnChild
public function spawnChild($tag = 'div') { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } return $this->children[] = new self($tag); }
php
public function spawnChild($tag = 'div') { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } return $this->children[] = new self($tag); }
Spawn child @param string $tag @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L357-L366
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.addChild
public function addChild(self $child) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } $this->children[] = $child; return $this; }
php
public function addChild(self $child) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } $this->children[] = $child; return $this; }
Add child to tag @param \SxCore\Html\HtmlElement $child @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L376-L387
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.addChildren
public function addChildren(array $children) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } foreach ($children as $child) { $this->addChild($child); } return $this; }
php
public function addChildren(array $children) { if ($this->isVoid) { throw new Exception\RuntimeException( 'Void elements can\'t have child elements.' ); } foreach ($children as $child) { $this->addChild($child); } return $this; }
Add children to tag @param array $children @throws Exception\RuntimeException @return \SxCore\Html\HtmlElement
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L397-L410
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.render
public function render() { if ($this->isVoid) { return $this->renderTag(); } $content = ''; if ($this->hasChildren()) { $content = $this->renderChildren(); } if ('append' === $this->contentConcat) { $content .= $this->getContent(); } else { $content = $this->getContent() . $content; } return $this->renderTag($content); }
php
public function render() { if ($this->isVoid) { return $this->renderTag(); } $content = ''; if ($this->hasChildren()) { $content = $this->renderChildren(); } if ('append' === $this->contentConcat) { $content .= $this->getContent(); } else { $content = $this->getContent() . $content; } return $this->renderTag($content); }
Render content @return string
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L453-L472
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.renderTag
protected function renderTag($content = null) { $attributes = $this->renderAttributes(); if ($this->isVoid) { return sprintf( '<%1$s%2$s%3$s>', $this->tag, $attributes, $this->isXhtml ? ' /' : '' ); } return sprintf( '<%1$s%2$s>%3$s</%1$s>', $this->tag, $attributes, $content ); }
php
protected function renderTag($content = null) { $attributes = $this->renderAttributes(); if ($this->isVoid) { return sprintf( '<%1$s%2$s%3$s>', $this->tag, $attributes, $this->isXhtml ? ' /' : '' ); } return sprintf( '<%1$s%2$s>%3$s</%1$s>', $this->tag, $attributes, $content ); }
Render tag @param string $content @return string
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L489-L508
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.renderAttributes
protected function renderAttributes() { $attributes = ''; foreach ($this->attributes as $key => $value) { $attributes .= " $key" . (null !== $value ? "=\"$value\"" : ''); } return $attributes; }
php
protected function renderAttributes() { $attributes = ''; foreach ($this->attributes as $key => $value) { $attributes .= " $key" . (null !== $value ? "=\"$value\"" : ''); } return $attributes; }
Render tag attributes @return string
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L515-L524
SpoonX/SxCore
library/SxCore/Html/HtmlElement.php
HtmlElement.renderChildren
public function renderChildren($children = null) { if (null === $children) { $children = $this->getChildren(); } if (!is_array($children)) { throw new Exception\InvalidArgumentException( 'Invalid children type supplied. Expected array or null.' ); } $content = ''; /* @var $child HtmlElement */ foreach ($children as $child) { $content .= $child->render(); } return $content; }
php
public function renderChildren($children = null) { if (null === $children) { $children = $this->getChildren(); } if (!is_array($children)) { throw new Exception\InvalidArgumentException( 'Invalid children type supplied. Expected array or null.' ); } $content = ''; /* @var $child HtmlElement */ foreach ($children as $child) { $content .= $child->render(); } return $content; }
@param null|HtmlElement[] $children @throws Exception\InvalidArgumentException @return string
https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L540-L560
ekyna/AdminBundle
Menu/MenuGroup.php
MenuGroup.setLabel
public function setLabel($label, $domain = null) { $this->label = $label; $this->setDomain($domain); return $this; }
php
public function setLabel($label, $domain = null) { $this->label = $label; $this->setDomain($domain); return $this; }
Sets the label. @param string $label @param string $domain @return MenuGroup
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Menu/MenuGroup.php#L115-L121