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->getMessageBag()]); } // If we have a next step, go for it. Else we redirect to somewhere else try { $nextStep = \SetupWizard::nextStep(); return redirect()->route('setup_wizard.show', ['slug' => $nextStep->getSlug()]); } catch (StepNotFoundException $e) { $finalRouteName = config('setup_wizard.routing.success_route', ''); if (!empty($finalRouteName)) return redirect()->route($finalRouteName); $finalRouteUrl = config('setup_wizard.routing.success_url', ''); if (!empty($finalRouteUrl)) return redirect()->to($finalRouteUrl); return redirect('/'); } }
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->packageDir . '/src/routes.php'); } // Facade $this->app->singleton('SetupWizard', function ($app) { $wizard = new DefaultSetupWizard($app); return $wizard; } ); $this->app->alias('SetupWizard', DefaultSetupWizard::class); // We have some views and translations for the wizard $this->loadViewsFrom($this->packageDir . '/resources/views', self::$RES_NAMESPACE); $this->loadTranslationsFrom($this->packageDir . '/resources/lang', self::$RES_NAMESPACE); // We publish some files to override if required $this->publishes([ $this->packageDir . '/config/' . self::$CONFIG_FILE => config_path(self::$CONFIG_FILE), ], 'config'); $this->publishes([ $this->packageDir . '/resources/views' => resource_path('views/vendor/' . self::$RES_NAMESPACE), ], 'views'); $this->publishes([ $this->packageDir . '/resources/lang' => resource_path('lang/vendor/' . self::$RES_NAMESPACE), ], 'translations'); $this->publishes([ $this->packageDir . '/resources/assets' => public_path('vendor/' . self::$RES_NAMESPACE), ], 'assets'); }
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 delimiter for regex %s', $regex)); }
@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()->getParameter('slug', ''); \SetupWizard::initialize($currentStepSlug); // Share common data with our views view()->share('currentStep', \SetupWizard::currentStep()); view()->share('allSteps', \SetupWizard::steps()); // Proceed as usual return $next($request); }
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) { // The last line was not removed so we start a new hunk. $current = new Hunk($line, Hunk::REMOVED, $line->getIndex()); } else { // continue adding the line to the hunk. $current->addLine($line); } break; case Line::ADDED: switch ($op) { case Line::REMOVED: // The hunk is a replacement. $current->setType(Hunk::REPLACED); $current->addLine($line); break; case Line::ADDED: $current->addLine($line); break; case Line::UNCHANGED: // Add a new hunk with the added type. $current = new Hunk($line, Hunk::ADDED, $line->getIndex()); break; } break; case Line::UNCHANGED: if ($current) { // The hunk exists so add it to the array. $hunks[] = $current; $current = null; } break; } $op = $line->getType(); } if ($current) { // The last line was part of a hunk, so add it. $hunks[] = $current; } return $hunks; }
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, $remote)); $localDiff = Line::createArray($this->differ->diffToArray($base, $local)); $baseLines = Line::createArray( array_map( function ($l) { return [$l, 0]; }, self::splitStringByLines($base) ) ); $remoteHunks = Hunk::createArray($remoteDiff); $localHunks = Hunk::createArray($localDiff); $conflicts = []; $merged = PhpMerge::mergeHunks($baseLines, $remoteHunks, $localHunks, $conflicts); $merged = implode("", $merged); if (!empty($conflicts)) { throw new MergeException('A merge conflict has occurred.', $conflicts, $merged); } return $merged; }
{@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 = false; $i = -1; // Loop over all indexes of the base and all hunks. while ($i < count($base) || $a->valid() || $b->valid()) { // Assure that $aa is the first hunk by swaping $a and $b if ($a->valid() && $b->valid() && $a->current()->getStart() > $b->current()->getStart()) { self::swap($a, $b, $flipped); } elseif (!$a->valid() && $b->valid()) { self::swap($a, $b, $flipped); } /** @var Hunk $aa */ $aa = $a->current(); /** @var Hunk $bb */ $bb = $b->current(); if ($aa) { assert($aa->getStart() >= $i, 'The start of the hunk is after the current index.'); } // The hunk starts at the current index. if ($aa && $aa->getStart() == $i) { // Hunks from both sources start with the same index. if ($bb && $bb->getStart() == $i) { if ($aa != $bb) { // If the hunks are not the same its a conflict. $conflicts[] = self::prepareConflict($base, $a, $b, $flipped, count($merged)); $aa = $a->current(); } else { // Advance $b it is the same as $a and will be merged. $b->next(); } } elseif ($aa->hasIntersection($bb)) { // The end overlaps with the start of the next other hunk. $conflicts[] = self::prepareConflict($base, $a, $b, $flipped, count($merged)); $aa = $a->current(); } } // The conflict resolution could mean the hunk starts now later. if ($aa && $aa->getStart() == $i) { if ($aa->getType() == Hunk::ADDED && $i >= 0) { $merged[] = $base[$i]->getContent(); } if ($aa->getType() != Hunk::REMOVED) { foreach ($aa->getAddedLines() as $line) { $merged[] = $line->getContent(); } } $i = $aa->getEnd(); $a->next(); } else { // Not dealing with a change, so return the line from the base. if ($i >= 0) { $merged[] = $base[$i]->getContent(); } } // Finally, advance the index. $i++; } return $merged; }
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 added but the other one does not start there. if ($aa->getType() == Hunk::ADDED && $bb->getType() != Hunk::ADDED) { $start = $bb->getStart(); $end = $bb->getEnd(); } elseif ($aa->getType() != Hunk::ADDED && $bb->getType() == Hunk::ADDED) { $start = $aa->getStart(); $end = $aa->getEnd(); } else { $start = min($aa->getStart(), $bb->getStart()); $end = max($aa->getEnd(), $bb->getEnd()); } // Add one to the merged line number if we advanced the start. $mergedLine += $start - min($aa->getStart(), $bb->getStart()); $baseLines = []; $remoteLines = []; $localLines = []; if ($aa->getType() != Hunk::ADDED || $bb->getType() != Hunk::ADDED) { // If the start is after the start of the hunk, include it first. if ($aa->getStart() < $start) { $remoteLines = $aa->getLinesContent(); } if ($bb->getStart() < $start) { $localLines = $bb->getLinesContent(); } for ($i = $start; $i <= $end; $i++) { $baseLines[] = $base[$i]->getContent(); // For conflicts that happened on overlapping lines. if ($i < $aa->getStart() || $i > $aa->getEnd()) { $remoteLines[] = $base[$i]->getContent(); } elseif ($i == $aa->getStart()) { if ($aa->getType() == Hunk::ADDED) { $remoteLines[] = $base[$i]->getContent(); } $remoteLines = array_merge($remoteLines, $aa->getLinesContent()); } if ($i < $bb->getStart() || $i > $bb->getEnd()) { $localLines[] = $base[$i]->getContent(); } elseif ($i == $bb->getStart()) { if ($bb->getType() == Hunk::ADDED) { $localLines[] = $base[$i]->getContent(); } $localLines = array_merge($localLines, $bb->getLinesContent()); } } } else { $remoteLines = $aa->getLinesContent(); $localLines = $bb->getLinesContent(); } $b->next(); return new MergeConflict($baseLines, $remoteLines, $localLines, $start, $mergedLine); }
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 line on which the merge conflict appears on the merged result. @return MergeConflict The merge conflict.
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)) { return $value; } } return static::value($default); }
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); continue; } $result = array_merge($result, static::flatten($item, $depth - 1)); continue; } $result[] = $item; } return $result; }
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); } return $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)) { $nodes = $doc->documentElement->getElementsByTagName($tagName); if (false == $elementCount) { $elementCount = $nodes->length; } for ($i = 0; $i < $elementCount; $i++) { $result[] = self::domNodeToArray($nodes->item($i)); } } else { $result = self::domNodeToArray($doc->documentElement); } return $result; }
@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. $this->setup(); $file = tempnam($this->dir, ''); try { return $this->mergeFile($file, $base, $remote, $local); } catch (GitException $e) { // Get conflicts by reading from the file. $conflicts = []; $merged = []; self::getConflicts($file, $base, $remote, $local, $conflicts, $merged); $merged = implode("", $merged); // Set the file to the merged one with the first text for conflicts. file_put_contents($file, $merged); $this->git->add($file); $this->git->commit('Resolve merge conflict.'); throw new MergeException('A merge conflict has occurred.', $conflicts, $merged, 0, $e); } }
{@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->checkoutNewBranch('original'); } else { $this->git->checkout('original'); $this->git->rebase('master'); } file_put_contents($file, $remote); $this->git->add($file); $this->git->commit('Add remote.'); $this->git->checkout('master'); file_put_contents($file, $local); $this->git->add($file); $this->git->commit('Add local.'); $this->git->merge('original'); return file_get_contents($file); }
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 = [ '<<<<<<< HEAD' => 'local', '||||||| merged common ancestors' => 'base', '=======' => 'remote', '>>>>>>> original' => 'end conflict', ]; // Create hunks from the text diff. $differ = new Differ(); $remoteDiff = Line::createArray($differ->diffToArray($baseText, $remoteText)); $localDiff = Line::createArray($differ->diffToArray($baseText, $localText)); $remote_hunks = new \ArrayObject(Hunk::createArray($remoteDiff)); $local_hunks = new \ArrayObject(Hunk::createArray($localDiff)); $remoteIterator = $remote_hunks->getIterator(); $localIterator = $local_hunks->getIterator(); $base = []; $remote = []; $local = []; $lineNumber = -1; $newLine = 0; $skipedLines = 0; $addingConflict = false; // Loop over all the lines in the file. while ($lineIterator->valid()) { $line = $lineIterator->current(); if (array_key_exists(trim($line), $conflictIndicator)) { // Check for a line matching a conflict indicator. $state = $conflictIndicator[trim($line)]; $skipedLines++; if ($state == 'end conflict') { // We just treated a merge conflict. $conflicts[] = new MergeConflict($base, $remote, $local, $lineNumber, $newLine); if ($lineNumber == -1) { $lineNumber = 0; } $lineNumber += count($base); $newLine += count($remote); $base = []; $remote = []; $local = []; $remoteIterator->next(); $localIterator->next(); if ($addingConflict) { // Advance the counter for conflicts with adding. $lineNumber++; $newLine++; $addingConflict = false; } $state = 'unchanged'; } } else { switch ($state) { case 'local': $local[] = $line; $skipedLines++; break; case 'base': $base[] = $line; $skipedLines++; if ($lineNumber == -1) { $lineNumber = 0; } break; case 'remote': $remote[] = $line; $merged[] = $line; break; case 'unchanged': if ($lineNumber == -1) { $lineNumber = 0; } $merged[] = $line; /** @var Hunk $r */ $r = $remoteIterator->current(); /** @var Hunk $l */ $l = $localIterator->current(); if ($r == $l) { // If they are the same, treat only one. $localIterator->next(); $l = $localIterator->current(); } // A hunk has been successfully merged, so we can just // tally the lines added and removed and skip forward. if ($r && $r->getStart() == $lineNumber) { if (!$r->hasIntersection($l)) { $lineNumber += count($r->getRemovedLines()); $newLine += count($r->getAddedLines()); $lineIterator->seek($newLine + $skipedLines - 1); $remoteIterator->next(); } else { // If the conflict occurs on added lines, the // next line in the merge will deal with it. if ($r->getType() == Hunk::ADDED && $l->getType() == Hunk::ADDED) { $addingConflict = true; } else { $lineNumber++; $newLine++; } } } elseif ($l && $l->getStart() == $lineNumber) { if (!$l->hasIntersection($r)) { $lineNumber += count($l->getRemovedLines()); $newLine += count($l->getAddedLines()); $lineIterator->seek($newLine + $skipedLines - 1); $localIterator->next(); } else { $lineNumber++; $newLine++; } } else { $lineNumber++; $newLine++; } break; } } $lineIterator->next(); } $rawBase = self::splitStringByLines($baseText); $lastConflict = end($conflicts); // Check if the last conflict was at the end of the text. if ($lastConflict->getBaseLine() + count($lastConflict->getBase()) == count($rawBase)) { // Fix the last lines of all the texts as we can not know from // the merged text if there was a new line at the end or not. $base = self::fixLastLine($lastConflict->getBase(), $rawBase); $remote = self::fixLastLine($lastConflict->getRemote(), self::splitStringByLines($remoteText)); $local = self::fixLastLine($lastConflict->getLocal(), self::splitStringByLines($localText)); $newConflict = new MergeConflict( $base, $remote, $local, $lastConflict->getBaseLine(), $lastConflict->getMergedLine() ); $conflicts[key($conflicts)] = $newConflict; $lastMerged = end($merged); $lastRemote = end($remote); if ($lastMerged !== $lastRemote && rtrim($lastMerged) === $lastRemote) { $merged[key($merged)] = $lastRemote; } } }
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 be apended to this array. @param string[] $merged The merged text resolving conflicts by using the first set of changes.
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 = $tempfile.'.git'; $this->git = $this->wrapper->init($this->dir); } if ($this->git) { $this->git->config('user.name', 'GitMerge'); $this->git->config('user.email', '[email protected]'); $this->git->config('merge.conflictStyle', 'diff3'); } }
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), \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileinfo) { if ($fileinfo->isDir()) { rmdir($fileinfo->getRealPath()); } else { unlink($fileinfo->getRealPath()); } } rmdir($this->dir); unset($this->git); } }
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 ($t) { return mb_strtolower($t, 'UTF-8'); }, preg_split("/[\\s$delimiters]+/", $string, -1, PREG_SPLIT_NO_EMPTY)), function ($word) use ($stopWords) { return !in_array($word, $stopWords); } )); if ($asString) { return implode(' ', $result); } return $result; }
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) { return $remote; } // Return nothing and let sub-classes deal with it. return null; }
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"; $response .= "laravel_session\n"; $response .= $this->session->getId()."\n"; $response .= 'timestamp='.time(); if ($this->session instanceof SessionInterface) { $this->session->set(self::SESSION_KEY.'_auth', $this->config->getLogin()); } elseif ($this->session instanceof Session) { $this->session->put(self::SESSION_KEY.'_auth', $this->config->getLogin()); } else { throw new Exchange1CException(sprintf('Session is not insatiable interface %s or %s', SessionInterface::class, Session::class)); } } else { $response = "failure\n"; } return $response; }
@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->getFilePart(); return $response; }
Запрос параметров от сайта Далее следует запрос следующего вида: http://<сайт>/<путь> /1c-exchange?type=catalog&mode=init В ответ система управления сайтом передает две строки: 1. zip=yes, если сервер поддерживает обмен в zip-формате - в этом случае на следующем шаге файлы должны быть упакованы в zip-формате или zip=no - в этом случае на следующем шаге файлы не упаковываются и передаются каждый по отдельности. 2. file_limit=<число>, где <число> - максимально допустимый размер файла в байтах для передачи за один запрос. Если системе "1С:Предприятие" понадобится передать файл большего размера, его следует разделить на фрагменты. @return string
entailment
public function import(): string { $this->authService->auth(); $filename = $this->request->get('filename'); switch ($filename) { case 'import.xml': { $this->categoryService->import(); break; } case 'offers.xml': { $this->offerService->import(); break; } } $response = "success\n"; $response .= "laravel_session\n"; $response .= $this->request->getSession()->getId()."\n"; $response .= 'timestamp='.time(); return $response; }
На последнем шаге по запросу из "1С:Предприятия" производится пошаговая загрузка данных по запросу с параметрами вида http://<сайт>/<путь> /1c_exchange.php?type=catalog&mode=import&filename=<имя файла> Во время загрузки система управления сайтом может отвечать в одном из следующих вариантов. 1. Если в первой строке содержится слово "progress" - это означает необходимость послать тот же запрос еще раз. В этом случае во второй строке будет возвращен текущий статус обработки, объем загруженных данных, статус импорта и т.д. 2. Если в ответ передается строка со словом "success", то это будет означать сообщение об успешном окончании обработки файла. Примечание. Если в ходе какого-либо запроса произошла ошибка, то в первой строке ответа системы управления сайтом будет содержаться слово "failure", а в следующих строках - описание ошибки, произошедшей в процессе обработки запроса. Если произошла необрабатываемая ошибка уровня ядра продукта или sql-запроса, то будет возвращен html-код. @return string
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; } } throw new Exchange1CException(sprintf('Model %s not instantiable interface %s', $config->getModelClass($interface), $interface)); }
Если модель в конфиге не установлена, то импорт не будет произведен. @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 -&gt; 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->xml) { $commerce->classifier->xml->saveXML($classifierFile); } else { $commerce->classifier->xml = simplexml_load_string(file_get_contents($classifierFile)); } $this->beforeProductsSync(); if ($groupClass = $this->getGroupClass()) { $groupClass::createTree1c($commerce->classifier->getGroups()); } $productClass = $this->getProductClass(); $productClass::createProperties1c($commerce->classifier->getProperties()); foreach ($commerce->catalog->getProducts() as $product) { if (!$model = $productClass::createModel1c($product)) { throw new Exchange1CException("Модель продукта не найдена, проверьте реализацию $productClass::createModel1c"); } $this->parseProduct($model, $product); $this->_ids[] = $model->getPrimaryKey(); $model = null; unset($model, $product); gc_collect_cycles(); } $this->afterProductsSync(); }
Базовый метод запуска импорта. @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->each(function ($item) { if (!$item->{$this->childrenName}) { $item->{$this->childrenName} = app()->make('Illuminate\Support\Collection'); } }); // Remove items with missing ancestor. if ($this->removeItemsWithMissingAncestor) { $collection = $this->reject(function ($item) use ($parentColumn) { if ($item->$parentColumn) { $missingAncestor = $this->anAncestorIsMissing($item); return $missingAncestor; } }); } // Add items to children collection. foreach ($collection->items as $key => $item) { if ($item->$parentColumn && isset($collection[$item->$parentColumn])) { $collection[$item->$parentColumn]->{$this->childrenName}->push($item); $keysToDelete[] = $item->id; } } // Delete moved items. $this->items = array_values(Arr::except($collection->items, $keysToDelete)); return $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) { if ($parent_string) { $item_string = ($parent_string === true) ? $item->$column : $parent_string.$indentChars.$item->$column; } else { $item_string = str_repeat($indentChars, $level).$item->$column; } $flattened[$item->id] = $item_string; if ($item->{$this->childrenName}) { $this->listsFlattened($column, $item->{$this->childrenName}, $level + 1, $flattened, $indentChars, ($parent_string) ? $item_string : null); } } return $flattened; }
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_string @return array
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->anAncestorIsMissing($parent); }
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($value); } $type = (\gettype($value) && $value !== null) ? \gettype($value) : 'string'; $func = $this->serializationMap[$type]; return $this->$func($value); }
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 supported in Serializer. Loop through it and serialize the output.' ); } if (\is_resource($value)) { throw new SerializerException('Resource is not supported in Serializer'); } }
@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->unserializeData($value); } if (isset($value[self::SCALAR_TYPE])) { return $this->getScalarValue($value); } if (isset($value[self::CLASS_PARENT_KEY]) && 0 === strcmp($value[self::CLASS_PARENT_KEY], 'SplFixedArray')) { return SplFixedArraySerializer::unserialize($this, $value[self::CLASS_IDENTIFIER_KEY], $value); } if (isset($value[self::CLASS_IDENTIFIER_KEY])) { return $this->unserializeObject($value); } return \array_map([$this, __FUNCTION__], $value); }
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 $value[self::SCALAR_VALUE]; case 'NULL': return self::NULL_VAR; } return $value[self::SCALAR_VALUE]; }
@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]); } if ($className[0] === '@') { return self::$objectMapping[substr($className, 1)]; } if (!class_exists($className)) { throw new SerializerException('Unable to find class '.$className); } return (null === ($obj = $this->unserializeDateTimeFamilyObject($value, $className))) ? $this->unserializeUserDefinedObject($value, $className) : $obj; }
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; } return $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:'.strlen($className).':"'.$className.'":', \serialize($obj) ); return \unserialize($serialized); }
@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); if (\method_exists($obj, '__wakeup')) { $obj->__wakeup(); } return $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, $this->unserializeData($propertyValue)); } catch (ReflectionException $e) { $obj->$property = $this->unserializeData($propertyValue); } } return $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] = $this->serializeData($field); } return $this->serializeData($toArray); }
@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($value); $className = $reflection->getName(); return $this->serializeInternalClass($value, $className, $reflection); }
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, $paramsToSerialize)); return $data; }
@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::replaceKeys($replacements, $value); } $return[$key] = $value; } return $return; }
@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 $array; }
@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 ReflectionClass($className); return $ref->newInstanceArgs( array($serializer->unserialize($value['data']['date']), $dateTimeZone) ); }
@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 $imapStream; }
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 inaccurate (see also RFC2060, section 6.4.4). @param string $criteria String, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted. Results will match all criteria entries. ALL - return all mails matching the rest of the criteria ANSWERED - match mails with the \\ANSWERED flag set BCC "string" - match mails with "string" in the Bcc: field BEFORE "date" - match mails with Date: before "date" BODY "string" - match mails with "string" in the body of the mail CC "string" - match mails with "string" in the Cc: field DELETED - match deleted mails FLAGGED - match mails with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set FROM "string" - match mails with "string" in the From: field KEYWORD "string" - match mails with "string" as a keyword NEW - match new mails OLD - match old mails ON "date" - match mails with Date: matching "date" RECENT - match mails with the \\RECENT flag set SEEN - match mails that have been read (the \\SEEN flag is set) SINCE "date" - match mails with Date: after "date" SUBJECT "string" - match mails with "string" in the Subject: TEXT "string" - match mails with text "string" TO "string" - match mails with "string" in the To: UNANSWERED - match mails that have not been answered UNDELETED - match mails that are not deleted UNFLAGGED - match mails that are not flagged UNKEYWORD "string" - match mails that do not have the keyword "string" UNSEEN - match mails which have not been read yet @return array Mails ids
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->serverEncoding); } if(isset($mail->from)) { $mail->from = $this->decodeMimeStr($mail->from, $this->serverEncoding); } if(isset($mail->to)) { $mail->to = $this->decodeMimeStr($mail->to, $this->serverEncoding); } } } return $mails; }
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 to this mail id in_reply_to - is a reply to this mail id size - size in bytes uid - UID the mail has in the mailbox msgno - mail sequence number in the mailbox recent - this mail is flagged as recent flagged - this mail is flagged answered - this mail is flagged as answered deleted - this mail is flagged for deletion seen - this mail is flagged as already read draft - this mail is flagged as being a draft @param array $mailsIds @return array
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 of mail in octets @param int $criteria @param bool $reverse @return array Mails ids
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->decodeMimeStr($head->subject, $this->serverEncoding) : null; $mail->fromName = isset($head->from[0]->personal) ? $this->decodeMimeStr($head->from[0]->personal, $this->serverEncoding) : null; $mail->fromAddress = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); if(isset($head->to)) { $toStrings = array(); foreach($head->to as $to) { if(!empty($to->mailbox) && !empty($to->host)) { $toEmail = strtolower($to->mailbox . '@' . $to->host); $toName = isset($to->personal) ? $this->decodeMimeStr($to->personal, $this->serverEncoding) : null; $toStrings[] = $toName ? "$toName <$toEmail>" : $toEmail; $mail->to[$toEmail] = $toName; } } $mail->toString = implode(', ', $toStrings); } if(isset($head->cc)) { foreach($head->cc as $cc) { $mail->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? $this->decodeMimeStr($cc->personal, $this->serverEncoding) : null; } } if(isset($head->reply_to)) { foreach($head->reply_to as $replyTo) { $mail->replyTo[strtolower($replyTo->mailbox . '@' . $replyTo->host)] = isset($replyTo->personal) ? $this->decodeMimeStr($replyTo->personal, $this->serverEncoding) : null; } } $mailStructure = imap_fetchstructure($this->getImapStream(), $mailId, FT_UID); if(empty($mailStructure->parts)) { $this->initMailPart($mail, $mailStructure, 0, $markAsSeen); } else { foreach($mailStructure->parts as $partNum => $partStructure) { $this->initMailPart($mail, $partStructure, $partNum + 1, $markAsSeen); } } return $mail; }
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_convert_encoding($string, $toEncoding, $fromEncoding); } } return $convertedString ?: $string; }
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->getName(), ), ); }
@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($value); }
@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 ($splFixedArray->toArray() as $key => $field) { $toArray[Serializer::SCALAR_VALUE][$key] = $serializer->serialize($field); } return $toArray; }
@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(); $instance->setSize(count($data)); foreach ($data as $k => $v) { $instance[$k] = $v; } return $instance; }
@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 => \sprintf( 'P%sY%sM%sDT%sH%sM%sS', $dateInterval->y, $dateInterval->m, $dateInterval->d, $dateInterval->h, $dateInterval->i, $dateInterval->s ), ), 'invert' => array( Serializer::SCALAR_TYPE => 'integer', Serializer::SCALAR_VALUE => (empty($dateInterval->invert)) ? 0 : 1, ), 'days' => array( Serializer::SCALAR_TYPE => \gettype($dateInterval->days), Serializer::SCALAR_VALUE => $dateInterval->days, ), ); }
@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->loadXML($xml); $xmlDoc->preserveWhiteSpace = false; $xmlDoc->formatOutput = true; return $xmlDoc->saveXML(); }
@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); $this->arrayToXml($value, $subnode); } else { $subnode = $xmlData->addChild("$key", "$value"); $type = \gettype($value); if ('array' !== $type) { $subnode->addAttribute('type', $type); } } } }
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' ); foreach (File::allFiles($skeletonDirPath, true) as $filePath) { $filePath = realpath($filePath); $destFilePath = Str::replaceFirst( $skeletonDirPath, $packagePath, $filePath ); $this->copyFileWithDirsCreating($filePath, $destFilePath); } $this->copyStubs($packagePath, $package, $packageFolderName); $variables = $this->getVariables( $vendor, $package, $vendorFolderName, $packageFolderName ); $this->replaceTemplates($packagePath, $variables); $this->info('Skeleton was successfully copied.'); }
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'; $configFilePath = $this->packageBaseDir.'/stubs/config.php'; $filePaths = [ $facadeFilePath => "$packagePath/src/Facades/$package.php.tpl", $mainClassFilePath => "$packagePath/src/$package.php.tpl", $mainClassTestFilePath => "$packagePath/tests/{$package}Test.php.tpl", $configFilePath => "$packagePath/config/$packageFolderName.php", ]; foreach ($filePaths as $filePath => $destFilePath) { $this->copyFileWithDirsCreating($filePath, $destFilePath); } }
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; } try { $newFileContent = $phpEngine->get($filePath, $variables); } catch (Exception $e) { $this->error("Template [$filePath] contains syntax errors"); $this->error($e->getMessage()); continue; } $filePathWithoutTplExt = Str::replaceLast( '.tpl', '', $filePath ); File::put($filePathWithoutTplExt, $newFileContent); File::delete($filePath); } }
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" ); $composerKeywords = $this->getComposerKeywords($packageWords); $packageHumanName = $this->askUser( 'The package human name?', Str::title($packageWords) ); return [ 'vendor' => $vendor, 'package' => $package, 'vendorFolderName' => $vendorFolderName, 'packageFolderName' => $packageFolderName, 'packageHumanName' => $packageHumanName, 'composerName' => "$vendorFolderName/$packageFolderName", 'composerDesc' => $composerDescription, 'composerKeywords' => $composerKeywords, 'license' => $this->askUser('The package licence?', 'MIT'), 'phpVersion' => $this->askUser('Php version constraint?', '>=7.0'), 'aliasName' => $packageFolderName, 'configFileName' => $packageFolderName, 'year' => date('Y'), 'name' => $this->askUser('Your name?'), 'email' => $this->askUser('Your email?'), 'githubPackageUrl' => "https://github.com/$vendorFolderName/$packageFolderName", ]; }
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 === false) { throw RuntimeException::noAccessTo($path); } return $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 "\"$keyword\""; }, $keywords); return implode(",\n".str_repeat(' ', 4), $keywords); }
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); } $this->info("\"$command\" was successfully ran."); }
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; } } return 'Elements'; }
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"; $packagePath = base_path($relPackagePath); try { $this->composerRemovePackage($vendorFolderName, $packageFolderName); $this->removePackageFolder($packagePath); $this->unregisterPackage($vendor, $package, "packages/$vendorFolderName/$packageFolderName"); $this->composerDumpAutoload(); } catch (Exception $e) { $this->error($e->getMessage()); return -1; } }
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) { throw RuntimeException::commandExecutionFailed( $command, $returnStatusCode ); } $this->info("\"$command\" was successfully ran."); }
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( $command, $returnStatusCode ); } $this->info("\"$command\" was successfully ran."); }
Init git repo. @param string $repoPath
entailment