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
ellipsephp/router-adapter
src/RouterMiddleware.php
RouterMiddleware.process
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $this->router->handle($request); } catch (NotFoundException $e) { return $handler->handle($request); } }
php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $this->router->handle($request); } catch (NotFoundException $e) { return $handler->handle($request); } }
Try to proxy the router request handler ->handle() method. Proxy the given request handler when the router request handler throws a not found exception. @param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Server\RequestHandlerInterface $handler @return \Psr\Http\Message\ResponseInterface
https://github.com/ellipsephp/router-adapter/blob/8f31baec3352d5592c339f67d747caad3748e4c3/src/RouterMiddleware.php#L40-L53
mlocati/concrete5-translation-library
src/Parser/DynamicItem/AttributeType.php
AttributeType.parseManual
public function parseManual(\Gettext\Translations $translations, $concrete5version) { if (class_exists('\AttributeType', true)) { foreach (\AttributeType::getList() as $at) { $this->addTranslation($translations, $at->getAttributeTypeName(), 'AttributeTypeName'); } } }
php
public function parseManual(\Gettext\Translations $translations, $concrete5version) { if (class_exists('\AttributeType', true)) { foreach (\AttributeType::getList() as $at) { $this->addTranslation($translations, $at->getAttributeTypeName(), 'AttributeTypeName'); } } }
{@inheritdoc} @see \C5TL\Parser\DynamicItem\DynamicItem::parseManual()
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/AttributeType.php#L35-L42
emaphp/omocha
lib/AnnotationBag.php
AnnotationBag.replace
public function replace(array $annotations) { $this->annotations = $annotations; $this->names = []; $index = 0; foreach ($annotations as $annotation) { $name = $annotation->getName(); if (!array_key_exists($name, $this->names)) { $this->names[$name] = []; } $this->names[$name][] = $index++; } }
php
public function replace(array $annotations) { $this->annotations = $annotations; $this->names = []; $index = 0; foreach ($annotations as $annotation) { $name = $annotation->getName(); if (!array_key_exists($name, $this->names)) { $this->names[$name] = []; } $this->names[$name][] = $index++; } }
Replaces a set of annotations values @param array $annotations
https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/AnnotationBag.php#L25-L37
emaphp/omocha
lib/AnnotationBag.php
AnnotationBag.get
public function get($key) { if ($this->has($key)) { return $this->annotations[$this->names[$key][0]]; } return null; }
php
public function get($key) { if ($this->has($key)) { return $this->annotations[$this->names[$key][0]]; } return null; }
Retrieves a single annotation @param string $key @return Annotation|NULL
https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/AnnotationBag.php#L61-L66
emaphp/omocha
lib/AnnotationBag.php
AnnotationBag.find
public function find($key, $filter = null) { if (!$this->has($key)) { return []; } $annotations = []; foreach ($this->names[$key] as $index) { if (!is_int($filter)) { $annotations[] = $this->annotations[$index]; continue; } $annotation = $this->annotations[$index]; $flags = 0; //match value type if ($filter & Filter::TYPE_ALL) { $value = $annotation->getValue(); if (is_null($value)) { $flags |= Filter::TYPE_NULL; } elseif (is_string($value)) { $flags |= Filter::TYPE_STRING; } elseif (is_int($value)) { $flags |= Filter::TYPE_INTEGER; } elseif (is_float($value)) { $flags |= Filter::TYPE_FLOAT; } elseif (is_bool($value)) { $flags |= Filter::TYPE_BOOLEAN; } elseif (is_array($value)) { $flags |= Filter::TYPE_ARRAY; } elseif (id_object($value)) { $flags |= Filter::TYPE_OBJECT; } } //match argument filter if ($filter & Filter::HAS_ARGUMENT || $filter & Filter::NOT_HAS_ARGUMENT) { if ($annotation->getArgument()) { $flags |= Filter::HAS_ARGUMENT; } else { $flags |= Filter::NOT_HAS_ARGUMENT; } } //add annotation if it meets all requirements if (($flags & $filter) == $flags) { $annotations[] = $annotation; } } return $annotations; }
php
public function find($key, $filter = null) { if (!$this->has($key)) { return []; } $annotations = []; foreach ($this->names[$key] as $index) { if (!is_int($filter)) { $annotations[] = $this->annotations[$index]; continue; } $annotation = $this->annotations[$index]; $flags = 0; //match value type if ($filter & Filter::TYPE_ALL) { $value = $annotation->getValue(); if (is_null($value)) { $flags |= Filter::TYPE_NULL; } elseif (is_string($value)) { $flags |= Filter::TYPE_STRING; } elseif (is_int($value)) { $flags |= Filter::TYPE_INTEGER; } elseif (is_float($value)) { $flags |= Filter::TYPE_FLOAT; } elseif (is_bool($value)) { $flags |= Filter::TYPE_BOOLEAN; } elseif (is_array($value)) { $flags |= Filter::TYPE_ARRAY; } elseif (id_object($value)) { $flags |= Filter::TYPE_OBJECT; } } //match argument filter if ($filter & Filter::HAS_ARGUMENT || $filter & Filter::NOT_HAS_ARGUMENT) { if ($annotation->getArgument()) { $flags |= Filter::HAS_ARGUMENT; } else { $flags |= Filter::NOT_HAS_ARGUMENT; } } //add annotation if it meets all requirements if (($flags & $filter) == $flags) { $annotations[] = $annotation; } } return $annotations; }
Retrieves a list of annotations by name @param string $key @param int $filter @return array
https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/AnnotationBag.php#L74-L133
emaphp/omocha
lib/AnnotationBag.php
AnnotationBag.filter
public function filter(\Closure $callback, $reindex = true) { $result = array_filter($this->annotations, $callback); if ($reindex) { $result = array_values($result); } return $result; }
php
public function filter(\Closure $callback, $reindex = true) { $result = array_filter($this->annotations, $callback); if ($reindex) { $result = array_values($result); } return $result; }
Filters elements with the given callback @param \Closure $callback @param boolean $reindex Reset indexes @return array
https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/AnnotationBag.php#L141-L149
Synapse-Cmf/synapse-cmf
src/Synapse/Page/Bundle/Form/Page/CreationType.php
CreationType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer($this) ->add('name', TextType::class) ->add('title', TextType::class) ->add('path', TextType::class, array( 'required' => false, )) ->add('parent', ChoiceType::class, array( 'required' => true, 'choices' => $this->pageLoader->retrieveAll(), 'choice_label' => function (Page $page) { return sprintf('%s (/%s)', $page->getName(), $page->getPath()); }, )) ->add('submit', SubmitType::class) ; }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer($this) ->add('name', TextType::class) ->add('title', TextType::class) ->add('path', TextType::class, array( 'required' => false, )) ->add('parent', ChoiceType::class, array( 'required' => true, 'choices' => $this->pageLoader->retrieveAll(), 'choice_label' => function (Page $page) { return sprintf('%s (/%s)', $page->getName(), $page->getPath()); }, )) ->add('submit', SubmitType::class) ; }
Page form prototype definition. @see FormInterface::buildForm()
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Page/Bundle/Form/Page/CreationType.php#L68-L86
xiewulong/yii2-wechat
Module.php
Module.checkSignature
public function checkSignature($signature, $timestamp, $nonce) { return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce]), $signature); }
php
public function checkSignature($signature, $timestamp, $nonce) { return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce]), $signature); }
验证签名 @method checkSignature @since 0.0.1 @param {string} $signature 加密签名 @param {string} $timestamp 时间戳 @param {string} $nonce 随机数 @return {boolean} @example $this->checkSignature($signature, $timestamp, $nonce);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L61-L63
xiewulong/yii2-wechat
Module.php
Module.checkMsgSignature
private function checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt) { return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), $msg_signature); }
php
private function checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt) { return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), $msg_signature); }
验证消息体签名 @method checkMsgSignature @since 0.0.1 @param {string} $msg_signature 消息体加密签名 @param {string} $timestamp 时间戳 @param {string} $nonce 随机数 @param {string} $encrypt 密文消息体 @return {boolean}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L75-L77
xiewulong/yii2-wechat
Module.php
Module.decode
private function decode($text) { $pad = ord(substr($text, -1)); if ($pad < 1 || $pad > 32) { $pad = 0; } return substr($text, 0, (strlen($text) - $pad)); }
php
private function decode($text) { $pad = ord(substr($text, -1)); if ($pad < 1 || $pad > 32) { $pad = 0; } return substr($text, 0, (strlen($text) - $pad)); }
对解密后的明文进行补位删除 @method decode @since 0.0.1 @param {string} $text 解密后的明文 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L86-L93
xiewulong/yii2-wechat
Module.php
Module.decrypt
private function decrypt($encrypted) { $this->key = base64_decode($this->manager->app->aeskey . '='); //使用BASE64对需要解密的字符串进行解码 $ciphertext_dec = base64_decode($encrypted); $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); $iv = substr($this->key, 0, 16); mcrypt_generic_init($module, $this->key, $iv); //解密 $decrypted = mdecrypt_generic($module, $ciphertext_dec); mcrypt_generic_deinit($module); mcrypt_module_close($module); //去除补位字符 $result = $this->decode($decrypted); //去除16位随机字符串,网络字节序和AppId if(strlen($result) < 16) { return false; } $content = substr($result, 16, strlen($result)); $len_list = unpack('N', substr($content, 0, 4)); $xml_len = $len_list[1]; $xml_content = substr($content, 4, $xml_len); $from_appid = substr($content, $xml_len + 4); return $from_appid == $this->manager->app->appid ? $xml_content : false; }
php
private function decrypt($encrypted) { $this->key = base64_decode($this->manager->app->aeskey . '='); //使用BASE64对需要解密的字符串进行解码 $ciphertext_dec = base64_decode($encrypted); $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); $iv = substr($this->key, 0, 16); mcrypt_generic_init($module, $this->key, $iv); //解密 $decrypted = mdecrypt_generic($module, $ciphertext_dec); mcrypt_generic_deinit($module); mcrypt_module_close($module); //去除补位字符 $result = $this->decode($decrypted); //去除16位随机字符串,网络字节序和AppId if(strlen($result) < 16) { return false; } $content = substr($result, 16, strlen($result)); $len_list = unpack('N', substr($content, 0, 4)); $xml_len = $len_list[1]; $xml_content = substr($content, 4, $xml_len); $from_appid = substr($content, $xml_len + 4); return $from_appid == $this->manager->app->appid ? $xml_content : false; }
对密文进行解密 @method decrypt @since 0.0.1 @param {string} $encrypted 需要解密的密文 @return {string|boolean}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L102-L131
xiewulong/yii2-wechat
Module.php
Module.decryptMessage
public function decryptMessage($msg_signature, $timestamp, $nonce, $encrypt) { if(!$this->checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt)) { return false; } $result = $this->decrypt($encrypt); return $result ? (array) simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA) : false; }
php
public function decryptMessage($msg_signature, $timestamp, $nonce, $encrypt) { if(!$this->checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt)) { return false; } $result = $this->decrypt($encrypt); return $result ? (array) simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA) : false; }
验证消息体签名, 并获取解密后的消息 @method decryptMessage @since 0.0.1 @param {string} $msg_signature 消息体加密签名 @param {string} $timestamp 时间戳 @param {string} $nonce 随机数 @param {string} $encrypt 密文消息体 @return {string|boolean} @example $this->decryptMessage($msg_signature, $timestamp, $nonce, $encrypt);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L144-L152
xiewulong/yii2-wechat
Module.php
Module.handleMessage
public function handleMessage($postObj) { if((isset($postObj['MsgId']) && WechatMessage::findOne(['msg_id' => $postObj['MsgId']])) || WechatMessage::findOne(['appid' => $this->manager->app->appid, 'to_user_name' => $postObj['ToUserName'], 'from_user_name' => $postObj['FromUserName'], 'create_time' => $postObj['CreateTime']])) { return null; } $message = new WechatMessage; $message->appid = $this->manager->app->appid; $message->to_user_name = $postObj['ToUserName']; $message->from_user_name = $postObj['FromUserName']; $message->create_time = $postObj['CreateTime']; $message->msg_type = $postObj['MsgType']; if(isset($postObj['MsgId'])) { $message->msg_id = $postObj['MsgId']; } switch($message->msg_type) { case 'text': $message->content = $postObj['Content']; break; case 'image': $message->media_id = $postObj['MediaId']; $message->pic_url = $postObj['PicUrl']; break; case 'voice': $message->media_id = $postObj['MediaId']; $message->format = $postObj['Format']; if(isset($postObj['Recognition'])) { $message->recognition = $postObj['Recognition']; } break; case 'video': case 'shortvideo': $message->media_id = $postObj['MediaId']; $message->thumb_media_id = $postObj['ThumbMediaId']; break; case 'location': $message->location_x = $postObj['Location_X']; $message->location_y = $postObj['Location_Y']; $message->scale = $postObj['Scale']; $message->label = $postObj['Label']; break; case 'link': $message->title = $postObj['Title']; $message->description = $postObj['Description']; $message->url = $postObj['Url']; break; case 'event': $message->event = $postObj['Event']; switch($message->event) { case 'unsubscribe': break; case 'subscribe': if(isset($postObj['EventKey']) && isset($postObj['Ticket'])) { $message->event_key = $postObj['EventKey']; $message->ticket = $postObj['Ticket']; } break; case 'SCAN': $message->event_key = $postObj['EventKey']; $message->ticket = $postObj['Ticket']; break; case 'LOCATION': $message->latitude = $postObj['Latitude']; $message->longitude = $postObj['Longitude']; $message->precision = $postObj['Precision']; break; case 'CLICK': $message->event_key = $postObj['EventKey']; break; case 'VIEW': $message->event_key = $postObj['EventKey']; if(isset($postObj['MenuID'])) { $message->menu_id = $postObj['MenuID']; } break; case 'scancode_push': case 'scancode_waitmsg': $message->event_key = $postObj['EventKey']; if(isset($postObj['ScanCodeInfo'])) { $message->scan_type = $postObj['ScanCodeInfo']['ScanType']; $message->scan_result = $postObj['ScanCodeInfo']['ScanResult']; } break; case 'pic_sysphoto': case 'pic_photo_or_album': case 'pic_weixin': $message->event_key = $postObj['EventKey']; if(isset($postObj['SendPicsInfo'])) { $message->count = $postObj['SendPicsInfo']['Count']; $message->pic_list = $postObj['SendPicsInfo']['PicList']; } break; case 'location_select': $message->event_key = $postObj['EventKey']; if(isset($postObj['SendLocationInfo'])) { $message->location_x = $postObj['SendLocationInfo']['Location_X']; $message->location_y = $postObj['SendLocationInfo']['Location_Y']; $message->scale = $postObj['SendLocationInfo']['Scale']; $message->label = $postObj['SendLocationInfo']['Label']; $message->poiname = $postObj['SendLocationInfo']['Poiname']; } break; } break; } return $message->save() ? $message->autoReply($this->messageClass) : null; }
php
public function handleMessage($postObj) { if((isset($postObj['MsgId']) && WechatMessage::findOne(['msg_id' => $postObj['MsgId']])) || WechatMessage::findOne(['appid' => $this->manager->app->appid, 'to_user_name' => $postObj['ToUserName'], 'from_user_name' => $postObj['FromUserName'], 'create_time' => $postObj['CreateTime']])) { return null; } $message = new WechatMessage; $message->appid = $this->manager->app->appid; $message->to_user_name = $postObj['ToUserName']; $message->from_user_name = $postObj['FromUserName']; $message->create_time = $postObj['CreateTime']; $message->msg_type = $postObj['MsgType']; if(isset($postObj['MsgId'])) { $message->msg_id = $postObj['MsgId']; } switch($message->msg_type) { case 'text': $message->content = $postObj['Content']; break; case 'image': $message->media_id = $postObj['MediaId']; $message->pic_url = $postObj['PicUrl']; break; case 'voice': $message->media_id = $postObj['MediaId']; $message->format = $postObj['Format']; if(isset($postObj['Recognition'])) { $message->recognition = $postObj['Recognition']; } break; case 'video': case 'shortvideo': $message->media_id = $postObj['MediaId']; $message->thumb_media_id = $postObj['ThumbMediaId']; break; case 'location': $message->location_x = $postObj['Location_X']; $message->location_y = $postObj['Location_Y']; $message->scale = $postObj['Scale']; $message->label = $postObj['Label']; break; case 'link': $message->title = $postObj['Title']; $message->description = $postObj['Description']; $message->url = $postObj['Url']; break; case 'event': $message->event = $postObj['Event']; switch($message->event) { case 'unsubscribe': break; case 'subscribe': if(isset($postObj['EventKey']) && isset($postObj['Ticket'])) { $message->event_key = $postObj['EventKey']; $message->ticket = $postObj['Ticket']; } break; case 'SCAN': $message->event_key = $postObj['EventKey']; $message->ticket = $postObj['Ticket']; break; case 'LOCATION': $message->latitude = $postObj['Latitude']; $message->longitude = $postObj['Longitude']; $message->precision = $postObj['Precision']; break; case 'CLICK': $message->event_key = $postObj['EventKey']; break; case 'VIEW': $message->event_key = $postObj['EventKey']; if(isset($postObj['MenuID'])) { $message->menu_id = $postObj['MenuID']; } break; case 'scancode_push': case 'scancode_waitmsg': $message->event_key = $postObj['EventKey']; if(isset($postObj['ScanCodeInfo'])) { $message->scan_type = $postObj['ScanCodeInfo']['ScanType']; $message->scan_result = $postObj['ScanCodeInfo']['ScanResult']; } break; case 'pic_sysphoto': case 'pic_photo_or_album': case 'pic_weixin': $message->event_key = $postObj['EventKey']; if(isset($postObj['SendPicsInfo'])) { $message->count = $postObj['SendPicsInfo']['Count']; $message->pic_list = $postObj['SendPicsInfo']['PicList']; } break; case 'location_select': $message->event_key = $postObj['EventKey']; if(isset($postObj['SendLocationInfo'])) { $message->location_x = $postObj['SendLocationInfo']['Location_X']; $message->location_y = $postObj['SendLocationInfo']['Location_Y']; $message->scale = $postObj['SendLocationInfo']['Scale']; $message->label = $postObj['SendLocationInfo']['Label']; $message->poiname = $postObj['SendLocationInfo']['Poiname']; } break; } break; } return $message->save() ? $message->autoReply($this->messageClass) : null; }
处理消息 @method handleMessage @since 0.0.1 @param {string} $postObj 消息 @return {array} @example $this->handleMessage($postObj);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L162-L270
xiewulong/yii2-wechat
Module.php
Module.encrypt
private function encrypt($text) { if(!$this->key) { $this->key = base64_decode($this->manager->app->aeskey . '='); } //获得16位随机字符串,填充到明文之前 $random = $this->manager->generateRandomString(16); $text = $random . pack("N", strlen($text)) . $text . $this->manager->app->appid; //网络字节序 $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); $iv = substr($this->key, 0, 16); //使用自定义的填充方式对明文进行补位填充 $text = $this->encode($text); mcrypt_generic_init($module, $this->key, $iv); //加密 $encrypted = mcrypt_generic($module, $text); mcrypt_generic_deinit($module); mcrypt_module_close($module); //使用BASE64对加密后的字符串进行编码 return base64_encode($encrypted); }
php
private function encrypt($text) { if(!$this->key) { $this->key = base64_decode($this->manager->app->aeskey . '='); } //获得16位随机字符串,填充到明文之前 $random = $this->manager->generateRandomString(16); $text = $random . pack("N", strlen($text)) . $text . $this->manager->app->appid; //网络字节序 $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); $iv = substr($this->key, 0, 16); //使用自定义的填充方式对明文进行补位填充 $text = $this->encode($text); mcrypt_generic_init($module, $this->key, $iv); //加密 $encrypted = mcrypt_generic($module, $text); mcrypt_generic_deinit($module); mcrypt_module_close($module); //使用BASE64对加密后的字符串进行编码 return base64_encode($encrypted); }
对密文进行加密 @method encrypt @since 0.0.1 @param {string} $text 需要加密的明文 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L306-L331
xiewulong/yii2-wechat
Module.php
Module.encryptMessage
public function encryptMessage($message, $timestamp, $nonce) { $encrypt = $this->encrypt(XmlResponseFormatter::formatData($message)); return [ 'Encrypt' => $encrypt, 'MsgSignature' => $this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), 'TimeStamp' => $timestamp, 'Nonce' => $nonce, ]; }
php
public function encryptMessage($message, $timestamp, $nonce) { $encrypt = $this->encrypt(XmlResponseFormatter::formatData($message)); return [ 'Encrypt' => $encrypt, 'MsgSignature' => $this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), 'TimeStamp' => $timestamp, 'Nonce' => $nonce, ]; }
加密回复消息 @method encryptMessage @since 0.0.1 @param {string} $message 回复消息 @param {string} $timestamp 时间戳 @param {string} $nonce 随机数 @return {array} @example $this->encryptMessage($message, $timestamp, $nonce);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Module.php#L343-L352
gplcart/base
Main.php
Main.checkRequiredModules
protected function checkRequiredModules(array $data, &$result) { if ($data['installer'] === 'base' && empty($data['step']) && !$this->getModel()->hasAllRequiredModules()) { $result = array( 'redirect' => '', 'severity' => 'warning', 'message' => gplcart_text('You cannot use this installer because some modules are missed in your distribution') ); } }
php
protected function checkRequiredModules(array $data, &$result) { if ($data['installer'] === 'base' && empty($data['step']) && !$this->getModel()->hasAllRequiredModules()) { $result = array( 'redirect' => '', 'severity' => 'warning', 'message' => gplcart_text('You cannot use this installer because some modules are missed in your distribution') ); } }
Check if all required modules in place @param array $data @param array $result
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/Main.php#L104-L116
pmdevelopment/tool-bundle
Twig/HashExtension.php
HashExtension.hash
public function hash($string, $algo) { if (true === empty($string)) { $string = microtime() . uniqid(); } return hash($algo, $string); }
php
public function hash($string, $algo) { if (true === empty($string)) { $string = microtime() . uniqid(); } return hash($algo, $string); }
@param string $string @param string $algo @return string
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/HashExtension.php#L46-L53
factorio-item-browser/api-client
src/Exception/ExceptionFactory.php
ExceptionFactory.create
public static function create( int $statusCode, string $message, string $request, string $response ): ApiClientException { switch ($statusCode) { case 400: $exception = new BadRequestException($message, $request, $response); break; case 401: $exception = new UnauthorizedException($message, $request, $response); break; case 403: $exception = new ForbiddenException($message, $request, $response); break; case 404: $exception = new NotFoundException($message, $request, $response); break; default: $exception = new ApiClientException($message, $statusCode, $request, $response); break; } return $exception; }
php
public static function create( int $statusCode, string $message, string $request, string $response ): ApiClientException { switch ($statusCode) { case 400: $exception = new BadRequestException($message, $request, $response); break; case 401: $exception = new UnauthorizedException($message, $request, $response); break; case 403: $exception = new ForbiddenException($message, $request, $response); break; case 404: $exception = new NotFoundException($message, $request, $response); break; default: $exception = new ApiClientException($message, $statusCode, $request, $response); break; } return $exception; }
Creates the exception corresponding to the specified status code. @param int $statusCode @param string $message @param string $request @param string $response @return ApiClientException
https://github.com/factorio-item-browser/api-client/blob/ebda897483bd537c310a17ff868ca40c0568f728/src/Exception/ExceptionFactory.php#L23-L47
danhanly/signalert
src/Signalert/Storage/SessionDriver.php
SessionDriver.store
public function store($message, $bucket) { // Get current messages for bucket $messages = $this->fetch($bucket); // Check current message does not exist if (true === in_array($message, $messages)) { // If message already exists, do not add the duplicate return false; } // Add message to stack $messages[] = $message; // Return the message stack to the session $_SESSION[self::ROOT_NODE][$bucket] = $messages; // Report Success return true; }
php
public function store($message, $bucket) { // Get current messages for bucket $messages = $this->fetch($bucket); // Check current message does not exist if (true === in_array($message, $messages)) { // If message already exists, do not add the duplicate return false; } // Add message to stack $messages[] = $message; // Return the message stack to the session $_SESSION[self::ROOT_NODE][$bucket] = $messages; // Report Success return true; }
Store the notifications using the driver @param string $message @param string $bucket @return bool
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Storage/SessionDriver.php#L19-L34
danhanly/signalert
src/Signalert/Storage/SessionDriver.php
SessionDriver.fetch
public function fetch($bucket, $flush = true) { // Ensure that the root node exists if (true === empty($_SESSION[self::ROOT_NODE])) { $_SESSION[self::ROOT_NODE] = []; } // Ensure that the bucket exists if (true === empty($_SESSION[self::ROOT_NODE][$bucket])) { $_SESSION[self::ROOT_NODE][$bucket] = []; } // Get the messages for the bucket $messages = $_SESSION[self::ROOT_NODE][$bucket]; // Flush the messages if applicable if (true === $flush) { $this->flush($bucket); } // Return the messages as an array return $messages; }
php
public function fetch($bucket, $flush = true) { // Ensure that the root node exists if (true === empty($_SESSION[self::ROOT_NODE])) { $_SESSION[self::ROOT_NODE] = []; } // Ensure that the bucket exists if (true === empty($_SESSION[self::ROOT_NODE][$bucket])) { $_SESSION[self::ROOT_NODE][$bucket] = []; } // Get the messages for the bucket $messages = $_SESSION[self::ROOT_NODE][$bucket]; // Flush the messages if applicable if (true === $flush) { $this->flush($bucket); } // Return the messages as an array return $messages; }
Fetch the notifications from the driver @param string $bucket @param bool $flush @return array
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Storage/SessionDriver.php#L43-L61
danhanly/signalert
src/Signalert/Storage/SessionDriver.php
SessionDriver.flush
public function flush($bucket) { if (false === empty($_SESSION[self::ROOT_NODE][$bucket])) { $_SESSION[self::ROOT_NODE][$bucket] = []; return true; } return false; }
php
public function flush($bucket) { if (false === empty($_SESSION[self::ROOT_NODE][$bucket])) { $_SESSION[self::ROOT_NODE][$bucket] = []; return true; } return false; }
Flush all notifications from the driver @param string $bucket @return bool
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Storage/SessionDriver.php#L69-L77
limingxinleo/phalcon-utils
src/Utils/Debug.php
Debug.dump
public static function dump($var, $label = null) { $label = (null === $label) ? '' : rtrim($label) . ':'; ob_start(); var_dump($var); $output = ob_get_clean(); $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output); if (IS_CLI) { $output = PHP_EOL . $label . $output . PHP_EOL; } else { if (!extension_loaded('xdebug')) { $output = htmlspecialchars($output, ENT_QUOTES); } $output = '<pre>' . $label . $output . '</pre>'; } echo $output; }
php
public static function dump($var, $label = null) { $label = (null === $label) ? '' : rtrim($label) . ':'; ob_start(); var_dump($var); $output = ob_get_clean(); $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output); if (IS_CLI) { $output = PHP_EOL . $label . $output . PHP_EOL; } else { if (!extension_loaded('xdebug')) { $output = htmlspecialchars($output, ENT_QUOTES); } $output = '<pre>' . $label . $output . '</pre>'; } echo $output; }
浏览器友好的变量输出 @param mixed $var 变量 @param string $label 标签 默认为空 @return void|string
https://github.com/limingxinleo/phalcon-utils/blob/6581a8982a1244908de9e5197dc9284e3949ded7/src/Utils/Debug.php#L20-L39
RowlandOti/ooglee-blogmodule
src/OoGlee/Application/Entities/Post/Category/CategoryContent.php
CategoryContent.make
public function make(ICategory $category) { //$category->setContent($this->view->make($category->getLayoutViewPath(), compact('category'))->render()); $category->setContent($this->view->make(\OogleeBConfig::get('config.category_view.view'), compact('category'))->render()); }
php
public function make(ICategory $category) { //$category->setContent($this->view->make($category->getLayoutViewPath(), compact('category'))->render()); $category->setContent($this->view->make(\OogleeBConfig::get('config.category_view.view'), compact('category'))->render()); }
Make the view content. @param ICategory $category
https://github.com/RowlandOti/ooglee-blogmodule/blob/d9c0fe4745bb09f8b94047b0cda4fd7438cde16a/src/OoGlee/Application/Entities/Post/Category/CategoryContent.php#L42-L46
payapi/payapi-sdk-php
src/payapi/plugin/plugin.oscommerce.php
plugin.payment
public function payment($tmp_order, $customer_id, $partialPaymentMethod = null) { $transaction_id = tep_create_random_value(16); $finalAddr = [ 'recipientName' => $tmp_order->delivery['firstname'] . ' '. $tmp_order->delivery['lastname'], 'co' => $tmp_order->delivery['company'], 'streetAddress' => $tmp_order->delivery['street_address'], 'streetAddress2' => $tmp_order->delivery['suburb'], 'city' => $tmp_order->delivery['city'], 'stateOrProvince' => $tmp_order->delivery['state'], 'postalCode' => $tmp_order->delivery['postcode'], 'countryCode' => $tmp_order->delivery['country']['iso_code_2'] ]; $items = $tmp_order->products; $products = []; if ($items) { $hasExtradata = false; $totalTaxes = 0; foreach ($items as $item) { // $imageUrl = tep_output_string(HTTPS_SERVER . DIR_WS_IMAGES . $item['products_image']); $excVat = floatval($item['final_price']); $percent = floatval($item['tax']); $taxes = $excVat * $percent / 100.0; $incVat = $excVat + $taxes; $qty = intval($item['qty']); $totalTaxes += $qty * $taxes; // Set attributes $attributes = ''; if (isset($item['attributes'])) { foreach ($item['attributes'] as $attribute) { $attributes .= ' ' . $attribute['option'] . ': ' . $attribute['value']; } } error_log('attributes: '.$attributes, 0); $products[] = [ "id" => (string)$item['id'], "quantity" => $qty, "title" => $item['name'] . $attributes, "model" => $item['model'], "priceInCentsIncVat" => round($incVat * 100), "priceInCentsExcVat" => round($excVat * 100), "vatInCents" => round($taxes * 100), "vatPercentage" => $percent, // "imageUrl" => "", ]; $hasExtradata = true; } // Merge extra data with the order object (serialized) $products[0] = array_merge( $products[0], array('extraData' => serialize($tmp_order)) ); // error_log(' products at index 0: '.json_encode($products[0]), 0); } $shipExcVat = $tmp_order->info['shipping_cost']; $shipTaxes = floatval($tmp_order->info['tax']) - $totalTaxes; $shipIncVat = $shipExcVat + $shipTaxes; $shipPercent = 0; if ($shipExcVat > 0) { $shipPercent = $shipTaxes * 100.0 / $shipExcVat; } $products[] = [ "id" => $tmp_order->info['shipping_method'], "quantity" => 1, "title" => 'Handling and Delivery', "priceInCentsIncVat" => round($shipIncVat * 100), "priceInCentsExcVat" => round($shipExcVat * 100), "vatInCents" => round($shipTaxes * 100), "vatPercentage" => $shipPercent, "extraData" => "", // "imageUrl" => "", ]; $baseExclTax = $tmp_order->info['subtotal']; $taxAmount = $tmp_order->info['tax'] - $shipTaxes; $totalOrdered = $tmp_order->info['total']; $order = ["sumInCentsIncVat" => round($totalOrdered * 100), "sumInCentsExcVat" => round(($baseExclTax + $shipExcVat) * 100), "vatInCents" => round(($taxAmount + $shipTaxes) * 100), "currency" => $tmp_order->info['currency'], "referenceId" => $transaction_id, "tosUrl" => "https://payapi.io/terms" ]; $consumer = [ "email" => $tmp_order->customer['email_address'], "consumerId" => (string)$customer_id ]; //Return URLs $returnUrls = [ "success" => $this->getStoreUrl() . "ext/modules/payment/payapi/checkout_success.php", "cancel" => $this->getStoreUrl() , "failed" => $this->getStoreUrl() ]; $callbackUrl = $this->getStoreUrl() . "ext/modules/payment/payapi/payapi_callbacks.php"; // $callbackUrl = $this->getStoreUrl() . "checkout_process.php"; $jsonCallbacks = [ "processing" => $callbackUrl, "success" => $callbackUrl, "failed" => $callbackUrl, "chargeback" => $callbackUrl, ]; $res = ["order" => $order, "products" => $products, "consumer" => $consumer, "shippingAddress" => $finalAddr, "returnUrls" => $returnUrls, "callbacks" => $jsonCallbacks ]; // error_log(' res in payment: '.json_encode($res), 0); return $res; }
php
public function payment($tmp_order, $customer_id, $partialPaymentMethod = null) { $transaction_id = tep_create_random_value(16); $finalAddr = [ 'recipientName' => $tmp_order->delivery['firstname'] . ' '. $tmp_order->delivery['lastname'], 'co' => $tmp_order->delivery['company'], 'streetAddress' => $tmp_order->delivery['street_address'], 'streetAddress2' => $tmp_order->delivery['suburb'], 'city' => $tmp_order->delivery['city'], 'stateOrProvince' => $tmp_order->delivery['state'], 'postalCode' => $tmp_order->delivery['postcode'], 'countryCode' => $tmp_order->delivery['country']['iso_code_2'] ]; $items = $tmp_order->products; $products = []; if ($items) { $hasExtradata = false; $totalTaxes = 0; foreach ($items as $item) { // $imageUrl = tep_output_string(HTTPS_SERVER . DIR_WS_IMAGES . $item['products_image']); $excVat = floatval($item['final_price']); $percent = floatval($item['tax']); $taxes = $excVat * $percent / 100.0; $incVat = $excVat + $taxes; $qty = intval($item['qty']); $totalTaxes += $qty * $taxes; // Set attributes $attributes = ''; if (isset($item['attributes'])) { foreach ($item['attributes'] as $attribute) { $attributes .= ' ' . $attribute['option'] . ': ' . $attribute['value']; } } error_log('attributes: '.$attributes, 0); $products[] = [ "id" => (string)$item['id'], "quantity" => $qty, "title" => $item['name'] . $attributes, "model" => $item['model'], "priceInCentsIncVat" => round($incVat * 100), "priceInCentsExcVat" => round($excVat * 100), "vatInCents" => round($taxes * 100), "vatPercentage" => $percent, // "imageUrl" => "", ]; $hasExtradata = true; } // Merge extra data with the order object (serialized) $products[0] = array_merge( $products[0], array('extraData' => serialize($tmp_order)) ); // error_log(' products at index 0: '.json_encode($products[0]), 0); } $shipExcVat = $tmp_order->info['shipping_cost']; $shipTaxes = floatval($tmp_order->info['tax']) - $totalTaxes; $shipIncVat = $shipExcVat + $shipTaxes; $shipPercent = 0; if ($shipExcVat > 0) { $shipPercent = $shipTaxes * 100.0 / $shipExcVat; } $products[] = [ "id" => $tmp_order->info['shipping_method'], "quantity" => 1, "title" => 'Handling and Delivery', "priceInCentsIncVat" => round($shipIncVat * 100), "priceInCentsExcVat" => round($shipExcVat * 100), "vatInCents" => round($shipTaxes * 100), "vatPercentage" => $shipPercent, "extraData" => "", // "imageUrl" => "", ]; $baseExclTax = $tmp_order->info['subtotal']; $taxAmount = $tmp_order->info['tax'] - $shipTaxes; $totalOrdered = $tmp_order->info['total']; $order = ["sumInCentsIncVat" => round($totalOrdered * 100), "sumInCentsExcVat" => round(($baseExclTax + $shipExcVat) * 100), "vatInCents" => round(($taxAmount + $shipTaxes) * 100), "currency" => $tmp_order->info['currency'], "referenceId" => $transaction_id, "tosUrl" => "https://payapi.io/terms" ]; $consumer = [ "email" => $tmp_order->customer['email_address'], "consumerId" => (string)$customer_id ]; //Return URLs $returnUrls = [ "success" => $this->getStoreUrl() . "ext/modules/payment/payapi/checkout_success.php", "cancel" => $this->getStoreUrl() , "failed" => $this->getStoreUrl() ]; $callbackUrl = $this->getStoreUrl() . "ext/modules/payment/payapi/payapi_callbacks.php"; // $callbackUrl = $this->getStoreUrl() . "checkout_process.php"; $jsonCallbacks = [ "processing" => $callbackUrl, "success" => $callbackUrl, "failed" => $callbackUrl, "chargeback" => $callbackUrl, ]; $res = ["order" => $order, "products" => $products, "consumer" => $consumer, "shippingAddress" => $finalAddr, "returnUrls" => $returnUrls, "callbacks" => $jsonCallbacks ]; // error_log(' res in payment: '.json_encode($res), 0); return $res; }
adapt specific store cart to secure form @param order (more like cart in OSCommerce) object @return secure form object
https://github.com/payapi/payapi-sdk-php/blob/6a675749c88742b261178d7977f2436d540132b4/src/payapi/plugin/plugin.oscommerce.php#L40-L166
brick/validation
src/AbstractValidator.php
AbstractValidator.isValid
final public function isValid(string $value) : bool { $this->failureMessages = []; $this->validate($value); return ! $this->failureMessages; }
php
final public function isValid(string $value) : bool { $this->failureMessages = []; $this->validate($value); return ! $this->failureMessages; }
{@inheritdoc}
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/AbstractValidator.php#L22-L28
brick/validation
src/AbstractValidator.php
AbstractValidator.addFailureMessage
final protected function addFailureMessage(string $messageKey) : void { $messages = $this->getPossibleMessages(); if (! isset($messages[$messageKey])) { throw new \RuntimeException('Unknown message key: ' . $messageKey); } $this->failureMessages[$messageKey] = $messages[$messageKey]; }
php
final protected function addFailureMessage(string $messageKey) : void { $messages = $this->getPossibleMessages(); if (! isset($messages[$messageKey])) { throw new \RuntimeException('Unknown message key: ' . $messageKey); } $this->failureMessages[$messageKey] = $messages[$messageKey]; }
Adds a failure message. @param string $messageKey The message key. @return void @throws \RuntimeException If the message key is unknown.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/AbstractValidator.php#L47-L56
alekitto/metadata
lib/Factory/AbstractMetadataFactory.php
AbstractMetadataFactory.getMetadataFor
public function getMetadataFor($value): ClassMetadataInterface { $class = $this->getClass($value); if (empty($class)) { throw InvalidArgumentException::create(InvalidArgumentException::VALUE_IS_NOT_AN_OBJECT, $value); } if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if (null !== $this->loadedClasses[$class] = $this->getFromCache($class)) { return $this->loadedClasses[$class]; } if (! class_exists($class) && ! interface_exists($class)) { throw InvalidArgumentException::create(InvalidArgumentException::CLASS_DOES_NOT_EXIST, $class); } $reflectionClass = new \ReflectionClass($class); $classMetadata = $this->createMetadata($reflectionClass); if (! $this->loader->loadClassMetadata($classMetadata)) { return $classMetadata; } $this->mergeSuperclasses($classMetadata); $this->validate($classMetadata); $this->dispatchClassMetadataLoadedEvent($classMetadata); $this->saveInCache($class, $classMetadata); return $this->loadedClasses[$class] = $classMetadata; }
php
public function getMetadataFor($value): ClassMetadataInterface { $class = $this->getClass($value); if (empty($class)) { throw InvalidArgumentException::create(InvalidArgumentException::VALUE_IS_NOT_AN_OBJECT, $value); } if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if (null !== $this->loadedClasses[$class] = $this->getFromCache($class)) { return $this->loadedClasses[$class]; } if (! class_exists($class) && ! interface_exists($class)) { throw InvalidArgumentException::create(InvalidArgumentException::CLASS_DOES_NOT_EXIST, $class); } $reflectionClass = new \ReflectionClass($class); $classMetadata = $this->createMetadata($reflectionClass); if (! $this->loader->loadClassMetadata($classMetadata)) { return $classMetadata; } $this->mergeSuperclasses($classMetadata); $this->validate($classMetadata); $this->dispatchClassMetadataLoadedEvent($classMetadata); $this->saveInCache($class, $classMetadata); return $this->loadedClasses[$class] = $classMetadata; }
{@inheritdoc}
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Factory/AbstractMetadataFactory.php#L54-L86
alekitto/metadata
lib/Factory/AbstractMetadataFactory.php
AbstractMetadataFactory.dispatchClassMetadataLoadedEvent
protected function dispatchClassMetadataLoadedEvent(ClassMetadataInterface $classMetadata): void { if (null === $this->eventDispatcher) { return; } $this->eventDispatcher->dispatch( ClassMetadataLoadedEvent::LOADED_EVENT, new ClassMetadataLoadedEvent($classMetadata) ); }
php
protected function dispatchClassMetadataLoadedEvent(ClassMetadataInterface $classMetadata): void { if (null === $this->eventDispatcher) { return; } $this->eventDispatcher->dispatch( ClassMetadataLoadedEvent::LOADED_EVENT, new ClassMetadataLoadedEvent($classMetadata) ); }
Dispatches a class metadata loaded event for the given class. @param ClassMetadataInterface $classMetadata
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Factory/AbstractMetadataFactory.php#L137-L147
alekitto/metadata
lib/Factory/AbstractMetadataFactory.php
AbstractMetadataFactory.getFromCache
private function getFromCache(string $class): ?ClassMetadataInterface { if (null === $this->cache) { return null; } if ($this->cache instanceof Cache) { $cached = $this->cache->fetch($class) ?: null; } else { $class = preg_replace('#[\{\}\(\)/\\\\@:]#', '_', str_replace('_', '__', $class)); $item = $this->cache->getItem($class); $cached = $item->isHit() ? $item->get() : null; } return $cached; }
php
private function getFromCache(string $class): ?ClassMetadataInterface { if (null === $this->cache) { return null; } if ($this->cache instanceof Cache) { $cached = $this->cache->fetch($class) ?: null; } else { $class = preg_replace('#[\{\}\(\)/\\\\@:]#', '_', str_replace('_', '__', $class)); $item = $this->cache->getItem($class); $cached = $item->isHit() ? $item->get() : null; } return $cached; }
Check a cache pool for cached metadata. @param string $class @return null|ClassMetadataInterface
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Factory/AbstractMetadataFactory.php#L156-L171
alekitto/metadata
lib/Factory/AbstractMetadataFactory.php
AbstractMetadataFactory.saveInCache
private function saveInCache(string $class, ClassMetadataInterface $classMetadata): void { if (null === $this->cache) { return; } if ($this->cache instanceof Cache) { $this->cache->save($class, $classMetadata); } else { $class = preg_replace('#[\{\}\(\)/\\\\@:]#', '_', str_replace('_', '__', $class)); $item = $this->cache->getItem($class); $item->set($classMetadata); $this->cache->save($item); } }
php
private function saveInCache(string $class, ClassMetadataInterface $classMetadata): void { if (null === $this->cache) { return; } if ($this->cache instanceof Cache) { $this->cache->save($class, $classMetadata); } else { $class = preg_replace('#[\{\}\(\)/\\\\@:]#', '_', str_replace('_', '__', $class)); $item = $this->cache->getItem($class); $item->set($classMetadata); $this->cache->save($item); } }
Saves a metadata into a cache pool. @param string $class @param ClassMetadataInterface $classMetadata
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Factory/AbstractMetadataFactory.php#L179-L194
alekitto/metadata
lib/Factory/AbstractMetadataFactory.php
AbstractMetadataFactory.getClass
private function getClass($value) { if (! is_object($value) && ! is_string($value)) { return false; } if (is_object($value)) { $value = get_class($value); } return ltrim($value, '\\'); }
php
private function getClass($value) { if (! is_object($value) && ! is_string($value)) { return false; } if (is_object($value)) { $value = get_class($value); } return ltrim($value, '\\'); }
Get the class name from a string or an object. @param string|object $value @return string|bool
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Factory/AbstractMetadataFactory.php#L203-L214
PHPColibri/framework
Migration/Migration/Collection.php
Collection.fillItems
protected function fillItems() { $migrations = []; foreach (Directory::iterator($this->folder) as $file) { $class = $this->namespace . '\\' . Str::cut($file->getFilename(), '.php'); $model = Model::fromClass($class); if ($this->mustBeFiltered($model)) { continue; } $migrations[] = $model; } $migrations = $this->sort($migrations); $this->items = $this->onlyOne ? count($migrations) ? [$migrations[0]] : [] : ($this->last === null ? $migrations : Arr::last($migrations, $this->last) ); }
php
protected function fillItems() { $migrations = []; foreach (Directory::iterator($this->folder) as $file) { $class = $this->namespace . '\\' . Str::cut($file->getFilename(), '.php'); $model = Model::fromClass($class); if ($this->mustBeFiltered($model)) { continue; } $migrations[] = $model; } $migrations = $this->sort($migrations); $this->items = $this->onlyOne ? count($migrations) ? [$migrations[0]] : [] : ($this->last === null ? $migrations : Arr::last($migrations, $this->last) ); }
@return void @throws \Colibri\Database\DbException @throws \Colibri\Database\Exception\SqlException @throws \UnexpectedValueException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Migration/Migration/Collection.php#L39-L59
PHPColibri/framework
Migration/Migration/Collection.php
Collection.sort
private function sort(array $migrations): array { $sorted = usort($migrations, function (Model $m1, Model $m2) { return $m1->createdAt->timestamp - $m2->createdAt->timestamp; }); if ( ! $sorted) { throw new \LogicException('Can`t sort migrations'); } return $migrations; }
php
private function sort(array $migrations): array { $sorted = usort($migrations, function (Model $m1, Model $m2) { return $m1->createdAt->timestamp - $m2->createdAt->timestamp; }); if ( ! $sorted) { throw new \LogicException('Can`t sort migrations'); } return $migrations; }
@param array $migrations @return array
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Migration/Migration/Collection.php#L122-L132
PHPColibri/framework
Migration/Migration/Collection.php
Collection.mustBeFiltered
private function mustBeFiltered(Model $model): bool { return ($this->withHash !== null && $model->hash !== $this->withHash) || ($this->thatNotMigrated && $model->migrated()) || ($this->onlyMigrated && ! $model->migrated()) ; }
php
private function mustBeFiltered(Model $model): bool { return ($this->withHash !== null && $model->hash !== $this->withHash) || ($this->thatNotMigrated && $model->migrated()) || ($this->onlyMigrated && ! $model->migrated()) ; }
@param Model $model @return bool
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Migration/Migration/Collection.php#L139-L146
easy-system/es-loader
src/ClassLoader.php
ClassLoader.register
public function register() { if (! $this->isRegistered) { spl_autoload_register([$this, 'load'], true, true); $this->isRegistered = true; } return $this; }
php
public function register() { if (! $this->isRegistered) { spl_autoload_register([$this, 'load'], true, true); $this->isRegistered = true; } return $this; }
Register the autoloader with spl_autoload. @return self
https://github.com/easy-system/es-loader/blob/4525867ab14e516b7837bbe1e5632ef3cbb3ffff/src/ClassLoader.php#L59-L67
easy-system/es-loader
src/ClassLoader.php
ClassLoader.registerPath
public function registerPath($namespace, $path, $prepend = false) { $namespace = Normalizer::ns($namespace, true); $index = substr($namespace, 0, 4); $this->indexes[$index] = true; $path = Normalizer::path($path, true); if (! isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } if ($prepend) { array_unshift($this->paths[$namespace], $path); return $this; } array_push($this->paths[$namespace], $path); return $this; }
php
public function registerPath($namespace, $path, $prepend = false) { $namespace = Normalizer::ns($namespace, true); $index = substr($namespace, 0, 4); $this->indexes[$index] = true; $path = Normalizer::path($path, true); if (! isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } if ($prepend) { array_unshift($this->paths[$namespace], $path); return $this; } array_push($this->paths[$namespace], $path); return $this; }
Registers a PSR-4 directory for a given namespace. @param string $namespace The namespace @param string $path The PSR-4 root directory @param bool $prepend Whether to prepend the directories @return self
https://github.com/easy-system/es-loader/blob/4525867ab14e516b7837bbe1e5632ef3cbb3ffff/src/ClassLoader.php#L117-L137
easy-system/es-loader
src/ClassLoader.php
ClassLoader.addClassMap
public function addClassMap(array $map) { if (empty($this->classMap)) { $this->classMap = $map; return $this; } $this->classMap = array_merge($this->classMap, $map); return $this; }
php
public function addClassMap(array $map) { if (empty($this->classMap)) { $this->classMap = $map; return $this; } $this->classMap = array_merge($this->classMap, $map); return $this; }
Adds the map of classes. @param array $map The map of classes @return self
https://github.com/easy-system/es-loader/blob/4525867ab14e516b7837bbe1e5632ef3cbb3ffff/src/ClassLoader.php#L157-L167
easy-system/es-loader
src/ClassLoader.php
ClassLoader.findFile
public function findFile($class) { $class = Normalizer::ns($class, false); if (isset($this->classMap[$class])) { return $this->classMap[$class]; } $index = substr($class, 0, 4); if (isset($this->indexes[$index])) { $namespace = $class; while (false !== $pos = strrpos($namespace, '\\')) { $namespace = substr($class, 0, $pos + 1); if (! isset($this->paths[$namespace])) { $namespace = rtrim($namespace, '\\'); continue; } $subclass = substr($class, $pos + 1); $subpath = Normalizer::path($subclass, false) . '.php'; foreach ($this->paths[$namespace] as $dir) { $path = $dir . $subpath; if (is_readable($path)) { if ($this->classRegistration) { $this->classMap[$class] = $path; } return $path; } } $namespace = rtrim($namespace, '\\'); } } if ($this->classRegistration) { $this->classMap[$class] = false; } return false; }
php
public function findFile($class) { $class = Normalizer::ns($class, false); if (isset($this->classMap[$class])) { return $this->classMap[$class]; } $index = substr($class, 0, 4); if (isset($this->indexes[$index])) { $namespace = $class; while (false !== $pos = strrpos($namespace, '\\')) { $namespace = substr($class, 0, $pos + 1); if (! isset($this->paths[$namespace])) { $namespace = rtrim($namespace, '\\'); continue; } $subclass = substr($class, $pos + 1); $subpath = Normalizer::path($subclass, false) . '.php'; foreach ($this->paths[$namespace] as $dir) { $path = $dir . $subpath; if (is_readable($path)) { if ($this->classRegistration) { $this->classMap[$class] = $path; } return $path; } } $namespace = rtrim($namespace, '\\'); } } if ($this->classRegistration) { $this->classMap[$class] = false; } return false; }
Finds the path to the file, that contains the specified class. @param string $class The fully-qualified class name @return string|false The path if found, false otherwise
https://github.com/easy-system/es-loader/blob/4525867ab14e516b7837bbe1e5632ef3cbb3ffff/src/ClassLoader.php#L204-L240
sqrt-pro/URL
src/SQRT/URL.php
URL.parse
public function parse($url, $cleanup = true) { if ($cleanup) { $this->removeArguments(); $this->removeParameters(); $this->setFileName(false); $this->setHost('localhost'); } if (is_array($url)) { $this->addParameters($url); } else { if ($this->checkSchemeExists($url)) { $a = $this->mbParseUrl($url); if (!empty($a['host'])) { $this->setHost($a['host']); } if (!empty($a['scheme'])) { $this->setScheme($a['scheme']); } $url = $a['path']; } $url = trim($url, '/'); $arr = array_filter(explode('/', urldecode($url))); if (empty($arr)) { return false; } $total = count($arr); foreach ($arr as $i => $str) { if (strpos($str, ':')) { $a = explode(':', $str, 2); if (count($a) == 2) { $this->addParameter($a[0], $a[1]); } } else { if ($total == $i + 1 && strpos($str, '.')) { $this->setFileName($str); } else { $this->addArgument($str); } } } } return $this; }
php
public function parse($url, $cleanup = true) { if ($cleanup) { $this->removeArguments(); $this->removeParameters(); $this->setFileName(false); $this->setHost('localhost'); } if (is_array($url)) { $this->addParameters($url); } else { if ($this->checkSchemeExists($url)) { $a = $this->mbParseUrl($url); if (!empty($a['host'])) { $this->setHost($a['host']); } if (!empty($a['scheme'])) { $this->setScheme($a['scheme']); } $url = $a['path']; } $url = trim($url, '/'); $arr = array_filter(explode('/', urldecode($url))); if (empty($arr)) { return false; } $total = count($arr); foreach ($arr as $i => $str) { if (strpos($str, ':')) { $a = explode(':', $str, 2); if (count($a) == 2) { $this->addParameter($a[0], $a[1]); } } else { if ($total == $i + 1 && strpos($str, '.')) { $this->setFileName($str); } else { $this->addArgument($str); } } } } return $this; }
Разбор адреса. Если передан относительный адрес, хост и схема по-умолчанию будут http://localhost $cleanup - нужно ли очищать предыдущие данные
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L45-L95
sqrt-pro/URL
src/SQRT/URL.php
URL.setHost
public function setHost($host) { if (!$this->checkSchemeExists($host)) { $host = 'http://' . $host; } $a = $this->mbParseUrl($host); $this->setScheme($a['scheme']); $puny = new Punycode(); $this->host = $puny->decode($a['host']); $a = explode('.', $this->host); krsort($a); $this->subdomains = $a; return $this->sortSubdomains(); }
php
public function setHost($host) { if (!$this->checkSchemeExists($host)) { $host = 'http://' . $host; } $a = $this->mbParseUrl($host); $this->setScheme($a['scheme']); $puny = new Punycode(); $this->host = $puny->decode($a['host']); $a = explode('.', $this->host); krsort($a); $this->subdomains = $a; return $this->sortSubdomains(); }
Полный домен
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L98-L115
sqrt-pro/URL
src/SQRT/URL.php
URL.getSubDomain
public function getSubDomain($level, $filter = null, $default = false) { if (!$this->hasSubDomain($level)) { return $default; } return Filter::Value($this->subdomains[$level], $filter, $default); }
php
public function getSubDomain($level, $filter = null, $default = false) { if (!$this->hasSubDomain($level)) { return $default; } return Filter::Value($this->subdomains[$level], $filter, $default); }
Получить значение поддомена. Нумерация с конца, с "1" $filter - callable или regexp $default - значение по-умолчанию, если значение не задано или не проходит фильтр
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L148-L155
sqrt-pro/URL
src/SQRT/URL.php
URL.getArgument
public function getArgument($num, $filter = null, $default = false) { if (!$this->hasArgument($num)) { return $default; } $v = $this->arguments[$num]; return Filter::Value($v, $filter, $default); }
php
public function getArgument($num, $filter = null, $default = false) { if (!$this->hasArgument($num)) { return $default; } $v = $this->arguments[$num]; return Filter::Value($v, $filter, $default); }
Получить значение аргумента. Нумерация с "1" $filter - callable или regexp $default - значение по-умолчанию, если значение не задано или не проходит фильтр
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L184-L193
sqrt-pro/URL
src/SQRT/URL.php
URL.setArgument
public function setArgument($num, $argument) { $this->arguments[$num] = $argument; $this->sortArguments(); return $this; }
php
public function setArgument($num, $argument) { $this->arguments[$num] = $argument; $this->sortArguments(); return $this; }
Установить значение аргумента. Нумерация с "1"
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L202-L209
sqrt-pro/URL
src/SQRT/URL.php
URL.addArguments
public function addArguments($mixed, $_ = null) { if (!is_array($mixed)) { $mixed = func_get_args(); } foreach ($mixed as $arg) { $this->addArgument($arg); } return $this; }
php
public function addArguments($mixed, $_ = null) { if (!is_array($mixed)) { $mixed = func_get_args(); } foreach ($mixed as $arg) { $this->addArgument($arg); } return $this; }
Установить значения аргументов. Значения могут быть указаны как массив или как список аргументов функции. Предыдущие значения затираются в соответствии по ключам
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L215-L226
sqrt-pro/URL
src/SQRT/URL.php
URL.removeArgument
public function removeArgument($num) { if ($this->hasArgument($num)) { unset($this->arguments[$num]); } return $this->sortArguments(); }
php
public function removeArgument($num) { if ($this->hasArgument($num)) { unset($this->arguments[$num]); } return $this->sortArguments(); }
Убрать значение аргумента. Остальные значения сдвигаются!
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L229-L236
sqrt-pro/URL
src/SQRT/URL.php
URL.removeArguments
public function removeArguments(array $arguments = null) { $this->arguments = array(); if ($arguments) { $this->addArguments($arguments); } return $this; }
php
public function removeArguments(array $arguments = null) { $this->arguments = array(); if ($arguments) { $this->addArguments($arguments); } return $this; }
Убрать все аргументы. Можно сразу задать массив новых аргументов
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L239-L248
sqrt-pro/URL
src/SQRT/URL.php
URL.addArgument
public function addArgument($argument, $prepend = false) { if ($prepend) { array_unshift($this->arguments, $argument); } else { array_push($this->arguments, $argument); } return $this->sortArguments(); }
php
public function addArgument($argument, $prepend = false) { if ($prepend) { array_unshift($this->arguments, $argument); } else { array_push($this->arguments, $argument); } return $this->sortArguments(); }
Добавить аргумент в конец строки. Параметр $prepend позволяет вставить элемент в начало строки. Остальные значения сдвигаются!
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L254-L263
sqrt-pro/URL
src/SQRT/URL.php
URL.getParameter
public function getParameter($name, $filter = null, $default = false) { if (!$this->hasParameter($name) || is_array($this->parameters[$name])) { return $default; } $v = $this->parameters[$name]; return Filter::Value($v, $filter, $default); }
php
public function getParameter($name, $filter = null, $default = false) { if (!$this->hasParameter($name) || is_array($this->parameters[$name])) { return $default; } $v = $this->parameters[$name]; return Filter::Value($v, $filter, $default); }
Получить значение параметра $filter - callable или regexp $default - значение по-умолчанию, если значение не задано или не проходит фильтр
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L276-L285
sqrt-pro/URL
src/SQRT/URL.php
URL.getParameterAsArray
public function getParameterAsArray($name, $filter = null, $default = array()) { if (!$this->hasParameter($name)) { return $default; } return Filter::Arr((array)$this->parameters[$name], $filter, $default); }
php
public function getParameterAsArray($name, $filter = null, $default = array()) { if (!$this->hasParameter($name)) { return $default; } return Filter::Arr((array)$this->parameters[$name], $filter, $default); }
Получить значение параметра в виде массива. Если передан один параметр - он будет в массиве $filter - callable или regexp, в результате будет оставлены только значения проходящие фильтр $default - значение по-умолчанию, если значение не задано или не проходит фильтр
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L293-L300
sqrt-pro/URL
src/SQRT/URL.php
URL.addParameter
public function addParameter($name, $parameter) { if ($this->hasParameter($name)) { $this->parameters[$name] = (array)$this->parameters[$name]; $this->parameters[$name][] = $parameter; } else { $this->parameters[$name] = $parameter; } return $this->sortParameters(); }
php
public function addParameter($name, $parameter) { if ($this->hasParameter($name)) { $this->parameters[$name] = (array)$this->parameters[$name]; $this->parameters[$name][] = $parameter; } else { $this->parameters[$name] = $parameter; } return $this->sortParameters(); }
Добавление параметра. Если такой параметр уже задан, значение будет добавлено в массив
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L317-L327
sqrt-pro/URL
src/SQRT/URL.php
URL.addParameters
public function addParameters(array $array) { foreach ($array as $key => $val) { $this->addParameter($key, $val); } return $this->sortParameters(); }
php
public function addParameters(array $array) { foreach ($array as $key => $val) { $this->addParameter($key, $val); } return $this->sortParameters(); }
Установка группы параметров
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L330-L337
sqrt-pro/URL
src/SQRT/URL.php
URL.removeParameters
public function removeParameters(array $parameters = null) { $this->parameters = array(); if ($parameters) { $this->addParameters($parameters); } return $this; }
php
public function removeParameters(array $parameters = null) { $this->parameters = array(); if ($parameters) { $this->addParameters($parameters); } return $this; }
Удаление всех параметров. Можно сразу задать массив новых параметров
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L350-L359
sqrt-pro/URL
src/SQRT/URL.php
URL.getFileName
public function getFileName($strict = false) { if (!$this->hasFileName()) { if ($strict) { return false; } $arr = $this->getArguments(); return current(array_slice($arr, -1)); } return $this->file_name; }
php
public function getFileName($strict = false) { if (!$this->hasFileName()) { if ($strict) { return false; } $arr = $this->getArguments(); return current(array_slice($arr, -1)); } return $this->file_name; }
Получить имя файла. Если оно не задано, будет возвращено значение последнего аргумента $strict - жесткая проверка, если файл не задан - вернется false
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L371-L384
sqrt-pro/URL
src/SQRT/URL.php
URL.setFileName
public function setFileName($filename) { $a = explode('.', $filename); $this->file_name = $filename; $this->file_extension = count($a) >= 2 ? array_pop($a) : false; return $this; }
php
public function setFileName($filename) { $a = explode('.', $filename); $this->file_name = $filename; $this->file_extension = count($a) >= 2 ? array_pop($a) : false; return $this; }
Задать имя файла
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L387-L395
sqrt-pro/URL
src/SQRT/URL.php
URL.setFileExtension
public function setFileExtension($extension) { if ($this->hasFileName()) { $a = explode('.', $this->getFileName(true)); if (count($a) >= 2) { array_pop($a); } $a[] = $extension; $this->file_name = join('.', $a); } else { $this->file_name = array_pop($this->arguments) . '.' . $extension; } return $this; }
php
public function setFileExtension($extension) { if ($this->hasFileName()) { $a = explode('.', $this->getFileName(true)); if (count($a) >= 2) { array_pop($a); } $a[] = $extension; $this->file_name = join('.', $a); } else { $this->file_name = array_pop($this->arguments) . '.' . $extension; } return $this; }
Установить расширение файла. Если имя файла не задано, последний аргумент будет конвертирован в имя файла
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L404-L418
sqrt-pro/URL
src/SQRT/URL.php
URL.getId
public function getId($as_array = false, $default = false) { $f = function ($var) { return is_numeric($var) && $var > 0; }; return $as_array ? $this->getParameterAsArray('id', $f, $default) : $this->getParameter('id', $f, $default); }
php
public function getId($as_array = false, $default = false) { $f = function ($var) { return is_numeric($var) && $var > 0; }; return $as_array ? $this->getParameterAsArray('id', $f, $default) : $this->getParameter('id', $f, $default); }
Получение ID из параметра
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L421-L428
sqrt-pro/URL
src/SQRT/URL.php
URL.asString
public function asString($absolute = false) { $url = '/'; if ($absolute) { $puny = new Punycode(); $url = $this->getScheme() . '://' . $puny->encode($this->getHost()) . '/'; } if ($a = $this->getArguments()) { foreach ($this->getArguments() as $str) { $url .= urlencode($str) . '/'; } } $url .= $this->buildParams(); if ($fn = $this->getFileName(true)) { $url .= urlencode($fn); } return $url; }
php
public function asString($absolute = false) { $url = '/'; if ($absolute) { $puny = new Punycode(); $url = $this->getScheme() . '://' . $puny->encode($this->getHost()) . '/'; } if ($a = $this->getArguments()) { foreach ($this->getArguments() as $str) { $url .= urlencode($str) . '/'; } } $url .= $this->buildParams(); if ($fn = $this->getFileName(true)) { $url .= urlencode($fn); } return $url; }
Возвратить адрес как строку
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L453-L474
sqrt-pro/URL
src/SQRT/URL.php
URL.buildParams
protected function buildParams($arr = null, $force_key = false) { if (is_null($arr)) { $arr = $this->getParameters(); } if (empty($arr)) { return false; } $out = ''; foreach ($arr as $key => $val) { if (is_array($val)) { $out .= $this->buildParams($val, $key); } else { $out .= urlencode($force_key ?: $key) . ':' . urlencode($val) . '/'; } } return $out; }
php
protected function buildParams($arr = null, $force_key = false) { if (is_null($arr)) { $arr = $this->getParameters(); } if (empty($arr)) { return false; } $out = ''; foreach ($arr as $key => $val) { if (is_array($val)) { $out .= $this->buildParams($val, $key); } else { $out .= urlencode($force_key ?: $key) . ':' . urlencode($val) . '/'; } } return $out; }
Построение строки параметров
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L489-L509
sqrt-pro/URL
src/SQRT/URL.php
URL.sortArguments
protected function sortArguments() { $i = 0; $res = array(); foreach ($this->arguments as $val) { $res[++$i] = $val; } $this->arguments = $res; return $this; }
php
protected function sortArguments() { $i = 0; $res = array(); foreach ($this->arguments as $val) { $res[++$i] = $val; } $this->arguments = $res; return $this; }
Сортировка аргументов
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L512-L524
sqrt-pro/URL
src/SQRT/URL.php
URL.sortSubdomains
protected function sortSubdomains() { $i = 0; $res = array(); foreach ($this->subdomains as $val) { $res[++$i] = $val; } $this->subdomains = $res; krsort($res); $this->host = join('.', $res); return $this; }
php
protected function sortSubdomains() { $i = 0; $res = array(); foreach ($this->subdomains as $val) { $res[++$i] = $val; } $this->subdomains = $res; krsort($res); $this->host = join('.', $res); return $this; }
Сортировка субдоменов
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L535-L549
sqrt-pro/URL
src/SQRT/URL.php
URL.mbParseUrl
protected function mbParseUrl($url) { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', function ($matches) { return urlencode($matches[0]); }, $url ); if ($parts = parse_url($enc_url)) { foreach ($parts as $name => $value) { $parts[$name] = urldecode($value); } } return $parts; }
php
protected function mbParseUrl($url) { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', function ($matches) { return urlencode($matches[0]); }, $url ); if ($parts = parse_url($enc_url)) { foreach ($parts as $name => $value) { $parts[$name] = urldecode($value); } } return $parts; }
Обертка для parse_url для корректной работы с UTF-8 строками
https://github.com/sqrt-pro/URL/blob/ac5ad32fedbd4e9d7a3e61896471fa2c66a1ab0b/src/SQRT/URL.php#L564-L581
kispiox/kispiox
src/Component/ServicesProvider.php
ServicesProvider.provides
public function provides($consumer) { $file = $this->getConfigFilePath(); $services = $this->config->get('services'); if (is_null($services)) { return; } foreach ($services as $name => $def) { // if no class is defined, throw an exception if (!isset($def['class'])) { throw new RuntimeException( 'no "class" in service "'.$name.'" defined in '.$file ); } $args = []; if (isset($def['args'])) { // if args are not an array, throw an exception if (!is_array($def['args'])) { throw new RuntimeException( 'invalid type for "args", expecting array in service "'.$name.'" defined in '.$file ); } $args = $def['args']; } $instance = $consumer->injectConstructor($def['class'], $args); $consumer->set($name, $instance); // process any setters if (isset($def['setters'])) { // if setters is not an array, throw an exception if (!is_array($def['setters'])) { throw new RuntimeException( 'invalid type for "setters", expecting array in service "'.$name.'" defined in '.$file ); } foreach ($def['setters'] as $i => $setter) { // if no setter name defined, throw an exception if (!isset($setter['name'])) { throw new RuntimeException( 'no "name" for setter #'.$i.' in service "'.$name.'" defined in '.$file ); } $args = []; if (isset($setter['args'])) { // if args is not an array, throw an exception if (!is_array($setter['args'])) { throw new RuntimeException( 'invalid type for "args", expecting array for setter #'.$i.' in service "'.$name.'" defined in '.$file ); } $args = $setter['args']; } $this->container->injectMethod($instance, $setter['name'], $args); } } // subscribe to any specified events if (isset($def['events'])) { // if events is not an array , throw an exception if (!is_array($def['events'])) { throw new RuntimeException( 'invalid type for "events", expecting array in service "'.$name.'" defined in '.$file ); } $dispatcher = $consumer->get('EventDispatcher'); foreach ($def['events'] as $i => $event) { // if no event name specified, throw an exception if (!isset($event['name'])) { throw new RuntimeException( 'no "name" for event #'.$i.' in service "'.$name.'" defined in '.$file ); } // if no event listener specified, throw an exception if (!isset($event['listener'])) { throw new RuntimeException( 'no "listener" for event #'.$i.' in service "'.$name.'" defined in '.$file ); } $dispatcher->addListener($event['name'], [$instance, $event['listener']]); } } } // foreach }
php
public function provides($consumer) { $file = $this->getConfigFilePath(); $services = $this->config->get('services'); if (is_null($services)) { return; } foreach ($services as $name => $def) { // if no class is defined, throw an exception if (!isset($def['class'])) { throw new RuntimeException( 'no "class" in service "'.$name.'" defined in '.$file ); } $args = []; if (isset($def['args'])) { // if args are not an array, throw an exception if (!is_array($def['args'])) { throw new RuntimeException( 'invalid type for "args", expecting array in service "'.$name.'" defined in '.$file ); } $args = $def['args']; } $instance = $consumer->injectConstructor($def['class'], $args); $consumer->set($name, $instance); // process any setters if (isset($def['setters'])) { // if setters is not an array, throw an exception if (!is_array($def['setters'])) { throw new RuntimeException( 'invalid type for "setters", expecting array in service "'.$name.'" defined in '.$file ); } foreach ($def['setters'] as $i => $setter) { // if no setter name defined, throw an exception if (!isset($setter['name'])) { throw new RuntimeException( 'no "name" for setter #'.$i.' in service "'.$name.'" defined in '.$file ); } $args = []; if (isset($setter['args'])) { // if args is not an array, throw an exception if (!is_array($setter['args'])) { throw new RuntimeException( 'invalid type for "args", expecting array for setter #'.$i.' in service "'.$name.'" defined in '.$file ); } $args = $setter['args']; } $this->container->injectMethod($instance, $setter['name'], $args); } } // subscribe to any specified events if (isset($def['events'])) { // if events is not an array , throw an exception if (!is_array($def['events'])) { throw new RuntimeException( 'invalid type for "events", expecting array in service "'.$name.'" defined in '.$file ); } $dispatcher = $consumer->get('EventDispatcher'); foreach ($def['events'] as $i => $event) { // if no event name specified, throw an exception if (!isset($event['name'])) { throw new RuntimeException( 'no "name" for event #'.$i.' in service "'.$name.'" defined in '.$file ); } // if no event listener specified, throw an exception if (!isset($event['listener'])) { throw new RuntimeException( 'no "listener" for event #'.$i.' in service "'.$name.'" defined in '.$file ); } $dispatcher->addListener($event['name'], [$instance, $event['listener']]); } } } // foreach }
Configure the container with services defined in a config file. @param \MattFerris\Di\ContainerInterface $consumer The container instance @throws \RuntimeException If the service definition contains missing or broken values
https://github.com/kispiox/kispiox/blob/eed0ae98f3b86b760dcd71fa632ac010fdaaf963/src/Component/ServicesProvider.php#L32-L138
as3io/modlr
src/Rest/RestConfiguration.php
RestConfiguration.setEntityFormat
public function setEntityFormat($format) { $this->validator->isFormatValid($format); $this->entityFormat = $format; return $this; }
php
public function setEntityFormat($format) { $this->validator->isFormatValid($format); $this->entityFormat = $format; return $this; }
Sets the entity type format. @param string $format @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestConfiguration.php#L109-L114
as3io/modlr
src/Rest/RestConfiguration.php
RestConfiguration.setFieldKeyFormat
public function setFieldKeyFormat($format) { $this->validator->isFormatValid($format); $this->fieldKeyFormat = $format; return $this; }
php
public function setFieldKeyFormat($format) { $this->validator->isFormatValid($format); $this->fieldKeyFormat = $format; return $this; }
Sets the field key format. @param string $format @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestConfiguration.php#L132-L137
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.getFeatures
public function getFeatures() { $featuresString = $this->storage->get($this->getFeaturesKey()); $features = explode(',', $featuresString); return $features; }
php
public function getFeatures() { $featuresString = $this->storage->get($this->getFeaturesKey()); $features = explode(',', $featuresString); return $features; }
Get all feature names @return string[]
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L45-L50
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.saveFeature
protected function saveFeature(RolloutableInterface $feature) { $this->storage->set($this->getKey($feature->getName()), (string)$feature); $features = $this->getFeatures(); if (false === in_array($feature->getName(), $features)) { $features[] = $feature->getName(); } $this->storage->set($this->getFeaturesKey(), implode(',', $features)); }
php
protected function saveFeature(RolloutableInterface $feature) { $this->storage->set($this->getKey($feature->getName()), (string)$feature); $features = $this->getFeatures(); if (false === in_array($feature->getName(), $features)) { $features[] = $feature->getName(); } $this->storage->set($this->getFeaturesKey(), implode(',', $features)); }
Saves a feature to the storage @param RolloutableInterface $feature
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L56-L64
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.activate
public function activate($featureName) { $feature = $this->getFeature($featureName); $feature->setPercentage(100); $this->saveFeature($feature); }
php
public function activate($featureName) { $feature = $this->getFeature($featureName); $feature->setPercentage(100); $this->saveFeature($feature); }
Activates a feature (for everyone) @param string $featureName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L89-L94
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.deactivate
public function deactivate($featureName) { $feature = $this->getFeature($featureName); $feature->clearConfig(); $this->saveFeature($feature); }
php
public function deactivate($featureName) { $feature = $this->getFeature($featureName); $feature->clearConfig(); $this->saveFeature($feature); }
Deactivates a feature (for everyone) @param string $featureName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L100-L105
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.activateRole
public function activateRole($featureName, $roleName) { $feature = $this->getFeature($featureName); $feature->addRole($roleName); $this->saveFeature($feature); }
php
public function activateRole($featureName, $roleName) { $feature = $this->getFeature($featureName); $feature->addRole($roleName); $this->saveFeature($feature); }
Activates a feature for a specific role @param string $featureName @param string $roleName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L112-L117
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.deactivateRole
public function deactivateRole($featureName, $roleName) { $feature = $this->getFeature($featureName); $feature->removeRole($roleName); $this->saveFeature($feature); }
php
public function deactivateRole($featureName, $roleName) { $feature = $this->getFeature($featureName); $feature->removeRole($roleName); $this->saveFeature($feature); }
Deactivates a feature for a specific role. @param string $featureName @param string $roleName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L124-L129
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.activateGroup
public function activateGroup($featureName, $groupName) { $feature = $this->getFeature($featureName); $feature->addGroup($groupName); $this->saveFeature($feature); }
php
public function activateGroup($featureName, $groupName) { $feature = $this->getFeature($featureName); $feature->addGroup($groupName); $this->saveFeature($feature); }
Activates a feature for a specific group @param string $featureName @param string $groupName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L136-L141
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.deactivateGroup
public function deactivateGroup($featureName, $groupName) { $feature = $this->getFeature($featureName); $feature->removeGroup($groupName); $this->saveFeature($feature); }
php
public function deactivateGroup($featureName, $groupName) { $feature = $this->getFeature($featureName); $feature->removeGroup($groupName); $this->saveFeature($feature); }
Deactivates a feature for a specific group. @param string $featureName @param string $groupName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L148-L153
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.activateUser
public function activateUser($featureName, $userId) { $feature = $this->getFeature($featureName); $feature->addUser($userId); $this->saveFeature($feature); }
php
public function activateUser($featureName, $userId) { $feature = $this->getFeature($featureName); $feature->addUser($userId); $this->saveFeature($feature); }
Activates a feature for a specific user @param string $featureName @param integer $userId
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L160-L165
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.deactivateUser
public function deactivateUser($featureName, $userId) { $feature = $this->getFeature($featureName); $feature->removeUser($userId); $this->saveFeature($feature); }
php
public function deactivateUser($featureName, $userId) { $feature = $this->getFeature($featureName); $feature->removeUser($userId); $this->saveFeature($feature); }
Deactivates a feature for a specific user @param string $featureName @param integer $userId
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L172-L177
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.activatePercentage
public function activatePercentage($featureName, $percentage) { $feature = $this->getFeature($featureName); $feature->setPercentage($percentage); $this->saveFeature($feature); }
php
public function activatePercentage($featureName, $percentage) { $feature = $this->getFeature($featureName); $feature->setPercentage($percentage); $this->saveFeature($feature); }
Activates a feature for a percentage of users @param string $featureName @param integer $percentage
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L184-L189
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.deactivatePercentage
public function deactivatePercentage($featureName) { $feature = $this->getFeature($featureName); $feature->setPercentage(0); $this->saveFeature($feature); }
php
public function deactivatePercentage($featureName) { $feature = $this->getFeature($featureName); $feature->setPercentage(0); $this->saveFeature($feature); }
Deactivates the percentage activation for a feature @param string $featureName
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L195-L200
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.isActive
public function isActive($featureName, DeterminableUserInterface $user = null) { $feature = $this->getFeature($featureName); return $feature->isActive($this, $user); }
php
public function isActive($featureName, DeterminableUserInterface $user = null) { $feature = $this->getFeature($featureName); return $feature->isActive($this, $user); }
Checks if a feature is active @param string $featureName @param DeterminableUserInterface $user @return bool
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L208-L212
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.userHasRole
public function userHasRole($roleName, DeterminableUserInterface $user) { $userHasRole = false; if (true === in_array($roleName, $user->getRoles())) { $userHasRole = true; } return $userHasRole; }
php
public function userHasRole($roleName, DeterminableUserInterface $user) { $userHasRole = false; if (true === in_array($roleName, $user->getRoles())) { $userHasRole = true; } return $userHasRole; }
Checks if a user has the given role @param string $roleName @param DeterminableUserInterface $user @return bool
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L220-L227
DarkGigaByte/rollout
src/DarkGigaByte/Rollout/RolloutAbstract.php
RolloutAbstract.userHasGroup
public function userHasGroup($groupName, DeterminableUserInterface $user) { $userHasGroup = false; if (true === in_array($groupName, $user->getGroups())) { $userHasGroup = true; } return $userHasGroup; }
php
public function userHasGroup($groupName, DeterminableUserInterface $user) { $userHasGroup = false; if (true === in_array($groupName, $user->getGroups())) { $userHasGroup = true; } return $userHasGroup; }
Checks if a user has the given group @param string $groupName @param DeterminableUserInterface $user @return bool
https://github.com/DarkGigaByte/rollout/blob/bff5f79df2211c9ebcfc35d4cba74daeeca19bcc/src/DarkGigaByte/Rollout/RolloutAbstract.php#L235-L242
Boolive/Core
data/Buffer.php
Buffer.get_entity
static function get_entity($uri) { if (isset(self::$list_entity[$uri])){ return self::$list_entity[$uri]; } return null; }
php
static function get_entity($uri) { if (isset(self::$list_entity[$uri])){ return self::$list_entity[$uri]; } return null; }
Выбор экземпляра сущности @param string $uri @return null|Entity
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Buffer.php#L21-L27
Boolive/Core
data/Buffer.php
Buffer.get_info
static function get_info($uri) { if (isset(self::$list_info[$uri])) { return self::$list_info[$uri]; } return null; }
php
static function get_info($uri) { if (isset(self::$list_info[$uri])) { return self::$list_info[$uri]; } return null; }
Выбор информации о сущности (только атрибуты сущности) @param string $uri @return null|array
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Buffer.php#L52-L58
Boolive/Core
data/Buffer.php
Buffer.set_info
static function set_info($info) { if (!isset($info['proto']) && $info['uri'] !='/vendor/boolive/basic/object'){ $info['proto'] = '/vendor/boolive/basic/object'; } if (isset($info['properties'])){ foreach ($info['properties'] as $name => $child){ if (is_scalar($child) || is_null($child)){ $child = ['value' => $child]; if (isset($info['proto'])) $child['proto'] = $info['proto'].'/'.$name; } $child['name'] = $name; $child['is_property'] = true; if (!empty($child['value'])) $child['is_default_value'] = false; if (!empty($child['file'])) $child['is_default_file'] = false; if (!isset($child['is_default_logic'])) $child['is_default_logic'] = true; if (!isset($child['created']) && isset($info['created'])) $child['created'] = $info['created']; if (!isset($child['updated']) && isset($info['updated'])) $child['updated'] = $info['updated']; $child['is_exists'] = $info['is_exists']; $child['uri'] = $info['uri'].'/'.$name; self::$list_props[$info['uri']][$name] = $child['uri']; self::set_info($child); } unset($info['properties']); } self::$list_info[$info['uri']] = $info; return $info; }
php
static function set_info($info) { if (!isset($info['proto']) && $info['uri'] !='/vendor/boolive/basic/object'){ $info['proto'] = '/vendor/boolive/basic/object'; } if (isset($info['properties'])){ foreach ($info['properties'] as $name => $child){ if (is_scalar($child) || is_null($child)){ $child = ['value' => $child]; if (isset($info['proto'])) $child['proto'] = $info['proto'].'/'.$name; } $child['name'] = $name; $child['is_property'] = true; if (!empty($child['value'])) $child['is_default_value'] = false; if (!empty($child['file'])) $child['is_default_file'] = false; if (!isset($child['is_default_logic'])) $child['is_default_logic'] = true; if (!isset($child['created']) && isset($info['created'])) $child['created'] = $info['created']; if (!isset($child['updated']) && isset($info['updated'])) $child['updated'] = $info['updated']; $child['is_exists'] = $info['is_exists']; $child['uri'] = $info['uri'].'/'.$name; self::$list_props[$info['uri']][$name] = $child['uri']; self::set_info($child); } unset($info['properties']); } self::$list_info[$info['uri']] = $info; return $info; }
Запись в буфер информации о сущности @param array $info Атрибуты и свойства сущности @return array Атрибуты без свойств
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/Buffer.php#L65-L92
oscarpalmer/shelf
src/oscarpalmer/Shelf/Cookies.php
Cookies.set
public function set($key, $value, int $expire = 30) : Cookies { setcookie($key, $value, time() + $expire); return $this; }
php
public function set($key, $value, int $expire = 30) : Cookies { setcookie($key, $value, time() + $expire); return $this; }
Set value for key in $_COOKIE. @param mixed $key Key to set. @param mixed $value Value for key. @param int $expire Expiry time in seconds. @return Session Session object for optional chaining.
https://github.com/oscarpalmer/shelf/blob/47bccf7fd8f1750defe1f2805480a6721f1a0e79/src/oscarpalmer/Shelf/Cookies.php#L65-L70
awjudd/l4-layoutview
src/Awjudd/Layoutview/LayoutviewServiceProvider.php
LayoutviewServiceProvider.register
public function register() { $this->app->singleton('view', function($app) { // Next we need to grab the engine resolver instance that will be used by the // environment. The resolver will be used by an environment to get each of // the various engine implementations such as plain PHP or Blade engine. $resolver = $app['view.engine.resolver']; $finder = $app['view.finder']; $env = new LayoutView($resolver, $finder, $app['events']); // We will also set the container instance on this view environment since the // view composers may be classes registered in the container, which allows // for great testable, flexible composers for the application developer. $env->setContainer($app); $env->share('app', $app); return $env; }); }
php
public function register() { $this->app->singleton('view', function($app) { // Next we need to grab the engine resolver instance that will be used by the // environment. The resolver will be used by an environment to get each of // the various engine implementations such as plain PHP or Blade engine. $resolver = $app['view.engine.resolver']; $finder = $app['view.finder']; $env = new LayoutView($resolver, $finder, $app['events']); // We will also set the container instance on this view environment since the // view composers may be classes registered in the container, which allows // for great testable, flexible composers for the application developer. $env->setContainer($app); $env->share('app', $app); return $env; }); }
Register the service provider. @return void
https://github.com/awjudd/l4-layoutview/blob/55fc25fbc8b3016c7133ca459636393d36ad10b9/src/Awjudd/Layoutview/LayoutviewServiceProvider.php#L30-L52
pmdevelopment/tool-bundle
Framework/Utilities/CollectionUtility.php
CollectionUtility.isValid
public static function isValid($collection) { if (false === is_array($collection) && false === ($collection instanceof Collection)) { return false; } return true; }
php
public static function isValid($collection) { if (false === is_array($collection) && false === ($collection instanceof Collection)) { return false; } return true; }
Is Valid Collection @param mixed $collection @return bool
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CollectionUtility.php#L28-L35
pmdevelopment/tool-bundle
Framework/Utilities/CollectionUtility.php
CollectionUtility.get
public static function get($property, $collection) { if (false === self::isValid($collection)) { return []; } $getter = sprintf('get%s', ucfirst($property)); $result = []; foreach ($collection as $entity) { $function = [ $entity, $getter ]; if (false === is_callable($function)) { throw new LogicException('Missing getter'); } $result[] = $entity->$getter(); } return $result; }
php
public static function get($property, $collection) { if (false === self::isValid($collection)) { return []; } $getter = sprintf('get%s', ucfirst($property)); $result = []; foreach ($collection as $entity) { $function = [ $entity, $getter ]; if (false === is_callable($function)) { throw new LogicException('Missing getter'); } $result[] = $entity->$getter(); } return $result; }
Get Property @param string $property @param array|mixed|Collection $collection @return array
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CollectionUtility.php#L45-L67
pmdevelopment/tool-bundle
Framework/Utilities/CollectionUtility.php
CollectionUtility.findOneBy
public static function findOneBy($collection, $fieldName, $searchValue, $default = null) { if (false === self::isValid($collection)) { return null; } $getter = sprintf('get%s', ucfirst($fieldName)); foreach ($collection as $entity) { $function = [ $entity, $getter ]; if (false === is_callable($function)) { throw new LogicException('Missing getter'); } if ($entity->$getter() === $searchValue) { return $entity; } } return $default; }
php
public static function findOneBy($collection, $fieldName, $searchValue, $default = null) { if (false === self::isValid($collection)) { return null; } $getter = sprintf('get%s', ucfirst($fieldName)); foreach ($collection as $entity) { $function = [ $entity, $getter ]; if (false === is_callable($function)) { throw new LogicException('Missing getter'); } if ($entity->$getter() === $searchValue) { return $entity; } } return $default; }
Find One By @param Collection|array $collection @param string $fieldName @param mixed $searchValue @param mixed $default @return null|object
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CollectionUtility.php#L103-L126
pmdevelopment/tool-bundle
Framework/Utilities/CollectionUtility.php
CollectionUtility.find
public static function find($collection, $id) { $id = intval($id); foreach ($collection as $entity) { if ($id === $entity->getId()) { return $entity; } } return null; }
php
public static function find($collection, $id) { $id = intval($id); foreach ($collection as $entity) { if ($id === $entity->getId()) { return $entity; } } return null; }
Find By Id @param Collection|array $collection @param int $id @return null|object
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CollectionUtility.php#L136-L146
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.indexAction
public function indexAction($path) { if (@is_dir($path)) { return $this->directoryAction($path); } else { return $this->fileAction($path); } }
php
public function indexAction($path) { if (@is_dir($path)) { return $this->directoryAction($path); } else { return $this->fileAction($path); } }
Default action @param string $path @return array
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L48-L55
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.directoryAction
public function directoryAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if ($dbfile->isFile()) { return $this->fileAction($this->getPath()); } $readme_content = $dir_content = ''; $index = $dbfile->findIndex(); if (file_exists($index)) { return $this->fileAction($index); } $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'dirscan' => $dbfile->getWDBScanStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $readme = $dbfile->findReadme(); if (file_exists($readme)) { $this->wdb->setInputFile($readme); $readme_dbfile = new WDBFile($readme); $readme_content = $readme_dbfile->viewFileInfos(); } $tpl_params['inpage_menu'] = !empty($readme_content) ? 'true' : 'false'; $dir_content = $this->wdb ->display('', 'dirindex', $tpl_params); return array('default', $dir_content.$readme_content, $tpl_params); }
php
public function directoryAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if ($dbfile->isFile()) { return $this->fileAction($this->getPath()); } $readme_content = $dir_content = ''; $index = $dbfile->findIndex(); if (file_exists($index)) { return $this->fileAction($index); } $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'dirscan' => $dbfile->getWDBScanStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $readme = $dbfile->findReadme(); if (file_exists($readme)) { $this->wdb->setInputFile($readme); $readme_dbfile = new WDBFile($readme); $readme_content = $readme_dbfile->viewFileInfos(); } $tpl_params['inpage_menu'] = !empty($readme_content) ? 'true' : 'false'; $dir_content = $this->wdb ->display('', 'dirindex', $tpl_params); return array('default', $dir_content.$readme_content, $tpl_params); }
Directory path action @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L64-L110
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.fileAction
public function fileAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getPath()); if ($dbfile->isDir()) { return $this->directoryAction($this->getPath()); } $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $content = $dbfile->viewFileInfos($tpl_params); return array('default', $content, $tpl_params); }
php
public function fileAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getPath()); if ($dbfile->isDir()) { return $this->directoryAction($this->getPath()); } $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $content = $dbfile->viewFileInfos($tpl_params); return array('default', $content, $tpl_params); }
File path action @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L119-L149
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.rssFeedAction
public function rssFeedAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); $contents = array(); $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $this->wdb->getResponse()->setContentType('xml'); $page = $dbfile->getWDBStack(); if ($dbfile->isDir()) { $contents = Helper::getFlatDirscans($dbfile->getWDBScanStack(true), true); foreach ($contents['dirscan'] as $i=>$item) { if ($item['type']!=='dir' && file_exists($item['path'])) { $dbfile = new WDBFile($item['path']); $contents['dirscan'][$i]['content'] = $dbfile->viewIntroduction(4000, false); } } } else { $page['content'] = $dbfile->viewIntroduction(4000, false); } $rss_content = $this->wdb->display('', 'rss', array( 'page' => $page, 'contents' => $contents )); return array('layout_empty_xml', $rss_content); }
php
public function rssFeedAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); $contents = array(); $tpl_params = array( 'page' => $dbfile->getWDBFullStack(), 'breadcrumbs' => TemplateHelper::getBreadcrumbs($this->getPath()), 'title' => TemplateHelper::buildPageTitle($this->getPath()), ); if (empty($tpl_params['title'])) { if (!empty($tpl_params['breadcrumbs'])) { $tpl_params['title'] = TemplateHelper::buildPageTitle(end($tpl_params['breadcrumbs'])); } else { $tpl_params['title'] = _T('Home'); } } $this->wdb->getResponse()->setContentType('xml'); $page = $dbfile->getWDBStack(); if ($dbfile->isDir()) { $contents = Helper::getFlatDirscans($dbfile->getWDBScanStack(true), true); foreach ($contents['dirscan'] as $i=>$item) { if ($item['type']!=='dir' && file_exists($item['path'])) { $dbfile = new WDBFile($item['path']); $contents['dirscan'][$i]['content'] = $dbfile->viewIntroduction(4000, false); } } } else { $page['content'] = $dbfile->viewIntroduction(4000, false); } $rss_content = $this->wdb->display('', 'rss', array( 'page' => $page, 'contents' => $contents )); return array('layout_empty_xml', $rss_content); }
RSS action for concerned path @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L158-L202
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.sitemapAction
public function sitemapAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isDir()) { throw new NotFoundException( 'Can not build a sitemap from a single file!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $this->wdb->getResponse()->setContentType('xml'); $contents = Helper::getFlatDirscans($dbfile->getWDBScanStack(true)); $rss_content = $this->wdb->display('', 'sitemap', array( 'page' => $dbfile->getWDBStack(), 'contents' => $contents )); return array('layout_empty_xml', $rss_content); }
php
public function sitemapAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isDir()) { throw new NotFoundException( 'Can not build a sitemap from a single file!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $this->wdb->getResponse()->setContentType('xml'); $contents = Helper::getFlatDirscans($dbfile->getWDBScanStack(true)); $rss_content = $this->wdb->display('', 'sitemap', array( 'page' => $dbfile->getWDBStack(), 'contents' => $contents )); return array('layout_empty_xml', $rss_content); }
Sitemap action for a path @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L211-L235
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.htmlOnlyAction
public function htmlOnlyAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $md_parser = $this->wdb->getMarkdownParser(); $md_content = $md_parser->transformSource($this->getPath()); return array('layout_empty_html', $md_content->getBody(), array('page_notes' => $md_content->getNotesToString()) ); }
php
public function htmlOnlyAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $md_parser = $this->wdb->getMarkdownParser(); $md_content = $md_parser->transformSource($this->getPath()); return array('layout_empty_html', $md_content->getBody(), array('page_notes' => $md_content->getNotesToString()) ); }
HTML only version of a path @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L244-L266
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.plainTextAction
public function plainTextAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $response = $this->wdb->getResponse(); // mime header $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $this->getPath()); if ( ! in_array($mime, $response::$content_types)) { $mime = 'text/plain'; } finfo_close($finfo); // content $ctt = $response->flush(file_get_contents($this->getPath()), $mime); return array('layout_empty_txt', $ctt); }
php
public function plainTextAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $response = $this->wdb->getResponse(); // mime header $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $this->getPath()); if ( ! in_array($mime, $response::$content_types)) { $mime = 'text/plain'; } finfo_close($finfo); // content $ctt = $response->flush(file_get_contents($this->getPath()), $mime); return array('layout_empty_txt', $ctt); }
Raw plain text action of a path @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L275-L304
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.downloadAction
public function downloadAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $this->wdb->getResponse() ->download($path, 'text/plain'); exit(0); }
php
public function downloadAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $dbfile = new WDBFile($this->getpath()); if (!$dbfile->isFile()) { throw new NotFoundException( 'Can not send raw content of a directory!', 0, null, TemplateHelper::getRoute($dbfile->getWDBPath()) ); } $this->wdb->getResponse() ->download($path, 'text/plain'); exit(0); }
Download action of a path @param string $path @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L312-L331
wdbo/webdocbook
src/WebDocBook/Controller/DefaultController.php
DefaultController.searchAction
public function searchAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $search = $this->wdb->getRequest()->getArgument('s'); if (empty($search)) { return $this->indexAction($path); } $_s = Helper::makeSearch($search, $this->getPath()); $title = _T('Search for "%search_str%"', array('search_str'=>$search)); $breadcrumbs = TemplateHelper::getBreadcrumbs($this->getPath()); $breadcrumbs[] = $title; $dbfile = new WDBFile($this->getpath()); $page = $dbfile->getWDBStack(); $page['type'] = 'search'; $tpl_params = array( 'page' => $page, 'breadcrumbs' => $breadcrumbs, 'title' => $title, ); $search_content = $this->wdb->display($_s, 'search', array( 'search_str' => $search, 'path' => TemplateHelper::buildPageTitle($this->getPath()), )); return array('default', $search_content, $tpl_params); }
php
public function searchAction($path) { try { $this->setPath($path); } catch (NotFoundException $e) { throw $e; } $search = $this->wdb->getRequest()->getArgument('s'); if (empty($search)) { return $this->indexAction($path); } $_s = Helper::makeSearch($search, $this->getPath()); $title = _T('Search for "%search_str%"', array('search_str'=>$search)); $breadcrumbs = TemplateHelper::getBreadcrumbs($this->getPath()); $breadcrumbs[] = $title; $dbfile = new WDBFile($this->getpath()); $page = $dbfile->getWDBStack(); $page['type'] = 'search'; $tpl_params = array( 'page' => $page, 'breadcrumbs' => $breadcrumbs, 'title' => $title, ); $search_content = $this->wdb->display($_s, 'search', array( 'search_str' => $search, 'path' => TemplateHelper::buildPageTitle($this->getPath()), )); return array('default', $search_content, $tpl_params); }
Global search action of a path @param string $path @return array @throws \WebDocBook\Exception\NotFoundException
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Controller/DefaultController.php#L340-L372
PhoxPHP/Glider
src/Console/Command/Seed.php
Seed.run
public function run(Array $argumentsList, int $argumentsCount) { $command = $argumentsList[0]; unset($argumentsList[0]); $arguments = array_values($argumentsList); switch ($command) { case 'create': return $this->createSeed(); break; case 'run': return $this->runSeeds(); break; case 'run-class': $path = $this->cmd->getConfigOpt('seeds_storage') . '/' . trim($arguments[0]) . '.php'; include $path; return $this->runSeed(basename($path, '.php')); break; default: return $this->env->sendOutput('No command run.'); break; } }
php
public function run(Array $argumentsList, int $argumentsCount) { $command = $argumentsList[0]; unset($argumentsList[0]); $arguments = array_values($argumentsList); switch ($command) { case 'create': return $this->createSeed(); break; case 'run': return $this->runSeeds(); break; case 'run-class': $path = $this->cmd->getConfigOpt('seeds_storage') . '/' . trim($arguments[0]) . '.php'; include $path; return $this->runSeed(basename($path, '.php')); break; default: return $this->env->sendOutput('No command run.'); break; } }
{@inheritDoc}
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/Command/Seed.php#L68-L90
PhoxPHP/Glider
src/Console/Command/Seed.php
Seed.createSeed
protected function createSeed() { $templateTags = []; $seedsDirectory = $this->cmd->getConfigOpt('seeds_storage'); $filename = trim($this->cmd->question('Seed filename?')); $templateTags['phx:class'] = Helper::getQualifiedClassName($filename); $path = $seedsDirectory . '/' . $filename . '.php'; if (file_exists($path)) { throw new SeedFileInvalidException( sprintf( 'Seed file [%s] exists.', $filename ) ); } $builder = new TemplateBuilder($this->cmd, $this->env); $builder->createClassTemplate('seed', $filename, $seedsDirectory, $templateTags); }
php
protected function createSeed() { $templateTags = []; $seedsDirectory = $this->cmd->getConfigOpt('seeds_storage'); $filename = trim($this->cmd->question('Seed filename?')); $templateTags['phx:class'] = Helper::getQualifiedClassName($filename); $path = $seedsDirectory . '/' . $filename . '.php'; if (file_exists($path)) { throw new SeedFileInvalidException( sprintf( 'Seed file [%s] exists.', $filename ) ); } $builder = new TemplateBuilder($this->cmd, $this->env); $builder->createClassTemplate('seed', $filename, $seedsDirectory, $templateTags); }
Create new seed class. @access protected @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/Command/Seed.php#L110-L131
PhoxPHP/Glider
src/Console/Command/Seed.php
Seed.runSeeds
protected function runSeeds() { foreach($this->getSeeders() as $file) { require_once $file; $className = basename($file, '.php'); $this->runSeed($className); } }
php
protected function runSeeds() { foreach($this->getSeeders() as $file) { require_once $file; $className = basename($file, '.php'); $this->runSeed($className); } }
Runs all seeders. @access protected @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/Command/Seed.php#L139-L146