sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function send(Message $message, $async = false, $ipPool = NULL, $sendAt = NULL){
return $this->request('send', array(
'message' => $message->toArray(),
'async' => $async,
'ip_pool' => $ipPool,
'send_at' => $sendAt
));
} | Send a message
@param Message $message
@param bool $async set to true to enable asynchronous sending
@param string $ipPool optional name of the ip pool which should be used to send the message
@param string $sendAt optional UTC timestamp (YYY-MM-DD HH:MM:SS) at which the message should be sent
@return array
@link https://mandrillapp.com/api/docs/messages.JSON.html#method=send | entailment |
public function sendTemplate($templateName, Message $message, array $templateContent = array(), $async = false, $ipPool = NULL, $sendAt = NULL){
if(!sizeof($templateContent)){
$templateContent = array(''); // Mandrill will not accept an empty array for template_content, but it does not require any actual content.
}
return $this->request('send-template', array(
'template_name' => $templateName,
'template_content'=> $templateContent,
'message' => $message->toArray(),
'async' => $async,
'ip_pool' => $ipPool,
'send_at' => $sendAt
));
} | Send a new transactional message through Mandrill using a template
@param string $templateName the immutable name or slug of a template that exists in the user's account
@param Message $message
@param array $templateContent array(array('name' => 'example_name', 'content' => 'example_content'))
@param bool $async set to true to enable asynchronous sending
@param string $ipPool optional name of the ip pool which should be used to send the message
@param string $sendAt optional UTC timestamp (YYY-MM-DD HH:MM:SS) at which the message should be sent
@return array
@link https://mandrillapp.com/api/docs/messages.JSON.html#method=send-template | entailment |
public function search($query = '*', $dateFrom = NULL, $dateTo = NULL, array $tags = array(), array $senders = array(), array $apiKeys = array(), $limit = 100) {
return $this->request('search', array(
'query' => $query,
'date_from' => $dateFrom,
'date_to' => $dateTo,
'tags' => $tags,
'senders' => $senders,
'api_keys' => $apiKeys,
'limit' => $limit
));
} | Search the content of recently sent messages and optionally narrow by date range, tags and senders
@param string $query the search terms to find matching messages for
@param string $dateFrom start date YYYY-MM-DD
@param string $dateTo end date
@param array $tags an array of tag names to narrow the search to, will return messages that contain ANY of the tags
@param array $senders an array of sender addresses to narrow the search to, will return messages sent by ANY of the senders
@param array $apiKeys an array of API keys to narrow the search to, will return messages sent by ANY of the keys
@param int $limit the maximum number of results to return, defaults to 100, 1000 is the maximum
@return array
@link https://mandrillapp.com/api/docs/messages.JSON.html#method=search | entailment |
public function searchTimeSeries($query = '*', $dateFrom = NULL, $dateTo = NULL, array $tags = array(), array $senders = array()){
return $this->request('search-time-series', array(
'query' => $query,
'date_from' => $dateFrom,
'date_to' => $dateTo,
'tags' => $tags,
'senders' => $senders
));
} | Search the content of recently sent messages and return the aggregated hourly stats for matching messages
@param string $query the search terms to find matching messages for
@param string $dateFrom start date YYYY-MM-DD
@param string $dateTo end date YYYY-MM-DD
@param array $tags an array of tag names to narrow the search to, will return messages that contain ANY of the tags
@param array $senders an array of sender addresses to narrow the search to, will return messages sent by ANY of the senders
@return array
@link https://mandrillapp.com/api/docs/messages.JSON.html#method=search-time-series | entailment |
public function sendRaw($rawMessage, $fromEmail = NULL, $fromName = NULL, array $to = array(), $async = false, $ipPool = NULL, $sendAt = NULL){
return $this->request('send-raw', array(
'raw_message' => $rawMessage,
'from_email' => $fromEmail,
'from_name' => $fromName,
'to' => $to,
'async' => $async,
'ip_pool' => $ipPool,
'send_at' => $sendAt
));
} | Take a raw MIME document for a message, and send it exactly as if it were sent through Mandrill's SMTP servers
@param string $rawMessage the full MIME document of an email message
@param string $fromEmail optionally define the sender address - otherwise we'll use the address found in the provided headers
@param string $fromName optionally define the sender alias
@param array $to optionally define the recipients to receive the message - otherwise we'll use the To, Cc, and Bcc headers provided in the document
@param bool $async set to true to enable asynchronous sending
@param string $ipPool optional name of the ip pool which should be used to send the message
@param string $sendAt optional UTC timestamp (YYY-MM-DD HH:MM:SS) at which the message should be sent
@return array
@link https://mandrillapp.com/api/docs/messages.JSON.html#method=send-raw | entailment |
protected function encode(array $messages)
{
if ($this->encode) {
foreach ($messages as $key => $message) {
if (($form = mb_detect_encoding($message)) != self::TARGET_ENCODING) {
$messages[$key] = mb_convert_encoding($message, self::TARGET_ENCODING, $form);
}
}
}
return $messages;
} | Encode messages.
@param array $messages
@return array | entailment |
public function lightness($lightness = null)
{
if (is_numeric($lightness)) {
$this->lightness = $lightness >= 0 && $lightness <= 100 ? $lightness : $this->lightness;
return $this;
}
return (int) $this->lightness;
} | @param int|string $lightness
@return int|$this | entailment |
protected function hueToRgb($p, $q, $t)
{
if ($t < 0) {
$t++;
}
if ($t > 1) {
$t--;
}
if ($t < 1/6) {
return $p + ($q - $p) * 6 * $t;
}
if ($t < 1/2) {
return $q;
}
if ($t < 2/3) {
return $p + ($q - $p) * (2/3 - $t) * 6;
}
return $p;
} | @param float $p
@param float $q
@param float $t
@return mixed | entailment |
private function hasNotAllowedChildren(MethodNode $node)
{
$children = $node->findChildrenOfType('ScopeStatement');
$allowedChildren = explode(
$this->getStringProperty('delimiter'),
$this->getStringProperty('allowedChildren')
);
/** @var AbstractNode $child */
foreach ($children as $child) {
if (true === in_array($child->getImage(), $allowedChildren) || true === $this->isChildOfTry($child)) {
continue;
}
return true;
}
return false;
} | @param MethodNode $node
@return bool | entailment |
private function isChildOfTry(AbstractNode $node)
{
$parent = $node->getParent();
while (is_object($parent)) {
if ($parent->isInstanceOf('TryStatement')) {
return true;
}
$parent = $parent->getParent();
}
return false;
} | @param AbstractNode $node
@return bool | entailment |
public function get($key)
{
$this->load();
return isset($this->ini[$key]) ? $this->ini[$key] : '';
} | @param string $key
@return string|array | entailment |
public function byteStringToInt($byte)
{
switch (strtoupper(substr($byte, -1, 1))) {
case 'K':
$int = substr($byte, 0, -1) * 1024;
break;
case 'M':
$int = substr($byte, 0, -1) * 1048576; // 1024 * 1024
break;
case 'G':
$int = substr($byte, 0, -1) * 1073741824; // 1024 * 1024 * 1024
break;
default:
$int = $byte;
}
return (int) $int;
} | @param string $byte
@return int | entailment |
public function byteIntToString($int)
{
if ($int % 1073741824 == 0) { // 1024 * 1024 * 1024
return ($int / 1073741824).'G';
} elseif ($int % 1048576 == 0) { // 1024 * 1024
return ($int / 1048576).'M';
} elseif ($int % 1024 == 0) {
return ($int / 1024).'K';
}
return (string) $int;
} | @param int $int
@return string | entailment |
protected function initialize($color)
{
return list($this->hue, $this->saturation, $this->value) = explode(',', $color);
} | @param string $color
@return array | entailment |
public function value($value = null)
{
if (is_numeric($value)) {
$this->value = $value >= 0 && $value <= 100 ? $value : $this->value;
return $this;
}
return (int) $this->value;
} | @param int|string $value
@return int|$this | entailment |
private function calculateNameToCommentSimilarityInPercent($node)
{
$docComment = $node->getComment();
if (empty($docComment)) {
return 0;
}
similar_text(
$this->transformString($node->getName()),
$this->getCommentDescription($docComment),
$percent
);
return round($percent);
} | @param AbstractNode|AbstractASTArtifact $node
@return float | entailment |
private function getCommentDescription($docComment)
{
$lines = explode(PHP_EOL, $docComment);
$descriptionLines = [];
foreach ($lines as $line) {
if (false === strpos($line, '@')) {
$descriptionLines[] = $line;
}
}
return $this->transformDescriptionLines($descriptionLines);
} | @param string $docComment
@return string | entailment |
private function transformDescriptionLines(array $descriptionLines)
{
$description = '';
foreach ($descriptionLines as $line) {
$description .= $this->transformString($line);
}
return $description;
} | @param array $descriptionLines
@return string | entailment |
private function hasCorrectPrefix(MethodNode $node)
{
foreach ($this->allowedPrefixes as $prefix) {
if ($prefix === substr($node->getImage(), 0, strlen($prefix))) {
return true;
}
}
return false;
} | @param MethodNode|ASTMethod $node
@return bool | entailment |
private function isSimpleMethod(MethodNode $node)
{
$countScope = count($node->findChildrenOfType('ScopeStatement'));
if (0 !== $countScope) {
return false;
}
$countReturn = count($node->findChildrenOfType('ReturnStatement'));
$countThis = $this->countThis($node);
$countSetter = $this->countSetter($node);
if (1 < $countReturn) {
return false;
}
if (($countReturn + 1) < $countThis - $countSetter) {
return false;
}
return true;
} | @param MethodNode|ASTMethod $node
@return bool | entailment |
private function countThis(MethodNode $node)
{
$count = 0;
$variables = $node->findChildrenOfType('Variable');
foreach ($variables as $variable) {
if ('$this' === $variable->getImage()) {
$count++;
}
}
return $count;
} | @param MethodNode $node
@return int | entailment |
public function alpha($alpha = null)
{
if ($alpha !== null) {
$this->alpha = $alpha <= 1 ? $alpha : 1;
return $this;
}
return $this->alpha;
} | @param null $alpha
@return $this|float | entailment |
protected function fixPrecision($color)
{
if (strpos($color, ',') !== false) {
$parts = explode(',', $color);
$parts[3] = strpos($parts[3], '.') === false ? $parts[3] . '.0' : $parts[3];
$color = implode(',', $parts);
}
return $color;
} | @param $color
@return string | entailment |
public function addResource($bundle, $format, $path = 'config')
{
$resource = '@'.$bundle.$path.'.'.$format;
$yaml = $this->getContent();
$yaml['imports'] = isset($yaml['imports']) ? $yaml['imports'] : [];
// check for duplicate
foreach ($yaml['imports'] as $import) {
if ($import['resource'] == $resource) {
return;
}
}
$yaml['imports'][] = ['resource' => $resource];
$this->setContent($yaml);
} | Add a routing resource.
@param string $bundle
@param string $format
@param string $path | entailment |
public function removeResource($bundle)
{
$yaml = $this->getContent();
if (!empty($yaml['imports'])) {
foreach ($yaml['imports'] as $key => $import) {
if (strpos($import['resource'], '@'.$bundle) === 0) {
unset($yaml['imports'][$key]);
$yaml['imports'] = array_values($yaml['imports']);
$this->setContent($yaml);
break;
}
}
}
} | Remove a routing resource.
@param string $bundle | entailment |
public function register()
{
parent::register();
$this->app->singleton('cache', function ($app) {
return new CacheManager($app);
});
$this->app->singleton('memcached.connector', function () {
return new MemcachedConnector();
});
} | Replace \Illuminate\Cache\CacheManager with B3IT\CacheManager.
@return void | entailment |
protected function getMigrationsConfig()
{
$dir = $this->getPackageDir();
// specific location
if ($migrations = $this->getPackageOptionFile('anime-db-migrations')) {
return $dir.$migrations;
}
if (file_exists($dir.'migrations.yml')) {
return $dir.'migrations.yml';
} elseif (file_exists($dir.'migrations.xml')) {
return $dir.'migrations.xml';
}
return;
} | Get path to migrations config file from package.
@return string|null | entailment |
protected function parseConfig($file)
{
$namespace = '';
$directory = '';
$config = file_get_contents($file);
switch (pathinfo($file, PATHINFO_EXTENSION)) {
case 'yml':
case 'yaml':
$config = Yaml::parse($config);
if (isset($config['migrations_namespace'])) {
$namespace = $config['migrations_namespace'];
}
if (isset($config['migrations_directory'])) {
$directory = $config['migrations_directory'];
}
break;
case 'xml':
$doc = new \DOMDocument();
$doc->loadXML($config);
$list = $doc->getElementsByTagName('migrations-namespace');
if ($list->length) {
$namespace = $list->item(0)->nodeValue;
}
$list = $doc->getElementsByTagName('migrations-directory');
if ($list->length) {
$directory = $list->item(0)->nodeValue;
}
break;
}
return [
'namespace' => $namespace && $namespace[0] == '\\' ? substr($namespace, 1) : $namespace,
'directory' => $directory,
];
} | Parse config file.
Return:
<code>
{
namespace: string,
directory: string
}
</code>
@param string $file
@return array | entailment |
protected function initialize($color)
{
list($this->hue, $this->saturation, $this->lightness, $this->alpha) = explode(',', $color);
$this->alpha = (double) $this->alpha;
} | @param string $color
@return void | entailment |
public function setMergeVars(array $vars){
$this->merge_vars = array();
foreach($vars as $name => $content){
$this->addMergeVar($name, $content);
}
return $this;
} | Set all merge variables for this recipient. Will overwrite any currently set merge vars.
@param array $vars associative array
@return $this | entailment |
public function getResults($url, $locale = 'en_US', $strategy = 'desktop', array $extraParams = null)
{
if (0 === preg_match('#http(s)?://.*#i', $url)) {
throw new InvalidArgumentException('Invalid URL');
}
$client = new \Guzzle\Service\Client($this->gateway);
/** @var $request \Guzzle\Http\Message\Request */
$request = $client->get('runPagespeed');
$request->getQuery()
->set('prettyprint', false) // reduce the response payload size
->set('url', $url)
->set('locale', $locale)
->set('strategy', $strategy);
if (isset($extraParams)) {
$query = $request->getQuery();
foreach($extraParams as $key=>$value)
{
$query[$key] = $value;
}
}
try {
$response = $request->send();
$response = $response->getBody();
$response = json_decode($response, true);
return $response;
} catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
$response = $e->getResponse();
$response = $response->getBody();
$response = json_decode($response);
throw new RuntimeException($response->error->message, $response->error->code);
}
} | Returns PageSpeed score, page statistics, and PageSpeed formatted results for specified URL
@param string $url
@param string $locale
@param string $strategy
@param optional array $extraParams
@return array
@throws Exception\InvalidArgumentException
@throws Exception\RuntimeException | entailment |
public function onAppDownloadedMergeComposerRequirements(Downloaded $event)
{
$old_config = file_get_contents($this->root_dir.'composer.json');
$old_config = json_decode($old_config, true);
$new_config = file_get_contents($event->getPath().'/composer.json');
$new_config = json_decode($new_config, true);
if ($old_config['require'] != $new_config['require']) {
$new_config['require'] = array_merge($old_config['require'], $new_config['require']);
$new_config = json_encode($new_config, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents($event->getPath().'/composer.json', $new_config);
}
} | Add requirements in composer.json from old version.
@param Downloaded $event | entailment |
public function onAppDownloadedMergeConfigs(Downloaded $event)
{
$files = [
'/app/config/parameters.yml',
'/app/config/vendor_config.yml',
'/app/config/routing.yml',
'/app/bundles.php',
];
foreach ($files as $file) {
if ($this->fs->exists($this->root_dir.$file)) {
$this->fs->copy($this->root_dir.$file, $event->getPath().$file);
}
}
} | Copy configs from old version.
@param Downloaded $event | entailment |
public function onAppDownloadedMergeBinRun(Downloaded $event)
{
// remove startup files
$this->fs->remove([
$this->root_dir.'bin/AnimeDB_Run.vbs',
$this->root_dir.'bin/AnimeDB_Stop.vbs',
$this->root_dir.'AnimeDB_Run.vbs',
$this->root_dir.'AnimeDB_Stop.vbs',
]);
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
// application has not yet has the monitor
if (!$this->fs->exists($this->root_dir.'/config.ini')) {
$monitor = sys_get_temp_dir().'/'.basename($this->monitor);
// download monitor if need
if (!$this->fs->exists($monitor)) {
$this->fs->copy($this->monitor, $monitor);
}
// unzip
if ($this->zip->open($monitor) !== true) {
throw new \RuntimeException('Failed unzip monitor');
}
$this->zip->extractTo($event->getPath());
$this->zip->close();
}
// copy params if need
$old_file = $this->root_dir.'/config.ini';
$new_file = $event->getPath().'/config.ini';
if ($this->fs->exists($new_file) && $this->fs->exists($old_file) &&
is_readable($new_file) &&
md5_file($old_file) != md5_file($new_file)
) {
$old_body = file_get_contents($old_file);
$new_body = $tmp_body = file_get_contents($new_file);
$new_body = $this->copyParam($old_body, $new_body, 'addr=%s'.PHP_EOL, self::DEFAULT_ADDRESS);
$new_body = $this->copyParam($old_body, $new_body, 'port=%s'.PHP_EOL, self::DEFAULT_PORT);
$new_body = $this->copyParam($old_body, $new_body, 'php=%s'.PHP_EOL, self::DEFAULT_PHP);
if ($new_body != $tmp_body) {
file_put_contents($new_file, $new_body);
}
}
}
} | Merge bin AnimeDB_Run.vbs commands.
@param Downloaded $event | entailment |
public function onAppDownloadedMergeBinService(Downloaded $event)
{
$old_file = $this->root_dir.'AnimeDB';
if (!$this->fs->exists($old_file)) { // old name
$old_file = $this->root_dir.'bin/service';
}
$new_file = $event->getPath().'/AnimeDB';
if (is_readable($new_file) && md5_file($old_file) != md5_file($new_file)) {
$old_body = file_get_contents($old_file);
$new_body = $tmp_body = file_get_contents($new_file);
$new_body = $this->copyParam($old_body, $new_body, 'addr=\'%s\'', self::DEFAULT_ADDRESS);
$new_body = $this->copyParam($old_body, $new_body, 'port=%s'.PHP_EOL, self::DEFAULT_PORT);
$new_body = $this->copyParam($old_body, $new_body, 'path=%s'.PHP_EOL, self::DEFAULT_PATH);
if ($new_body != $tmp_body) {
file_put_contents($new_file, $new_body);
}
}
} | Merge bin AnimeDB commands.
@param Downloaded $event | entailment |
protected function copyParam($from, $target, $param, $default)
{
// param has been changed
if (strpos($from, sprintf($param, $default)) === false) {
list($left, $right) = explode('%s', $param);
$start = strpos($from, $left) + strlen($left);
$end = strpos($from, $right, $start);
$value = substr($from, $start, $end - $start);
$target = str_replace(sprintf($param, $default), sprintf($param, $value), $target);
}
return $target;
} | Copy param value if need.
@param string $from
@param string $target
@param string $param
@param string $default
@return string | entailment |
public function onAppDownloadedChangeAccessToFiles(Downloaded $event)
{
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->fs->chmod([
$event->getPath().'/AnimeDB',
$event->getPath().'/app/console',
], 0755);
}
} | Change access to executable files.
@param Downloaded $event | entailment |
public function add($email, $comment = NULL, $subaccount = NULL){
return $this->request('add', array(
'email' => $email,
'comment' => $comment,
'subaccount' => $subaccount
));
} | Adds an email to your email rejection blacklist.
@param string $email an email address to block
@param string $comment an optional comment describing the rejection
@param string $subaccount an optional unique identifier for the subaccount to limit the blacklist entry
@return array
@link https://mandrillapp.com/api/docs/rejects.JSON.html#method=add | entailment |
public function getList($email = NULL, $includeExpired = false, $subaccount = NULL) {
return $this->listRejects($email, $includeExpired, $subaccount);
} | Alias function of listRejects so that it's easier to migrate from the official mandrill PHP library.
@see listRejects() | entailment |
public function listRejects($email = NULL, $includeExpired = false, $subaccount = NULL) {
return $this->request('list', array(
'email' => $email,
'include_expired' => $includeExpired,
'subaccount' => $subaccount
));
} | Retrieves your email rejection blacklist
@param string $email an optional email address to search by
@param bool $includeExpired whether to include rejections that have already expired.
@param string $subaccount an optional unique identifier for the subaccount to limit the blacklist
@return array
@link https://mandrillapp.com/api/docs/rejects.JSON.html#method=list | entailment |
private function getPackageConfig($name, $option = '')
{
// specific location
if ($option && ($config = $this->getPackageOptionFile($option))) {
return $config;
}
$finder = Finder::create()
->files()
->in($this->getPackageDir())
->path('/\/Resources\/config\/([^\/]+\/)*'.$name.'.(yml|xml)$/')
->name('/^'.$name.'.(yml|xml)$/');
// ignor configs in test
if (stripos($this->getPackage()->getName(), 'test') === false) {
$finder->notPath('/test/i');
}
/* @var $file \SplFileInfo */
foreach ($finder as $file) {
$path = str_replace(DIRECTORY_SEPARATOR, '/', $file->getPathname());
return substr($path, strrpos($path, '/Resources/config/'));
}
return '';
} | @param string $name
@param string $option
@return string | entailment |
protected function validate($code)
{
$color = str_replace(['rgba', '(', ')', ' '], '', DefinedColor::find($code, 1));
if (substr_count($color, ',') === 2) {
$color = "{$color},1.0";
}
$color = $this->fixPrecision($color);
if (preg_match($this->validationRules(), $color, $matches)) {
if ($matches[1] > 255 || $matches[2] > 255 || $matches[3] > 255 || $matches[4] > 1) {
return false;
}
return $color;
}
return false;
} | @param string $code
@return bool|mixed|string | entailment |
protected function initialize($color)
{
$colors = explode(',', $color);
list($this->red, $this->green, $this->blue) = array_map('intval', $colors);
$this->alpha = (double) $colors[3];
$this->background = $this->defaultBackground();
} | @param string $color
@return void | entailment |
protected function validate($code)
{
list($class, $index) = property_exists($this, 'lightness') ? ['hsl', 2] : ['hsv', 3];
$color = str_replace([$class, '(', ')', ' ', '%'], '', DefinedColor::find($code, $index));
if (preg_match('/^(\d{1,3}),(\d{1,3}),(\d{1,3})$/', $color, $matches)) {
if ($matches[1] > 360 || $matches[2] > 100 || $matches[3] > 100) {
return false;
}
return $color;
}
return false;
} | @param string $code
@return string|bool | entailment |
public function hue($hue = null)
{
if (is_numeric($hue)) {
$this->hue = $hue >= 0 && $hue <= 360 ? $hue : $this->hue;
return $this;
}
return (int) $this->hue;
} | @param int|string $hue
@return int|$this | entailment |
public function saturation($saturation = null)
{
if (is_numeric($saturation)) {
$this->saturation = $saturation >= 0 && $saturation <= 100 ? $saturation : $this->saturation;
return $this;
}
return (int) $this->saturation;
} | @param int|string $saturation
@return int|$this | entailment |
public function valuesInUnitInterval()
{
return [
$this->hue() / 360,
$this->saturation() / 100,
(property_exists($this, 'lightness') ? $this->lightness() : $this->value()) / 100
];
} | Values in [0, 1] range
@return array | entailment |
private function hasMethodsChainAllowedPrefixes(AbstractNode $memberPrimaryPrefix, array $allowedPrefixes)
{
$methodPostfixes = $memberPrimaryPrefix->findChildrenOfType('MethodPostfix');
foreach ($methodPostfixes as $methodPostfix) {
foreach ($allowedPrefixes as $allowedPrefix) {
if ($allowedPrefix === substr($methodPostfix->getName(), 0, strlen($allowedPrefix))) {
continue 2;
}
}
return false;
}
return true;
} | @param AbstractNode $memberPrimaryPrefix
@param array $allowedPrefixes
@return bool | entailment |
private function isMethodsChainExcessively(AbstractNode $memberPrimaryPrefix, $chainCount)
{
for ($chain = 0; $chain < $chainCount; $chain++) {
$children = $memberPrimaryPrefix->getChildren();
if (false === isset($children[1]) || !$children[1] instanceof ASTMemberPrimaryPrefix) {
return false;
}
$memberPrimaryPrefix = $children[1];
}
return true;
} | @param AbstractNode $memberPrimaryPrefix
@param int $chainCount
@return bool | entailment |
public function get($key)
{
$yaml = $this->getContent();
return isset($yaml['parameters']) && isset($yaml['parameters'][$key]) ? $yaml['parameters'][$key] : '';
} | @param string $key
@return string | entailment |
public function dispatch($event_name, Event $event)
{
$dir = $this->events_dir.$event_name.'/';
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
$event = serialize($event);
file_put_contents($dir.md5($event).'.meta', $event);
} | Store the event and dispatch it later.
@param string $event_name
@param Event $event | entailment |
public static function bootHasKeptFlagBehavior(): void
{
static::creating(function ($entity) {
if (!$entity->is_kept) {
$entity->is_kept = false;
}
});
static::updating(function ($entity) {
if (!$entity->is_kept && $entity->setKeptOnUpdate) {
$entity->is_kept = true;
}
});
} | Boot the bootHasKeptFlagBehavior trait for a model.
@return void | entailment |
protected function addExpire(Builder $builder): void
{
$builder->macro('expire', function (Builder $builder) {
return $builder->update(['expired_at' => Date::now()]);
});
} | Add the `expire` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithExpired(Builder $builder): void
{
$builder->macro('withExpired', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
} | Add the `withExpired` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithoutExpired(Builder $builder): void
{
$builder->macro('withoutExpired', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNull('expired_at');
});
} | Add the `withoutExpired` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addOnlyExpired(Builder $builder): void
{
$builder->macro('onlyExpired', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNotNull('expired_at');
});
} | Add the `onlyExpired` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
public function createExecutableFromCommand(
CommandInterface $command,
ConfigurationInterface $configuration
): ExecutableInterface {
return $this->createCommandLineExecutable($command, $configuration);
} | @param \Spryker\Install\Stage\Section\Command\CommandInterface $command
@param \Spryker\Install\Configuration\ConfigurationInterface $configuration
@return \Spryker\Install\Executable\ExecutableInterface | entailment |
protected function addUndoClose(Builder $builder): void
{
$builder->macro('undoClose', function (Builder $builder) {
$builder->withClosed();
return $builder->update(['is_closed' => 0]);
});
} | Add the `undoClose` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addClose(Builder $builder): void
{
$builder->macro('close', function (Builder $builder) {
return $builder->update(['is_closed' => 1]);
});
} | Add the `close` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithClosed(Builder $builder): void
{
$builder->macro('withClosed', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
} | Add the `withClosed` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithoutClosed(Builder $builder): void
{
$builder->macro('withoutClosed', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->where('is_closed', 0);
});
} | Add the `withoutClosed` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addOnlyClosed(Builder $builder): void
{
$builder->macro('onlyClosed', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->where('is_closed', 1);
});
} | Add the `onlyClosed` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
public function addTranslation(TranslationInterface $translation)
{
if (!$this->translations->contains($translation)) {
$this->translations[$translation->getLocale()] = $translation;
$translation->setTranslatable($this);
}
return $this;
} | Add a translation
@param TranslationInterface $translation
@return self | entailment |
public static function createFromFile($_)
{
$files = array_reverse(func_get_args());
if (is_array($files[0])) {
$files = $files[0];
}
while (count($files) > 0) {
try {
$file = array_pop($files);
if (! is_readable($file)) {
continue;
}
$config = static::createFromArray(
static::getFromCache($file, function ($file) {
return Loader::load($file);
})
);
if (null === $config) {
continue;
}
return $config;
} catch (Exception $exception) {
// Fail silently and try next file.
}
}
return static::createFromArray([]);
} | Create a new ConfigInterface object from a file.
If a comma-separated list of files is provided, they are checked in sequence until the first one could be loaded
successfully.
@since 0.3.0
@param string|array $_ List of files.
@return ConfigInterface Instance of a ConfigInterface implementation. | entailment |
public static function create($_)
{
if (func_num_args() < 1) {
return static::createFromArray([]);
}
$arguments = func_get_args();
if (is_array($arguments[0]) && func_num_args() === 1) {
return static::createFromArray($arguments[0]);
}
return static::createFromFile($arguments);
} | Create a new ConfigInterface object.
Tries to deduce the correct creation method by inspecting the provided arguments.
@since 0.3.0
@param mixed $_ Array with configuration values.
@return ConfigInterface Instance of a ConfigInterface implementation. | entailment |
public static function merge($_)
{
if (func_num_args() < 1) {
return static::createFromArray([]);
}
$arguments = func_get_args();
if (is_array($arguments[0]) && func_num_args() === 1) {
return static::createFromArray($arguments[0]);
}
return static::mergeFromFiles($arguments);
} | Create a new ConfigInterface object, by merging several files together.
Duplicate keys in later files will override those in earlier files.
@since 0.4.6
@param mixed $_ Array with configuration values.
@return ConfigInterface Instance of a ConfigInterface implementation. | entailment |
public static function mergeFromFiles($_)
{
$files = array_reverse(func_get_args());
$data = [];
if (is_array($files[0])) {
$files = array_reverse($files[0]);
}
while (count($files) > 0) {
try {
$file = array_pop($files);
if (! is_readable($file)) {
continue;
}
$new_data = static::getFromCache($file, function ($file) {
return Loader::load($file);
});
if (null === $data) {
continue;
}
$data = array_replace_recursive($data, $new_data);
} catch (Exception $exception) {
// Fail silently and try next file.
}
}
return static::createFromArray($data);
} | Create a new ConfigInterface object by merging data from several files.
If a comma-separated list of files is provided, they are loaded in sequence and later files override settings in
earlier files.
@since 0.4.6
@param string|array $_ List of files.
@return ConfigInterface Instance of a ConfigInterface implementation. | entailment |
public static function createSubConfig($_)
{
if (func_num_args() < 2) {
return static::createFromArray([]);
}
$arguments = func_get_args();
$file = array_shift($arguments);
$config = static::createFromFile($file);
return $config->getSubConfig($arguments);
} | Create a new ConfigInterface object from a file and return a sub-portion of it.
The first argument needs to be the file name to load, and the subsequent arguments will be passed on to
`Config::getSubConfig()`.
@since 0.4.5
@param mixed $_ File name of the config to load as a string, followed by an array of keys to pass to
`Config::getSubConfig()`.
@return ConfigInterface Instance of a ConfigInterface implementation. | entailment |
protected static function getFromCache($identifier, $fallback)
{
if (! array_key_exists($identifier, static::$configFilesCache)) {
static::$configFilesCache[$identifier] = is_callable($fallback)
? $fallback($identifier)
: $fallback;
}
return static::$configFilesCache[$identifier];
} | Get a config file from the config file cache.
@since 0.4.4
@param string $identifier Identifier to look for in the cache.
@param mixed $fallback Fallback to use to fill the cache. If $fallback is a callable, it will be executed
with $identifier as an argument.
@return mixed The latest content of the cache for the given identifier. | entailment |
protected function addUndoDraft(Builder $builder): void
{
$builder->macro('undoDraft', function (Builder $builder) {
$builder->withDrafted();
return $builder->update(['drafted_at' => null]);
});
} | Add the `undoDraft` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addDraft(Builder $builder): void
{
$builder->macro('draft', function (Builder $builder) {
return $builder->update(['drafted_at' => Date::now()]);
});
} | Add the `draft` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithDrafted(Builder $builder): void
{
$builder->macro('withDrafted', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
} | Add the `withDrafted` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithoutDrafted(Builder $builder): void
{
$builder->macro('withoutDrafted', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNull('drafted_at');
});
} | Add the `withoutDrafted` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addOnlyDrafted(Builder $builder): void
{
$builder->macro('onlyDrafted', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNotNull('drafted_at');
});
} | Add the `onlyDrafted` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
public function run(SectionInterface $section, ConfigurationInterface $configuration)
{
$configuration->getOutput()->startSection($section);
if ($section->hasPreCommand()) {
$preCommand = $configuration->findCommand($section->getPreCommand());
$this->commandRunner->run($preCommand, $configuration);
}
foreach ($section->getCommands() as $command) {
$this->commandRunner->run($command, $configuration);
}
if ($section->hasPostCommand()) {
$postCommand = $configuration->findCommand($section->getPostCommand());
$this->commandRunner->run($postCommand, $configuration);
}
$configuration->getOutput()->endSection($section);
} | @param \Spryker\Install\Stage\Section\SectionInterface $section
@param \Spryker\Install\Configuration\ConfigurationInterface $configuration
@return void | entailment |
protected function addUndoArchive(Builder $builder): void
{
$builder->macro('undoArchive', function (Builder $builder) {
$builder->withArchived();
return $builder->update(['archived_at' => null]);
});
} | Add the `undoArchive` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addArchive(Builder $builder): void
{
$builder->macro('archive', function (Builder $builder) {
return $builder->update(['archived_at' => Date::now()]);
});
} | Add the `archive` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithArchived(Builder $builder): void
{
$builder->macro('withArchived', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
} | Add the `withArchived` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addWithoutArchived(Builder $builder): void
{
$builder->macro('withoutArchived', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNull('archived_at');
});
} | Add the `withoutArchived` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
protected function addOnlyArchived(Builder $builder): void
{
$builder->macro('onlyArchived', function (Builder $builder) {
return $builder->withoutGlobalScope($this)->whereNotNull('archived_at');
});
} | Add the `onlyArchived` extension to the builder.
@param \Illuminate\Database\Eloquent\Builder $builder
@return void | entailment |
private function _batchUrl($batchId, $subPath = '')
{
$ebid = rawurlencode($batchId);
if (empty($ebid)) {
throw new \InvalidArgumentException("Empty batch ID given");
}
return $this->_url('/batches/' . $ebid . $subPath);
} | Builds an endpoint URL for the given batch and sub-path.
@param string $batchId a batch identifier
@param string $subPath additional sub-path
@return string a complete URL
@throws \InvalidArgumentException if given an invalid batch ID | entailment |
private function _groupUrl($groupId, $subPath = '')
{
$egid = rawurlencode($groupId);
if (empty($egid)) {
throw new \InvalidArgumentException("Empty group ID given");
}
return $this->_url('/groups/' . $egid . $subPath);
} | Builds an endpoint URL for the given group and sub-path.
@param string $groupId a group identifier
@param string $subPath additional sub-path
@return string a complete URL
@throws \InvalidArgumentException if given an invalid group ID | entailment |
private function _curlHelper(&$url, &$json = null)
{
$headers = [
'Accept: application/json',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
'Authorization: Bearer ' . $this->_token
];
/*
* If this is a request that has a body then we need to
* include the content type, which in our case always is JSON.
*/
if (isset($json)) {
array_push($headers, 'Content-Type: application/json');
curl_setopt($this->_curlHandle, CURLOPT_POSTFIELDS, $json);
}
curl_setopt($this->_curlHandle, CURLOPT_URL, $url);
curl_setopt($this->_curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->_curlHandle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->_curlHandle, CURLOPT_USERAGENT, $this->_userAgent);
$result = curl_exec($this->_curlHandle);
if ($result === false) {
throw new HttpCallException(curl_error($this->_curlHandle));
}
$httpStatus = curl_getinfo($this->_curlHandle, CURLINFO_HTTP_CODE);
// If we have a logger then we can emit a bit of debug info.
if (isset($this->_logger)) {
$httpTime = curl_getinfo($this->_curlHandle, CURLINFO_TOTAL_TIME);
$this->_logger->debug(
'Request: {req}; Response (status {status}, took {time}s): {rsp}',
[
'req' => $json,
'rsp' => $result,
'status' => $httpStatus,
'time' => $httpTime
]
);
}
switch ($httpStatus) {
case 200: // OK
case 201: // Created
break;
case 400: // Bad Request
case 403: // Forbidden
$e = Deserialize::error($result);
throw new ErrorResponseException($e->getCode(), $e->getText());
case 404: // Not Found
throw new NotFoundException($url);
case 401: // Unauthorized
throw new UnauthorizedException(
$this->_servicePlanId, $this->_token
);
default: // Everything else
throw new UnexpectedResponseException(
"Unexpected HTTP status $httpStatus", $result
);
}
return $result;
} | Helper method that asks cURL to do an HTTP request.
@param string $url URL that should receive the request
@param string|null $json request body, if needed
@return string the request result body | entailment |
private function _get($url)
{
curl_setopt($this->_curlHandle, CURLOPT_HTTPGET, true);
curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
return $this->_curlHelper($url);
} | Helper that performs a HTTP GET operation.
@param string $url the URL to GET
@return string the response | entailment |
private function _post($url, &$json)
{
curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, 'POST');
return $this->_curlHelper($url, $json);
} | Helper that performs a HTTP POST operation.
@param string $url the URL to POST to
@param string $json the JSON payload
@return string the response | entailment |
private function _put($url, &$json)
{
curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, 'PUT');
return $this->_curlHelper($url, $json);
} | Helper that performs a HTTP PUT operation.
@param string $url the URL to PUT to
@param string $json the JSON payload
@return string the response | entailment |
public function createTextBatch(Api\MtBatchTextSmsCreate $batch)
{
$json = Serialize::textBatch($batch);
$result = $this->_post($this->_url('/batches'), $json);
return Deserialize::batchResponse($result);
} | Creates a new text batch.
The text batch will be created as described in the given
object.
@param Api\MtBatchTextSmsCreate $batch the batch description
@return Api\MtBatchTextSmsResult the creation result | entailment |
public function createBinaryBatch(Api\MtBatchBinarySmsCreate $batch)
{
$json = Serialize::binaryBatch($batch);
$result = $this->_post($this->_url('/batches'), $json);
return Deserialize::batchResponse($result);
} | Creates a new binary batch.
The binary batch will be created as described in the given
object.
@param Api\MtBatchBinarySmsCreate $batch the batch description
@return Api\MtBatchBinarySmsResult the creation result | entailment |
public function createBatchDryRun(
Api\MtBatchSmsCreate $batch, $numRecipients = null
) {
if ($batch instanceof Api\MtBatchTextSmsCreate) {
$json = Serialize::textBatch($batch);
} else if ($batch instanceof Api\MtBatchBinarySmsCreate) {
$json = Serialize::binaryBatch($batch);
} else {
throw new \InvalidArgumentException(
'Expected text or binary batch'
);
}
$path = '/batches/dry_run';
if (isset($numRecipients)) {
$path .= "?per_recipient=true&number_of_recipients=$numRecipients";
}
$result = $this->_post($this->_url($path), $json);
return Deserialize::batchDryRun($result);
} | Simulates sending the given batch.
The method takes an optional argument for instructing XMS to
respond with per-recipient statistics, if non-null then this
number of recipients will be returned in the result.
@param Api\MtBatchSmsCreate $batch the batch to simulate
@param int|null $numRecipients number of recipients
to show in per-recipient result
@return Api\MtBatchDryRunResult result of dry-run | entailment |
public function replaceTextBatch(
$batchId, Api\MtBatchTextSmsCreate $batch
) {
$json = Serialize::textBatch($batch);
$result = $this->_put($this->_batchUrl($batchId), $json);
return Deserialize::batchResponse($result);
} | Replaces the batch with the given ID with the given text batch.
@param string $batchId identifier of the batch
@param Api\MtBatchTextSmsCreate $batch the replacement batch
@return Api\MtBatchTextSmsResult the resulting batch | entailment |
public function replaceBinaryBatch(
$batchId, Api\MtBatchBinarySmsCreate $batch
) {
$json = Serialize::binaryBatch($batch);
$result = $this->_put($this->_batchUrl($batchId), $json);
return Deserialize::batchResponse($result);
} | Replaces the batch with the given ID with the given binary
batch.
@param string $batchId identifier of the batch
@param Api\MtBatchBinarySmsCreate $batch the replacement batch
@return Api\MtBatchBinarySmsResult the resulting batch | entailment |
public function updateTextBatch(
$batchId, Api\MtBatchTextSmsUpdate $batch
) {
$json = Serialize::textBatchUpdate($batch);
$result = $this->_post($this->_batchUrl($batchId), $json);
return Deserialize::batchResponse($result);
} | Updates the text batch with the given identifier.
@param string $batchId identifier of the batch
@param Api\MtBatchTextSmsUpdate $batch the update description
@return Api\MtBatchTextSmsResult the updated batch | entailment |
public function updateBinaryBatch(
$batchId, Api\MtBatchBinarySmsUpdate $batch
) {
$json = Serialize::binaryBatchUpdate($batch);
$result = $this->_post($this->_batchUrl($batchId), $json);
return Deserialize::batchResponse($result);
} | Updates the binary batch with the given identifier.
@param string $batchId identifier of the batch
@param Api\MtBatchBinarySmsUpdate $batch the update description
@return Api\MtBatchBinarySmsResult the updated batch | entailment |
public function replaceBatchTags($batchId, array $tags)
{
$json = Serialize::tags($tags);
$result = $this->_put($this->_batchUrl($batchId, '/tags'), $json);
return Deserialize::tags($result);
} | Replaces the tags of the given batch.
@param string $batchId identifier of the batch
@param string[] $tags the new set of batch tags
@return string[] the new batch tags | entailment |
public function updateBatchTags(
$batchId, array $tagsToAdd, array $tagsToRemove
) {
$json = Serialize::tagsUpdate($tagsToAdd, $tagsToRemove);
$result = $this->_post($this->_batchUrl($batchId, '/tags'), $json);
return Deserialize::tags($result);
} | Updates the tags of the given batch.
@param string $batchId batch identifier
@param string[] $tagsToAdd tags to add to batch
@param string[] $tagsToRemove tags to remove from batch
@return string[] the updated batch tags | entailment |
public function fetchBatch($batchId)
{
$result = $this->_get($this->_batchUrl($batchId));
return Deserialize::batchResponse($result);
} | Fetches the batch with the given batch identifier.
@param string $batchId batch identifier
@return Api\MtBatchSmsResult the corresponding batch | entailment |
public function fetchBatches(BatchFilter $filter = null)
{
return new Api\Pages(
function ($page) use ($filter) {
$params = ["page=$page"];
if (!is_null($filter)) {
if (null != $filter->getPageSize()) {
array_push(
$params, 'page_size=' . $filter->getPageSize()
);
}
if (null != $filter->getSenders()) {
$val = urlencode(join(',', $filter->getSenders()));
array_push($params, 'from=' . $val);
}
if (null != $filter->getTags()) {
$val = urlencode(join(',', $filter->getTags()));
array_push($params, 'tags=' . $val);
}
if (null != $filter->getStartDate()) {
$val = $filter->getStartDate()->format('Y-m-d');
array_push($params, 'start_date=' . $val);
}
if (null != $filter->getEndDate()) {
$val = $filter->getEndDate()->format('Y-m-d');
array_push($params, 'end_date=' . $val);
}
}
$q = join('&', $params);
$result = $this->_get($this->_url('/batches?' . $q));
return Deserialize::batchesPage($result);
}
);
} | Fetch the batches matching the given filter.
Note, calling this method does not actually cause any network
traffic. Listing batches in XMS may return the result over
multiple pages and this call therefore returns an object of the
type {@link \Clx\Xms\Api\Pages}, which will fetch result pages
as needed.
@param BatchFilter|null $filter the batch filter
@return Api\Pages the result pages | entailment |
public function fetchBatchTags($batchId)
{
$result = $this->_get($this->_batchUrl($batchId, '/tags'));
return Deserialize::tags($result);
} | Fetches the tags associated with the given batch.
@param string $batchId the batch identifier
@return string[] a list of tags | entailment |
public function fetchDeliveryReport(
$batchId,
$type = null,
array $status = null,
array $code = null
) {
$params = [];
if (isset($type)) {
array_push($params, 'type=' . $type);
}
if (!empty($status)) {
$val = urlencode(join(',', $status));
array_push($params, 'status=' . $val);
}
if (!empty($code)) {
$val = urlencode(join(',', $code));
array_push($params, 'code=' . $val);
}
$path = '/delivery_report';
if (!empty($params)) {
$path .= '?' . join('&', $params);
}
$result = $this->_get($this->_batchUrl($batchId, $path));
return Deserialize::batchDeliveryReport($result);
} | Fetches a delivery report for a batch.
The report type can be either
{@link Clx\Xms\DeliveryReportType::FULL "full"}
or
{@link Clx\Xms\DeliveryReportType::SUMMARY "summary"}
and when "full" the report includes the individual recipients.
The report can be further limited by status and code. For
example, to retrieve a summary report limited to messages
having delivery status "Delivered" or "Failed" and codes "0",
"11", or "400", one could call
```php
$conn->fetchDeliveryReport(
'MyBatchId',
Clx\Xms\DeliveryReportType::SUMMARY,
['Delivered', 'Failed'],
[0, 11, 400]
);
```
If the non-identifier parameters are left as `null` then the
XMS defaults are used. In particular, all statuses and codes
are included in the report.
@param string $batchId identifier of the batch
@param string|null $type delivery report type
@param string[]|null $status statuses to fetch
@param int[]|null $code codes to fetch
@return Api\BatchDeliveryReport the batch delivery report | entailment |
public function fetchRecipientDeliveryReport($batchId, $recipient)
{
$path = '/delivery_report/' . urlencode($recipient);
$result = $this->_get($this->_batchUrl($batchId, $path));
return Deserialize::batchRecipientDeliveryReport($result);
} | Fetches a delivery report for a specific batch recipient.
@param string $batchId the batch identifier
@param string $recipient the batch recipient
@return Api\BatchRecipientDeliveryReport the delivery report | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.