sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getResponseCookie($name) { $cookies = $this->getResponseCookies(); return isset($cookies[$name]) ? $cookies[$name] : null; }
Returns the cookie value by specified name @param string $name @return string|null
entailment
protected function parseCookie($header) { $elements = explode(';', $header); $cookies = array(); $currentName = null; foreach ($elements as $element) { $pieces = explode('=', trim($element), 2); if (!isset($pieces[1])) { continue; } list($name, $value) = $pieces; if (strtolower($name) == 'expires' && strtotime($value) < time()) { // Removes expired cookie unset($cookies[$currentName]); } elseif (in_array(strtolower($name), array('domain', 'path', 'comment', 'expires', 'secure', 'max-age'))) { // Ignore cookie attribute continue; } else { $cookies[$name] = trim(urldecode($value)); $currentName = $name; } } return $cookies; }
Parse cookie from header, returns result like $_COOKIE @param string $header @return array
entailment
public function get($url, $data = array(), $dataType = null) { return $this->processMethod($url, $data, $dataType, 'GET'); }
Execute a GET method request @param string $url @param array $data @param string $dataType @return $this
entailment
public function post($url, $data = array(), $dataType = null) { return $this->processMethod($url, $data, $dataType, 'POST'); }
Execute a POST method request @param string $url @param array $data @param string $dataType @return $this
entailment
public function put($url, $data = array(), $dataType = null) { return $this->processMethod($url, $data, $dataType, 'PUT'); }
Execute a PUT method request @param string $url @param array $data @param string $dataType @return $this
entailment
public function delete($url, $data = array(), $dataType = null) { return $this->processMethod($url, $data, $dataType, 'DELETE'); }
Execute a DELETE method request @param string $url @param array $data @param string $dataType @return $this
entailment
public function patch($url, $data = array(), $dataType = null) { return $this->processMethod($url, $data, $dataType, 'PATCH'); }
Execute a PATCH method request @param string $url @param array $data @param string $dataType @return $this
entailment
protected function processMethod($url, $data, $dataType, $method) { return $this->__invoke(array( 'url' => $url, 'method' => $method, 'dataType' => $dataType, 'data' => $data )); }
Execute a specified method request @param string $url @param array $data @param string $dataType @param string $method @return $this
entailment
public function getCurlInfo($option = null) { return $option ? curl_getinfo($this->ch, $option) : curl_getinfo($this->ch); }
Get information from curl @param null|int $option @return array
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } $length = strlen($input); if ($this->minLength && $length < $this->minLength) { $this->addError('lengthTooShort'); return false; } if ($this->maxLength && $length > $this->maxLength) { $this->addError('lengthTooLong'); return false; } // Find out what kind of characters are missing $missing = array(); foreach ($this->regexMap as $type => $regex) { if (!preg_match('/[' . $regex . ']/', $input)) { $missing[$type] = true; } } $needTypes = array(); foreach (array('digit', 'letter', 'nonAlnum') as $type) { $propertyName = 'need' . ucfirst($type); if ($this->$propertyName && isset($missing[$type])) { $needTypes[] = $type; } } if (count($needTypes)) { $this->missingTypes = array_intersect_key($this->typeNames, array_flip($needTypes)); $this->addError('missingCharType'); return false; } if ($this->atLeastPresent) { unset($missing['letter']); // 'digit', 'lower', 'upper', 'nonAlnum' $total = 4; $remains = count($missing); $needPresent = $this->atLeastPresent - ($total - $remains); if ($needPresent > 0) { $this->missingTypes = array_intersect_key($this->typeNames, $missing); if (count($missing) == $needPresent) { $this->addError('missingCharType'); } else { $this->missingCount = $needPresent; $this->addError('missingChar'); } return false; } } return true; }
{@inheritdoc}
entailment
public function getMessages($name = null) { if ($this->missingTypes) { $this->loadTranslationMessages(); $types = array(); foreach ($this->missingTypes as $type) { $types[] = $this->t($type); } $this->missingType = implode(', ', $types); } return parent::getMessages($name); }
{@inheritdoc}
entailment
public function setOption($name, $value = null) { // Set options if (is_array($name)) { foreach ($name as $k => $v) { $this->setOption($k, $v); } return $this; } if (method_exists($this, $method = 'set' . $name)) { return $this->$method($value); } else { $this->$name = $value; return $this; } }
Set option property value @param string|array $name @param mixed $value @return $this
entailment
public function getOption($name) { if (method_exists($this, $method = 'get' . $name)) { return $this->$method(); } else { return isset($this->$name) ? $this->$name : null; } }
Returns the value of option @param string $name The name of property @return mixed
entailment
protected function doValidate($input) { is_string($input) && $input = strtolower($input); return parent::doValidate($input); }
{@inheritdoc}
entailment
public function sendRequest(string $method, string $path, $body = null, array $headers = []) { try { $request = $this->createRequest($method, $path, $body, $headers); $content = $this->doSendRequest($request); } catch (InvalidResponseException $e) { if (($e->getResponse()->getStatusCode() === 401 || $e->getResponse()->getStatusCode() === 403) && $this->cacheProxy->hasItem($this->cacheKey) ) { $this->resetApiToken(); $request = $this->createRequest($method, $path, $body, $headers); $content = $this->doSendRequest($request); } else { throw $e; } } return $content; }
Sends a request @param string $method @param string $path @param array|resource|string|StreamInterface|null $body @param array $headers @return mixed @throws TransferException @throws InvalidResponseException @throws AuthenficationException
entailment
private function createRequest( string $method, string $path, $data = null, array $headers = [], bool $withAuthorization = true ): RequestInterface { $uri = $this->baseUrl.'/'.$path; $body = null; if (in_array($method, $this->getQueryMethods())) { $query = is_array($data) ? http_build_query($data) : $data; if (is_string($query) && $query !== '') { $uri .= '?'.$query; } } else { $body = is_array($data) ? json_encode($data) : $data; } $baseHeaders = ['Content-Type' => 'application/json']; if ($withAuthorization) { $baseHeaders['Authorization'] = $this->getAuthorizationHeader(); } return $this->getMessageFactory()->createRequest($method, $uri, $headers + $baseHeaders, $body); }
@param string $method @param string $path @param null $body @param array $headers @param bool $withAuthorization @return RequestInterface
entailment
public function setWide($wide) { $wide=Wide::getConstants()["W" . $wide]; $this->addToPropertyCtrl("class", $wide, Wide::getConstants()); return $this->addToPropertyCtrl("class", "column", array ("column" )); }
Defines the grid width (alias for setWidth) @param int $wide
entailment
public function setColsCount($numCols, $toCreate=true, $width=NULL) { /*if (isset($width)==false) { $this->setWide($numCols); }*/ if ($toCreate == true) { $count=$this->count(); if ($count == 0 || $this->hasOnlyCols($count)) { for($i=$count; $i < $numCols; $i++) { $this->addItem(new HtmlGridCol("col-" . $this->identifier . "-" . $i, $width)); } } else { for($i=0; $i < $count; $i++) { $this->getItem($i)->setColsCount($numCols); } } } return $this; }
Defines the number of columns in the grid @param int $numCols @param boolean $toCreate @param int $width @return \Ajax\semantic\html\collections\HtmlGrid
entailment
public function getCell($row, $col) { if ($row < 2 && $this->hasOnlyCols($this->count())) return $this->getItem($col); $row=$this->getItem($row); if (isset($row)) { $col=$row->getItem($col); } return $col; }
Returns the cell (HtmlGridCol) at position rrow,$col @param int $row @param int $col @return \Ajax\semantic\html\collections\HtmlGridCol
entailment
public function setProperty(string $name, $value) { if (isset($this->properties[$name])) { $this->properties[$name] = $value; return true; } return false; }
Set value in $properties by name @see $properties @param string $name Property name @return bool True on success
entailment
public function get(string $name) { if (empty($name)) { return null; } if (isset($this->{$name})) { return $this->{$name}; } if (isset($this->properties[$name])) { return $this->properties[$name]; } return null; }
Get value by name from property of class or $properties (if class property don't exist) @see $properties @param string $name Property name @return null|mixed
entailment
public function set(string $name, $value) { if (empty($name)) { return false; } if (isset($this->{$name})) { $this->{$name} = $value; } else { $this->properties[$name] = $value; } return true; }
Set $value for class property or $properties (if class property don't exist) by $name Value will be overridden @param string $name Property name @param mixed $value Property value @return bool True on success
entailment
protected function buildUrl($path) { $path = str_replace('%2F', '/', $path); $path = str_replace(' ', '%20', $path); return rtrim($this->base, '/') . '/' . $path; }
Returns the URL to perform an HTTP request. @param string $path @return string
entailment
protected function head($path) { $defaults = stream_context_get_options(stream_context_get_default()); $options = $this->context; if ($this->supportsHead) { $options['http']['method'] = 'HEAD'; } stream_context_set_default($options); $headers = get_headers($this->buildUrl($path), 1); stream_context_set_default($defaults); if ($headers === false || strpos($headers[0], ' 200') === false) { return false; } return array_change_key_case($headers); }
Performs a HEAD request. @param string $path @return array|false
entailment
protected function parseMetadata($path, array $headers) { $metadata = [ 'path' => $path, 'visibility' => $this->visibility, 'mimetype' => $this->parseMimeType($path, $headers), ]; if (false !== $timestamp = $this->parseTimestamp($headers)) { $metadata['timestamp'] = $timestamp; } if (isset($headers['content-length']) && is_numeric($headers['content-length'])) { $metadata['size'] = (int) $headers['content-length']; } return $metadata; }
Parses metadata out of response headers. @param string $path @param array $headers @return array
entailment
protected function parseMimeType($path, array $headers) { if (isset($headers['content-type'])) { list($mimetype) = explode(';', $headers['content-type'], 2); return trim($mimetype); } // Remove any query strings or fragments. list($path) = explode('#', $path, 2); list($path) = explode('?', $path, 2); return MimeType::detectByFilename($path); }
Parses the mimetype out of response headers. @param string $path @param array $headers @return string
entailment
public function generate($url) { $time = time(); $query = parse_url($url, PHP_URL_QUERY); parse_str($query, $query); $query = $this->filterKeys($query, $this->params); $query['timestamp'] = $time; $signature = $this->generateToken($query); return $url . '&timestamp=' . $time . '&signature=' . $signature; }
Generate a URL with signature @param string $url @return string
entailment
public function verify() { // Check if time is expired $time = $this->request->getQuery('timestamp'); if ($this->expireTime && time() - $time > $this->expireTime) { return false; } // Remove signature parameters $query = $this->request->getParameterReference('get'); $token = $this->request->getQuery('signature'); unset($query['signature']); $timestamp = $query['timestamp']; $query = $this->filterKeys($query, $this->params); $query['timestamp'] = $timestamp; return $this->generateToken($query) == $token; }
Verify whether the URL signature is OK @return bool
entailment
public function searchAndReplace( $text ) { $state = 0; $length = strlen( $text ); $matches = []; 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; $matches[$offset] = $match; } } ksort( $matches ); $buf = ''; $lastInsert = 0; foreach ( $matches as $offset => $match ) { if ( $offset >= $lastInsert ) { $buf .= substr( $text, $lastInsert, $offset - $lastInsert ); $buf .= $this->replacePairs[$match]; $lastInsert = $offset + $this->searchKeywords[$match]; } } $buf .= substr( $text, $lastInsert ); return $buf; }
Search and replace a set of keywords in some text. @param string $text The string to search in. @return string The input text with replacements. @par Example: @code $replacer = new MultiStringReplacer( array( 'csh' => 'sea shells' ) ); $replacer->searchAndReplace( 'She sells csh by the sea shore.' ); // result: 'She sells sea shells by the sea shore.' @endcode
entailment
protected function processGetResult($key, $result, $expire, $fn) { if (false === $result && ($expire || $fn)) { // Avoid using null as expire second, for null will be convert to 0 // which means that store the cache forever, and make it hart to debug. if (!is_numeric($expire) && $fn) { throw new \InvalidArgumentException(sprintf( 'Expire time for cache "%s" must be numeric, %s given', $key, is_object($expire) ? get_class($expire) : gettype($expire) )); } // Example: get($key, function(){}); if ($expire && !$fn) { $fn = $expire; $expire = 0; } $result = call_user_func($fn, $this->wei, $this); $this->set($key, $result, $expire); } return $result; }
Store data to cache when data is not false and callback is provided @param string $key @param mixed $result @param int $expire @param callable $fn @throws \RuntimeException @throws \InvalidArgumentException @return mixed
entailment
public function getMulti(array $keys) { $results = array(); foreach ($keys as $key) { $results[$key] = $this->get($key); } return $results; }
Retrieve multiple items @param array $keys The name of items @return array
entailment
public function setMulti(array $keys, $expire = 0) { $results = array(); foreach ($keys as $key => $value) { $results[$key] = $this->set($key, $value, $expire); } return $results; }
Store multiple items @param array $keys The name of items @param int $expire @return array
entailment
public function getFileContent($file, $fn) { $key = $file . filemtime($file); return $this->get($key, function($wei, $cache) use ($file, $fn) { return $fn($file, $wei, $cache); }); }
Use the file modify time as cache key to store an item from a callback @param string $file The path of file @param callable $fn The callback to get and parse file content @return mixed
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } $checksum = $this->getChecksum(substr($input, 0, -1)); if ($checksum != substr($input, -1)) { return false; } return true; }
{@inheritdoc}
entailment
protected function getChecksum($string) { $checksum = ''; foreach (str_split(strrev($string)) as $i => $d) { $checksum .= ($i % 2 === 0) ? ($d * 2) : $d; } return (10 - array_sum(str_split($checksum)) % 10) % 10; }
Return the checksum char of luhn algorithm @param string $string @return string
entailment
public function toArray(): array { $result = [ $this->type => $this->script ? ['script' => $this->script] : array_merge(['field' => $this->field], $this->additionalParams), ]; if ($this->subAggregations) { $result['aggs'] = $this->subAggregations; } return $result; }
Convert to array @return array
entailment
public function start() { if (!session_id() || !$this->isActive()) { $file = $line = null; if (headers_sent($file, $line)) { throw new \RuntimeException(sprintf('Unable to start session, output started at %s:%s', $file, $line)); } session_start(); } if ($this->namespace) { if (!isset($_SESSION[$this->namespace])) { $_SESSION[$this->namespace] = array(); } $this->data = &$_SESSION[$this->namespace]; } else { $this->data = &$_SESSION; } }
Start session @throws \RuntimeException When header has been sent
entailment
public function setInis($inis) { foreach ($inis as $name => $value) { ini_set('session.' . $name, $value); } $this->inis = $inis + $this->inis; return $this; }
Set session configuration options @param array $inis @return $this
entailment
protected function isActive() { $setting = 'session.use_trans_sid'; $current = ini_get($setting); if (false === $current) { throw new \UnexpectedValueException(sprintf('Setting %s does not exists.', $setting)); } $result = @ini_set($setting, $current); return $result !== $current; }
Check if session is started For 5.4+, use session_status instead @return bool @link http://stackoverflow.com/questions/3788369/how-to-tell-if-a-session-is-active/7656468#7656468
entailment
public static function binToDec($bin, $length = 0) { $gmp = gmp_init($bin, 2); $dec = gmp_strval($gmp, 10); return self::pad($dec, $length); }
Converts binary string into decimal string. @param string $bin Binary string. @param int $length Minimum output length. @return string Decimal string.
entailment
public static function binToHex($bin, $length = 0) { $gmp = gmp_init($bin, 2); $hex = gmp_strval($gmp, 16); return self::pad($hex, $length); }
Converts binary string into hexadecimal string. @param string $bin Binary string. @param int $length Minimum output length. @return string Hexadecimal string.
entailment
public static function decToHex($dec, $length = 0) { $gmp = gmp_init($dec, 10); $hex = gmp_strval($gmp, 16); return self::pad($hex, $length); }
Converts decimal string into hexadecimal string. @param string $dec Decimal string. @param int $length Minimum output length. @return string Hexadecimal string.
entailment
public static function rawToBin($raw, $length = 0) { $gmp = gmp_import($raw); $bin = gmp_strval($gmp, 2); return self::pad($bin, $length); }
Converts stream of bytes into binary string. @param mixed $raw Stream of bytes. @param int $length Minimum output length. @return string Binary string.
entailment
public static function rawToDec($raw, $length = 0) { $gmp = gmp_import($raw); $dec = gmp_strval($gmp, 10); return self::pad($dec, $length); }
Converts stream of bytes into decimal string. @param mixed $raw Stream of bytes. @param int $length Minimum output length. @return string Decimal string.
entailment
public static function rawToHex($raw, $length = 0) { $gmp = gmp_import($raw); $hex = gmp_strval($gmp, 16); return self::pad($hex, $length); }
Converts stream of bytes into hexadecimal string. @param mixed $raw Stream of bytes. @param int $length Minimum output length. @return string Hex string.
entailment
public static function pad($input, $length = 0) { $input = ltrim($input, '0'); if ($input == '') { $input = '0'; } return str_pad($input, $length, '0', STR_PAD_LEFT); }
Pad left with zeroes to match given length. @param string $input @param int $length @return string
entailment
public function setDriver($driver) { $class = $this->wei->getClass($driver); if (!class_exists($class)) { throw new \InvalidArgumentException(sprintf('Cache driver class "%s" not found', $class)); } if (!is_subclass_of($class, 'Wei\BaseCache')) { throw new \InvalidArgumentException(sprintf('Cache driver class "%s" must extend "Wei\BaseCache"', $class)); } $this->driver = $driver; $this->object = $this->wei->get($driver); return $this; }
Set cache driver @param string $driver @return $this @throws \InvalidArgumentException
entailment
public function get($key, $expire = null, $fn = null) { $result = $this->object->get($key); return $this->processGetResult($key, $result, $expire, $fn); }
{@inheritdoc}
entailment
public function add($key, $value, $expire = 0) { return $this->object->add($key, $value, $expire); }
{@inheritdoc}
entailment
public function handle(Request $request, Closure $next) { // We must let the response get handled before naming the transaction, otherwise the necessary route i // information won't be available in the request object. $response = $next($request); $this->newRelic->nameTransaction($this->getTransactionName($request)); return $response; }
Handles the request by naming the transaction for New Relic @param Request $request @param Closure $next
entailment
public function getTransactionName(Request $request) { $route = $request->route(); if (is_array($route)) { // Try the assigned controller action if (isset($route[1]) && isset($route[1]['uses'])) { return $route[1]['uses']; } // Try named routes elseif (isset($route[1]) && isset($route[1]['as'])) { return $route[1]['as']; } } return 'index.php'; }
Builds the transaction name. It will return the assigned controller action first, then the route name before falling back to just "index.php" @param Request $request @return string
entailment
public function set($key, $value, $expire = 0) { $key = $this->namespace . $key; return $expire >= 0 ? apc_store($key, $value, $expire) : apc_delete($key); }
{@inheritdoc}
entailment
public function replace($key, $value, $expire = 0) { $key = $this->namespace . $key; if (apc_exists($key)) { return apc_store($key, $value, $expire); } else { return false; } }
{@inheritdoc}
entailment
public function incr($key, $offset = 1) { $key = $this->namespace . $key; $value = apc_inc($key, $offset, $success); if ($success) { return $value; } else { return apc_store($key, $offset) ? $offset : false; } }
{@inheritdoc}
entailment
public function isSatisfiedBy(User $user) { return $this->email === $user->email && password_verify($this->password, $user->password); }
@param User $user @return bool
entailment
public function subscribe(string $email, string $name = '') { $userList = $this->filter(new IsUserEmail($email))->limit(1)->all(); $user = $userList[0] ?? new User([ 'email' => $email, 'name' => $name, 'guid' => Guid::Generate(), 'isSubscriber' => 1, ]); if ((new IsUserSubscriber())->isSatisfiedBy($user)) { return null; } if ($user->id) { return $this->update($user->id, ['isSubscriber' => 1]); } return $this->create($user); }
Subscribe user @see $properties @param $email @param $name @return User|null @throws \SphereMall\MS\Exceptions\EntityNotFoundException
entailment
public function unsubscribe(string $guid) { $userList = $this->fields(['isSubscriber']) ->filter(['guid' => [FilterOperators::EQUAL => $guid]]) ->limit(1) ->all(); if (!isset($userList[0]) || !(new IsUserSubscriber())->isSatisfiedBy($userList[0])) { return null; } return $this->update($userList[0]->id, ['isSubscriber' => 0]); }
Unsubscribe user @see $properties @param $guid @return User|null @throws \SphereMall\MS\Exceptions\EntityNotFoundException
entailment
public function getWishList(int $userId) { $response = $this->handler->handle('GET', false, 'wishlist/' . $userId); return $this->make($response, true); }
@param int $userId @return WishListItem[] @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function install(array $options = null, OutputInterface $output = null) { return $this->call_command('install', $this->prepare_array_input_args($options), $output); }
Reads the composer.json file from the current directory, resolves the dependencies, and installs them: see https://getcomposer.org/doc/03-cli.md#install @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function search(array $search_terms, array $options = null, OutputInterface $output = null) { $arguments = array(); if (is_array($search_terms) && count($search_terms) > 0){ $arguments['packages'] = $search_terms; } if ($options = $this->prepare_array_input_args($options)){ $arguments += $options; } return $this->call_command('search', $arguments, $output); }
Search through the current project's package repositories: see https://getcomposer.org/doc/03-cli.md#search @param array $search_terms @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function show(array $options = null, OutputInterface $output = null) { return $this->call_command('show', $this->prepare_array_input_args($options), $output); }
Lists all installed packages: see https://getcomposer.org/doc/03-cli.md#show. E.g. $composer->show(array('--latest')) will show all packages with the respective latest version available @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function outdated(array $options = null, OutputInterface $output = null) { return $this->call_command('outdated', $this->prepare_array_input_args($options), $output); }
Shows a list of installed packages that have updates available, including their current and latest versions: see https://getcomposer.org/doc/03-cli.md#outdated E.g. $composer->outdated() will list only outdated packages while $composer->outdated(array('--all')) will list alle packages installed with the respective latest versions. @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function suggests(array $package_names = null, array $options = null, OutputInterface $output = null){ $arguments = array(); if (is_array($package_names) && count($package_names) > 0){ $arguments['packages'] = $package_names; } if ($options = $this->prepare_array_input_args($options)){ $arguments += $options; } return $this->call_command('suggests', $arguments, $output); }
Lists all packages suggested by currently installed set of packages: see https://getcomposer.org/doc/03-cli.md#suggests. E.g. $composer->suggests(array('monolog/monolog', 'slim/slim'), array('--by-package')) will show packages suggested by monolog and Slim grouped by package @param array $package_names @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function depends($package_name, $version = null, array $options = null, OutputInterface $output = null){ $arguments = array(); $arguments['package'] = $package_name; if (!is_null($version)){ $arguments['constraint'] = $version; } if ($options = $this->prepare_array_input_args($options)){ $arguments += $options; } return $this->call_command('depends', $arguments, $output); }
Tells you which other packages depend on a certain package: see https://getcomposer.org/doc/03-cli.md#depends. E.g. $composer->depends('doctrine/lexer', array('--tree')) will show packages, that require the doctrine lexer with all subrequirements in the form of a tree. @param string $package_name @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function validate(array $options = null, OutputInterface $output = null) { return $this->call_command('validate', $this->prepare_array_input_args($options), $output); }
Validates the composer.json file: see https://getcomposer.org/doc/03-cli.md#validate @param array $options @param OutputInterface $output @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function config($setting_key, array $setting_values, array $options = null, OutputInterface $output = null){ $arguments = array(); if ($options = $this->prepare_array_input_args($options)){ $arguments += $options; } if ($setting_key != ''){ $arguments['setting-key'] = $setting_key; } else { throw new \InvalidArgumentException('Invalid setting key "' . $setting_key . '"!'); } if (is_array($setting_values) && count($setting_values) > 0){ $arguments['setting-value'] = $setting_values; } return $this->call_command('config', $arguments, $output); }
Edits config settings and repositories in either the composer.json file: see https://getcomposer.org/doc/03-cli.md#config @param string $setting_key @param array $setting_values @param array $options @param OutputInterface $output @throws \InvalidArgumentException @return \Symfony\Component\Console\Output\OutputInterface
entailment
public function getElement($index) { if (is_int($index)) return $this->content[$index]; else { $elm=$this->getElementById($index, $this->content); return $elm; } }
Return the element at index @param int $index @return HtmlButton
entailment
protected function saveFile($uploadedFile) { $ext = $this->getExt(); $fullExt = $ext ? '.' . $ext : ''; if ($this->fileName) { $fileName = $this->fileName; } else { $fileName = substr($uploadedFile['name'], 0, strlen($uploadedFile['name']) - strlen($fullExt)); } $this->file = $this->dir . '/' . $fileName . $fullExt; if (!$this->overwrite) { $i = 1; while(is_file($this->file)) { $this->file = $this->dir . '/' . $fileName . '-' . $i . $fullExt; $i++; } } if (!$this->moveUploadedFile($uploadedFile['tmp_name'], $this->file)) { $this->addError('cantMove'); return false; } return true; }
Save uploaded file to upload directory @param array $uploadedFile @return boolean
entailment
public function setDir($dir) { $dir = rtrim($dir, '/'); if (!is_dir($dir)) { mkdir($dir, 0700, true); } $this->dir = $dir; return $this; }
Set upload directory @param string $dir @return $this
entailment
protected function getIniSize($name) { $size = ini_get($name); return is_numeric($size) ? $this->fromBytes($size) : $size; }
Returns a human readable file size (e.g. 1.2MB, 10KB), which recive from the ini configuration @param string $name The name of ini configuration @return string
entailment
protected function moveUploadedFile($from, $to) { return $this->unitTest ? copy($from, $to) : @move_uploaded_file($from, $to); }
Moves an uploaded file to a new location, if $this->unitTest is enable, it will use `copy` function instead @param string $from The uploaded file name @param string $to The destination of the moved file. @return bool
entailment
private function getName($value) { if (is_object($value)) { return get_class($value); } if (is_array($value)) { return $this->getArrayName(); } return $this->getScalarName($value); }
@param $value @return string
entailment
private function getScalarName($value) { if (is_bool($value)) { return $value ? 'true' : 'false'; } if ($value === null) { return 'null'; } if (is_string($value)) { return "'{$value}'"; } if (is_int($value)) { return $value; } $name = sprintf('(%s) %s', gettype($value), (string) $value); return $name; }
@param $value @return string
entailment
public function isSatisfiedBy(Entity $entity) { if (property_exists($entity, 'active')) { return (bool)$entity->active; } throw new InvalidArgumentException("Property 'active' does not exist in class " . get_class($entity)); }
@param Entity $entity @return bool
entailment
public static function create($handle, $name = '', $url = '') { $result = new static(); $result->handle = (string) $handle; $result->name = (string) $name; $result->url = (string) $url; $result->latestVersion = null; $result->createdOn = new DateTime(); return $result; }
@param string $handle @param string $name @param string $url @return static
entailment
public function getDisplayName() { if ($this->name !== '') { $result = $this->name; } else { $result = ''; $string = trim($this->handle, '_-'); $segments = preg_split('/[_-]+/', $string); foreach ($segments as $segment) { if ($segment !== '') { $len = mb_strlen($segment); if ($len === 1) { $segment = mb_strtoupper($segment); } else { $segment = mb_strtoupper(mb_substr($segment, 0, 1)) . mb_substr($segment, 1); } if ($result === '') { $result = $segment; } else { $result .= ' ' . $segment; } } } if ($result === '') { $result = $this->handle; } } return $result; }
Get the package display name. @return string
entailment
public function getSortedProductionVersions($descending = false) { $versions = []; foreach ($this->getVersions() as $v) { if (strpos($v->getVersion(), Package\Version::DEV_PREFIX) !== 0) { $versions[] = $v; } } usort($versions, function (Package\Version $a, Package\Version $b) use ($descending) { return version_compare($a->getVersion(), $b->getVersion()) * ($descending ? -1 : 1); }); return $versions; }
Get the production versions, sorted in ascending or descending order. @param bool $descending @return \CommunityTranslation\Entity\Package\Version[]
entailment
public function getSortedVersions($descending = false, $developmentVersionsFirst = null) { if ($developmentVersionsFirst === null) { $versionComparer = new VersionComparer(); $result = $versionComparer->sortPackageVersionEntities($this->getVersions()->toArray(), $descending); } else { $devVersions = $this->getSortedDevelopmentVersions($descending); $prodVersions = $this->getSortedProductionVersions($descending); if ($developmentVersionsFirst) { $result = array_merge($devVersions, $prodVersions); } else { $result = array_merge($prodVersions, $devVersions); } } return $result; }
Get the versions, sorted in ascending or descending order, with development or production versions first. @param bool $descending @param bool|null $developmentVersionsFirst If null, development versions are placed among the production versions @return Package\Version[]
entailment
public function isValidControllerTask($method, $parameters = []) { $result = false; if (parent::isValidControllerTask($method, $parameters)) { if ($this->isControllerTaskInstanceSpecific($method)) { $bID = array_pop($parameters); if ((is_string($bID) && is_numeric($bID)) || is_int($bID)) { if ($this->bID == $bID) { $result = true; } } } else { $result = true; } } return $result; }
{@inheritdoc} @see CoreBlockController::isValidControllerTask()
entailment
public function getBlockActionURL(BlockView $view, $task) { $actionArguments = func_get_args(); array_shift($actionArguments); $result = call_user_func_array([$view, 'action'], $actionArguments); if ($this->bID && $result instanceof UrlImmutable && !$this->isControllerTaskInstanceSpecific("action_$task")) { $pathParts = $result->getPath()->toArray(); /* @var \Concrete\Core\Url\Components\Path $pathParts */ if (array_pop($pathParts) == $this->bID) { $result = $result->setPath($pathParts); } } return $result; }
Creates a URL that can be posted or navigated to that, when done so, will automatically run the corresponding method inside the block's controller. <code> <a href="<?= $controller->getBlockActionURL($view, 'get_results') ?>">Get the results</a> </code>. @param string $task @return string $url
entailment
public function validate($args) { $check = $this->normalizeArgs(is_array($args) ? $args : []); return is_array($check) ? true : $check; }
{@inheritdoc} @see CoreBlockController::validate()
entailment
public function save($args) { $normalized = $this->normalizeArgs(is_array($args) ? $args : []); if (!is_array($normalized)) { throw new Exception(implode("\n", $normalized->getList())); } parent::save($normalized); }
{@inheritdoc} @see CoreBlockController::save()
entailment
public function get($key = null, $default = null) { return isset($this->entries[$key]) ? $this->entries[$key] : $default; }
Get a key's value from the cache. @param string $key @param mixed $default @return mixed
entailment
public function expired() { // Update if empty if (empty($this->entries)) { return true; } // Check timestamps if ($this->timestampManager) { return $this->timestampManager->check($this->getTimestamp()); } return false; }
Check if cached as expired. @return bool
entailment
public function save() { // Update time - now $updated = time(); // Update timestamp $this->entries[$this->timestampKey] = $updated; // Update timestamp manager if ($this->timestampManager) { $this->timestampManager->update($updated); } return (bool) file_put_contents($this->path, json_encode($this->entries)); }
Save to cache. @return bool
entailment
public function validateFile(FileReport $report) { $file = $report->getFile()->getRealPath(); if (empty($file)) { return false; } $domDoc = new \DOMDocument(); $loaded = $domDoc->load($file, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_PEDANTIC); if (false === $loaded) { return false; } $validation = $this->getSchemaValidationFile($domDoc); if (false === $validation) { return true; } $validationSource = $this->getSchemaValidationSource($validation, $report); if (false === $validationSource) { return false; } libxml_clear_errors(); if (true !== $domDoc->schemaValidateSource($validationSource)) { $errors = libxml_get_errors(); foreach ($this->formatter->formatErrors($errors) as $problem) { $report->reportProblem($problem); } return false; } return true; }
{@inheritdoc}
entailment
private function getSchemaValidationSource($filename, $report) { if ((0 === preg_match('/^(http|https|ftp):/i', $filename))) { if (false === file_exists($filename)) { $filename = $report->getFile()->getPath() . '/' . $filename; } if (!is_readable($filename)) { $report->reportProblem('unable to validate, schema file is not readable: ' . $filename); return false; } } if (isset($this->cache[$filename])) { return $this->cache[$filename]; } $validationSource = @file_get_contents($filename); if (false === $validationSource) { $report->reportProblem('unable to load schema file from: ' . $filename); return false; } if (empty($validationSource)) { $report->reportProblem(sprintf('xsd validation file is empty ("%s").', $filename)); return false; } return $this->cache[$filename] = $validationSource; }
@param string $filename @param FileReport $report @return bool|string
entailment
private function getSchemaValidationFile(\DOMDocument $document) { $firstChild = $this->getFirstChild($document); // @codeCoverageIgnoreStart if (false === $firstChild) { return false; } // @codeCoverageIgnoreEnd $attribute = $firstChild->getAttribute('xsi:noNamespaceSchemaLocation'); if (empty($attribute)) { return false; } return $attribute; }
@param \DOMDocument $document @return bool|string
entailment
private function getFirstChild(\DOMDocument $document) { foreach ($document->childNodes as $child) { if ($child instanceof \DOMElement) { return $child; // @codeCoverageIgnoreStart } } return false; // @codeCoverageIgnoreEnd }
@param \DOMDocument $document @return bool|\DOMElement
entailment
public function importDirectory($directory, $packageHandle, $packageVersion, $basePlacesDirectory) { $parsed = $this->parser->parseDirectory($packageHandle, $packageVersion, $directory, $basePlacesDirectory, ParserInterface::DICTIONARY_NONE); $translations = $parsed ? $parsed->getSourceStrings() : null; if ($translations === null) { $translations = new Translations(); $translations->setLanguage($this->app->make('community_translation/sourceLocale')); } return $this->importTranslations($translations, $packageHandle, $packageVersion); }
Parse a directory and extract the translatable strings, and import them into the database. @param string $directory @param string $packageHandle @param string $packageVersion @param string $basePlacesDirectory @throws UserMessageException @return bool returns true if some translatable strings changed, false otherwise
entailment
private function buildInsertTranslatablePlacesSQL(PackageVersionEntity $packageVersion, $numRecords) { $fields = '(packageVersion, translatable, locations, comments, sort)'; $values = '(' . $packageVersion->getID() . ', ?, ?, ?, ?),'; $sql = 'INSERT INTO CommunityTranslationTranslatablePlaces '; $sql .= ' ' . $fields; $sql .= ' VALUES ' . rtrim(str_repeat($values, $numRecords), ','); return $sql; }
@param int $packageVersionID @param int $numRecords @return string
entailment
public function importTranslations(Translations $translations, $packageHandle, $packageVersion) { $packageRepo = $this->app->make(PackageRepository::class); $someStringChanged = false; $numStringsAdded = 0; $connection = $this->em->getConnection(); $connection->beginTransaction(); try { $package = $packageRepo->findOneBy(['handle' => $packageHandle]); if ($package === null) { $package = PackageEntity::create($packageHandle); $this->em->persist($package); $this->em->flush($package); } $version = null; $packageIsNew = true; foreach ($package->getVersions() as $pv) { $packageIsNew = false; if (version_compare($pv->getVersion(), $packageVersion) === 0) { $version = $pv; break; } } if ($version === null) { $packageVersionIsNew = true; $version = PackageVersionEntity::create($package, $packageVersion); $this->em->persist($version); $this->em->flush($version); } else { $packageVersionIsNew = false; } $searchHash = $connection->prepare('SELECT id FROM CommunityTranslationTranslatables WHERE hash = ? LIMIT 1')->getWrappedStatement(); /* @var \Concrete\Core\Database\Driver\PDOStatement $searchHash */ $insertTranslatable = $connection->prepare('INSERT INTO CommunityTranslationTranslatables SET hash = ?, context = ?, text = ?, plural = ?')->getWrappedStatement(); /* @var \Concrete\Core\Database\Driver\PDOStatement $insertTranslatable */ $insertPlaces = $connection->prepare($this->buildInsertTranslatablePlacesSQL($version, self::IMPORT_BATCH_SIZE))->getWrappedStatement(); /* @var \Concrete\Core\Database\Driver\PDOStatement $insertPlaces */ if ($packageVersionIsNew) { $prevHash = null; } else { $prevHash = (string) $connection->fetchColumn( 'select md5(group_concat(translatable)) from CommunityTranslationTranslatablePlaces where packageVersion = ? order by translatable', [$version->getID()] ); $connection->executeQuery( 'delete from CommunityTranslationTranslatablePlaces where packageVersion = ?', [$version->getID()] ); } $insertPlacesParams = []; $insertPlacesCount = 0; $importCount = 0; foreach ($translations as $translationKey => $translation) { /* @var \Gettext\Translation $translation */ $plural = $translation->getPlural(); $hash = md5(($plural === '') ? $translationKey : "$translationKey\005$plural"); $searchHash->execute([$hash]); $translatableID = $searchHash->fetchColumn(0); $searchHash->closeCursor(); if ($translatableID === false) { $insertTranslatable->execute([ $hash, $translation->getContext(), $translation->getOriginal(), $plural, ]); $translatableID = (int) $connection->lastInsertId(); $someStringChanged = true; ++$numStringsAdded; } else { $translatableID = (int) $translatableID; } // translatable $insertPlacesParams[] = $translatableID; // locations $locations = []; foreach ($translation->getReferences() as $tr) { $locations[] = isset($tr[1]) ? implode(':', $tr) : $tr[0]; } $insertPlacesParams[] = serialize($locations); // comments $insertPlacesParams[] = serialize($translation->getExtractedComments()); // sort $insertPlacesParams[] = $importCount; ++$insertPlacesCount; if ($insertPlacesCount === self::IMPORT_BATCH_SIZE) { $insertPlaces->execute($insertPlacesParams); $insertPlacesParams = []; $insertPlacesCount = 0; } ++$importCount; } if ($insertPlacesCount > 0) { $connection->executeQuery( $this->buildInsertTranslatablePlacesSQL($version, $insertPlacesCount), $insertPlacesParams ); } if ($someStringChanged === false && !$packageVersionIsNew) { $newHash = (string) $connection->fetchColumn( 'select md5(group_concat(translatable)) from CommunityTranslationTranslatablePlaces where packageVersion = ? order by translatable', [$version->getID()] ); if ($newHash !== $prevHash) { $someStringChanged = true; } } if ($someStringChanged) { $version->setUpdatedOn(new DateTime()); $this->em->persist($version); $this->em->flush($version); $this->em->clear(TranslatableEntity::class); } $connection->commit(); } catch (Exception $x) { try { $connection->rollBack(); } catch (Exception $foo) { } throw $x; } if ($someStringChanged) { try { $this->events->dispatch( 'community_translation.translatableUpdated', new GenericEvent( $version, [ 'packageIsNew' => $packageIsNew, 'numStringsAdded' => $numStringsAdded, ] ) ); } catch (Exception $foo) { } } return $someStringChanged; }
Import translatable strings into the database. This function works directly with the database, not with entities (so that working on thousands of strings requires seconds instead of minutes). This implies that entities related to Translatable may become invalid. @param Translations $translations The strings to be imported @param string $packageHandle The package handle @param string $packageVersion The package version @throws UserMessageException @return bool returns true if some translatable strings changed, false otherwise
entailment
public function validateFile(FileReport $report) { $status = true; foreach ($this->collection as $validation) { $status = $validation->validateFile($report) && $status; } return $status; }
{@inheritdoc}
entailment
public function sortPackageVersionEntities($packageVersions, $descending = false) { $keys = []; foreach ($packageVersions as $pv) { $keys[$pv->getVersion()] = $pv; } $sortedKeys = $this->sortPackageVersions(array_keys($keys), $descending); $result = []; foreach ($sortedKeys as $sortedKey) { $result[] = $keys[$sortedKey]; } return $result; }
Sort a list of package version entities. @param \CommunityTranslation\Entity\Package\Version[] $packageVersions @param bool $descending @return \CommunityTranslation\Entity\Package\Version[]
entailment
public function sortPackageVersions($packageVersions, $descending = false) { usort($packageVersions, function ($a, $b) use ($descending) { $aIsDev = (strpos($a, PackageVersionEntity::DEV_PREFIX) === 0); $aVer = $aIsDev ? substr($a, strlen(PackageVersionEntity::DEV_PREFIX)) : $a; $m = null; while (preg_match('/^(\.)\.0+$/', $aVer, $m)) { $aVer = $m[1]; } if ($aIsDev) { $aVer .= str_repeat('.' . PHP_INT_MAX, 5); } $bIsDev = (strpos($b, PackageVersionEntity::DEV_PREFIX) === 0); $bVer = $bIsDev ? substr($b, strlen(PackageVersionEntity::DEV_PREFIX)) : $b; while (preg_match('/^(\.)\.0+$/', $bVer, $m)) { $bVer = $m[1]; } if ($bIsDev) { $bVer .= str_repeat('.' . PHP_INT_MAX, 5); } return version_compare($aVer, $bVer) * ($descending ? -1 : 1); }); return $packageVersions; }
Sort a list of package version entities. @param string[] $packageVersions @param bool $descending @return string[]
entailment
public function matchPackageVersionEntities($availableVersions, $wantedVersion) { if (empty($availableVersions)) { $result = null; } else { $keys = []; foreach ($availableVersions as $pv) { $keys[$pv->getVersion()] = $pv; } $bestKey = $this->matchPackageVersions(array_keys($keys), $wantedVersion); $result = $keys[$bestKey]; } return $result; }
Guess the best package version entity corresponding to a list of entity instances. @param \CommunityTranslation\Entity\Package\Version[] $availableVersions @param string $wantedVersion @return \CommunityTranslation\Entity\Package\Version|null Returns null if $availableVersions is empty, an entity instance otherwise
entailment
public function matchPackageVersions($availableVersions, $wantedVersion) { $m = null; if (preg_match('/^(\d+(?:\.\d+)*)(?:dev|alpha|a|beta|b|rc)/i', $wantedVersion, $m)) { $wantedVersionBase = $m[1]; } else { $wantedVersionBase = $wantedVersion; } $wantedVersionComparable = preg_replace('/^(.*?\d)(\.0+)+$/', '\1', $wantedVersionBase); $result = null; $availableVersions = $this->sortPackageVersions($availableVersions, false); foreach ($availableVersions as $availableVersion) { if ($result === null) { $result = $availableVersion; } if (strpos($availableVersion, PackageVersionEntity::DEV_PREFIX) === 0) { $availableVersionBase = substr($availableVersion, strlen(PackageVersionEntity::DEV_PREFIX)); $availableVersionIsDev = true; } else { $availableVersionBase = $availableVersion; $availableVersionIsDev = false; } $availableVersionComparable = preg_replace('/^(.*?\d)(\.0+)+$/', '\1', $availableVersionBase); if ($availableVersionIsDev) { $availableVersionIsDev .= str_repeat('.' . PHP_INT_MAX, 6); } $cmp = version_compare($availableVersionComparable, $wantedVersionComparable); if ($cmp > 0) { if ($availableVersionIsDev && strpos($availableVersionBase . '.', $wantedVersionBase . '.') === 0) { $result = $availableVersion; } break; } $result = $availableVersion; if ($cmp === 0) { break; } } return $result; }
Guess the best package version entity corresponding to a list of versions. @param string[] $availableVersions @param string $wantedVersion @return string|null Returns null if $availableVersions is empty, a version otherwise
entailment
public static function create(UserEntity $user, Package $package, $notifyNewVersions = false, DateTime $sendNotificationsAfter = null) { $result = new static(); $result->user = $user; $result->package = $package; $result->notifyNewVersions = $notifyNewVersions ? true : false; $result->sendNotificationsAfter = $sendNotificationsAfter === null ? new DateTime() : null; return $result; }
@param UserEntity $user User associated to this subscription @param Package $package package associated to this subscription @param bool $notifyNewVersions Send notifications about new package versions? @param DateTime|null $sendNotificationsAfter Send notifications for events after this date/time (if null: current date/time) @return static
entailment
public function fromPot(Translations $pot, LocaleEntity $locale) { $cn = $this->app->make(EntityManager::class)->getConnection(); $po = clone $pot; $po->setLanguage($locale->getID()); $numPlurals = $locale->getPluralCount(); $searchQuery = $cn->prepare(' select CommunityTranslationTranslations.* from CommunityTranslationTranslatables inner join CommunityTranslationTranslations on CommunityTranslationTranslatables.id = CommunityTranslationTranslations.translatable where CommunityTranslationTranslations.locale = ' . $cn->quote($locale->getID()) . ' and CommunityTranslationTranslations.current = 1 and CommunityTranslationTranslatables.hash = ? limit 1 ')->getWrappedStatement(); foreach ($po as $translationKey => $translation) { $plural = $translation->getPlural(); $hash = md5(($plural === '') ? $translationKey : "$translationKey\005$plural"); $searchQuery->execute([$hash]); $row = $searchQuery->fetch(); $searchQuery->closeCursor(); if ($row !== false) { $translation->setTranslation($row['text0']); if ($plural !== '') { switch ($numPlurals) { case 6: $translation->setPluralTranslation($row['text5'], 4); /* @noinspection PhpMissingBreakStatementInspection */ case 5: $translation->setPluralTranslation($row['text4'], 3); /* @noinspection PhpMissingBreakStatementInspection */ case 4: $translation->setPluralTranslation($row['text3'], 2); /* @noinspection PhpMissingBreakStatementInspection */ case 3: $translation->setPluralTranslation($row['text2'], 1); /* @noinspection PhpMissingBreakStatementInspection */ case 2: $translation->setPluralTranslation($row['text1'], 0); /* @noinspection PhpMissingBreakStatementInspection */ break; } } } } return $po; }
Fill in the translations for a specific locale. @param Translations $translations @param LocaleEntity $locale @return Translations
entailment
protected function getBaseSelectString(LocaleEntity $locale, $withPlaces, $excludeUntranslatedStrings) { $cn = $this->app->make(EntityManager::class)->getConnection(); $queryLocaleID = $cn->quote($locale->getID()); $result = ' select CommunityTranslationTranslatables.id, CommunityTranslationTranslatables.context, CommunityTranslationTranslatables.text, CommunityTranslationTranslatables.plural, '; if ($withPlaces) { $result .= ' CommunityTranslationTranslatablePlaces.locations, CommunityTranslationTranslatablePlaces.comments, '; } else { $result .= " 'a:0:{}' as locations, 'a:0:{}' as comments, "; } $result .= ' CommunityTranslationTranslations.approved, CommunityTranslationTranslations.text0, CommunityTranslationTranslations.text1, CommunityTranslationTranslations.text2, CommunityTranslationTranslations.text3, CommunityTranslationTranslations.text4, CommunityTranslationTranslations.text5 from CommunityTranslationTranslatables '; if ($withPlaces) { $result .= ' inner join CommunityTranslationTranslatablePlaces on CommunityTranslationTranslatables.id = CommunityTranslationTranslatablePlaces.translatable '; } $result .= ($excludeUntranslatedStrings ? 'inner join' : 'left join') . " CommunityTranslationTranslations on CommunityTranslationTranslatables.id = CommunityTranslationTranslations.translatable and 1 = CommunityTranslationTranslations.current and $queryLocaleID = CommunityTranslationTranslations.locale " ; return $result; }
Builds the base select query string to retrieve some translatable/translated strings. @param LocaleEntity $locale @param bool $withPlaces @param bool $excludeUntranslatedStrings @return string
entailment