sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
protected function nextStep(Request $request)
{
// Apply the current step. If success, we can redirect to next one
$currentStep = \SetupWizard::currentStep();
if (!$currentStep->apply($request->all())) {
return view()->make('setup_wizard::steps.default', ['errors' => $currentStep... | Apply current step and move on to next step
@param Request $request
@return Response | entailment |
public function boot()
{
parent::boot();
$config = $this->app['config'];
// Add the setup wizard routes if asked to
$loadDefaultRoutes = $config->get('setup_wizard.routing.load_default');
if ($loadDefaultRoutes && !$this->app->routesAreCached()) {
require($this-... | Register any other events for your application.
@return void | entailment |
private function findDelimiter($regex)
{
static $choices = ['/', '|', '#', '~', '@'];
foreach ($choices as $choice) {
if (strpos($regex, $choice) === false) {
return $choice;
}
}
throw new \InvalidArgumentException(sprintf('Unable to determine... | @param $regex
@return string | entailment |
public function handle($request, Closure $next, $guard = null)
{
// Send a forbidden status if wizard should not be triggered
if (TriggerHelper::hasWizardCompleted()) return $this->forbiddenResponse();
// Get the current step from the route slug
$currentStepSlug = $request->route()-... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function handle($request, Closure $next, $guard = null)
{
if (TriggerHelper::shouldWizardBeTriggered()) return $this->redirectToWizard();
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function addLine(Line $line)
{
$this->lines[] = $line;
$this->end = $line->getIndex();
} | Add a new line to the hunk.
@param \PhpMerge\Line $line
The line to add. | entailment |
public static function createArray($lines)
{
$op = Line::UNCHANGED;
$hunks = [];
/** @var Hunk $current */
$current = null;
foreach ($lines as $line) {
switch ($line->getType()) {
case Line::REMOVED:
if ($op != Line::REMOVED) {
... | Create an array of hunks out of an array of lines.
@param Line[] $lines
The lines of the diff.
@return Hunk[]
The hunks in the lines. | entailment |
public function getRemovedLines()
{
return array_values(array_filter(
$this->lines,
function (Line $line) {
return $line->getType() == Line::REMOVED;
}
));
} | Get the removed lines.
@return Line[] | entailment |
public function getAddedLines()
{
return array_values(array_filter(
$this->lines,
function (Line $line) {
return $line->getType() == Line::ADDED;
}
));
} | Get the added lines.
@return Line[] | entailment |
public function isLineNumberAffected($line)
{
// Added lines also affect the ones afterwards in conflict resolution,
// because they are added in between.
$bleed = ($this->type == self::ADDED ? 1 : 0);
return ($line >= $this->start && $line <= $this->end + $bleed);
} | Test whether the hunk is to be considered for a conflict resolution.
@param int $line
The line number in the original text to test.
@return bool
Whether the line is affected by the hunk. | entailment |
public function merge(string $base, string $remote, string $local) : string
{
// Skip merging if there is nothing to do.
if ($merged = PhpMergeBase::simpleMerge($base, $remote, $local)) {
return $merged;
}
$remoteDiff = Line::createArray($this->differ->diffToArray($base,... | {@inheritdoc} | entailment |
protected static function mergeHunks(array $base, array $remote, array $local, array &$conflicts = []) : array
{
$remote = new \ArrayObject($remote);
$local = new \ArrayObject($local);
$merged = [];
$a = $remote->getIterator();
$b = $local->getIterator();
$flipped =... | The merge algorithm.
@param Line[] $base
The lines of the original text.
@param Hunk[] $remote
The hunks of the remote changes.
@param Hunk[] $local
The hunks of the local changes.
@param MergeConflict[] $conflicts
The merge conflicts.
@return string[]
The merged text. | entailment |
protected static function prepareConflict($base, &$a, &$b, &$flipped, $mergedLine)
{
if ($flipped) {
self::swap($a, $b, $flipped);
}
/** @var Hunk $aa */
$aa = $a->current();
/** @var Hunk $bb */
$bb = $b->current();
// If one of the hunks is adde... | Get a Merge conflict from the two array iterators.
@param Line[] $base
The original lines of the base text.
@param \ArrayIterator $a
The first hunk iterator.
@param \ArrayIterator $b
The second hunk iterator.
@param bool $flipped
Whether or not the a corresponds to remote and b to local.
@param int $mergedLine
The lin... | entailment |
protected static function swap(&$a, &$b, &$flipped)
{
$c = $a;
$a = $b;
$b = $c;
$flipped = !$flipped;
} | Swaps two variables.
@param mixed $a
The first variable which will become the second.
@param mixed $b
The second variable which will become the first.
@param bool $flipped
The boolean indicator which will change its value. | entailment |
public static function first($array, $callback = null, $default = null)
{
if (is_null($callback)) {
return empty($array) ? static::value($default) : reset($array);
}
foreach ($array as $key => $value) {
if (call_user_func($callback, $key, $value)) {
r... | Return the first element in an array passing a given truth test.
@param array $array
@param Closure $callback
@param mixed $default
@return mixed | entailment |
public static function flatten($array, $depth = INF)
{
$result = [];
foreach ($array as $item) {
$item = $item instanceof Collection ? $item->all() : $item;
if (is_array($item)) {
if ($depth === 1) {
$result = array_merge($result, $item);... | Flatten a multi-dimensional array into a single level.
@param array $array
@param int $depth
@return array | entailment |
public static function sortRecursive($array)
{
foreach ($array as &$value) {
if (is_array($value)) {
$value = static::sortRecursive($value);
}
}
if (static::isAssociative($array)) {
ksort($array);
} else {
sort($array);... | Recursively sort an array by keys and values.
@param array $array
@return array | entailment |
public static function xmlStrToArray($xmlString, $tagName = false, $elementCount = false)
{
$doc = new DOMDocument();
try {
$doc->loadXML($xmlString);
} catch (Exception $exc) {
return [];
}
$result = [];
if (is_string($tagName)) {
... | @param $xmlString
@param bool $tagName
@param bool $elementCount
@return array | entailment |
public function merge(string $base, string $remote, string $local) : string
{
// Skip merging if there is nothing to do.
if ($merged = PhpMergeBase::simpleMerge($base, $remote, $local)) {
return $merged;
}
// Only set up the git wrapper if we really merge something.
... | {@inheritdoc} | entailment |
protected function mergeFile(string $file, string $base, string $remote, string $local) : string
{
file_put_contents($file, $base);
$this->git->add($file);
$this->git->commit('Add base.');
if (!in_array('original', $this->git->getBranches()->all())) {
$this->git->checkou... | Merge three strings in a specified file.
@param string $file
The file name in the git repository to which the content is written.
@param string $base
The common base text.
@param string $remote
The first changed text.
@param string $local
The second changed text
@return string
The merged text. | entailment |
protected static function getConflicts($file, $baseText, $remoteText, $localText, &$conflicts, &$merged)
{
$raw = new \ArrayObject(self::splitStringByLines(file_get_contents($file)));
$lineIterator = $raw->getIterator();
$state = 'unchanged';
$conflictIndicator = [
'<<<<<... | Get the conflicts from a file which is left with merge conflicts.
@param string $file
The file name.
@param string $baseText
The original text used for merging.
@param string $remoteText
The first chaned text.
@param string $localText
The second changed text.
@param MergeConflict[] $conflicts
The merge conflicts will ... | entailment |
protected static function fixLastLine(array $lines, array $all): array
{
$last = end($all);
$lastLine = end($lines);
if ($lastLine !== false && $last !== $lastLine && rtrim($lastLine) === $last) {
$lines[key($lines)] = $last;
}
return $lines;
} | @param array $lines
@param array $all
@return array | entailment |
protected function setup()
{
if (!$this->dir) {
// Greate a temporary directory.
$tempfile = tempnam(sys_get_temp_dir(), '');
mkdir($tempfile.'.git');
if (file_exists($tempfile)) {
unlink($tempfile);
}
$this->dir = $temp... | Set up the git wrapper and the temporary directory. | entailment |
protected function cleanup()
{
if (is_dir($this->dir)) {
// Recursively delete all files and folders.
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->dir, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterat... | Clean the temporary directory used for merging. | entailment |
public static function removeStopWords($string, $asString = false)
{
$delimiters = preg_quote(static::$delimiters, '/');
$stopWords = explode(',', static::$stopWords);
$result = array_map(function ($token) {
return $token;
}, array_filter(
array_map(function ... | Remove stop words
@param $string
@param bool $asString
@return array|string | entailment |
public static function removePunctuationSymbols($words, $glue = ' ')
{
if (is_array($words)) {
$words = implode($glue, $words);
}
return trim(str_replace(static::$punctuationSymbols, '', $words));
} | Remove punctuation symbols from string
@param $words
@param string $glue
@return mixed | entailment |
protected static function simpleMerge(string $base, string $remote, string $local)
{
// Skip complex merging if there is nothing to do.
if ($base == $remote) {
return $local;
}
if ($base == $local) {
return $remote;
}
if ($remote == $local) {
... | Merge obvious cases when only one text changes..
@param string $base
The original text.
@param string $remote
The first variant text.
@param string $local
The second variant text.
@return string|null
The merge result or null if the merge is not obvious. | entailment |
public function checkAuth()
{
if (
$this->request->server->get('PHP_AUTH_USER') === $this->config->getLogin() &&
$this->request->server->get('PHP_AUTH_PW') === $this->config->getPassword()
) {
$this->session->save();
$response = "success\n";
... | @throws Exchange1CException
@return string | entailment |
public function init(): string
{
$this->authService->auth();
$this->loaderService->clearImportDirectory();
$zipEnable = function_exists('zip_open') && $this->config->isUseZip();
$response = 'zip='.($zipEnable ? 'yes' : 'no')."\n";
$response .= 'file_limit='.$this->config->get... | Запрос параметров от сайта
Далее следует запрос следующего вида:
http://<сайт>/<путь> /1c-exchange?type=catalog&mode=init
В ответ система управления сайтом передает две строки:
1. zip=yes, если сервер поддерживает обмен
в zip-формате - в этом случае на следующем шаге файлы должны быть упакованы в zip-формате
или zip=n... | entailment |
public function import(): string
{
$this->authService->auth();
$filename = $this->request->get('filename');
switch ($filename) {
case 'import.xml':
{
$this->categoryService->import();
break;
}
cas... | На последнем шаге по запросу из "1С:Предприятия" производится пошаговая загрузка данных по запросу
с параметрами вида http://<сайт>/<путь> /1c_exchange.php?type=catalog&mode=import&filename=<имя файла>
Во время загрузки система управления сайтом может отвечать в одном из следующих вариантов.
1. Если в первой строке сод... | entailment |
protected function findProductModelById(string $id): ?ProductInterface
{
/**
* @var ProductInterface
*/
$class = $this->modelBuilder->getInterfaceClass($this->config, ProductInterface::class);
return $class::findProductBy1c($id);
} | @param string $id
@return ProductInterface|null | entailment |
public function getInterfaceClass(Config $config, string $interface)
{
$model = $config->getModelClass($interface);
if ($model) {
$modelInstance = new $model();
if ($modelInstance instanceof $interface) {
return $modelInstance;
}
}
... | Если модель в конфиге не установлена, то импорт не будет произведен.
@param Config $config
@param string $interface
@throws Exchange1CException
@return null|mixed | entailment |
private function configure(array $config = []): void
{
foreach ($config as $param => $value) {
$property = $this->toCamelCase($param);
if (property_exists(self::class, $property)) {
$this->$property = $value;
}
}
} | Overrides default configuration settings.
@param array $config | entailment |
public function getModelClass(string $modelName): ?string
{
if (isset($this->models[$modelName])) {
return $this->models[$modelName];
}
return null;
} | @param string $modelName
@return null|string | entailment |
private function toCamelCase($str): string
{
$func = function ($c) {
return strtoupper($c[1]);
};
return preg_replace_callback('/_([a-z])/', $func, $str);
} | Translates a string with underscores into camel case (e.g. first_name -> firstName).
@param string $str String in underscore format
@return string $str translated into camel caps | entailment |
public function clearImportDirectory(): void
{
$tmp_files = glob($this->config->getImportDir().DIRECTORY_SEPARATOR.'*.*');
if (is_array($tmp_files)) {
foreach ($tmp_files as $v) {
unlink($v);
}
}
} | Delete all files from tmp directory. | entailment |
public function import(): void
{
$filename = basename($this->request->get('filename'));
$commerce = new CommerceML();
$commerce->loadImportXml($this->config->getFullPath($filename));
$classifierFile = $this->config->getFullPath('classifier.xml');
if ($commerce->classifier->xm... | Базовый метод запуска импорта.
@throws Exchange1CException | entailment |
public function nest()
{
$parentColumn = $this->parentColumn;
if (!$parentColumn) {
return $this;
}
// Set id as keys.
$this->items = $this->getDictionary();
$keysToDelete = [];
// Add empty collection to each items.
$collection = $this-... | Nest items.
@return mixed NestableCollection | entailment |
public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = null, $parent_string = null)
{
$collection = $collection ?: $this;
$indentChars = $indentChars ?: $this->indentChars;
foreach ($collection as $item) {
... | Recursive function that flatten a nested Collection
with characters (default is four spaces).
@param string $column
@param BaseCollection|null $collection
@param int $level
@param array &$flattened
@param string|null $indentChars
@param string|boolen|null $parent_str... | entailment |
public function listsFlattenedQualified($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = null)
{
return $this->listsFlattened($column, $collection, $level, $flattened, $indentChars, true);
} | Returns a fully qualified version of listsFlattened.
@param BaseCollection|null $collection
@param string $column
@param int $level
@param array &$flattened
@param string $indentChars
@return array | entailment |
public function anAncestorIsMissing($item)
{
$parentColumn = $this->parentColumn;
if (!$item->$parentColumn) {
return false;
}
if (!$this->has($item->$parentColumn)) {
return true;
}
$parent = $this[$item->$parentColumn];
return $this-... | Check if an ancestor is missing.
@param $item
@return bool | entailment |
public function serialize($value)
{
$this->recursiveSetValues($value);
$this->recursiveUnset($value, [Serializer::CLASS_IDENTIFIER_KEY]);
$this->recursiveFlattenOneElementObjectsToScalarType($value);
return $value;
} | @param mixed $value
@return string | entailment |
public function serialize($value)
{
$this->reset();
return $this->serializationStrategy->serialize($this->serializeData($value));
} | Serialize the value in JSON.
@param mixed $value
@return string JSON encoded
@throws SerializerException | entailment |
protected function serializeData($value)
{
$this->guardForUnsupportedValues($value);
if ($this->isInstanceOf($value, 'SplFixedArray')) {
return SplFixedArraySerializer::serialize($this, $value);
}
if (\is_object($value)) {
return $this->serializeObject($valu... | Parse the data to be json encoded.
@param mixed $value
@return mixed
@throws SerializerException | entailment |
private function isInstanceOf($value, $classFQN)
{
return is_object($value)
&& (strtolower(get_class($value)) === strtolower($classFQN) || \is_subclass_of($value, $classFQN, true));
} | Check if a class is instance or extends from the expected instance.
@param mixed $value
@param string $classFQN
@return bool | entailment |
protected function guardForUnsupportedValues($value)
{
if ($value instanceof Closure) {
throw new SerializerException('Closures are not supported in Serializer');
}
if ($value instanceof \DatePeriod) {
throw new SerializerException(
'DatePeriod is not... | @param mixed $value
@throws SerializerException | entailment |
public function unserialize($value)
{
if (\is_array($value) && isset($value[self::SCALAR_TYPE])) {
return $this->unserializeData($value);
}
$this->reset();
return $this->unserializeData($this->serializationStrategy->unserialize($value));
} | Unserialize the value from string.
@param mixed $value
@return mixed | entailment |
protected function unserializeData($value)
{
if ($value === null || !is_array($value)) {
return $value;
}
if (isset($value[self::MAP_TYPE]) && !isset($value[self::CLASS_IDENTIFIER_KEY])) {
$value = $value[self::SCALAR_VALUE];
return $this->unserializeDat... | Parse the json decode to convert to objects again.
@param mixed $value
@return mixed | entailment |
protected function getScalarValue($value)
{
switch ($value[self::SCALAR_TYPE]) {
case 'integer':
return \intval($value[self::SCALAR_VALUE]);
case 'float':
return \floatval($value[self::SCALAR_VALUE]);
case 'boolean':
return ... | @param $value
@return float|int|null|bool | entailment |
protected function unserializeObject(array $value)
{
$className = $value[self::CLASS_IDENTIFIER_KEY];
unset($value[self::CLASS_IDENTIFIER_KEY]);
if (isset($value[self::MAP_TYPE])) {
unset($value[self::MAP_TYPE]);
unset($value[self::SCALAR_VALUE]);
}
... | Convert the serialized array into an object.
@param array $value
@return object
@throws SerializerException | entailment |
protected function unserializeDateTimeFamilyObject(array $value, $className)
{
$obj = null;
if ($this->isDateTimeFamilyObject($className)) {
$obj = $this->restoreUsingUnserialize($className, $value);
self::$objectMapping[self::$objectMappingIndex++] = $obj;
}
... | @param array $value
@param string $className
@return mixed | entailment |
protected function isDateTimeFamilyObject($className)
{
$isDateTime = false;
foreach ($this->dateTimeClassType as $class) {
$isDateTime = $isDateTime || \is_subclass_of($className, $class, true) || $class === $className;
}
return $isDateTime;
} | @param string $className
@return bool | entailment |
protected function restoreUsingUnserialize($className, array $attributes)
{
foreach ($attributes as &$attribute) {
$attribute = $this->unserializeData($attribute);
}
$obj = (object) $attributes;
$serialized = \preg_replace(
'|^O:\d+:"\w+":|',
'O:'... | @param string $className
@param array $attributes
@return mixed | entailment |
protected function unserializeUserDefinedObject(array $value, $className)
{
$ref = new ReflectionClass($className);
$obj = $ref->newInstanceWithoutConstructor();
self::$objectMapping[self::$objectMappingIndex++] = $obj;
$this->setUnserializedObjectProperties($value, $ref, $obj);
... | @param array $value
@param string $className
@return object | entailment |
protected function setUnserializedObjectProperties(array $value, ReflectionClass $ref, $obj)
{
foreach ($value as $property => $propertyValue) {
try {
$propRef = $ref->getProperty($property);
$propRef->setAccessible(true);
$propRef->setValue($obj, ... | @param array $value
@param ReflectionClass $ref
@param mixed $obj
@return mixed | entailment |
protected function serializeScalar($value)
{
$type = \gettype($value);
if ($type === 'double') {
$type = 'float';
}
return [
self::SCALAR_TYPE => $type,
self::SCALAR_VALUE => $value,
];
} | @param $value
@return string | entailment |
protected function serializeArray(array $value)
{
if (\array_key_exists(self::MAP_TYPE, $value)) {
return $value;
}
$toArray = [self::MAP_TYPE => 'array', self::SCALAR_VALUE => []];
foreach ($value as $key => $field) {
$toArray[self::SCALAR_VALUE][$key] = $th... | @param array $value
@return array | entailment |
protected function serializeObject($value)
{
if (self::$objectStorage->contains($value)) {
return [self::CLASS_IDENTIFIER_KEY => '@'.self::$objectStorage[$value]];
}
self::$objectStorage->attach($value, self::$objectMappingIndex++);
$reflection = new ReflectionClass($va... | Extract the data from an object.
@param mixed $value
@return array | entailment |
protected function serializeInternalClass($value, $className, ReflectionClass $ref)
{
$paramsToSerialize = $this->getObjectProperties($ref, $value);
$data = [self::CLASS_IDENTIFIER_KEY => $className];
$data += \array_map([$this, 'serializeData'], $this->extractObjectData($value, $ref, $param... | @param mixed $value
@param string $className
@param ReflectionClass $ref
@return array | entailment |
protected function getObjectProperties(ReflectionClass $ref, $value)
{
$props = [];
foreach ($ref->getProperties() as $prop) {
$props[] = $prop->getName();
}
return \array_unique(\array_merge($props, \array_keys(\get_object_vars($value))));
} | Return the list of properties to be serialized.
@param ReflectionClass $ref
@param $value
@return array | entailment |
protected function extractObjectData($value, ReflectionClass $rc, array $properties)
{
$data = [];
$this->extractCurrentObjectProperties($value, $rc, $properties, $data);
$this->extractAllInhertitedProperties($value, $rc, $data);
return $data;
} | Extract the object data.
@param mixed $value
@param \ReflectionClass $rc
@param array $properties
@return array | entailment |
public function serialize($value)
{
$value = self::replaceKeys($this->replacements, $value);
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>');
$this->arrayToXml($value, $xml);
return $xml->asXML();
} | @param mixed $value
@return string | entailment |
private static function replaceKeys(array &$replacements, array $input)
{
$return = [];
foreach ($input as $key => $value) {
$key = \str_replace(\array_keys($replacements), \array_values($replacements), $key);
if (\is_array($value)) {
$value = self::replaceKe... | @param array $replacements
@param array $input
@return array | entailment |
public function unserialize($value)
{
$array = (array) \simplexml_load_string($value);
self::castToArray($array);
self::recoverArrayNumericKeyValues($array);
$replacements = \array_flip($this->replacements);
$array = self::replaceKeys($replacements, $array);
return $... | @param $value
@return array | entailment |
private static function getNumericKeyValue($key)
{
$newKey = \str_replace('np_serializer_element_', '', $key);
list($type, $index) = \explode('_', $newKey);
if ('integer' === $type) {
$index = (int) $index;
}
return $index;
} | @param $key
@return float|int | entailment |
public static function unserialize(Serializer $serializer, $className, array $value)
{
$dateTimeZone = DateTimeZoneSerializer::unserialize(
$serializer,
'DateTimeZone',
array($serializer->unserialize($value['data']['timezone']))
);
$ref = new ReflectionCl... | @param Serializer $serializer
@param string $className
@param array $value
@return object | entailment |
public function setConnectionArgs($options = 0, $retriesNum = 0, array $params = []) {
$this->imapOptions = $options;
$this->imapRetriesNum = $retriesNum;
$this->imapParams = $params;
} | Set custom connection arguments of imap_open method. See http://php.net/imap_open
@param int $options
@param int $retriesNum
@param array $params | entailment |
public function getImapStream($forceConnection = true) {
static $imapStream;
if($forceConnection) {
if($imapStream && (!is_resource($imapStream) || !imap_ping($imapStream))) {
$this->disconnect();
$imapStream = null;
}
if(!$imapStream) {
$imapStream = $this->initImapStream();
}
}
return ... | Get IMAP mailbox connection stream
@param bool $forceConnection Initialize connection if it's not initialized
@return null|resource | entailment |
public function getListingFolders() {
$folders = imap_list($this->getImapStream(), $this->imapPath, "*");
foreach ($folders as $key => $folder)
{
$folder = str_replace($this->imapPath, "", imap_utf7_decode($folder));
$folders[$key] = $folder;
}
return $folders;
} | Gets listing the folders
This function returns an object containing listing the folders.
The object has the following properties: messages, recent, unseen, uidnext, and uidvalidity.
@return array listing the folders | entailment |
public function searchMailbox($criteria = 'ALL')
{
$mailsIds = imap_search($this->getImapStream(), $criteria, SE_UID, $this->searchEncoding);
return $mailsIds ? $mailsIds : array();
} | This function performs a search on the mailbox currently opened in the given IMAP stream.
For example, to match all unanswered mails sent by Mom, you'd use: "UNANSWERED FROM mom".
Searches appear to be case insensitive. This list of criteria is from a reading of the UW
c-client source code and may be incomplete or inac... | entailment |
public function setFlag(array $mailsIds, $flag) {
return imap_setflag_full($this->getImapStream(), implode(',', $mailsIds), $flag, ST_UID);
} | Causes a store to add the specified flag to the flags set for the mails in the specified sequence.
@param array $mailsIds
@param string $flag which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by RFC2060.
@return bool | entailment |
public function clearFlag(array $mailsIds, $flag) {
return imap_clearflag_full($this->getImapStream(), implode(',', $mailsIds), $flag, ST_UID);
} | Cause a store to delete the specified flag to the flags set for the mails in the specified sequence.
@param array $mailsIds
@param string $flag which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by RFC2060.
@return bool | entailment |
public function getMailsInfo(array $mailsIds) {
$mails = imap_fetch_overview($this->getImapStream(), implode(',', $mailsIds), FT_UID);
if(is_array($mails) && count($mails))
{
foreach($mails as &$mail)
{
if(isset($mail->subject)) {
$mail->subject = $this->decodeMimeStr($mail->subject, $this->serverE... | Fetch mail headers for listed mails ids
Returns an array of objects describing one mail header each. The object will only define a property if it exists. The possible properties are:
subject - the mails subject
from - who sent it
to - recipient
date - when was it sent
message_id - Mail-ID
references - is a reference t... | entailment |
public function sortMails($criteria = SORTARRIVAL, $reverse = true) {
return imap_sort($this->getImapStream(), $criteria, $reverse, SE_UID);
} | Gets mails ids sorted by some criteria
Criteria can be one (and only one) of the following constants:
SORTDATE - mail Date
SORTARRIVAL - arrival date (default)
SORTFROM - mailbox in first From address
SORTSUBJECT - mail subject
SORTTO - mailbox in first To address
SORTCC - mailbox in first cc address
SORTSIZE - size o... | entailment |
public function getMail($mailId, $markAsSeen = true) {
$head = imap_rfc822_parse_headers(imap_fetchheader($this->getImapStream(), $mailId, FT_UID));
$mail = new IncomingMail();
$mail->id = $mailId;
$mail->date = self::getDateTime($head->date);
$mail->subject = isset($head->subject) ? $this->decodeMimeS... | Get mail data
@param $mailId
@param bool $markAsSeen
@return IncomingMail | entailment |
protected function convertStringEncoding($string, $fromEncoding, $toEncoding) {
$convertedString = null;
if($string && $fromEncoding != $toEncoding) {
$convertedString = @iconv($fromEncoding, $toEncoding . '//IGNORE', $string);
if(!$convertedString && extension_loaded('mbstring')) {
$convertedString = @mb... | Converts a string from one encoding to another.
@param string $string
@param string $fromEncoding
@param string $toEncoding
@return string Converted string if conversion was successful, or the original string if not | entailment |
public static function getDateTime($date)
{
$_date = time();
if (isset($date) && self::isValidDate($date)) {
$_date = strtotime(preg_replace('/\(.*?\)/', '', $date));
}
return date('Y-m-d H:i:s', $_date);
} | Get date time
@param string $date
@return false|string | entailment |
public static function isValidDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
} | Check valid date time format
@param string $date
@param string $format
@return bool | entailment |
public static function serialize(Serializer $serializer, DateTimeZone $dateTimeZone)
{
return array(
Serializer::CLASS_IDENTIFIER_KEY => 'DateTimeZone',
'timezone' => array(
Serializer::SCALAR_TYPE => 'string',
Serializer::SCALAR_VALUE => $dateTimeZone... | @param Serializer $serializer
@param DateTimeZone $dateTimeZone
@return mixed | entailment |
public static function unserialize(Serializer $serializer, $className, array $value)
{
$ref = new ReflectionClass($className);
foreach ($value as &$v) {
if (\is_array($v)) {
$v = $serializer->unserialize($v);
}
}
return $ref->newInstanceArgs(... | @param Serializer $serializer
@param string $className
@param array $value
@return object | entailment |
public static function serialize(Serializer $serializer, SplFixedArray $splFixedArray)
{
$toArray = [
Serializer::CLASS_IDENTIFIER_KEY => get_class($splFixedArray),
Serializer::CLASS_PARENT_KEY => 'SplFixedArray',
Serializer::SCALAR_VALUE => [],
];
foreach... | @param Serializer $serializer
@param SplFixedArray $splFixedArray
@return array | entailment |
public static function unserialize(Serializer $serializer, $className, array $value)
{
$data = $serializer->unserialize($value[Serializer::SCALAR_VALUE]);
/* @var SplFixedArray $instance */
$ref = new ReflectionClass($className);
$instance = $ref->newInstanceWithoutConstructor();
... | @param Serializer $serializer
@param string $className
@param array $value
@return mixed | entailment |
public static function unserialize(Serializer $serializer, $className, array $value)
{
$ref = new ReflectionClass($className);
return self::fillObjectProperties(self::getTypedValue($serializer, $value), $ref);
} | @param Serializer $serializer
@param string $className
@param array $value
@return object | entailment |
protected static function fillObjectProperties(array $value, ReflectionClass $ref)
{
$obj = $ref->newInstanceArgs([$value['construct']]);
unset($value['construct']);
foreach ($value as $k => $v) {
$obj->$k = $v;
}
return $obj;
} | @param array $value
@param ReflectionClass $ref
@return object | entailment |
protected static function getTypedValue(Serializer $serializer, array $value)
{
foreach ($value as &$v) {
$v = $serializer->unserialize($v);
}
return $value;
} | @param Serializer $serializer
@param array $value
@return mixed | entailment |
public static function serialize(Serializer $serializer, DateInterval $dateInterval)
{
return array(
Serializer::CLASS_IDENTIFIER_KEY => \get_class($dateInterval),
'construct' => array(
Serializer::SCALAR_TYPE => 'string',
Serializer::SCALAR_VALUE => \... | @param Serializer $serializer
@param DateInterval $dateInterval
@return mixed | entailment |
public function serialize($value)
{
$array = parent::serialize($value);
$xmlData = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>');
$this->arrayToXml($array, $xmlData);
$xml = $xmlData->asXML();
$xmlDoc = new DOMDocument();
$xmlDoc->loadX... | @param mixed $value
@return string | entailment |
private function arrayToXml(array &$data, SimpleXMLElement $xmlData)
{
foreach ($data as $key => $value) {
if (\is_array($value)) {
if (\is_numeric($key)) {
$key = 'sequential-item';
}
$subnode = $xmlData->addChild($key);
... | Converts an array to XML using SimpleXMLElement.
@param array $data
@param SimpleXMLElement $xmlData | entailment |
protected function copySkeleton(
$packagePath,
$vendor,
$package,
$vendorFolderName,
$packageFolderName
) {
$this->info('Copy skeleton.');
$skeletonDirPath = $this->getPathFromConfig(
'skeleton_dir_path', $this->packageBaseDir.'/skeleton'
... | Copy skeleton to package folder.
@param string $packagePath
@param string $vendor
@param string $package
@param string $vendorFolderName
@param string $packageFolderName
@throws RuntimeException | entailment |
protected function copyStubs($packagePath, $package, $packageFolderName)
{
$facadeFilePath = $this->packageBaseDir.'/stubs/Facade.php.tpl';
$mainClassFilePath = $this->packageBaseDir.'/stubs/MainClass.php.tpl';
$mainClassTestFilePath = $this->packageBaseDir.'/stubs/MainClassTest.php.tpl';
... | Copy stubs.
@param $packagePath
@param $package
@param $packageFolderName | entailment |
protected function replaceTemplates($packagePath, $variables)
{
$phpEngine = app()->make(PhpEngine::class);
foreach (File::allFiles($packagePath, true) as $filePath) {
$filePath = realpath($filePath);
if (! Str::endsWith($filePath, '.tpl')) {
continue;
... | Substitute all variables in *.tpl files and remove tpl extension.
@param string $packagePath
@param array $variables | entailment |
protected function copyFileWithDirsCreating($src, $dest)
{
$dirPathOfDestFile = dirname($dest);
if (! File::exists($dirPathOfDestFile)) {
File::makeDirectory($dirPathOfDestFile, 0755, true);
}
if (! File::exists($dest)) {
File::copy($src, $dest);
}
... | Copy source file to destination with needed directories creating.
@param string $src
@param string $dest | entailment |
protected function getVariables(
$vendor,
$package,
$vendorFolderName,
$packageFolderName
) {
$packageWords = str_replace('-', ' ', Str::snake($packageFolderName));
$composerDescription = $this->askUser(
'The composer description?', "A $packageWords"
... | Get variables for substitution in templates.
@param string $vendor
@param string $package
@param string $vendorFolderName
@param string $packageFolderName
@return array | entailment |
protected function getPathFromConfig($configName, $default)
{
$path = config("laravel-package-generator.$configName");
if (empty($path)) {
$path = $default;
} else {
$path = base_path($path);
}
$realPath = realpath($path);
if ($realPath === ... | Get path from config.
@param string $configName
@param string $default
@return string
@throws RuntimeException | entailment |
protected function getComposerKeywords($packageWords)
{
$keywords = $this->askUser(
'The composer keywords? (comma delimited)', str_replace(' ', ',', $packageWords)
);
$keywords = explode(',', $keywords);
$keywords = array_map(function ($keyword) {
return "\"$... | Get composer keywords.
@param $packageWords
@return string | entailment |
protected function composerRunCommand($command)
{
$this->info("Run \"$command\".");
$output = [];
exec($command, $output, $returnStatusCode);
if ($returnStatusCode !== 0) {
throw RuntimeException::commandExecutionFailed($command, $returnStatusCode);
}
$... | Run arbitrary composer command.
@param $command | entailment |
public function getOwnedAreaRelationName()
{
$has_one = $this->config()->get('has_one');
foreach ($has_one as $relationName => $relationClass) {
if ($relationClass === ElementalArea::class && $relationName !== 'Parent') {
return $relationName;
}
}
... | Retrieve a elemental area relation name which this element owns
@return string | entailment |
public function handle()
{
$vendor = $this->getVendor();
$package = $this->getPackage();
$vendorFolderName = $this->getVendorFolderName($vendor);
$packageFolderName = $this->getPackageFolderName($package);
$relPackagePath = "packages/$vendorFolderName/$packageFolderName";
... | Execute the console command.
@return mixed | entailment |
protected function cloneRepo($url, $dest, $branch)
{
$command = "git clone --branch=$branch $url $dest";
$this->info("Run \"$command\".");
File::makeDirectory($dest, 0755, true);
$output = [];
exec($command, $output, $returnStatusCode);
if ($returnStatusCode !== 0)... | Clone repo.
@param $url
@param $dest
@param $branch
@throws RuntimeException | entailment |
protected function initRepo($repoPath)
{
$command = "git init $repoPath";
$this->info("Run \"$command\".");
$output = [];
exec($command, $output, $returnStatusCode);
if ($returnStatusCode !== 0) {
throw RuntimeException::commandExecutionFailed(
$... | Init git repo.
@param string $repoPath | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.