sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse): void
{
/**
* Disable tracy bar
*/
if (class_exists('\Tracy\Debugger') && property_exists('\Tracy\Debugger', 'productionMode')) {
\Tracy\Debugger::$productionMode = TRUE;
}
/**
* Set Content-Type header
*/
$httpResponse->setContentType($this->contentType, $this->output_encoding);
/**
* Set Content-Disposition header
*/
$httpResponse->setHeader('Content-Disposition', 'attachment'
. '; filename="' . $this->name . '"');
/*. '; filename*=' . $this->output_encoding . '\'\'' . rawurlencode($this->name));*/
/**
* Set other headers
*/
foreach ($this->headers as $key => $value) {
$httpResponse->setHeader($key, $value);
}
if (function_exists('ob_start')) {
ob_start();
}
/**
* Output data
*/
if($this->include_bom && strtolower($this->output_encoding) == 'utf-8'){
echo b"\xEF\xBB\xBF";
}
$delimiter = '"' . $this->delimiter . '"';
foreach ($this->data as $row) {
if (strtolower($this->output_encoding) == 'utf-8') {
echo('"' . implode($delimiter, (array) $row) . '"');
} else {
echo(iconv('UTF-8', $this->output_encoding, '"' . implode($delimiter, (array) $row) . '"'));
}
echo "\r\n";
}
if (function_exists('ob_end_flush')) {
ob_end_flush();
}
} | Sends response to output.
@param Nette\Http\IRequest $httpRequest
@param Nette\Http\IResponse $httpResponse
@return void | entailment |
protected function doRender(array $options)
{
if (!isset($this->templateEngine)) {
throw new InvalidArgumentException('Missing template engine');
}
if (!isset($this->label)) {
throw new InvalidArgumentException('Missing provider label');
}
if (isset($options[$this->label])) {
$options = array_merge($this->options, $options[$this->label], $options);
unset($options[$this->label]);
} else {
$options = $options + $this->options;
}
$template = sprintf(
'EzSystemsShareButtonsBundle::%s/%s',
$this->templateName,
$options['template']
);
return $this->templateEngine->render($template, $options);
} | Performs share button rendering.
@param array $options
@return string
@throws \InvalidArgumentException if template engine is not set
@throws \InvalidArgumentException if provider label is not set | entailment |
public static function create($id)
{
$language = GettextLanguage::getById($id);
if ($language === null) {
throw new UserMessageException(t('Unknown locale identifier: %s', $id));
}
$pluralForms = [];
foreach ($language->categories as $category) {
$pluralForms[] = $category->id . ':' . $category->examples;
}
$result = new static();
$result->id = $language->id;
$result
->setIsApproved(false)
->setIsSource(false)
->setName($language->name)
->setPluralForms($pluralForms)
->setPluralFormula($language->formula)
->setRequestedBy(null)
->setRequestedOn(null)
;
return $result;
} | Create a new (unsaved and unapproved) Locale instance given its locale ID.
@param string $id
@return static | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$method = strtoupper($request->getMethod());
// if the request not is cachable, move to $next
if ('GET' !== $method && 'HEAD' !== $method) {
return $next($request);
}
// If we can cache the request
$key = $this->createCacheKey($request);
$cacheItem = $this->pool->getItem($key);
if ($cacheItem->isHit()) {
// return cached response
$data = $cacheItem->get();
$response = $data['response'];
$response = $response->withBody($this->streamFactory->createStream($data['body']));
return new FulfilledPromise($response);
}
return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) {
if ($this->isCacheable($response)) {
$bodyStream = $response->getBody();
$body = $bodyStream->__toString();
if ($bodyStream->isSeekable()) {
$bodyStream->rewind();
} else {
$response = $response->withBody($this->streamFactory->createStream($body));
}
$cacheItem->set(['response' => $response, 'body' => $body])
->expiresAfter($this->getMaxAge($response));
$this->pool->save($cacheItem);
}
return $response;
});
} | {@inheritdoc} | entailment |
protected function isCacheable(ResponseInterface $response)
{
if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) {
return false;
}
if (!$this->config['respect_cache_headers']) {
return true;
}
if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) {
return false;
}
return true;
} | Verify that we can cache this response.
@param ResponseInterface $response
@return bool | entailment |
public function addVisit($type, $count = 1, DateTime $dateTime = null, AddressInterface $ipAddress = null)
{
$count = (int) $count;
if ($count > 0) {
if ($dateTime === null) {
$dateTime = new DateTime();
}
if ($ipAddress === null) {
$ipAddress = $this->getIPAddress();
}
$this->connection->executeQuery(
'insert into CommunityTranslationIPControl
(type, ip, dateTime, count)
values (?, ?, ?, ?)
on duplicate key update count = count + ?
',
[
(string) $type,
(string) $ipAddress,
$dateTime->format($this->connection->getDatabasePlatform()->getDateTimeFormatString()),
$count,
$count,
]
);
}
} | Count a visit for a specified type.
@param string $type The type identifier
@param int $count The number of visits to count [default: 1]
@param DateTime $dateTime The date/time to record [default: now]
@param AddressInterface $ipAddress The IP address to record [default: the current one] | entailment |
public function clearVisits(DateTime $before, $type = null)
{
$query = 'delete from CommunityTranslationIPControl where dateTime < ?';
$params = [$before->format($this->connection->getDatabasePlatform()->getDateTimeFormatString())];
if ($type !== null) {
$query .= ' and type = ?';
$params[] = (string) $type;
}
$rs = $this->connection->executeQuery($query, $params);
return (int) $rs->rowCount();
} | Clear visits older than a specified date/time.
@param DateTime $before
@param string|null $type The type identifier for the visits to be deleted. Set to null to delete logs for all types
@return int Returns the number of deleted records | entailment |
protected function approveTranslation($access, TranslationEntity $translation, UserEntity $user, $packageVersionID)
{
if ($access < Access::ADMIN) {
throw new UserMessageException(t('Access denied'));
}
if ($translation->isCurrent()) {
throw new UserMessageException(t('The selected translation is already the current one'));
}
$translationID = $translation->getID();
$translations = $this->convertTranslationToGettext($translation, false);
$importer = $this->app->make(Importer::class);
$importer->import($translations, $translation->getLocale(), $user, ImportOptions::forAdministrators());
$this->getEntityManager()->clear();
$translation = $this->app->make(TranslationRepository::class)->find($translationID);
$result = $this->app->make(Editor::class)->getTranslations($translation->getLocale(), $translation->getTranslatable());
return $this->app->make(ResponseFactoryInterface::class)->json($result);
} | @param int $access
@param TranslationEntity $translation
@param UserEntity $user
@param mixed $packageVersionID
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function denyTranslation($access, TranslationEntity $translation)
{
if ($access < Access::ADMIN) {
throw new UserMessageException(t('Access denied'));
}
if ($translation->isCurrent()) {
throw new UserMessageException(t('The selected translation is already the current one'));
}
$em = $this->getEntityManager();
$translation->setIsApproved(false);
$em->persist($translation);
$em->flush();
$result = $this->app->make(Editor::class)->getTranslations($translation->getLocale(), $translation->getTranslatable());
unset($result['current']);
return $this->app->make(ResponseFactoryInterface::class)->json($result);
} | @param int $access
@param TranslationEntity $translation
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function reuseTranslation($access, TranslationEntity $translation, UserEntity $user, $packageVersionID)
{
if ($translation->isCurrent()) {
throw new UserMessageException(t('The selected translation is already the current one'));
}
$translationID = $translation->getID();
$translations = $this->convertTranslationToGettext($translation, $access < Access::ADMIN);
$importer = $this->app->make(Importer::class);
$imported = $importer->import($translations, $translation->getLocale(), $user, ($access >= Access::ADMIN) ? ImportOptions::forAdministrators() : ImportOptions::forTranslators());
$this->getEntityManager()->clear();
$translation = $this->app->make(TranslationRepository::class)->find($translationID);
if ($imported->newApprovalNeeded > 0) {
$this->app->make(NotificationRepository::class)->translationsNeedApproval(
$translation->getLocale(),
$imported->newApprovalNeeded,
$user->getUserID(),
($packageVersionID === self::PACKAGEVERSION_UNREVIEWED) ? null : $packageVersionID
);
}
$result = $this->app->make(Editor::class)->getTranslations($translation->getLocale(), $translation->getTranslatable());
if ($imported->newApprovalNeeded && !$imported->addedAsCurrent) {
$result['message'] = t('Since the current translation is approved, you have to wait that this new translation will be approved');
}
if ($imported->addedNotAsCurrent || $imported->existingNotCurrentUntouched) {
unset($result['current']);
}
return $this->app->make(ResponseFactoryInterface::class)->json($result);
} | @param int $access
@param TranslationEntity $translation
@param UserEntity $user
@param mixed $packageVersionID
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function setTranslationFromEditor($access, LocaleEntity $locale, TranslatableEntity $translatable, UserEntity $user, PackageVersionEntity $packageVersion = null)
{
$translation = null;
$strings = $this->post('translated');
$numStrings = ($translatable->getPlural() === '') ? 1 : $locale->getPluralCount();
if (is_array($strings)) {
$strings = array_values($strings);
if (count($strings) === $numStrings) {
foreach ($strings as $index => $string) {
if (is_string($string)) {
$string = str_replace("\r", "\n", str_replace("\r\n", "\n", $string));
} else {
$string = '';
}
if (trim($string) === '') {
$translation = null;
break;
}
if ($index === 0) {
$translation = TranslationEntity::create($locale, $translatable, $strings[0]);
} else {
$translation->{"setText$index"}($string);
}
}
}
}
if ($translation === null) {
throw new UserMessageException(t('Please specify the translations'));
}
if ($access >= Access::ADMIN) {
if ($this->post('approved') === '1') {
$approved = true;
} elseif ($this->post('approved') === '0') {
$approved = false;
} else {
throw new UserMessageException(t('Missing parameter: %s', 'approved'));
}
} else {
$approved = false;
}
$translations = $this->convertTranslationToGettext($translation, !$approved);
$importer = $this->app->make(Importer::class);
$imported = $importer->import($translations, $locale, $user, ($access >= Access::ADMIN) ? ImportOptions::forAdministrators() : ImportOptions::forTranslators());
$this->getEntityManager()->clear();
$translatable = $this->app->make(TranslatableRepository::class)->find($translatable->getID());
$locale = $this->app->make(LocaleRepository::class)->find($locale->getID());
if ($imported->newApprovalNeeded > 0) {
$this->app->make(NotificationRepository::class)->translationsNeedApproval(
$locale,
$imported->newApprovalNeeded,
$user->getUserID(),
($packageVersion === null) ? null : $packageVersion->getID()
);
}
$result = $this->app->make(Editor::class)->getTranslations($locale, $translatable);
if ($imported->newApprovalNeeded && !$imported->addedAsCurrent) {
$result['message'] = t('Since the current translation is approved, you have to wait that this new translation will be approved');
}
return $this->app->make(ResponseFactoryInterface::class)->json($result);
} | @param int $access
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@param PackageVersionEntity $packageVersion
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function unsetTranslationFromEditor($access, LocaleEntity $locale, TranslatableEntity $translatable)
{
$currentTranslation = $this->app->make(TranslationRepository::class)->findOneBy([
'locale' => $locale,
'translatable' => $translatable,
'current' => true,
]);
if ($currentTranslation !== null) {
/* @var TranslationEntity $currentTranslation */
$em = $this->getEntityManager();
if ($currentTranslation->isApproved() && $access < Access::ADMIN) {
throw new UserMessageException(t("The current translation is marked as reviewed, so you can't remove it."));
}
$currentTranslation->setIsCurrent(false);
$em->persist($currentTranslation);
$em->flush();
$this->app->make(StatsRepository::class)->resetForTranslation($currentTranslation);
$result = $this->app->make(Editor::class)->getTranslations($locale, $translatable);
} else {
$result = [];
}
return $this->app->make(ResponseFactoryInterface::class)->json($result);
} | @param int $access
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
private function convertTranslationToGettext(TranslationEntity $translation, $markAsFuzzy)
{
$translatable = $translation->getTranslatable();
$locale = $translation->getLocale();
$translations = new GettextTranslations();
$translations->setLanguage($locale->getID());
$t = $translations->insert($translatable->getContext(), $translatable->getText(), $translatable->getPlural());
$t->setTranslation($translation->getText0());
if ($translatable->getPlural() !== '') {
switch ($locale->getPluralCount()) {
case 6:
$t->setPluralTranslation($translation->getText5(), 4);
/* @noinspection PhpMissingBreakStatementInspection */
case 5:
$t->setPluralTranslation($translation->getText4(), 3);
/* @noinspection PhpMissingBreakStatementInspection */
case 4:
$t->setPluralTranslation($translation->getText3(), 2);
/* @noinspection PhpMissingBreakStatementInspection */
case 3:
$t->setPluralTranslation($translation->getText2(), 1);
/* @noinspection PhpMissingBreakStatementInspection */
case 2:
$t->setPluralTranslation($translation->getText1(), 0);
break;
}
}
if ($markAsFuzzy) {
$t->addFlag('fuzzy');
}
return $translations;
} | @param TranslationEntity $translation
@param bool $markAsFuzzy
@return GettextTranslations | entailment |
private function getPackageSubscription(PackageEntity $package)
{
$em = $this->getEntityManager();
$me = $this->getAccessHelper()->getUserEntity('current');
$repo = $this->app->make(PackageSubscriptionRepository::class);
/* @var PackageSubscriptionRepository $repo */
$ps = $repo->find(['user' => $me, 'package' => $package]);
if ($ps === null) {
$ps = PackageSubscriptionEntity::create($me, $package, false);
$em->persist($ps);
$em->flush($ps);
}
return $ps;
} | @param PackageEntity $package
@return PackageSubscriptionEntity | entailment |
private function getPackageVersionSubscriptions(PackageEntity $package)
{
$result = [];
$me = $this->getAccessHelper()->getUserEntity('current');
$repo = $this->app->make(PackageVersionSubscriptionRepository::class);
/* @var PackageVersionSubscriptionRepository $repo */
$pvsList = $repo->createQueryBuilder('s')
->innerJoin(PackageVersionEntity::class, 'pv', 'WITH', 's.packageVersion = pv.id')
->where('s.user = :user')->setParameter('user', $me)
->andWhere('pv.package = :package')->setParameter('package', $package)
->getQuery()
->execute();
foreach ($package->getSortedVersions(true) as $packageVersion) {
$pvs = null;
foreach ($pvsList as $existing) {
if ($existing->getPackageVersion() === $packageVersion) {
$pvs = $existing;
break;
}
}
if ($pvs === null) {
$pvs = PackageVersionSubscriptionEntity::create($me, $packageVersion, false);
}
$result[] = $pvs;
}
return $result;
} | @param PackageEntity $package
@return PackageVersionSubscriptionEntity[] | entailment |
public static function create($domain, $whois)
{
$tld = substr(strrchr($domain, '.'), 1);
$parserClass = 'Wisdom\\Whois\\Parser\\Tld\\'.ucfirst($tld);
if (!class_exists($parserClass)) {
throw new WhoisParserNotFoundException(sprintf(
'Whois parser for .%s domains not found.',
$tld
));
}
return new $parserClass($domain, $whois);
} | Creates whois parser for given domain name.
@param string $domain
@param string $whois
@return Interface | entailment |
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/lightspeed-api.php', 'lightspeed-api');
$this->app->singleton(Lightspeed::class, function ($app) {
$config = $app['config']['lightspeed-api'];
return new Lightspeed($config);
});
$this->app->alias(Lightspeed::class, 'lightspeedapi');
} | Register the application services. | entailment |
public function purchase(array $parameters = [])
{
if ($this->isOldApi()) {
$requestClass = OldPurchaseRequest::class;
} else {
$requestClass = PurchaseRequest::class;
}
return $this->createRequest($requestClass, $parameters);
} | @param array $parameters
@return \Omnipay\InterKassa\Message\PurchaseRequest|\Omnipay\InterKassa\Message\OldPurchaseRequest | entailment |
public function completePurchase(array $parameters = [])
{
if ($this->isOldApi()) {
$requestClass = OldCompletePurchaseRequest::class;
} else {
$requestClass = CompletePurchaseRequest::class;
}
return $this->createRequest($requestClass, $parameters);
} | @param array $parameters
@return \Omnipay\InterKassa\Message\CompletePurchaseRequest|\Omnipay\InterKassa\Message\OldCompletePurchaseRequest | entailment |
public function findById($id)
{
$id = (int) $id;
if ($id) {
$sql = sprintf("SELECT id, name, created_at FROM {$this->tableName} WHERE id=%d LIMIT 1", $id);
if ($row = $this->adapter->selectRow($sql)) {
return $this->_makeModel($row);
}
}
return null;
} | FindByID
@param int $id
@return \Blade\Migrations\Migration|null | entailment |
public function findLast()
{
$sql = sprintf("SELECT id, name, created_at FROM {$this->tableName} ORDER BY id DESC LIMIT 1");
if ($row = $this->adapter->selectRow($sql)) {
return $this->_makeModel($row);
}
return null;
} | FindLast
@return \Blade\Migrations\Migration|null | entailment |
public function all()
{
$sql ="SELECT id, name, created_at FROM {$this->tableName} ORDER BY id DESC";
$data = $this->adapter->selectAll($sql);
$result = [];
foreach ($data as $row) {
$result[] = $this->_makeModel($row);
}
return $result;
} | Получить список всех Миграций
@return Migration[] | entailment |
public function insert(Migration $migration)
{
$sql = sprintf("INSERT INTO {$this->tableName} (name, data) VALUES ('%s', '%s')",
$this->adapter->escape($migration->getName()),
$this->adapter->escape($migration->getSql())
);
$this->getAdapter()->execute($sql);
} | Добавить Миграцию в базу
@param Migration $migration | entailment |
public function delete(Migration $migration)
{
if ($migration->isNew()) {
throw new \InvalidArgumentException(__METHOD__.": Expected NOT NEW migration");
}
$this->adapter->execute(sprintf("DELETE FROM {$this->tableName} WHERE id='%d'", $migration->getId()));
} | Удалить Миграцию из базы
@param Migration $migration | entailment |
public static function getCurrentArch(): string
{
$arch = php_uname('m');
if ($arch === "x86_64") {
$arch = "amd64";
} elseif ($arch === "i386") {
$arch = "386";
} else {
// TODO: Whats here?
printf('ERROR: Unexpected, please contact the maintainer or provide a pull request :)%s', PHP_EOL);
exit(1);
}
return $arch;
} | Returns the architecture of the current machine | entailment |
public static function getBinaryPath(): string
{
$binaryName = Utilities::getReleaseName();
$binaryPath = sprintf('%s/bin/%s', Utilities::getBasePath(), $binaryName);
return $binaryPath;
} | returns the binary name | entailment |
public static function downloadReleaseArchive(string $releaseName, string $version): bool
{
$archiveName = $releaseName . '.tar.gz';
$archivePath = sprintf('%s/%s', Utilities::getBasePath(), $archiveName);
$releaseUrl = sprintf(
'https://github.com/editorconfig-checker/editorconfig-checker/releases/download/%s/%s',
$version,
$archiveName
);
$result = file_put_contents($archivePath, fopen($releaseUrl, 'r'));
return $result > 0 || $result;
} | Downloads the release from the release page | entailment |
public static function extractReleaseArchive(string $releaseName): bool
{
return Utilities::decompress($releaseName) && Utilities::unpack($releaseName);
} | decompresses and extracts the release archive | entailment |
public static function decompress(string $releaseName): bool
{
try {
$p = new \PharData(sprintf("%s/%s.tar.gz", Utilities::getBasePath(), $releaseName));
$p->decompress();
} catch (Exception $e) {
printf('ERROR: Can not decompress the archive%s%s', PHP_EOL, $e);
return false;
}
return true;
} | decompresses the release archive | entailment |
public static function unpack(string $releaseName): bool
{
try {
$p = new \PharData(sprintf("%s/%s.tar", Utilities::getBasePath(), $releaseName));
$p->extractTo(Utilities::getBasePath());
if (!unlink(sprintf("%s/%s.tar", Utilities::getBasePath(), $releaseName))) {
printf('ERROR: Can not remove the decompressed archive%s', PHP_EOL);
return false;
}
} catch (\PharException $e) {
printf('ERROR: Can not unpack the archive%s%s', PHP_EOL, $e);
return false;
}
return true;
} | unpacks the release archive | entailment |
public static function constructStringFromArguments(array $arguments): string
{
$result = '';
foreach ($arguments as $argument) {
$result .= ' ' . $argument;
}
return $result;
} | Constructs the arguments the binary needs to be called by
the arguments providedunline | entailment |
public static function cleanup(): void
{
$releaseName = sprintf("%s/%s", Utilities::getBasePath(), Utilities::getReleaseName());
if (is_file($releaseName . '.tar.gz')) {
unlink($releaseName . '.tar.gz');
}
if (is_file($releaseName . '.tar')) {
unlink($releaseName . '.tar');
}
} | Removes all intermediate files | entailment |
public function setTopic($value)
{
$this->assertValidString($value, false);
if ($value === '') {
throw new \InvalidArgumentException('The topic must not be empty.');
}
$this->topic = $value;
} | Sets the topic.
@param string $value
@throws \InvalidArgumentException | entailment |
public function buildUrl($base)
{
$url = $base.$this::getApiName();
$parameters = http_build_query($this->getParams());
if (!empty($parameters)) {
$parameters = preg_replace(
'/%5B(?:[0-9]|[1-9][0-9]+)%5D=/',
'%5B%5D=',
$parameters
);
$url .= '?'.$parameters;
}
return $url;
} | BuildUrl
@param string $base
@return string | entailment |
public function processParameters()
{
$parameters = $this->getParameters();
$factory = $this->buildFactory();
$parametersType = $this->buildParametersType();
$request = $factory->create($parametersType);
if (!is_null($parameters)) {
$processorFactory = new ParametersProcessorFactory();
$processor = $processorFactory->create(gettype($parameters));
$request = $processor->convertToObjectParameters(
$request,
$parameters
);
}
return $request;
} | Fonction de process pour les parametres
@return mixed | entailment |
public function getAttributes()
{
$defaultPrefix = PhoneNumber::config()->get('default_country_code');
$attributes = [
'class' => 'text',
'placeholder' => _t(
__CLASS__ . '.Placeholder',
'Phone number links will be prefixed with +{prefix}',
['prefix' => $defaultPrefix]
),
];
return array_merge(
parent::getAttributes(),
$attributes
);
} | Return field attributes
@param Null
@return Array | entailment |
public function validate($validator)
{
// Don't validate empty fields
$this->value = trim($this->value);
if (empty($this->value)) {
return true;
}
$phone = PhoneNumber::create()->setValue($this->value);
if (!$phone->Link()) {
$validator->validationError(
$this->name,
_t(__CLASS__ . '.ValidationError', 'Please enter a valid phone number'),
'validation'
);
return false;
}
return true;
} | Return validation result
@param Validator $validator
@return Boolean | entailment |
public function setAction($action)
{
if (gettype($action) !== 'string') {
throw new BadParametersException(
sprintf(
' The action type ("%s") must be a string',
gettype($action)
)
);
}
$this->action = $action;
return $this;
} | setAction
Setter pour le nom de l'action
@param string $action
@return \Navitia\Component\Request\CoverageRequest | entailment |
public function matches($filter, $topic)
{
// Created by Steffen (https://github.com/kernelguy)
$tokens = explode('/', $filter);
$parts = [];
for ($i = 0, $count = count($tokens); $i < $count; ++$i) {
$token = $tokens[$i];
switch ($token) {
case '+':
$parts[] = '[^/#\+]*';
break;
case '#':
if ($i === 0) {
$parts[] = '[^\+\$]*';
} else {
$parts[] = '[^\+]*';
}
break;
default:
$parts[] = str_replace('+', '\+', $token);
break;
}
}
$regex = implode('/', $parts);
$regex = str_replace('$', '\$', $regex);
$regex = ';^'.$regex.'$;';
return preg_match($regex, $topic) === 1;
} | Check if the given topic matches the filter.
@param string $filter e.g. A/B/+, A/B/#
@param string $topic e.g. A/B/C, A/B/foo/bar/baz
@return bool true if topic matches the pattern | entailment |
protected function log($message, $context)
{
$logger = $this->getLogger();
if ($logger !== null) {
$logger->error($message, $context);
}
} | Curl operation error logging function
@param string $message
@param array $context | entailment |
private function readRemainingLength(PacketStream $stream)
{
$this->remainingPacketLength = 0;
$multiplier = 1;
do {
$encodedByte = $stream->readByte();
$this->remainingPacketLength += ($encodedByte & 127) * $multiplier;
$multiplier *= 128;
if ($multiplier > 128 * 128 * 128 * 128) {
throw new MalformedPacketException('Malformed remaining length.');
}
} while (($encodedByte & 128) !== 0);
} | Reads the remaining length from the given stream.
@param PacketStream $stream
@throws MalformedPacketException | entailment |
private function writeRemainingLength(PacketStream $stream)
{
$x = $this->remainingPacketLength;
do {
$encodedByte = $x % 128;
$x = (int) ($x / 128);
if ($x > 0) {
$encodedByte |= 128;
}
$stream->writeByte($encodedByte);
} while ($x > 0);
} | Writes the remaining length to the given stream.
@param PacketStream $stream | entailment |
protected function assertPacketFlags($value, $fromPacket = true)
{
if ($this->packetFlags !== $value) {
$this->throwException(
sprintf(
'Expected flags %02x but got %02x.',
$value,
$this->packetFlags
),
$fromPacket
);
}
} | Asserts that the packet flags have a specific value.
@param int $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertRemainingPacketLength($value = null, $fromPacket = true)
{
if ($value === null && $this->remainingPacketLength === 0) {
$this->throwException('Expected payload but remaining packet length is zero.', $fromPacket);
}
if ($value !== null && $this->remainingPacketLength !== $value) {
$this->throwException(
sprintf(
'Expected remaining packet length of %d bytes but got %d.',
$value,
$this->remainingPacketLength
),
$fromPacket
);
}
} | Asserts that the remaining length is greater than zero and has a specific value.
@param int|null $value value to test or null if any value greater than zero is valid
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidStringLength($value, $fromPacket = true)
{
if (strlen($value) > 0xFFFF) {
$this->throwException(
sprintf(
'The string "%s" is longer than 65535 byte.',
substr($value, 0, 50)
),
$fromPacket
);
}
} | Asserts that the given string is a well-formed MQTT string.
@param string $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidString($value, $fromPacket = true)
{
$this->assertValidStringLength($value, $fromPacket);
if (!mb_check_encoding($value, 'UTF-8')) {
$this->throwException(
sprintf(
'The string "%s" is not well-formed UTF-8.',
substr($value, 0, 50)
),
$fromPacket
);
}
if (preg_match('/[\xD8-\xDF][\x00-\xFF]|\x00\x00/x', $value)) {
$this->throwException(
sprintf(
'The string "%s" contains invalid characters.',
substr($value, 0, 50)
),
$fromPacket
);
}
} | Asserts that the given string is a well-formed MQTT string.
@param string $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidQosLevel($level, $fromPacket = true)
{
if ($level < 0 || $level > 2) {
$this->throwException(
sprintf(
'Expected a quality of service level between 0 and 2 but got %d.',
$level
),
$fromPacket
);
}
} | Asserts that the given quality of service level is valid.
@param int $level
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
public function up(Migration $migration)
{
if (!$migration->isNew()) {
throw new \InvalidArgumentException(__METHOD__.": Expected NEW migration");
}
// Загрузить SQL
$this->fileRepository->loadSql($migration);
$func = function () use ($migration) {
$this->_processMigrationSql($migration->getUp());
$this->getDbRepository()->insert($migration);
};
$this->_processMigration($migration, $func);
} | UP
@param Migration $migration
@throws \Exception | entailment |
public function down(Migration $migration, $loadFromFile = false)
{
if ($loadFromFile) {
$this->fileRepository->loadSql($migration);
} else {
$this->dbRepository->loadSql($migration);
}
$func = function () use ($migration) {
$this->_processMigrationSql($migration->getDown());
$this->dbRepository->delete($migration);
};
$this->_processMigration($migration, $func);
} | DOWN
@param Migration $migration
@param bool $loadFromFile | entailment |
private function _processMigration(Migration $migration, callable $command)
{
if ($migration->isTransaction()) {
$this->getDbRepository()->getAdapter()->transaction($command);
} else {
if ($this->logger) {
$this->logger->alert('NO TRANSACTION!');
}
$command();
}
} | Выполнить миграцию
@param Migration $migration
@param callable $command
@throws \Exception | entailment |
private function _processMigrationSql(array $sqlList)
{
foreach ($sqlList as $sql) {
if ($this->logger) {
$this->logger->info($sql.PHP_EOL);
}
$this->getDbRepository()->getAdapter()->execute($sql);
}
} | Выполнить полученный SQL
@param array $sqlList | entailment |
public static function run(array $arguments): int
{
$releaseName = Utilities::getReleaseName();
$binaryPath = Utilities::getBinaryPath();
if (!is_file($binaryPath)) {
Utilities::cleanup();
if (!Utilities::downloadReleaseArchive($releaseName, CORE_VERSION)) {
printf('ERROR: Can not download the archive%s', PHP_EOL);
return 1;
}
if (!Utilities::extractReleaseArchive($releaseName)) {
printf('ERROR: can not extract the archive%s', PHP_EOL);
return 1;
}
Utilities::cleanup();
}
array_shift($arguments);
$args = Utilities::constructStringFromArguments($arguments);
system($binaryPath . $args, $result);
return $result;
} | Entry point of this class to invoke all needed steps | entailment |
protected function applyCasts(bool $scalarOnly = false): void
{
// @codeCoverageIgnoreStart
if ( ! $scalarOnly) {
foreach (array_keys($this->casts()) as $key) {
$this->applyCast($key);
}
return;
}
// @codeCoverageIgnoreEnd
foreach ($this->casts() as $key => $type) {
if ( ! in_array($type, static::SCALAR_CASTS)) {
continue;
}
$this->applyCast($key);
}
} | Applies casts to currently set attributes.
This updates the values stored for the attributes with a cast type.
@param bool $scalarOnly | entailment |
protected function applyCast(string $key): void
{
$casts = $this->casts();
if ( ! count($casts) || ! array_key_exists($key, $casts)) {
return;
}
if ( ! isset($this->attributes[ $key ])) {
$value = null;
} else {
$value = $this->attributes[ $key ];
}
// If the cast type is a simple scalar, apply it and return
if (in_array($casts[ $key ], static::SCALAR_CASTS)) {
$this->attributes[ $key ] = call_user_func([$this, 'castValueAs' . ucfirst($casts[ $key ])], $value);
return;
}
// Otherwise attempt a data object cast
$dataObjectClass = $casts[ $key ];
$dataObjectArray = false;
// If the model is postfixed with [], an array of models is expected
if (substr($dataObjectClass, -2) === '[]') {
$dataObjectClass = substr($dataObjectClass, 0, -2);
$dataObjectArray = true;
}
if (null === $value) {
if ($dataObjectArray) {
$this->attributes[ $key ] = [];
return;
}
if ($this->castUnsetObjects) {
$this->attributes[ $key ] = $this->makeNestedDataObject($dataObjectClass, [], $key);
}
return;
}
if ($dataObjectArray) {
if (is_array($this->attributes[ $key ])) {
foreach ($this->attributes[ $key ] as $index => &$item) {
if (null === $item && ! $this->castUnsetObjects) {
continue;
}
if ( ! ($item instanceof $dataObjectClass)) {
$item = $this->makeNestedDataObject($dataObjectClass, $item ?: [], $key . '.' . $index);
}
}
}
unset($item);
return;
}
// Single data object
if ( ! ($this->attributes[ $key ] instanceof $dataObjectClass)) {
$this->attributes[ $key ] = $this->makeNestedDataObject(
$dataObjectClass,
$this->attributes[ $key ],
$key
);
}
} | Applies cast for a given attribute key.
@param string $key | entailment |
protected function makeNestedDataObject(string $class, $data, $key): DataObjectInterface
{
$data = ($data instanceof Arrayable) ? $data->toArray() : $data;
if ( ! is_array($data)) {
throw new UnexpectedValueException(
"Cannot instantiate data object '{$class}' with non-array data for key '{$key}'"
. (is_scalar($data) || is_object($data) && method_exists($data, '__toString')
? ' (data: ' . (string) $data . ')'
: null)
);
}
/** @var DataObjectInterface $data */
return new $class($data);
} | Makes a new nested data object for a given class and data.
@param string $class
@param mixed $data
@param string $key
@return DataObjectInterface | entailment |
public function getNextValue(string $sequenceName): int
{
$sequenceValue = $this->rawCollection()->findOneAndUpdate(
['_id' => $sequenceName],
['$inc' => ['seq' => 1]],
['upsert' => true]
);
if ($sequenceValue) {
$_id = $sequenceValue->seq + 1;
}
return $_id ?? 1;
} | Get next value for the sequence.
@param string $sequenceName sequence identifier string
@return int | entailment |
public function reduce( $degree, $lookAhead=null )
{
if ($lookAhead) {
$this->lookAhead = (int)$lookAhead;
}
$epsilon = deg2rad($degree);
$results = array();
for ($i = 0; $i < $this->count(); $i++) {
$j = min($i + $this->lookAhead, $this->lastKey());
$basePoint = $this->points[$i];
$results[] = $basePoint;
$boundPoint = $this->points[$j];
$theta = $this->_theta($basePoint, $boundPoint);
$a1 = $theta - $epsilon;
$a2 = $theta + $epsilon;
while (++$i < $j) {
$testPoint = $this->points[$i];
$delta = $this->_theta($basePoint, $testPoint);
if ($a1 < $delta && $delta < $a2) {
// Ommit this point
} else {
// This point is outside of the sleeve.
// Make this point the new base point.
break;
}
}
$i--; // Backup iterator
}
return $this->points = $results;
} | Reduce points with modified version of Zhao-Saalfeld simplification.
@param double $degree Angle between 0 & 360 to compare points.
@param integer $lookAhead Number of points to include in each sector
bound iteration.
@return array Reduced set of points | entailment |
private function _theta(PointInterface $a, PointInterface $b)
{
list($x1, $y1) = $a->getCoordinates();
list($x2, $y2) = $b->getCoordinates();
return atan2($y2-$y1, $x2 - $x1) + 2 * M_PI;
} | Calculate the angle, and add 2pi to protect against underflow.
@param PointInterface $a Base coordinate point.
@param PointInterface $b Subject coordinate point.
@return double None negative radian. | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(ControllerReadyEvent::class, function(ControllerReadyEvent $event) {
$event->addParameters($this->getParameters($event));
});
} | {@inheritdoc} | entailment |
private function getParameters(ControllerReadyEvent $event) : array
{
$controller = $event->getRouteMatch()->getControllerReflection();
$currentParameters = $event->getParameters();
$newParameters = [];
foreach ($controller->getParameters() as $parameter) {
$name = $parameter->getName();
if (isset($currentParameters[$name])) {
$newParameters[$name] = $this->getParameterValue($parameter, $currentParameters[$name]);
}
}
return $newParameters;
} | @param ControllerReadyEvent $event
@return array The value to assign to the function parameter.
@throws HttpException If the object cannot be instantiated. | entailment |
private function getParameterValue(\ReflectionParameter $parameter, $value)
{
$class = $parameter->getClass();
if ($class) {
$className = $class->getName();
if ($parameter->isVariadic()) {
$result = [];
foreach ($value as $subValue) {
$result[] = $this->getObject($className, $subValue);
}
return $result;
}
return $this->getObject($className, $value);
}
return $value;
} | @param \ReflectionParameter $parameter
@param mixed $value
@return mixed
@throws HttpException If the object cannot be instantiated. | entailment |
private function getObject(string $className, $value)
{
$packedObject = new PackedObject($className, $value);
try {
$object = $this->objectPacker->unpack($packedObject);
}
catch (ObjectNotConvertibleException $e) {
throw new HttpBadRequestException($e->getMessage(), $e);
}
catch (ObjectNotFoundException $e) {
throw new HttpNotFoundException($e->getMessage(), $e);
}
if ($object === null) {
throw new HttpInternalServerErrorException('No object packer available for ' . $className);
}
return $object;
} | @param string $className The resulting object class name.
@param mixed $value The raw parameter value to convert to an object.
@return object
@throws HttpException If the object cannot be instantiated. | entailment |
public function findOrCreateState($name)
{
if (!$this->stateCollection->hasState($name)) {
if ($this->stateCollection instanceof StateCollection) {
$this->stateCollection->addState($this->createState($name));
} else {
throw new \InvalidArgumentException('Overwrite this method to implement a different type!');
}
}
return $this->stateCollection->getState($name);
} | @param $name
@return \MetaborStd\Statemachine\StateInterface
@throws \Exception | entailment |
protected function findTransition(StateInterface $sourceState, StateInterface $targetState, $eventName = null, ConditionInterface $condition = null)
{
$conditionName = $condition ? $condition->getName() : null;
/* @var $transition TransitionInterface */
foreach ($sourceState->getTransitions() as $transition) {
$hasSameTargetState = ($transition->getTargetState() === $targetState);
$hasSameCondition = ($transition->getConditionName() == $conditionName);
$hasSameEvent = ($transition->getEventName() == $eventName);
if ($hasSameTargetState && $hasSameCondition && $hasSameEvent) {
return $transition;
}
}
} | @param StateInterface $sourceState
@param StateInterface $targetState
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
protected function addTransition(StateInterface $sourceState, TransitionInterface $sourceTransition)
{
if ($sourceState instanceof State) {
$sourceState->addTransition($sourceTransition);
} else {
throw new \InvalidArgumentException('Overwrite this method to implement a different type!');
}
} | @param StateInterface $sourceState
@param TransitionInterface $sourceTransition
@throws \InvalidArgumentException | entailment |
public function createTransition(StateInterface $sourceState, StateInterface $targetState, $eventName = null, ConditionInterface $condition = null)
{
return new Transition($targetState, $eventName, $condition);
} | @param StateInterface $sourceState
@param StateInterface $targetState
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
public function findOrCreateTransition($sourceStateName, $targetStateName, $eventName = null, ConditionInterface $condition = null)
{
$sourceState = $this->findOrCreateState($sourceStateName);
$targetState = $this->findOrCreateState($targetStateName);
$transition = $this->findTransition($sourceState, $targetState, $eventName, $condition);
if (!$transition) {
$transition = $this->createTransition($sourceState, $targetState, $eventName, $condition);
$this->addTransition($sourceState, $transition);
}
return $transition;
} | @param string $sourceStateName
@param string $targetStateName
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
public function createEvent(StateInterface $sourceState, $eventName)
{
if ($sourceState instanceof State) {
return $sourceState->getEvent($eventName);
} else {
throw new \InvalidArgumentException('Overwrite this method to implement a different type!');
}
} | @param StateInterface $sourceState
@param string $eventName
@return EventInterface | entailment |
public function addCommand($sourceStateName, $eventName, \SplObserver $command)
{
$this->findOrCreateEvent($sourceStateName, $eventName)->attach($command);
} | If there is no Transition from the SourceState with this Event use addCommandAndSelfTransition().
@param $sourceStateName
@param string $eventName
@param \SplObserver $command | entailment |
public function getData()
{
$migrations = $this->migrator->status();
if (!$migrations) {
return [];
}
$data = [];
$newMigrations = [];
foreach ($migrations as $migration) {
$name = $migration->getName();
if ($migration->isNew()) {
$status = '<comment>A</comment>';
$name = "<comment>{$name}</comment>";
} else if ($migration->isRemove()) {
$status = '<fg=red>D</fg=red>';
$name = "<fg=red>{$name}</fg=red>";
} else {
$status = '<info>Y</info>';
}
$row = [
$status,
$migration->getId(),
$migration->isNew() ? '' : $migration->getDate()->format('d.m.Y H:i:s'),
$name
];
if ($migration->isNew()) {
$newMigrations[] = $row;
} else {
$data[] = $row;
}
}
$data = array_reverse($data);
return array_merge($data, $newMigrations);
} | Run | entailment |
public function read($count)
{
$contentLength = strlen($this->data);
if ($this->position > $contentLength || $count > $contentLength - $this->position) {
throw new EndOfStreamException(
sprintf(
'End of stream reached when trying to read %d bytes. content length=%d, position=%d',
$count,
$contentLength,
$this->position
)
);
}
$chunk = substr($this->data, $this->position, $count);
if ($chunk === false) {
$chunk = '';
}
$readBytes = strlen($chunk);
$this->position += $readBytes;
return $chunk;
} | Returns the desired number of bytes.
@param int $count
@throws EndOfStreamException
@return string | entailment |
public function writeWord($value)
{
$this->write(chr(($value & 0xFFFF) >> 8));
$this->write(chr($value & 0xFF));
} | Appends a single word.
@param int $value | entailment |
public function cut()
{
$this->data = substr($this->data, $this->position);
if ($this->data === false) {
$this->data = '';
}
$this->position = 0;
} | Removes all bytes from the beginning to the current position. | entailment |
public static function where(
array $query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->where(
$query,
$projection,
$useCache
);
} | Gets a cursor of this kind of entities that matches the query from the
database.
@param array $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves a CacheableCursor instead
@return \Mongolid\Cursor\Cursor | entailment |
public static function first(
$query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->first(
$query,
$projection,
$useCache
);
} | Gets the first entity of this kind that matches the query.
@param mixed $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves the entity through a CacheableCursor
@return ActiveRecord | entailment |
public static function firstOrFail(
$query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->firstOrFail(
$query,
$projection,
$useCache
);
} | Gets the first entity of this kind that matches the query. If no
document was found, throws ModelNotFoundException.
@param mixed $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves the entity through a CacheableCursor
@throws ModelNotFoundException if no document was found
@return ActiveRecord | entailment |
public static function firstOrNew($id)
{
if ($entity = self::getDataMapperInstance()->first($id)) {
return $entity;
}
$entity = new static();
$entity->_id = $id;
return $entity;
} | Gets the first entity of this kind that matches the query. If no
document was found, a new entity will be returned with the
_if field filled.
@param mixed $id document id
@return ActiveRecord | entailment |
public function getDataMapper()
{
$dataMapper = Ioc::make(DataMapper::class);
$dataMapper->setSchema($this->getSchema());
return $dataMapper;
} | Returns a DataMapper configured with the Schema and collection described
in this entity.
@return DataMapper | entailment |
public function getSchema(): Schema
{
if ($schema = $this->instantiateSchemaInFields()) {
return $schema;
}
$schema = new DynamicSchema();
$schema->entityClass = get_class($this);
$schema->fields = $this->fields;
$schema->dynamic = $this->dynamic;
$schema->collection = $this->collection;
return $schema;
} | {@inheritdoc} | entailment |
protected function instantiateSchemaInFields()
{
if (is_string($this->fields)) {
if (is_subclass_of($instance = Ioc::make($this->fields), Schema::class)) {
return $instance;
}
}
} | Will check if the current value of $fields property is the name of a
Schema class and instantiate it if possible.
@return Schema|null | entailment |
protected function execute(string $action)
{
if (!$this->getCollectionName()) {
return false;
}
$options = [
'writeConcern' => new WriteConcern($this->getWriteConcern()),
];
if ($result = $this->getDataMapper()->$action($this, $options)) {
$this->syncOriginalAttributes();
}
return $result;
} | Performs the given action into database.
@param string $action datamapper function to execute
@return bool | entailment |
private static function getDataMapperInstance()
{
$instance = Ioc::make(get_called_class());
if (!$instance->getCollectionName()) {
throw new NoCollectionNameException();
}
return $instance->getDataMapper();
} | Returns the a valid instance from Ioc.
@throws NoCollectionNameException throws exception when has no collection filled
@return mixed | entailment |
public function loadConfiguration(): void
{
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('factory'))
->setImplement(IStandaloneFormFactory::class);
} | Register services | entailment |
public function run(callable $confirmationCallback = null, $migrationName = null)
{
if ($this->logger) {
$this->service->setLogger($this->logger);
}
// Выбранную миграцию
if ($migrationName) {
if (strpos($migrationName, DIRECTORY_SEPARATOR) !== false) {
$migrationName = basename($migrationName);
}
$migrations = [];
foreach ($this->service->getDiff(true) as $migration) {
if ($migration->getName() == $migrationName) {
$migrations[] = $migration;
}
}
if (!$migrations) {
$this->alert("<error>Migration `{$migrationName}` not found or applied already</error>");
return;
}
// Все миграции по списку
} else {
$migrations = $this->service->getDiff(!$this->optAuto); // только новые
}
if (!$migrations) {
$this->alert('<error>Nothing to migrate</error>');
return;
}
foreach ($migrations as $next) {
$title = $next->getName();
if ($next->isRemove()) {
$title = 'Rollback: ' . $title;
}
if ($this->optForce) {
// Добавление
if ($next->isNew()) {
$this->info("<info>{$title}</info>");
// Удаление
} else {
$this->error("<error>{$title}</error>");
}
// Если без --force, то спрашиваем подтверждение на каждую миграцию
} else if ($confirmationCallback && !$confirmationCallback($title)) {
return;
}
if ($next->isNew() && !$next->isRemove()) {
$this->service->up($next);
} elseif (!$next->isNew() && $next->isRemove()) {
$this->service->down($next);
}
if (!$this->optAuto) {
break;
}
}
$this->info('Done');
} | Run
@param callable|null $confirmationCallback - Спросить подтверждение у пользователя перед запуском каждой миграции
функция должна вернуть true/false
принимает $migrationTitle
@param string $migrationName - Название миграции которую надо явно запустить | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(IncomingRequestEvent::class, function(IncomingRequestEvent $event) {
$this->session->handleRequest($event->getRequest());
});
$dispatcher->addListener(ResponseReceivedEvent::class, function(ResponseReceivedEvent $event) {
$this->session->handleResponse($event->getResponse());
});
} | {@inheritdoc} | entailment |
protected function succeed($result = null)
{
$this->isFinished = true;
$this->isSuccess = true;
$this->result = $result;
} | Marks the flow as successful and sets the result.
@param mixed|null $result | entailment |
protected function fail($error = '')
{
$this->isFinished = true;
$this->isSuccess = false;
$this->error = $error;
} | Marks the flow as failed and sets the error message.
@param string $error | entailment |
public static function isObjectId($value)
{
if (is_object($value) && method_exists($value, '__toString')) {
$value = (string) $value;
}
return is_string($value) && 24 == strlen($value) && ctype_xdigit($value);
} | Checks if the given value can be a valid ObjectId.
@param mixed $value string to be evaluated if it can be used as a valid ObjectID
@return bool true if is valid | entailment |
public function compile(array $classNames) : array
{
$result = [];
foreach ($classNames as $className) {
$reflectionClass = new \ReflectionClass($className);
$prefixPath = '';
$prefixRegexp = '';
$classParameterNames = [];
foreach ($this->annotationReader->getClassAnnotations($reflectionClass) as $annotation) {
if ($annotation instanceof Route) {
$prefixPath = $annotation->path;
[$prefixRegexp, $classParameterNames] = $this->processAnnotation($annotation);
break;
}
}
foreach ($reflectionClass->getMethods() as $reflectionMethod) {
$methodName = $reflectionMethod->getName();
foreach ($this->annotationReader->getMethodAnnotations($reflectionMethod) as $annotation) {
if ($annotation instanceof Route) {
[$regexp, $methodParameterNames] = $this->processAnnotation($annotation);
$pathRegexp = '/^' . $prefixRegexp . $regexp . '$/';
$httpMethods = $annotation->methods;
if (! $httpMethods) {
$httpMethods = $this->defaultMethods;
}
$this->routes[] = [
$prefixPath . $annotation->path,
$annotation->methods,
$className,
$methodName
];
$result[] = [
$pathRegexp,
$httpMethods,
$className,
$methodName,
$classParameterNames,
$methodParameterNames
];
}
}
}
}
// Sort routes by path & methods
sort($this->routes);
return $result;
} | @param string[] $classNames An array of controller class names to get routes from.
@return array
@throws \LogicException | entailment |
public function processAnnotation(Route $annotation) : array
{
$parameterNames = [];
$regexp = preg_replace_callback('/\{([^\}]+)\}|(.+?)/', function(array $matches) use ($annotation, & $parameterNames) : string {
if (isset($matches[2])) {
return preg_quote($matches[2], '/');
}
$parameterName = $matches[1];
$parameterNames[] = $parameterName;
if (isset($annotation->patterns[$parameterName])) {
$pattern = $annotation->patterns[$parameterName];
} else {
$pattern = '[^\/]+';
}
return '(' . $pattern. ')';
}, $annotation->path);
foreach ($annotation->patterns as $parameterName => $pattern) {
if (! in_array($parameterName, $parameterNames, true)) {
throw new \LogicException(sprintf('Pattern does not match any parameter: "%s".', $parameterName));
}
}
return [$regexp, $parameterNames];
} | @todo 0.4.0 make private
Creates a path regular expression and infer the parameter names from a Route annotation.
@param Route $annotation The annotation to process.
@return array The path regexp, and the parameter names.
@throws \LogicException | entailment |
protected function getScriptPath() : string
{
$class = new \ReflectionClass($this->getClassName());
$path = $class->getFileName();
$path = preg_replace('/\.php$/', '.phtml', $path, -1, $count);
if ($count !== 1) {
throw new \RuntimeException('The class filename does not end with .php');
}
return $path;
} | Returns the view script path.
Defaults to the class file path, with a .phtml extension, but can be overridden by child classes.
@return string
@throws \RuntimeException | entailment |
public function all()
{
$finder = new \Symfony\Component\Finder\Finder;
$finder->files()->in($this->dir)->sortByName();
$found = [];
foreach ($finder as $file) {
$found[$file->getBasename()] = $file->getPath();
}
return $found;
} | Получить список всех Миграций
@return array - FILE => PATH | entailment |
public function insert(Migration $migration)
{
$fileName = $this->_getFileName($migration);
if (is_file($fileName)) {
throw new \InvalidArgumentException(__METHOD__.": Migration file `{$migration->getName()}` exists");
}
file_put_contents($fileName, $migration->getSql());
} | Добавить Миграцию в файл
@param Migration $migration | entailment |
public function loadSql(Migration $migration)
{
$fileName = $this->_getFileName($migration);
if (!is_file($fileName)) {
throw new \InvalidArgumentException(__METHOD__.": migration file `{$migration->getName()}` not found in dir `{$this->dir}`");
}
$migration->setSql(file_get_contents($fileName));
} | Загрузить SQL
@param Migration $migration | entailment |
protected function printFormNew(){
$str = parent::printFormNew();
$str .=
"<div class=\"row\">\n".
"<div class=\"col-md-12\">\n".
"<h3>Step1: get table data</h3>\n".
"<span class=\"glyphicon glyphicon-open pull-right icon-medium\" style=\"top:-38px;\"></span>\n".
Form::open(array( 'url' => $this->getProcessUrl(), 'role' => 'form'))."\n".
$this->createSelectTables().
"<div class=\"form-group\">".
Form::label('separator','Type of separator: ').
Form::select('separator' , array( ','=>'comma ,' , ';'=>'semicolon ;' ) , ',', array("class" => "form-control") ).
"</div>".
"<div class=\"form-group\">\n".
Form::label('max_rows','Max number of lines to show in preview: ')."\n".
Form::select('max_rows' , array('10'=>'10', '50'=>'50', '100'=>'100', '150'=>'150') , '10', array("class"=> "form-control") )."\n".
"</div>\n".
Form::submit('Open' , array('class'=>'btn btn-success'))."\n".
Form::close().
"</div>\n". // form-group
"</div>\n". // col
"</div>\n". // row
"<hr/>\n";
return $str;
} | Return the form that needs to be processed | entailment |
public function processForm(array $input = null, $validator = null)
{
if($input)
{
$this->form_input = $input;
}
else
{
$this->fillFormInput();
}
$validator = ($validator) ? $validator : new ValidatorFormInputModel($this);
if ( $validator->validateInput() )
{
try
{
$table_preview = $this->getDataTable();
}
catch(BadMethodCallException $e)
{
$this->appendError("BadMethod" , "Invalid input data: cannot show the table." );
return $this->getIsExecuted();
}
catch(NoDataException $e)
{
$this->appendError("NoData" , "The table is empty." );
return $this->getIsExecuted();
}
$exchange_data = array(
"preview" => $table_preview,
"table_name" => $this->form_input["table_name"],
"form_input" => $this->form_input,
"column_names" => $this->getTableHeader(),
"separator" => $this->form_input["separator"]
);
$this->is_executed = true;
// save data for next state
Session::put($this->exchange_key, $exchange_data);
}
else
{
$this->appendError("fileEmpty" , "No data found in the file" );
}
return $this->getIsExecuted();
} | Process the form
@return Boolean $is_executed if the state is executed successfully | entailment |
protected function getTableValuesSelect($dbm = null)
{
$dbm = $dbm ? $dbm : new DBM;
$table_raw = $dbm->getTableList();
return $table_raw ? array_combine(array_values($table_raw), array_values($table_raw) ) : false;
} | Return value with table names for a select
@return Array | entailment |
protected function getDataTable()
{
$data = $this->getTableData();
$header = $this->getTableHeader();
$table = new Table();
// set the configuration
$table->setConfig(array(
"table-hover"=>true,
"table-condensed"=>false,
"table-responsive" => true,
"table-striped" => true,
));
// set header
$table->setHeader( $header );
// set data
foreach($data as $val)
{
$table->addRows( get_object_vars($val) );
}
return $table->getHtml();
} | Return the table for the preview
@return String $table | entailment |
protected function getTableData()
{
$data = array();
$form_input = $this->getFormInput();
if( $form_input['table_name'] && $form_input['max_rows'] )
{
$connection_name = Config::get('laravel-import-export::baseconf.connection_name');
$temp_data = DB::connection($connection_name)
->table($this->form_input['table_name'])
->select("*")
->take($this->form_input['max_rows']);
if( $temp_data->exists() )
{
$data = $temp_data->get();
}
else
{
throw new NoDataException;
}
}
else
{
throw new \BadMethodCallException;
}
return $data;
} | Get the data from the db for the preview
@throws BadMethodCallException
@throws NoDataException
@return Array $data | entailment |
protected function getTableHeader($dbm = null)
{
$dbm = $dbm ? $dbm : new DBM;
$columns = array();
$form_input = $this->getFormInput();
if( $form_input['table_name'] )
{
$dbal_columns = $dbm->getTableColumns($this->form_input['table_name']);
foreach($dbal_columns as $column)
{
$array_columns = $column->toArray();
$columns[] = $array_columns["name"];
}
}
else
{
throw new \BadMethodCallException;
}
return $columns;
} | Get the header for the preview
@throws BadMethodCallException
@return Array $columns | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.