sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function filter($filter)
{
if (!is_a($filter, FilterBuilder::class)) {
throw new \Exception ("Filter must be extend class 'FilterBuilder'");
}
$this->filter = $filter;
return $this;
} | @param array|\SphereMall\MS\Lib\Filters\Filter|\SphereMall\MS\Lib\Specifications\Basic\FilterSpecification $filter
@return $this|Resource
@throws \Exception | entailment |
private function getRelations($element, $included)
{
foreach ($element['relationships'] as $type => $value) {
foreach ($value['data'] as $key => $relation) {
if (!isset($included[$type][$relation['id']])) {
continue;
}
$item = $included[$type][$relation['id']];
if (count($item['relationships']) > 0) {
$item = $this->getRelations($item, $included);
}
unset($element['relationships'][$type]['data']);
$element['relationships'][$type][$key] = $item;
}
}
return $element;
} | @param $element
@param $included
@return mixed | entailment |
public function click($element='this', $js='', $ret_false=TRUE) {
return $this->js->_click($element, $js, $ret_false);
} | Outputs a javascript library click event
@param string $element element to attach the event to
@param string $js code to execute
@param boolean $ret_false or not to return false
@return string | entailment |
public function hover($element='this', $over, $out) {
return $this->js->_hover($element, $over, $out);
} | Outputs a javascript library hover event
@param string $element
@param string $over code for mouse over
@param string $out code for mouse out
@return string | entailment |
public function setShould(ShouldQuery $should)
{
$this->result = array_merge($this->result, $should->toArray()['bool']);
return $this;
} | @param ShouldQuery $should
@return $this | entailment |
public function setMust(MustQuery $must)
{
$this->result = array_merge($this->result, $must->toArray()['bool']);
return $this;
} | @param MustQuery $must
@return $this | entailment |
public function setMustNot(MustNotQuery $mustNot)
{
$this->result = array_merge($this->result, $mustNot->toArray()['bool']);
return $this;
} | @param MustNotQuery $mustNot
@return $this | entailment |
public function setFilter(FilterQuery $filter)
{
$this->result = array_merge($this->result, $filter->toArray()['bool']);
return $this;
} | @param FilterQuery $filter
@return $this | entailment |
public function getHistory(int $userId, int $id = null)
{
$params = $this->getQueryParams();
$uriAppend = "history/{$userId}" . (!is_null($id) ? "/{$id}" : '');
$response = $this->handler->handle('GET', false, $uriAppend, $params);
return $this->make($response, true, new OrdersMaker());
} | @param int $userId
@param int|null $id
@return Order[]
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
private function getOrderByParam($uriAppend)
{
$params = $this->getQueryParams();
$response = $this->handler->handle('GET', false, $uriAppend, $params);
if ($response->getData()) {
$maker = empty($response->getData()[0]['relationships']) ? new ObjectMaker() : new OrdersMaker();
/** @var $order Order */
$order = $this->make($response, false, $maker);
$orderFinalized = new OrderFinalized($this->client);
$orderFinalized->setOrderData($order);
return $orderFinalized;
}
return null;
} | @param $uriAppend
@return null|OrderFinalized
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function getProductVariantsByIds($ids)
{
$this->ids($ids);
$params = $this->getQueryParams();
$uriAppend = 'detail/variants';
$response = $this->handler->handle('GET', false, $uriAppend, $params);
return $this->make($response);
} | @param $ids
@return array|int|\SphereMall\MS\Entities\Entity|\SphereMall\MS\Lib\Collection
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function getRelatedProducts($id)
{
$params = $this->getQueryParams();
$uriAppend = "related/$id";
$response = $this->handler->handle('GET', false, $uriAppend, $params);
return $this->make($response);
} | @param $id
@return array|int|\SphereMall\MS\Entities\Entity|\SphereMall\MS\Lib\Collection
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function findAll($host = null, callable $callback = null)
{
/** @var QueryBuilder $queryBuilder */
$queryBuilder = $this->entityManager->createQueryBuilder();
$query = $queryBuilder
->select('r')
->from($this->getEntityClassName(), 'r');
if ($host !== null) {
$query->andWhere('r.host = :host')
->setParameter('host', $host);
} else {
$query->andWhere('r.host IS NULL');
}
$query->orderBy('r.host', 'ASC');
$query->addOrderBy('r.sourceUriPath', 'ASC');
return $this->iterate($query->getQuery()->iterate(), $callback);
} | Finds all objects and return an IterableResult
@param string $host Full qualified host name
@param callable $callback
@return \Generator<Redirect> | entailment |
public function findDistinctHosts()
{
/** @var Query $query */
$query = $this->entityManager->createQuery('SELECT DISTINCT r.host FROM Neos\RedirectHandler\DatabaseStorage\Domain\Model\Redirect r');
return array_map(function ($record) {
return $record['host'];
}, $query->getResult());
} | Return a list of all hosts
@return array | entailment |
protected function iterate(IterableResult $iterator, callable $callback = null)
{
$iteration = 0;
foreach ($iterator as $object) {
/** @var Redirect $object */
$object = current($object);
yield $object;
if ($callback !== null) {
call_user_func($callback, $iteration, $object);
}
$iteration++;
}
} | Iterator over an IterableResult and return a Generator
@param IterableResult $iterator
@param callable $callback
@return \Generator<RedirectDto> | entailment |
protected function doCreateObject(array $array)
{
$factor = new Factor($array);
if (isset($array['factorValues']) && is_array($array['factorValues'])) {
foreach ($array['factorValues'] as $factorValueData) {
$mapper = new FactorValuesMapper();
$factor->values[] = $mapper->createObject($factorValueData);
}
}
return $factor;
} | @param array $array
@return Factor | entailment |
protected function doCreateObject(array $array)
{
$order = new Order(isset($array['attributes']) && is_array($array['attributes']) ? $array['attributes'] : $array);
$relationShips = $array['relationships'] ?? [];
if (isset($relationShips['orderItems']) || isset($relationShips['items'])) {
$mapper = new OrderItemsMapper();
foreach ($relationShips['orderItems'] ?? $relationShips['items'] as $item) {
$order->items[$item['id']] = $mapper->createObject($item);
}
}
if (isset($relationShips['paymentMethods'])) {
$mapper = new PaymentMethodsMapper();
foreach ($relationShips['paymentMethods'] as $item) {
$order->paymentMethods[$item['id']] = $mapper->createObject($item['attributes']);
}
}
// old structure
if (isset($array['items'])) {
$orderItemMapper = new OrderItemsMapper();
$order->items = array_map(function ($item) use ($orderItemMapper) {
return $orderItemMapper->createObject($item);
}, $array['items']);
}
return $order;
} | @param array $array
@return Order | entailment |
protected function doValidate($input)
{
if (!$this->isString($input)) {
$this->addError('notString');
return false;
}
if (mb_strtolower($input, mb_detect_encoding($input)) != $input) {
$this->addError('invalid');
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function init()
{
parent::init();
self::$plugin = $this;
$this->name = Craft::t('password-policy', 'Password Policy');
if (Craft::$app->request->isCpRequest) {
Craft::$app->view->registerAssetBundle(PasswordPolicyAsset::class);
}
Event::on(
User::class,
User::EVENT_BEFORE_VALIDATE,
function (ModelEvent $event) {
if ($event->sender->newPassword) {
$errors = $this->passwordService->getValidationErrors($event->sender->newPassword);
$event->isValid = count($errors) === 0;
if (!$event->isValid) {
/** @var User $user */
$user = $event->sender;
foreach ($errors as $error) {
$user->addError('newPassword', $error);
}
}
}
}
);
} | Set our $plugin static property to this class so that it can be accessed via
PasswordPolicy::$plugin.
Called after the plugin class is instantiated; do any one-time initialization
here such as hooks and events.
If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
you do not need to load it in your init() method. | entailment |
public function handle(string $method, $body = false, $uriAppend = false, array $queryParams = [])
{
$client = $this->createElasticClient();
$param = $queryParams[0];
$endPoint = "search";
if (is_a($param, Search::class)) {
$endPoint = "search";
$queryParams = $param->getParams();
} elseif (is_a($param, MSearch::class)) {
$endPoint = "msearch";
$queryParams = $param->getParams();
}
try {
$elasticData = $client->{$endPoint}($queryParams);
if ($client->transport->getLastConnection()) {
$elasticData['debug'] = $client->transport->getLastConnection()->getLastRequestInfo();
}
if ($endPoint == 'msearch') {
foreach ($elasticData['responses'] as $key => $responseItem) {
$responseItem['debug'] = $elasticData['debug'];
$response[] = new Response($responseItem);
}
} else {
$response = new Response($elasticData, $queryParams['body']['size'] ?? 0, $queryParams['body']['from'] ?? 0);
}
} catch (\Exception $ex) {
$error = json_decode($ex->getMessage());
throw new \Exception($error->error->reason ?? $ex->getMessage());
}
return $response;
} | @param string $method
@param bool $body
@param bool $uriAppend
@param array $queryParams
@return \GuzzleHttp\Promise\PromiseInterface|Response|\SphereMall\MS\Lib\Http\Response
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
if (!$options['expanded']) {
throw new LogicException('The option "expanded" cannot the set to false, use the choice field instead.');
}
} | {@inheritdoc} | entailment |
public function detailByCode($factorCode)
{
$response = $this->handler->handle('GET', false, "detail/code/{$factorCode}");
return $this->make($response);
} | @param $factorCode
@return array|int|\SphereMall\MS\Entities\Entity|\SphereMall\MS\Lib\Collection
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
protected function doCreateObject(array $array)
{
$this->data = $array;
$this->document = new Document($this->data);
$this->setFunctionalNames()
->setAttributes()
->setMedia();
return $this->document;
} | @param array $array
@return Document | entailment |
private function getAttributeValues($attribute, $attributeValues)
{
$values = [];
foreach ($attributeValues as $attributeValue) {
if ($attribute['id'] == $attributeValue['attributeId']) {
$values[] = $attributeValue;
}
}
return $values;
} | @param $attribute
@param $attributeValues
@return array | entailment |
public function set(int $userId, array $factors, array $context)
{
$uriAppend = 'set';
$params = [
'userId' => $userId,
'factors' => $factors,
'context' => $context,
];
$response = $this->handler->handle('POST', $params, $uriAppend);
return $this->make($response);
} | Set consumer factors for history and for current entity factors
@see https://spheremall.atlassian.net/wiki/spaces/MIC/pages/1272676386/Grapher+2.3.5+Release+Notes
@param int $userId
@param array $factors
@param array $context
@return array|int|\SphereMall\MS\Entities\Entity|\SphereMall\MS\Lib\Collection
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function setStyle($cssStyle) {
if (!PhalconUtils::startsWith($cssStyle, "panel"))
$cssStyle="panel".$cssStyle;
return $this->addToPropertyCtrl("class", $cssStyle, CssRef::Styles("panel"));
} | define the Panel style
avaible values : "panel-default","panel-primary","panel-success","panel-info","panel-warning","panel-danger"
@param string|int $cssStyle
@return \Ajax\bootstrap\html\HtmlPanel default : "panel-default" | entailment |
public function authorize_url($client_id, $redirect_uri, $scope = 'AdministerAccount', $state = false) {
$qs = 'type=web_server';
$qs .= '&client_id=' . urlencode($client_id);
$qs .= '&redirect_uri=' . urlencode($redirect_uri);
$qs .= '&scope=' . urlencode($scope);
if ($state)
$qs .= '&state=' . urlencode($state);
return self::OAUTH_URL . '?' . $qs;
} | Get the authorization URL for your application.
@param $client_id int The Client ID of your registered OAuth application.
@param $redirect_uri string The Redirect URI of your registered OAuth application.
@param $scope string The comma-separated permission scope your application requires.
@param $state string Optional state data to be included in the URL.
@return string The authorization URL to which users of your application should be redirected.
@access public | entailment |
public function exchange_token($client_id, $client_secret, $redirect_uri, $code = '') {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code
);
return $this->_request('oauth', $params, self::OAUTH_TOKEN_URL);
} | Exchange a provided OAuth code for an OAuth access token, 'expires in'
value and refresh token.
@param $client_id int The Client ID of your registered OAuth application.
@param $client_secret string The Client Secret of your registered OAuth application.
@param $redirect_uri string The Redirect URI of your registered OAuth application.
@param $code string The unique OAuth code to be exchanged for an access token.
@return A successful response will be an array of the form:
array(
'access_token' => The access token to use for API calls
'expires_in' => The number of seconds until this access token expires
'refresh_token' => The refresh token to refresh the access token once it expires
)
@access public | entailment |
public function refresh_token() {
if (!isset($this->auth_details['refresh_token']))
trigger_error('Error refreshing token. There is no refresh token set on this object.', E_USER_ERROR);
$params = array(
'grant_type' => 'refresh_token',
'refresh_token' => $this->auth_details['refresh_token']
);
return $this->_request('oauth', $params, self::OAUTH_TOKEN_URL);
} | Refresh the current OAuth token using the current refresh token.
@access public | entailment |
private function _request($method, $params = array(), $url = self::API_ENDPOINT) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Elvanto_API-PHP/1.0.0');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Exchange or refresh a token
if ($method === 'oauth') {
$headers = array('Content-Type: application/x-www-form-urlencoded');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
// Call an API method
} else {
$url = self::API_ENDPOINT . '/' . $method . '.json';
$params['grant_type'] = 'client_credentials';
$headers = array('Content-Type: application/json; charset=utf-8');
if (isset($this->auth_details['access_token'])) { // Authenticating using OAuth
$headers[] = 'Authorization: Bearer ' . $this->auth_details['access_token'];
} else if (isset($this->auth_details['api_key'])) { // Authenticating using an API key
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->auth_details['api_key'] . ':nopass');
}
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch)) {
trigger_error('API call to ' . $url . ' failed: ' . curl_error($ch), E_USER_ERROR);
return false;
}
curl_close($ch);
return $response ? json_decode($response) : false;
} | Call a method.
@param string $method The name of the method to call.
@param array $params The parameters to pass to the method.
@param string $url The URL to post to.
@return array The response from the API method.
@access private | entailment |
public function getInt($name, $min = null, $max = null)
{
$value = (int) $this($name);
if (!is_null($min) && $value < $min) {
return $min;
} elseif (!is_null($max) && $value > $max) {
return $max;
}
return $value;
} | Returns a integer value in the specified range
@param string $name The parameter name
@param integer|null $min The min value for the parameter
@param integer|null $max The max value for the parameter
@return int The parameter value | entailment |
public function getInArray($name, array $array)
{
$value = $this->get($name);
return in_array($value, $array) ? $value : $array[key($array)];
} | Returns a parameter value in the specified array, if not in, returns the
first element instead
@param string $name The parameter name
@param array $array The array to be search
@return mixed The parameter value | entailment |
public function set($name, $value = null)
{
if (!is_array($name)) {
$this->data[$name] = $value;
} else {
foreach ($name as $key => $value) {
$this->data[$key] = $value;
}
}
return $this;
} | Set parameter value
@param string|array $name The parameter name or A key-value array
@param mixed $value The parameter value
@return $this | entailment |
public function has($name)
{
return isset($this->data[$name]) && !in_array($this->data[$name], ['', null, false, array()], true);
} | Check if the parameter has value
For example, 0, ' ', 0.0 are all have value
@param string $name
@return bool | entailment |
public function &offsetGet($offset)
{
if (!isset($this->data[$offset])) {
$this->extraKeys[$offset] = true;
}
return $this->data[$offset];
} | Get the offset value
@param string $offset
@return mixed | entailment |
public function offsetSet($offset, $value)
{
unset($this->extraKeys[$offset]);
return $this->data[$offset] = $value;
} | Set the offset value
@param string $offset
@param mixed $value
@return mixed | entailment |
public function getHost()
{
$host = $this->getServer('HTTP_HOST') ?: $this->getServer('SERVER_NAME') ?: $this->getServer('REMOTE_ADDR');
return preg_replace('/:\d+$/', '', $host);
} | Returns the request host
@return string | entailment |
public function getRequestUri()
{
if ($this->requestUri === null) {
$this->requestUri = $this->detectRequestUri();
}
return $this->requestUri;
} | Get the request URI.
@return string | entailment |
public function getBaseUrl()
{
if ($this->baseUrl === null) {
$this->setBaseUrl($this->detectBaseUrl());
}
return $this->baseUrl;
} | Get the base URL.
@return string | entailment |
public function getPathInfo()
{
if ($this->pathInfo === null) {
$this->pathInfo = $this->detectPathInfo();
}
return $this->pathInfo;
} | Return request path info
@return string | entailment |
public function getSchemeAndHost()
{
$port = $this->getServer('SERVER_PORT');
if ($port == 80 || $port == 443 || empty($port)) {
$port = '';
} else {
$port = ':' . $port;
}
return $this->getScheme() . '://' . $this->getHost() . $port;
} | Returns scheme and host which contains scheme://domain[:port]
@return string | entailment |
public function getIp($default = '0.0.0.0')
{
$ip = $this->getServer('HTTP_X_FORWARDED_FOR')
? current(explode(',', $this->getServer('HTTP_X_FORWARDED_FOR'))) : $this->getServer('HTTP_CLIENT_IP')
?: $this->getServer('REMOTE_ADDR');
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $default;
} | Returns the client IP address
If the IP could not receive from the server parameter, or the IP address
is not valid, return the $default value instead
@link http://en.wikipedia.org/wiki/X-Forwarded-For
@param string $default The default ip address
@return string | entailment |
public function getMethod()
{
if (null === $this->method) {
$this->method = $this->getServer('REQUEST_METHOD', 'GET');
}
return $this->method;
} | Returns the HTTP request method
@return string | entailment |
public function getContent()
{
if (null === $this->content && $this->fromGlobal) {
$this->content = file_get_contents('php://input');
}
return $this->content;
} | Returns the request message body
@return string | entailment |
public function getServer($name, $default = null)
{
return isset($this->servers[$name]) ? $this->servers[$name] : $default;
} | Return the server and execution environment parameter value ($_SERVER)
@param string $name The name of parameter
@param mixed $default The default parameter value if the parameter does not exist
@return mixed | entailment |
public function setServer($name, $value = null)
{
if (!is_array($name)) {
$this->servers[$name] = $value;
} else {
$this->servers = $name + $this->servers;
}
return $this;
} | Set the server and execution environment parameter value ($_SERVER)
@param string $name
@param string $value
@return $this | entailment |
public function getQuery($name, $default = null)
{
return isset($this->gets[$name]) ? $this->gets[$name] : $default;
} | Return the URL query parameter value ($_GET)
@param string $name The name of parameter
@param mixed $default The default parameter value if the parameter does not exist
@return mixed | entailment |
public function setQuery($name, $value = null)
{
if (!is_array($name)) {
$this->gets[$name] = $value;
} else {
$this->gets = $name + $this->gets;
}
return $this;
} | Set the URL query parameter value ($_GET)
@param string $name
@param string $value
@return $this | entailment |
public function getPost($name, $default = null)
{
return isset($this->posts[$name]) ? $this->posts[$name] : $default;
} | Return the HTTP request parameters value ($_POST)
@param string $name The name of parameter
@param mixed $default The default parameter value if the parameter does not exist
@return mixed | entailment |
public function setPost($name, $value = null)
{
if (!is_array($name)) {
$this->posts[$name] = $value;
} else {
$this->posts = $name + $this->posts;
}
} | Set the HTTP request parameters value ($_POST)
@param string $name
@param string $value
@return $this | entailment |
public function getHeaders()
{
$headers = array();
foreach ($this->servers as $name => $value) {
if (0 === strpos($name, 'HTTP_')) {
$headers[substr($name, 5)] = $value;
}
}
return $headers;
} | Returns the HTTP request headers
@return array | entailment |
protected function detectRequestUri()
{
$requestUri = null;
// Check this first so IIS will catch.
$httpXRewriteUrl = $this->getServer('HTTP_X_REWRITE_URL');
if ($httpXRewriteUrl !== null) {
$requestUri = $httpXRewriteUrl;
}
// Check for IIS 7.0 or later with ISAPI_Rewrite
$httpXOriginalUrl = $this->getServer('HTTP_X_ORIGINAL_URL');
if ($httpXOriginalUrl !== null) {
$requestUri = $httpXOriginalUrl;
}
// IIS7 with URL Rewrite: make sure we get the unencoded url
// (double slash problem).
$iisUrlRewritten = $this->getServer('IIS_WasUrlRewritten');
$unencodedUrl = $this->getServer('UNENCODED_URL', '');
if ('1' == $iisUrlRewritten && '' !== $unencodedUrl) {
return $unencodedUrl;
}
// HTTP proxy requests setup request URI with scheme and host [and port]
// + the URL path, only use URL path.
if (!$httpXRewriteUrl) {
$requestUri = $this->getServer('REQUEST_URI');
}
if ($requestUri !== null) {
return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
}
// IIS 5.0, PHP as CGI.
$origPathInfo = $this->getServer('ORIG_PATH_INFO');
if ($origPathInfo !== null) {
$queryString = $this->getServer('QUERY_STRING', '');
if ($queryString !== '') {
$origPathInfo .= '?' . $queryString;
}
return $origPathInfo;
}
return '/';
} | Detect the base URI for the request
Looks at a variety of criteria in order to attempt to autodetect a base
URI, including rewrite URIs, proxy URIs, etc.
@return string | entailment |
protected function detectPathInfo()
{
$uri = $this->getRequestUri();
$pathInfo = '/' . trim(substr($uri, strlen($this->getBaseUrl())), '/');
if (false !== $pos = strpos($pathInfo, '?')) {
$pathInfo = substr($pathInfo, 0, $pos);
}
return $pathInfo;
} | Detect the path info for the request
@return string | entailment |
protected function removeExtraKeys()
{
foreach ($this->extraKeys as $offset => $value) {
if ($this->data[$offset] === null) {
unset($this->data[$offset]);
}
}
$this->extraKeys = [];
} | Removes extra keys in data | entailment |
public function _click($element='this', $js=array(), $ret_false=TRUE) {
if (!is_array($js)) {
$js=array (
$js
);
}
if ($ret_false) {
$js[]="return false;";
}
return $this->_add_event($element, $js, 'click');
} | Outputs a jQuery click event
@param string $element The element to attach the event to
@param mixed $js The code to execute
@param boolean $ret_false whether or not to return false
@return string | entailment |
public function _hover($element='this', $over, $out) {
$event="\n\t$(".$this->_prep_element($element).").hover(\n\t\tfunction()\n\t\t{\n\t\t\t{$over}\n\t\t}, \n\t\tfunction()\n\t\t{\n\t\t\t{$out}\n\t\t});\n";
$this->jquery_code_for_compile[]=$event;
return $event;
} | Outputs a jQuery hover event
@param string - element
@param string - Javascript code for mouse over
@param string - Javascript code for mouse out
@return string | entailment |
public function toOptions($name)
{
$html = '';
foreach ($this->wei->getConfig($name) as $value => $text) {
if (is_array($text)) {
$html .= '<optgroup label="' . $value . '">';
foreach ($text as $v => $t) {
$html .= '<option value="' . $v . '">' . $t . '</option>';
}
$html .= '</optgroup>';
} else {
$html .= '<option value="' . $value . '">' . $text . '</option>';
}
}
return $html;
} | Convert configuration data to HTML select options
@param string $name The name of configuration item
@return string | entailment |
public function asLink($href=NULL) {
if (isset($href)) {
$this->wrap("<a href='" . $href . "'>", "</a>");
}
return $this->addToProperty("class", "link");
} | icon formatted as a link
@return \Ajax\semantic\html\HtmlIcon | entailment |
public function nextState( $currentState, $inputChar ) {
$initialState = $currentState;
while ( true ) {
$transitions =& $this->yesTransitions[$currentState];
if ( isset( $transitions[$inputChar] ) ) {
$nextState = $transitions[$inputChar];
// Avoid failure transitions next time.
if ( $currentState !== $initialState ) {
$this->yesTransitions[$initialState][$inputChar] = $nextState;
}
return $nextState;
}
if ( $currentState === 0 ) {
return 0;
}
$currentState = $this->noTransitions[$currentState];
}
// Unreachable outside 'while'
} | Map the current state and input character to the next state.
@param int $currentState The current state of the string-matching
automaton.
@param string $inputChar The character the string-matching
automaton is currently processing.
@return int The state the automaton should transition to. | entailment |
public function searchIn( $text ) {
if ( !$this->searchKeywords || $text === '' ) {
return []; // fast path
}
$state = 0;
$results = [];
$length = strlen( $text );
for ( $i = 0; $i < $length; $i++ ) {
$ch = $text[$i];
$state = $this->nextState( $state, $ch );
foreach ( $this->outputs[$state] as $match ) {
$offset = $i - $this->searchKeywords[$match] + 1;
$results[] = [ $offset, $match ];
}
}
return $results;
} | Locate the search keywords in some text.
@param string $text The string to search in.
@return array[] An array of matches. Each match is a vector
containing an integer offset and the matched keyword.
@par Example:
@code
$keywords = new MultiStringMatcher( array( 'ore', 'hell' ) );
$keywords->searchIn( 'She sells sea shells by the sea shore.' );
// result: array( array( 15, 'hell' ), array( 34, 'ore' ) )
@endcode | entailment |
protected function computeYesTransitions() {
$this->yesTransitions = [ [] ];
$this->outputs = [ [] ];
foreach ( $this->searchKeywords as $keyword => $length ) {
$state = 0;
for ( $i = 0; $i < $length; $i++ ) {
$ch = $keyword[$i];
if ( !empty( $this->yesTransitions[$state][$ch] ) ) {
$state = $this->yesTransitions[$state][$ch];
} else {
$this->yesTransitions[$state][$ch] = $this->numStates;
$this->yesTransitions[] = [];
$this->outputs[] = [];
$state = $this->numStates++;
}
}
$this->outputs[$state][] = $keyword;
}
} | Get the state transitions which the string-matching automaton
shall make as it advances through input text.
Constructs a directed tree with a root node which represents the
initial state of the string-matching automaton and from which a
path exists which spells out each search keyword. | entailment |
protected function computeNoTransitions() {
$queue = [];
$this->noTransitions = [];
foreach ( $this->yesTransitions[0] as $ch => $toState ) {
$queue[] = $toState;
$this->noTransitions[$toState] = 0;
}
while ( true ) {
$fromState = array_shift( $queue );
if ( $fromState === null ) {
break;
}
foreach ( $this->yesTransitions[$fromState] as $ch => $toState ) {
$queue[] = $toState;
$state = $this->noTransitions[$fromState];
while ( $state !== 0 && empty( $this->yesTransitions[$state][$ch] ) ) {
$state = $this->noTransitions[$state];
}
if ( isset( $this->yesTransitions[$state][$ch] ) ) {
$noState = $this->yesTransitions[$state][$ch];
} else {
$noState = 0;
}
$this->noTransitions[$toState] = $noState;
$this->outputs[$toState] = array_merge(
$this->outputs[$toState], $this->outputs[$noState] );
}
}
} | Get the state transitions which the string-matching automaton
shall make when a partial match proves false. | entailment |
protected function doValidate($input)
{
if ($this->required && $this->isInvalid($input)) {
$this->addError('required');
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function stopAndSave()
{
$this->codeCoverage->stop();
Storage::storeCodeCoverage(
$this->codeCoverage,
$this->storageDirectory,
uniqid(date('YmdHis'), true)
);
} | Stop collecting code coverage data and save it. | entailment |
public function toArray(): array
{
$result = [
'size' => $this->size,
'from' => $this->from,
];
if ($this->sort) {
$result['sort'] = $this->sort;
}
if ($this->source) {
$result['_source'] = $this->source;
}
return [
'top_hits' => $result,
];
} | Convert to array
@return array | entailment |
public function get(int $id, $params = [])
{
if ($this->fields) {
$params['fields'] = implode(',', $this->fields);
}
$uriAppend = 'byId/' . $id;
$response = $this->handler->handle('GET', false, $uriAppend, $params);
return $this->make($response, false);
} | Get entity by id
@param int $id
@param array $params
@return Entity
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function new($data)
{
$response = $this->handler->handle('POST', $data, 'new');
return $this->make($response, false);
} | @param $data
@return Entity
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function removeItems(array $params)
{
$response = $this->handler->handle('DELETE', $params);
return $this->make($response, false);
} | @param array $params
@return Entity
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function update($id, $data)
{
$response = $this->handler->handle('PUT', $data);
return $this->make($response, false);
} | @param $id
@param $data
@return Entity
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function copy($id)
{
$uriAppend = 'copy/' . $id;
$response = $this->handler->handle('POST', false, $uriAppend);
return $this->make($response, false);
} | @param $id
@return array|int|Entity|\SphereMall\MS\Lib\Collection|Order
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function detail(int $id)
{
$response = $this->handler->handle('GET', false, 'detail/' . $id);
return $this->make($response, false);
} | Detail dealer information
@param $id | entailment |
public function detailWithAddresses($id)
{
$dealer = $this->detail($id);
if ($dealer->dealersToAddresses) {
$addressesId = array_map(function($value) {
return $value['addressId'];
}, $dealer->dealersToAddresses);
$addresses = $this->client->addresses()
->ids(array_values($addressesId))
->all();
$dealer->addresses = $addresses;
}
return $dealer;
} | Detail dealer information with additional request to addresses
@param $id
@return Dealer
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function getEmailBy($criteria, $first)
{
$mailIds = $this->search($criteria);
if (!$mailIds) {
throw new \Exception(sprintf("No email found with given criteria %s", $criteria));
}
if ($first){
$mailId = reset($mailIds);
}else{
$mailId = end($mailIds);
}
$mail = $this->mailbox->getMail($mailId);
return $mail;
} | @param $criteria
@return IncomingMail
@throws \Exception | entailment |
public function getEmailsBy($criteria, $count)
{
$mails = [];
$mailIds = $this->search($criteria);
if (!$count) {
if (!$mailIds) {
throw new \Exception(sprintf("No email found with given criteria %s", $criteria));
}
}
foreach ($mailIds as $mailId) {
$mails[] = $this->mailbox->getMail($mailId);
}
return $mails;
} | @param $criteria
@return array
@throws \Exception | entailment |
protected function retry($criteria, $numberOfRetries, $waitInterval)
{
$mailIds = [];
while ($numberOfRetries > 0) {
sleep($waitInterval);
$mailIds = $this->mailbox->searchMailBox($criteria);
if (!empty($mailIds)) {
break;
}
$numberOfRetries--;
codecept_debug("Failed to find the email, retrying ... ({$numberOfRetries}) trie(s) left");
}
return $mailIds;
} | @param string $criteria
@param int $numberOfRetries
@param int $waitInterval
@return array | entailment |
protected function getResultFromResponse(Response $response)
{
$result = [];
foreach ($response->getData() as $element) {
$item = $this->getAttributes($element);
$item['type'] = $element['type'];
$result[] = new ElasticIndexer($item);
}
return $result;
} | @param Response $response
@return array
@throws EntityNotFoundException | entailment |
public function send($content = null, $status = null)
{
// Render json when content is array
if (is_array($content)) {
return $this->json($content)->send();
} elseif (null !== $content) {
$this->setContent($content);
}
if (null !== $status) {
$this->setStatusCode($status);
}
// Trigger the after send callback
$this->beforeSend && call_user_func($this->beforeSend, $this, $content);
$this->sendHeader();
$this->sendContent();
// Trigger the after send callback
$this->afterSend && call_user_func($this->afterSend, $this);
return $this;
} | Send response header and content
@param string $content
@param int $status
@return $this | entailment |
public function setStatusCode($code, $text = null)
{
$this->statusCode = (int)$code;
if ($text) {
$this->statusText = $text;
} elseif (isset($this->statusTexts[$code])) {
$this->statusText = $this->statusTexts[$code];
}
return $this;
} | Set the header status code
@param int $code The status code
@param string|null $text The status text
@return $this | entailment |
public function setHeader($name, $values = null, $replace = true)
{
if (is_array($name)) {
foreach ($name as $key => $value) {
$this->setHeader($key, $value);
}
return $this;
}
$values = (array)$values;
if (true === $replace || !isset($this->headers[$name])) {
$this->headers[$name] = $values;
} else {
$this->headers[$name] = array_merge($this->headers[$name], $values);
}
return $this;
} | Set the header string
@param string|array $name The header name or header array
@param string|array $values The header values
@param bool $replace Whether replace the exists values or not
@return $this | entailment |
public function getHeader($name, $default = null, $first = true)
{
if (!isset($this->headers[$name])) {
return $default;
}
if (is_array($this->headers[$name]) && $first) {
return current($this->headers[$name]);
}
return $this->headers[$name];
} | Get the header string
@param string $name The header name
@param mixed $default The default value
@param bool $first Return the first element or the whole header values
@return mixed | entailment |
public function sendHeader()
{
$file = $line = null;
if ($this->isHeaderSent($file, $line)) {
if ($this->wei->has('logger')) {
$this->logger->debug(sprintf('Header has been at %s:%s', $file, $line));
}
return false;
}
// Send status
$this->sendRawHeader(sprintf('HTTP/%s %d %s', $this->version, $this->statusCode, $this->statusText));
// Send headers
foreach ($this->headers as $name => $values) {
foreach ($values as $value) {
$this->sendRawHeader($name . ': ' . $value);
}
}
$this->sendCookie();
return true;
} | Send HTTP headers, including HTTP status, raw headers and cookies
@return bool If the header has been seen, return false, otherwise, return true | entailment |
protected function sendRawHeader($header)
{
$this->unitTest ? ($this->sentHeaders[] = $header) : header($header, false);
} | Send a raw HTTP header
If in unit test mode, the response will store header string into
`sentHeaders` property without send it for testing purpose
@param string $header | entailment |
public function isHeaderSent(&$file = null, &$line = null)
{
return $this->unitTest ? (bool)$this->sentHeaders : headers_sent($file, $line);
} | Checks if or where headers have been sent
If NOT in unit test mode and the optional `file` and `line` parameters
are set, `isHeaderSent()` will put the PHP source file name and line
number where output started in the file and line variables
@param string $file
@param int $line The line number where the output started
@return bool
@link http://php.net/manual/en/function.headers-sent.php | entailment |
public function getCookie($key, $default = null)
{
return isset($this->cookies[$key]) ? $this->cookies[$key]['value'] : $default;
} | Get response cookie
@param string $key The name of cookie
@param mixed $default The default value when cookie not exists
@return mixed | entailment |
public function setCookie($key, $value, array $options = array())
{
$this->cookies[$key] = array('value' => $value) + $options;
return $this;
} | Set response cookie
@param string $key The name of cookie
@param mixed $value The value of cookie
@param array $options The options of cookie
@return $this | entailment |
public function sendCookie()
{
$time = time();
// Anonymous function for unit test
$setCookie = function () {
};
foreach ($this->cookies as $name => $o) {
$o += $this->cookieOption;
$fn = $this->unitTest ? $setCookie : ($o['raw'] ? 'setrawcookie' : 'setcookie');
$fn($name, $o['value'], $time + $o['expires'], $o['path'], $o['domain'], $o['secure'], $o['httpOnly']);
}
return $this;
} | Send cookie
@return $this | entailment |
public function getHeaderString()
{
$string = '';
foreach ($this->headers as $name => $values) {
foreach ($values as $value) {
$string .= $name . ': ' . $value . "\r\n";
}
}
return $string;
} | Returns response header as string
@return string | entailment |
public function setRedirectView($redirectView)
{
if (!is_file($redirectView)) {
throw new \RuntimeException(sprintf('Redirect view file "%s" not found', $redirectView));
}
$this->redirectView = $redirectView;
return $this;
} | Set redirect view file
@param string $redirectView The view file
@return $this
@throws \RuntimeException When view file not found | entailment |
public function redirect($url = null, $statusCode = 302, $options = array())
{
$this->setStatusCode($statusCode);
$this->setOption($options);
// The variables for custom redirect view
$escapedUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
$wait = (int)$this->redirectWait;
// Location header does not support delay
if (0 === $wait) {
$this->setHeader('Location', $url);
}
// Prepare response content
if ($this->redirectView) {
ob_start();
require $this->redirectView;
$content = ob_get_clean();
} else {
$content = sprintf('<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="%d;url=%2$s">
<title>Redirecting to %s</title>
</head>
<body>
<h1>Redirecting to <a href="%2$s">%2$s</a></h1>
</body>
</html>', $wait, $escapedUrl);
}
return $this->setContent($content);
} | Send a redirect response
@param string $url The url redirect to
@param int $statusCode The response status code
@param array $options The redirect wei options
@return $this | entailment |
public function json($data, $jsonp = false)
{
$options = 0;
defined('JSON_UNESCAPED_UNICODE') && $options = JSON_UNESCAPED_UNICODE;
$content = json_encode($data, $options);
if ($jsonp && preg_match('/^[$A-Z_][0-9A-Z_$.]*$/i', $this->request['callback']) === 1) {
$this->setHeader('Content-Type', 'application/javascript');
$content = $this->request['callback'] . '(' . $content . ')';
} else {
$this->setHeader('Content-Type', 'application/json');
}
return $this->setContent($content);
} | Response JSON or JSONP format string
@param mixed $data The variable to be convert to JSON string
@param bool $jsonp Whether allow response json format on demand
@return $this | entailment |
public function flush($content = null)
{
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', '1');
}
/**
* Disable zlib to compress output
* @link http://www.php.net/manual/en/zlib.configuration.php
*/
if (!headers_sent() && extension_loaded('zlib')) {
ini_set('zlib.output_compression', '0');
}
/**
* Turn implicit flush on
* @link http://www.php.net/manual/en/function.ob-implicit-flush.php
*/
ob_implicit_flush();
$this->send($content);
/**
* Send blank characters for output_buffering
* @link http://www.php.net/manual/en/outcontrol.configuration.php
*/
if ($length = ini_get('output_buffering')) {
echo str_pad('', $length);
}
while (ob_get_level()) {
ob_end_flush();
}
return $this;
} | Flushes content to browser immediately
@param string $content
@return $this | entailment |
public function download($file = null, array $downloadOptions = array())
{
$o = $downloadOptions + $this->downloadOption;
if (!is_file($file)) {
throw new \RuntimeException('File not found', 404);
}
$name = $o['filename'] ? : basename($file);
$name = rawurlencode($name);
// For IE
$userAgent = $this->request->getServer('HTTP_USER_AGENT');
if (preg_match('/MSIE ([\w.]+)/', $userAgent)) {
$filename = '=' . $name;
} else {
$filename = "*=UTF-8''" . $name;
}
$this->setHeader(array(
'Content-Description' => 'File Transfer',
'Content-Type' => $o['type'],
'Content-Disposition' => $o['disposition'] . ';filename' . $filename,
'Content-Transfer-Encoding' => 'binary',
'Expires' => '0',
'Cache-Control' => 'must-revalidate',
'Pragma' => 'public',
'Content-Length' => filesize($file),
));
// Send headers
$this->send();
// Send file content
readfile($file);
return $this;
} | Send file download response
@param string $file The path of file
@param array $downloadOptions The download options
@return $this
@throws \RuntimeException When file not found | entailment |
public function loadConfiguration(): void
{
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('client'))
->setFactory(CurlClient::class);
} | Register services | entailment |
protected function doCreateObject(array $array)
{
$catalogItem = new CatalogItem($array);
$catalogItem->filterSettings = json_decode((string)$catalogItem->filterSettings, true);
return $catalogItem;
} | @param array $array
@return CatalogItem | entailment |
public function run(JsUtils $js) {
if($this->propertyContains("class", "simple")===false){
if(isset($this->_bsComponent)===false)
$this->_bsComponent=$js->semantic()->dropdown("#".$this->identifier,$this->_params);
$this->addEventsOnRun($js);
return $this->_bsComponent;
}
} | /*
(non-PHPdoc)
@see BaseHtml::run() | entailment |
public static function setHttPortToUrl(string $url, bool $https = null): string
{
if (preg_match("/([a-z0-9]{2,9})\:([0-9]+)/Ui", $url)) {
return $url;
}
$urlArray = explode(self::DELIMITER, $url);
$port = self::DEFAULT_PORT_HTTP;
if (($https === true || $urlArray[0] == 'https' || static::isSecure($https, $urlArray[0])) && $https !== false) {
$port = self::DEFAULT_PORT_HTTPS;
}
return $urlArray[0] . self::DELIMITER . static::addPort($urlArray[1], $port);
} | @param string $url
@param bool $https
@return string | entailment |
public static function addPort(string $url, int $port)
{
$url = explode('/', $url);
$url[0] .= ':' . $port;
return join('/', $url);
} | @param string $url
@param int $port
@return string | entailment |
public static function isSecure(bool $https = null, string $urlHttp): bool
{
return ($https === true || $urlHttp == 'https' || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') && $https !== false);
} | @param bool|null $https
@param string $urlHttp
@return bool | entailment |
public function release($key)
{
if ($this->cache->remove($key)) {
if (($index = array_search($key, $this->keys)) !== false) {
unset($this->keys[$index]);
}
return true;
} else {
return false;
}
} | Release a lock key
@param string $key
@return bool | entailment |
public function before($to, $element, $immediatly=false){
return $this->js->_genericCallElement('before',$to, $element, $immediatly);
} | Insert content, specified by the parameter, before each element in the set of matched elements
@param string $to
@param string $element
@param boolean $immediatly defers the execution if set to false
@return string | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.