sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function attr($element='this', $attributeName='value', $value='', $immediatly=false) { return $this->js->_attr($element, $attributeName, $value, $immediatly); }
Get or set the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element. @param string $element @param string $attributeName @param string $value @param boolean $immediatly defers the execution if set to false
entailment
public function val($element='this',$value='',$immediatly=false){ return $this->js->_genericCallValue('val',$element,$value,$immediatly); }
Get or set the value of the first element in the set of matched elements or set one or more attributes for every matched element. @param string $element @param string $value @param boolean $immediatly defers the execution if set to false
entailment
public function html($element='this', $value='', $immediatly=false) { return $this->js->_genericCallValue('html',$element, $value, $immediatly); }
Get or set the html of an attribute for the first element in the set of matched elements. @param string $element @param string $value @param boolean $immediatly defers the execution if set to false
entailment
public function animate($element='this', $params=array(), $speed='', $extra='', $immediatly=false) { return $this->js->_animate($element, $params, $speed, $extra, $immediatly); }
Outputs a javascript library animate event @param string $element element @param array $params @param string $speed One of 'slow', 'normal', 'fast', or time in milliseconds @param string $extra @param boolean $immediatly defers the execution if set to false @return string
entailment
public function append($to, $element, $immediatly=false) { return $this->js->_genericCallElement('append',$to, $element, $immediatly); }
Insert content, specified by the parameter $element, to the end of each element in the set of matched elements $to. @param string $to @param string $element @param boolean $immediatly defers the execution if set to false @return string
entailment
public function fadeIn($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_fadeIn($element, $speed, $callback, $immediatly); }
Execute a javascript library hide action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function fadeOut($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_fadeOut($element, $speed, $callback, $immediatly); }
Execute a javascript library hide action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function slideUp($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_slideUp($element, $speed, $callback, $immediatly); }
Execute a javascript library slideUp action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function slideDown($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_slideDown($element, $speed, $callback, $immediatly); }
Execute a javascript library slideDown action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function slideToggle($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_slideToggle($element, $speed, $callback, $immediatly); }
Execute a javascript library slideToggle action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function hide($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_hide($element, $speed, $callback, $immediatly); }
Execute a javascript library hide action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function trigger($element='this', $event='click', $immediatly=false) { return $this->js->_trigger($element, $event, $immediatly); }
Execute all handlers and behaviors attached to the matched elements for the given event. @param string $element @param string $event @param boolean $immediatly defers the execution if set to false
entailment
public function show($element='this', $speed='', $callback='', $immediatly=false) { return $this->js->_show($element, $speed, $callback, $immediatly); }
Execute a javascript library show action @param string - element @param string - One of 'slow', 'normal', 'fast', or time in milliseconds @param string - Javascript callback function @param boolean $immediatly defers the execution if set to false @return string
entailment
public function condition($condition, $jsCodeIfTrue, $jsCodeIfFalse=null, $immediatly=false) { return $this->js->_condition($condition, $jsCodeIfTrue, $jsCodeIfFalse, $immediatly); }
Allows to attach a condition @param string $condition @param string $jsCodeIfTrue @param string $jsCodeIfFalse @param boolean $immediatly defers the execution if set to false
entailment
public function doJQueryOn($event, $element, $elementToModify, $jqueryCall, $param="", $parameters=array()) { $jsCallback=""; $stopPropagation=false; $preventDefault=false; $immediatly=true; extract($parameters); return $this->js->_doJQueryOn($event, $element, $elementToModify, $jqueryCall, $param, $preventDefault, $stopPropagation, $jsCallback,$immediatly); }
Calls the JQuery callback $jqueryCall on $element with facultative parameter $param in response to an event $event @param string $event @param string $element @param string $elementToModify @param string $jqueryCall @param string $param @param array $parameters default : array("preventDefault"=>false,"stopPropagation"=>false,"jsCallback"=>'',"immediatly"=>true)
entailment
public function exec($js, $immediatly=false) { $script=$this->js->_exec($js, $immediatly); return $script; }
Executes the code $js @param string $js Code to execute @param boolean $immediatly delayed if false @return String
entailment
public function execOn($event, $element, $js, $parameters=array()) { $stopPropagation=false; $preventDefault=false; $immediatly=true; extract($parameters); $script=$this->js->_execOn($element, $event, $js, $preventDefault, $stopPropagation,$immediatly); return $script; }
Executes the javascript code $js when $event fires on $element @param string $event @param string $element @param string $js Code to execute @param array $parameters default : array("preventDefault"=>false,"stopPropagation"=>false,"immediatly"=>true) @return String
entailment
public function get($url, $responseElement="", $params="{}", $jsCallback=NULL,$hasLoader=true) { return $this->js->_get($url, $params, $responseElement, $jsCallback, NULL, $hasLoader,true); }
Performs an ajax GET request @param string $url The url of the request @param string $params JSON parameters @param string $responseElement selector of the HTML element displaying the answer @param string $jsCallback javascript code to execute after the request @param boolean $hasLoader true for showing ajax loader. default : true
entailment
public function json($url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context="document",$immediatly=false) { return $this->js->_json($url, $method, $params, $jsCallback, $attr, $context,$immediatly); }
Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name @param string $url the request url @param string $params JSON parameters @param string $method Method used @param string $jsCallback javascript code to execute after the request @param boolean $immediatly
entailment
public function jsonOn($event,$element, $url,$parameters=array()) { return $this->js->_jsonOn($event, $element, $url,$parameters); }
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element @param string $element @param string $event @param string $url the request address @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
entailment
public function jsonDeferred($url, $method="get", $params="{}", $jsCallback=NULL) { return $this->js->_json($url, $method, $params, $jsCallback, NULL, false); }
Prepares an ajax request delayed and receives the JSON data types by assigning DOM elements with the same name @param string $url the request url @param string $params Paramètres passés au format JSON @param string $method Method used @param string $jsCallback javascript code to execute after the request
entailment
public function jsonArray($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL) { return $this->js->_jsonArray($maskSelector, $url, $method, $params, $jsCallback, NULL, true); }
Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name @param string $url the request url @param string $params The JSON parameters @param string $method Method used @param string $jsCallback javascript code to execute after the request
entailment
public function jsonArrayDeferred($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL) { return $this->js->_jsonArray($maskSelector, $url, $method, $params, $jsCallback, NULL, false); }
Peforms an ajax request delayed and receives a JSON array data types by copying and assigning them to the DOM elements with the same name @param string $maskSelector the selector of the element to clone @param string $url the request url @param string $params JSON parameters @param string $method Method used @param string $jsCallback javascript code to execute after the request
entailment
public function jsonArrayOn($event,$element,$maskSelector, $url,$parameters=array()) { return $this->js->_jsonArrayOn($event,$element,$maskSelector, $url, $parameters); }
Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name when $event fired on $element @param string $element @param string $event @param string $url the request url @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
entailment
public function getDeferred($url, $responseElement="", $params="{}", $jsCallback=NULL,$attr="id") { return $this->js->_get($url, $params, $responseElement, $jsCallback, $attr, false); }
Prepares a Get ajax request To use on an event @param string $url The url of the request @param string $params JSON parameters @param string $responseElement selector of the HTML element displaying the answer @param string $jsCallback javascript code to execute after the request @param string $attr the html attribute added to the request
entailment
public function getOn($event, $element, $url, $responseElement="", $parameters=array()) { $params=JArray::getDefaultValue($parameters, "params", "{}"); return $this->js->_getOn($event, $element, $url, $params, $responseElement, $parameters); }
Performs a get to $url on the event $event on $element and display it in $responseElement @param string $event @param string $element @param string $url The url of the request @param string $responseElement The selector of the HTML element displaying the answer @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
entailment
public function post($url, $responseElement="", $params="{}", $jsCallback=NULL,$hasLoader=true) { return $this->js->_post($url, $params, $responseElement, $jsCallback, NULL, $hasLoader,true); }
Makes an ajax post @param string $url the request url @param string $params JSON parameters @param string $responseElement selector of the HTML element displaying the answer @param string $jsCallback javascript code to execute after the request @param boolean $hasLoader true for showing ajax loader. default : true
entailment
public function postDeferred($url, $responseElement="", $params="{}", $jsCallback=NULL, $attr="id",$hasLoader=true) { return $this->js->_post($url, $params, $responseElement, $jsCallback, $attr, $hasLoader,false); }
Prepares a delayed ajax POST to use on an event @param string $url the request url @param string $params JSON parameters @param string $attr the html attribute added to the request @param string $responseElement selector of the HTML element displaying the answer @param string $jsCallback javascript code to execute after the request @param boolean $hasLoader true for showing ajax loader. default : true
entailment
public function postOn($event, $element, $url, $params="{}", $responseElement="", $parameters=array()) { return $this->js->_postOn($event, $element, $url, $params, $responseElement, $parameters); }
Performs a post to $url on the event $event fired on $element and pass the parameters $params Display the result in $responseElement @param string $event @param string $element @param string $url The url of the request @param string $params The parameters to send @param string $responseElement selector of the HTML element displaying the answer @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
entailment
public function postForm($url, $form, $responseElement, $validation=false, $jsCallback=NULL,$hasLoader=true) { return $this->js->_postForm($url, $form, $responseElement, $validation, $jsCallback, NULL, $hasLoader,true); }
Performs a post form with ajax @param string $url The url of the request @param string $form The form HTML id @param string $responseElement selector of the HTML element displaying the answer @param string $jsCallback javascript code to execute after the request @param boolean $hasLoader true for showing ajax loader. default : true
entailment
public function postFormOn($event, $element, $url, $form, $responseElement="", $parameters=array()) { return $this->js->_postFormOn($event,$element, $url, $form, $responseElement, $parameters); }
Performs a post form with ajax in response to an event $event on $element display the result in $responseElement @param string $event @param string $element @param string $url @param string $form @param string $responseElement selector of the HTML element displaying the answer @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
entailment
public function getMessages($name = null) { !$name && $name = $this->name; $this->negative && $this->addError('negative'); $this->loadTranslationMessages(); $messages = array(); foreach ($this->errors as $optionName => $message) { preg_match_all('/\%(.+?)\%/', $message, $matches); $parameters = array(); foreach ($matches[1] as $match) { if ('name' == $match) { $parameters['%name%'] = $this->t($name); } else { if (!property_exists($this, $match)) { throw new \UnexpectedValueException(sprintf('Unknown parameter "%%%s%%" in message "%s"', $match, $message)); } $parameters['%' . $match . '%'] = is_array($this->$match) ? implode(', ', $this->$match) : $this->$match; } } $messages[$optionName] = $this->t($message, $parameters); } return $messages; }
Returns the error messages @param string $name The name display in error message @return array @throws \UnexpectedValueException When message contains unknown parameter
entailment
protected function addError($name, $customMessage = null) { $this->errors[$name] = $customMessage ?: $this->message ?: $this->{$name . 'Message'}; }
Adds error definition @param string $name The name of error @param string $customMessage The custom error message
entailment
protected function isString($input) { return is_scalar($input) || is_null($input) || (is_object($input) && method_exists($input, '__toString')); }
Checks if the input value could be convert to string @param mixed $input @return bool
entailment
protected function storeOption($name, $value = null) { // Handle array if (is_array($name)) { foreach ($name as $key => $value) { $this->storeOption($key, $value); } return; } if (property_exists($this, $name)) { if (!array_key_exists($name, $this->backup)) { $this->backup[$name] = $this->$name; } $this->store[count($this->store) - 1][$name] = $value; } $this->setOption($name, $value); }
Set property value @param string|array $name The name of property @param mixed $value The value of property @internal This method should be use to set __invoke arguments only
entailment
protected function reset() { $this->errors = array(); if (count($this->store) >= 2) { $last = end($this->store); foreach ($this->backup as $name => $value) { if (!array_key_exists($name, $last)) { $this->$name = $value; } } array_shift($this->store); } $this->store[] = array(); }
Reset validator status @internal
entailment
protected function doCreateObject(array $array) { $this->data = $array; $this->product = new Product($this->data); $this->setBrands() ->setFunctionalNames() ->setPromotions() ->setProductsToPromotions() ->setOptions() ->setAttributes() ->setMedia(); return $this->product; }
@param array $array @return Product
entailment
protected function connect() { if (!$this->object) { $this->object = new \Memcache; } foreach ($this->servers as $server) { call_user_func_array(array($this->object, 'addServer'), $server); } }
Instance memcache object and connect to server
entailment
public function exists($key) { $key = $this->namespace . $key; if ($this->object->add($key, true)) { $this->object->delete($key); return false; } return true; }
{@inheritdoc}
entailment
public function parse() { if (!$this->checkToken()) { return $this->parseRet = array('code' => -1, 'message' => 'Token不正确'); } $attrs = $this->xmlToArray($this->postData); if ($this->isEncrypted()) { $ret = $this->decryptMsg($attrs['Encrypt']); if ($ret['code'] !== 1) { return $this->parseRet = $ret; } $attrs = $this->xmlToArray($ret['xml']); } $this->attrs = $attrs; return $this->parseRet = array('code' => 1, 'message' => '解析成功'); }
Parse post data to message attributes @return array
entailment
protected function checkToken() { $query = $this->query; $signature = $this->sign( $this->token, isset($query['timestamp']) ? $query['timestamp'] : '', isset($query['nonce']) ? $query['nonce'] : '' ); return isset($query['signature']) && $signature === $query['signature']; }
Check if the WeChat server signature is valid
entailment
public function run() { // The token or post data is invalid if ($this->parseRet['code'] !== 1) { return false; } // Output 'echostr' for first time authentication if (isset($this->query['echostr'])) { return htmlspecialchars($this->query['echostr'], ENT_QUOTES, 'UTF-8'); } $msg = $this->handleMsg(); if (!$msg) { return 'success'; } return $this->isEncrypted() ? $this->encryptMsg($msg) : $msg; }
Execute the matched rule and returns the rule result Returns false when the token is invalid or no rules matched @return string|false
entailment
protected function handleMsg() { switch ($this->getMsgType()) { case 'text': if ($result = $this->handleText()) { return $result; } break; case 'event': case 'device_event': $event = strtolower($this->getEvent()); switch ($event) { case 'subscribe': $result = $this->handleEvent('subscribe'); $scanResult = null; if ($this->getTicket()) { $scanResult = $this->handleEvent('scan'); } if ($result) { return $result; } if ($scanResult) { return $scanResult; } break; case 'scan': if ($result = $this->handleEvent('scan')) { return $result; } break; default: if ($result = $this->handleEvent($event, $this->getEventKey())) { return $result; } break; } break; // Including location, image, voice, video and link default: if (isset($this->rules[$this->getMsgType()])) { return $this->handle($this->rules[$this->getMsgType()]); } } // Check if enable to transfer to customer service if (isset($this->rules['transferCustomer'])) { return $this->handle($this->rules['transferCustomer']); } // Fallback to the default rule if (!$this->handled && $this->defaults) { return $this->handle($this->defaults); } return false; }
Executes the matched rule and returns the rule result Returns false when the token is invalid or no rules matched @return string|false
entailment
public function on($name, $key, Closure $fn = null) { $name = strtolower($name); if ($key instanceof Closure) { $this->rules['event'][$name][''] = $key; } else { $this->rules['event'][$name][$key] = $fn; } return $this; }
Adds a rule to handle user event, such as click, subscribe @param string $name @param Closure|string $key @param Closure $fn @return $this
entailment
public function sendMusic($title, $description, $url, $hqUrl = null) { return $this->send('music', array( 'Music' => array( 'Title' => $title, 'Description' => $description, 'MusicUrl' => $url, 'HQMusicUrl' => $hqUrl, ), )); }
Generate music message for output @param string $title The title of music @param string $description The description display blow the title @param string $url The music URL for player @param string $hqUrl The HQ music URL for player when user in WIFI @return array
entailment
public function sendArticle(array $articles) { // Convert single article array if (!is_int(key($articles))) { $articles = array($articles); } $response = array( 'ArticleCount' => count($articles), 'Articles' => array( 'item' => array(), ), ); foreach ($articles as $article) { $article += array( 'title' => null, 'description' => null, 'picUrl' => null, 'url' => null, ); $response['Articles']['item'][] = array( 'Title' => $article['title'], 'Description' => $article['description'], 'PicUrl' => $article['picUrl'], 'Url' => $article['url'], ); } return $this->send('news', $response); }
Generate article message for output ``` // Sends one article $app->sendArticle(array( 'title' => 'The title of article', 'description' => 'The description of article', 'picUrl' => 'The picture URL of article', 'url' => 'The URL link to of article' )); // Sends two or more articles $app->sendArticle(array( array( 'title' => 'The title of article', 'description' => 'The description of article', 'picUrl' => 'The picture URL of article', 'url' => 'The URL link to of article' ), array( 'title' => 'The title of article', 'description' => 'The description of article', 'picUrl' => 'Te picture URL of article', 'url' => 'The URL link to of article' ), // more... )); ``` @param array $articles The article array @return array
entailment
public function getAttr($name) { return isset($this->attrs[$name]) ? $this->attrs[$name] : null; }
Returns the XML element value @param string $name @return mixed
entailment
public function getScanSceneId() { $eventKey = $this->getEventKey(); if (strpos($eventKey, 'qrscene_') === 0) { $eventKey = substr($eventKey, 8); } return $eventKey; }
Returns the scene id from the scan result, available when the message event is subscribe or scan @return string
entailment
public function getKeyword() { if ($this->getMsgType() == 'text') { return strtolower($this->getContent()); } elseif ($this->getMsgType() == 'event' && strtolower($this->getEvent()) == 'click') { return strtolower($this->getEventKey()); } return false; }
Returns the user inputted content or clicked button value @return bool|string
entailment
public function send($type, array $response) { return $response + array( 'ToUserName' => $this->getFromUserName(), 'FromUserName' => $this->getToUserName(), 'MsgType' => $type, 'CreateTime' => time(), ); }
Generate message for output @param string $type The type of message @param array $response The response content @return array
entailment
protected function addTextRule($type, $keyword, Closure $fn) { $this->rules['text'][] = array( 'type' => $type, 'keyword' => $keyword, 'fn' => $fn, ); return $this; }
Adds a rule to handle user text input @param string $type @param string $keyword @param Closure $fn @return $this
entailment
protected function handleText() { $content = $this->getContent(); foreach ($this->rules['text'] as $rule) { if ($rule['type'] == 'is' && 0 === strcasecmp($content, $rule['keyword'])) { return $this->handle($rule['fn']); } if ($rule['type'] == 'has' && false !== mb_stripos($content, $rule['keyword'])) { return $this->handle($rule['fn']); } if ($rule['type'] == 'startsWith' && 0 === mb_stripos($content, $rule['keyword'])) { return $this->handle($rule['fn']); } if ($rule['type'] == 'match' && preg_match($rule['keyword'], $content)) { return $this->handle($rule['fn']); } } return false; }
Handle text rule @return string|false
entailment
protected function handle($fn) { $this->handled = true; // Converts string to array $content = $fn($this, $this->wei) ?: ''; if ($content && !is_array($content)) { $content = $this->sendText($content); } $this->beforeSend && call_user_func_array($this->beforeSend, array($this, &$content, $this->wei)); return $content ? $this->arrayToXml($content)->asXML() : ''; }
Executes callback handler @param Closure $fn @return string
entailment
protected function arrayToXml(array $array, SimpleXMLElement $xml = null) { if ($xml === null) { $xml = new SimpleXMLElement('<xml/>'); } foreach ($array as $key => $value) { if (is_array($value)) { if (isset($value[0])) { foreach ($value as $subValue) { $subNode = $xml->addChild($key); $this->arrayToXml($subValue, $subNode); } } else { $subNode = $xml->addChild($key); $this->arrayToXml($value, $subNode); } } else { // Wrap cdata for non-numeric string if (is_numeric($value)) { $xml->addChild($key, $value); } else { $child = $xml->addChild($key); $node = dom_import_simplexml($child); $node->appendChild($node->ownerDocument->createCDATASection($value)); } } } return $xml; }
Convert to XML element @param array $array @param SimpleXMLElement $xml @return SimpleXMLElement
entailment
protected function xmlToArray($xml) { // Do not output libxml error messages to screen $useErrors = libxml_use_internal_errors(true); $array = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); libxml_use_internal_errors($useErrors); // Fix the issue that XML parse empty data to new SimpleXMLElement object return array_map('strval', (array) $array); }
Convert XML string to array @param string $xml @return array
entailment
protected function prpcryptDecrypt($encrypted, $encodingAesKey, $appId) { try { $key = base64_decode($encodingAesKey . '='); $iv = substr($key, 0, 16); $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', substr($key, 0, 32), OPENSSL_ZERO_PADDING, $iv); } catch (\Exception $e) { return array('code' => -2002, 'message' => 'AES解密失败', 'e' => (string) $e); } try { // 去除补位字符 $result = $this->pkcs7Decode($decrypted); // 去除16位随机字符串,网络字节序和AppId if (strlen($result) < 16) { return array('code' => -2003, 'message' => '解密后结果不能小于16位', 'result' => $result); } $content = substr($result, 16, strlen($result)); $lenList = unpack('N', substr($content, 0, 4)); $xmlLen = $lenList[1]; $xml = substr($content, 4, $xmlLen); $fromAppId = substr($content, $xmlLen + 4); } catch (\Exception $e) { return array('code' => -2004, 'message' => '解密后得到的buffer非法', 'e' => (string) $e); } if ($fromAppId != $appId) { return array('code' => -2005, 'message' => 'AppId 校验错误', 'appId' => $appId, 'fromAppId' => $fromAppId); } return array('code' => 1, 'message' => '解密成功', 'xml' => $xml); }
对密文进行解密 @param string $encrypted 需要解密的密文 @param string $encodingAesKey @param string $appId @return array
entailment
protected function sign($_ = null) { $arr = func_get_args(); sort($arr, SORT_STRING); $str = implode($arr); return sha1($str); }
Generate the signature @param string $_ @return string
entailment
protected function getRandomStr() { $str = ''; $strPol = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; $max = strlen($strPol) - 1; for ($i = 0; $i < 16; $i++) { $str .= $strPol[mt_rand(0, $max)]; } return $str; }
Generate random string @return string 生成的字符串
entailment
protected function pkcs7Encode($text) { $size = 32; $textLength = strlen($text); // 计算需要填充的位数 $amountToPad = $size - ($textLength % $size); if ($amountToPad == 0) { $amountToPad = $size; } // 获得补位所用的字符 $padChr = chr($amountToPad); $tmp = ''; for ($index = 0; $index < $amountToPad; $index++) { $tmp .= $padChr; } return $text . $tmp; }
对需要加密的明文进行填充补位 @param string $text 需要进行填充补位操作的明文 @return string 补齐明文字符串
entailment
protected function pkcs7Decode($text) { $pad = ord(substr($text, -1)); if ($pad < 1 || $pad > 32) { $pad = 0; } return substr($text, 0, (strlen($text) - $pad)); }
对解密后的明文进行补位删除 @param string $text 解密后的明文 @return string 删除填充补位后的明文
entailment
public function findPrice(PriceConfigurationFilter $priceConfigurationFilter) { $data = $priceConfigurationFilter->getData(); $response = $this->handler->handle('POST', $data); if (!$response->getSuccess()) { throw new EntityNotFoundException($response->getErrorMessage()); } return $this->make($response); }
@param PriceConfigurationFilter $priceConfigurationFilter @return array|ProductPriceConfiguration[] @throws \SphereMall\MS\Exceptions\SMSDKException @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function findProductPrice(PriceProduct $product) { $priceConfigurationFilter = new PriceConfigurationFilter(); $priceConfigurationFilter->addProduct($product); $result = $this->findPrice($priceConfigurationFilter); if (isset($result[0])) { return $result[0]; } return null; }
@param PriceProduct $product @return ProductPriceConfiguration|null @throws \SphereMall\MS\Exceptions\SMSDKException @throws \GuzzleHttp\Exception\GuzzleException
entailment
public static function fromValue($just, $nothing = null) : self { return $just !== $nothing ? self::just($just) : self::nothing(); }
fromValue method. @param mixed $just @param mixed $nothing @return object Maybe
entailment
public static function lift(callable $fn) : callable { return function () use ($fn) { if ( array_reduce( func_get_args($fn), function ($status, Maybe $val) { return $val->isNothing() ? false : $status; }, true ) ) { $args = array_map( function (Maybe $maybe) { return $maybe->getOrElse(null); }, func_get_args($fn) ); return self::just(call_user_func($fn, ...$args)); } return self::nothing(); }; }
lift method. @param callable $fn @return callable
entailment
public function hash($password, $salt = null) { $hash_format = sprintf("$2y$%02d$", $this->cost); !$salt && $salt = $this->generateSalt(); if (strlen($salt) < 22) { throw new \InvalidArgumentException(sprintf("Provided salt is too short: %d expecting %d", strlen($salt), 22)); } $hash = $hash_format . $salt; $ret = crypt($password, $hash); if (!is_string($ret) || strlen($ret) <= 13) { return false; } return $ret; }
Hash the password using the specified algorithm @param string $password The password to hash @param string $salt The salt string for the algorithm to use @throws \InvalidArgumentException @return string|false The hashed password, or false on error.
entailment
public function getInfo($hash) { $return = array( 'algo' => 0, 'algoName' => 'unknown', 'options' => array(), ); if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { $return['algo'] = PASSWORD_BCRYPT; $return['algoName'] = 'bcrypt'; list($cost) = sscanf($hash, "$2y$%d$"); $return['options']['cost'] = $cost; } return $return; }
Get information about the password hash. Returns an array of the information that was used to generate the password hash. array( 'algo' => 1, 'algoName' => 'bcrypt', 'options' => array( 'cost' => 10, ), ) @param string $hash The password hash to extract info from @return array The array of information about the hash.
entailment
public function needsRehash($hash, $algo, array $options = array()) { $info = $this->getInfo($hash); if ($info['algo'] != $algo) { return true; } switch ($algo) { case PASSWORD_BCRYPT: $cost = isset($options['cost']) ? $options['cost'] : 10; if ($cost != $info['options']['cost']) { return true; } break; } return false; }
Determine if the password hash needs to be rehashed according to the options provided If the answer is true, after validating the password using password_verify, rehash it. @param string $hash The hash to test @param int $algo The algorithm used for new password hashes @param array $options The options array passed to password_hash @return boolean True if the password needs to be rehashed.
entailment
public function verify($password, $hash) { $ret = crypt($password, $hash); $len = strlen($ret); if (!is_string($ret) || $len != strlen($hash) || strlen($ret) <= 13) { return false; } $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (ord($ret[$i]) ^ ord($hash[$i])); } return $status === 0; }
Verify a password against a hash using a timing attack resistant approach @param string $password The password to verify @param string $hash The hash to verify against @return boolean If the password matches the hash
entailment
public function setCost($cost) { if ($cost < 4 || $cost > 31) { throw new \InvalidArgumentException(sprintf("Invalid bcrypt cost parameter specified: %s", $cost)); } $this->cost = $cost; return $this; }
Set the cost parameter for bcrypt @param int $cost @return $this @throws \InvalidArgumentException
entailment
public function generateSalt() { // The length of salt to generate $raw_salt_len = 16; // The length required in the final serialization $required_salt_len = 22; $buffer = function_exists('random_bytes') ? random_bytes($raw_salt_len) : mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); $salt = str_replace('+', '.', base64_encode($buffer)); $salt = substr($salt, 0, $required_salt_len); return $salt; }
Generate a 22 bytes salt string @return string
entailment
protected function setOperator(?string $operator): bool { if (!$operator) { $this->operator = self::DEFAULT_OPERATOR; return true; } if (in_array($operator, self::SUPPORTED_OPERATORS)) { $this->operator = $operator; return true; } throw new Exception("Not supported operator"); }
@param string $operator @return bool @throws Exception
entailment
public function attachEvent($selector, $action=NULL) { if (isset($action)!==false||\is_numeric($action)===true) { $js='$("#%identifier%").checkbox("attach events", "'.$selector.'", "'.$action.'");'; } else { $js='$("#%identifier%").checkbox("attach events", "'.$selector.'");'; } $js=\str_replace("%identifier%", $this->identifier, $js); return $this->executeOnRun($js); }
Attach $this to $selector and fire $action @param string $selector jquery selector of the associated element @param string $action action to execute : check, uncheck or NULL for toggle @return \Ajax\semantic\html\collections\form\AbstractHtmlFormRadioCheckbox
entailment
public function ap(Monadic $app) : Monadic { return $this->bind(function ($func) use ($app) { return $app->map($func); }); }
ap method.
entailment
public function list($entityCode, $entityId, $param = null) { $entityCode = strtolower($entityCode); $uriAppend = "{$entityCode}/{$entityId}"; $params = $this->getQueryParams(); $response = $this->handler->handle('GET', false, $uriAppend, $params); return $this->make($response); }
Get list factor values for current entity @param string $entityCode @param int $entityId @return Entity|Entity[] @throws \GuzzleHttp\Exception\GuzzleException @throws \Exception
entailment
public function set($entityToCode , $entityId, array $factorValueIds) { $uriAppend = 'set'; $params = array_merge($this->getQueryParams(), [ 'entityToCode' => $entityToCode, 'entityId' => $entityId, 'factorValueIds' => implode(',', $factorValueIds) ]); $response = $this->handler->handle('POST', $params, $uriAppend); return $this->make($response); }
Set factor value for current entity @param string $entityToCode @param int $entityId @param int|array $factorValueIds @return Entity|Entity[] @throws \GuzzleHttp\Exception\GuzzleException @throws \Exception
entailment
public function forISBN($isbn) { if (!$this->isValidISBN($isbn)) { throw new InvalidArgumentException('ISBN is not valid. Got: '.$isbn); } // Example: https://www.googleapis.com/books/v1/volumes?q=isbn:9780525953739 $response = $this->client->request('GET', 'volumes', [ 'query' => ['q' => 'isbn:'.$isbn], 'http_errors' => false, ]); $status = $response->getStatusCode(); if ($status != 200) { throw new InvalidResponseException('Invalid response. Status: '.$status.'. Body: '.$response->getBody()); } $res = json_decode($response->getBody(), true); $totalItems = intval($res['totalItems']); if ($totalItems != 1) { throw new InvalidResponseException('Did not get 1 result. Got: '.$totalItems); } return $this->extractBook($res); }
Retrieve information about a book given its ISBN. @param string $isbn @throws InvalidArgumentException When the ISBN has not the expected format @throws InvalidResponseException When the client got an unexpected response @return Book
entailment
private function parseDate($rawDate) { foreach (['Y-m-d', 'Y-m', 'Y'] as $dateFormat) { $publishedDate = DateTime::createFromFormat($dateFormat.'|', $rawDate); if ($publishedDate !== false) { break; } } if ($publishedDate === false) { $publishedDate = null; } return [$publishedDate, $dateFormat]; }
Parse the publication date. @param string $rawDate @return array The publication in DateTime and the date format
entailment
public function fromDispatcher(JsUtils $js,$dispatcher, $startIndex=0) { return $this->addItems($js->fromDispatcher($dispatcher)); }
Add new elements in breadcrumbs corresponding to request dispatcher : controllerName, actionName, parameters @param JsUtils $js @param Dispatcher $dispatcher the request dispatcher @return \Ajax\bootstrap\html\HtmlBreadcrumbs
entailment
public function large($email, $default = null, $rating = null) { return $this->__invoke($email, $this->largeSize, $default, $rating); }
Generate a large size Gravatar URL for a specified email address @param string $email The email address @param string $default The image type or URL when email do not have a Gravatar image @param string $rating The image rating @return string
entailment
public function small($email, $default = null, $rating = null) { return $this->__invoke($email, $this->smallSize, $default, $rating); }
Generate a small size Gravatar URL for a specified email address @param string $email The email address @param string $default The image type or URL when email do not have a Gravatar image @param string $rating The image rating @return string
entailment
protected static function bootHistoryTracker() { self::created(function ($model) { $model->saveHistory(); }); self::updated(function ($model) { $model->saveHistory(); }); self::deleted(function ($model) { if (method_exists($model, 'bootSoftDeletes')) { $model->saveHistory(); } }); }
protected $historyModel = HistoryModel::class;
entailment
public function connect() { if ($this->object) { return true; } $this->object = new \Redis; $connect = $this->persistent ? 'pconnect' : 'connect'; $result = $this->object->$connect($this->host, $this->port, $this->timeout); if ($result && $this->auth) { $result = $this->object->auth($this->auth); } if ($result) { foreach ($this->options as $key => $value) { $this->object->setOption($key, $value); } } return $result; }
Connect the redis server and set redis options @return bool true on success, false on error
entailment
public function set($key, $value, $expire = 0) { // Use null instead of 0 for redis extension 2.2.8, otherwise the key will expire after set return $this->object->set($this->namespace . $key, $value, $expire === 0 ? null : $expire); }
{@inheritdoc}
entailment
public function getMulti(array $keys) { $keysWithPrefix = array(); foreach ($keys as $key) { $keysWithPrefix[] = $this->namespace . $key; } return array_combine($keys, $this->object->mGet($keysWithPrefix)); }
{@inheritdoc}
entailment
public function setMulti(array $items, $expire = 0) { $keys = array_keys($items); $keysWithPrefix = array(); foreach ($keys as $key) { $keysWithPrefix[] = $this->namespace . $key; } $items = array_combine($keysWithPrefix, $items); $result = $this->object->mset($items); return array_combine($keys, array_pad(array(), count($items), $result)); }
{@inheritdoc} Note: 1. The "$expire" parameter is not support by redis MSET command 2. The elements in returning values are all true or false, see links for more detail @link http://redis.io/commands/mset @link https://github.com/nicolasff/phpredis/blob/master/redis_array.c#L844
entailment
public function add($key, $value, $expire = 0) { $key = $this->namespace . $key; $result = $this->object->setnx($key, $value); if (true === $result && $expire) { $this->object->expire($key, $expire); } return $result; }
{@inheritdoc}
entailment
public function replace($key, $value, $expire = 0) { if (false === $this->get($key)) { return false; } return $this->set($key, $value, $expire); }
Note: This method is not an atomic operation {@inheritdoc}
entailment
public function belong(string $entityClass, int $attributeGroupId = null, int $attributeId = null) { $uriAppend = '/belong/' . strtolower((new \ReflectionClass($entityClass))->getShortName()) . "s"; $params = $this->getQueryParams(); if (!is_null($attributeGroupId)) { $uriAppend .= "/$attributeGroupId"; if (!is_null($attributeId)) { $uriAppend .= "/$attributeId"; } } $response = $this->handler->handle('GET', false, $uriAppend, $params); return $this->make($response); }
@param string $entityClass class name like Entity::class @param int|null $attributeGroupId @param int|null $attributeId @return array|\SphereMall\MS\Lib\Collection @throws \GuzzleHttp\Exception\GuzzleException @throws \ReflectionException
entailment
public function isSatisfiedBy(Entity $entity) { if (property_exists($entity, 'visible')) { return (bool)$entity->visible; } throw new InvalidArgumentException("Property 'visible' does not exist in class " . get_class($entity)); }
@param Entity $entity @return bool
entailment
public function add(array $params) { if (is_null($this->getId())) { $this->createBasket(); } $this->callResourceAction(function ($params) { return $this->client->basketResource($this->version) ->create($params); }, $params); }
@param array $params @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function update(array $params = []) { if (is_null($this->getId())) { $this->createBasket(); } $params = array_merge($params, $this->updateParams); $this->callResourceAction(function ($params) { return $this->client->basketResource($this->version) ->update($this->getId(), $params); }, $params); $this->updateParams = []; }
@param array $params @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function setDelivery(Delivery $delivery) { if (!$delivery->id) { throw new InvalidArgumentException("Can not set delivery. Delivery id is empty."); } $this->updateParams['deliveryProviderId'] = $delivery->id; $this->updateParams['deliveryCost'] = $delivery->getCost(); return $this; }
@param Delivery $delivery @return $this
entailment
protected function getBasket(int $id) { /** @var Order $order */ $order = $this->client->basketResource($this->version) ->get($id, ['recalculate' => true]); if (is_null($order)) { throw new EntityNotFoundException("Can not found basket with id: $id"); } $this->id = (int)$order->id; $this->setProperties($order); }
@param int $id @throws EntityNotFoundException @throws \GuzzleHttp\Exception\GuzzleException
entailment
protected function setAddress(Address $address, $addressKey) { if (!$address->id) { $addressResource = $this->client ->addresses() ->create($address->asArray()); if ($addressResource) { $address = $addressResource; } } $this->updateParams["{$addressKey}Id"] = $address->id; }
@param Address $address @param $addressKey @throws EntityNotFoundException @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function add($element, $postion=null, $type=null) { parent::add($element, $postion, $type); }
/* (non-PHPdoc) @see \Phalcon\Forms\Form::add()
entailment
public function get($key, $expire = null, $fn = null) { $result = $this->object->findOne(array('_id' => $this->namespace . $key), array('value', 'expire')); if (null === $result || $result['expire'] < time()) { $result = false; } else { $result = unserialize($result['value']); } return $this->processGetResult($key, $result, $expire, $fn); }
{@inheritdoc}
entailment
public function set($key, $value, $expire = 0) { $result = $this->object->save(array( '_id' => $this->namespace . $key, 'value' => serialize($value), 'expire' => $expire ? time() + $expire : 2147483647, 'lastModified' => time() )); return $result['ok'] === 1.0; }
{@inheritdoc}
entailment
public function exists($key) { $result = $this->object->findOne(array('_id' => $this->namespace . $key), array('expire')); if (null === $result || $result['expire'] < time()) { return false; } else { return true; } }
{@inheritdoc}
entailment
public function add($key, $value, $expire = 0) { if ($this->exists($key)) { return false; } else { return $this->set($key, $value, $expire); } }
{@inheritdoc}
entailment
public function replace($key, $value, $expire = 0) { if ($this->exists($key)) { return $this->set($key, $value, $expire); } else { return false; } }
{@inheritdoc}
entailment