sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function fillTranslations($formatHandle)
{
$this->start();
try {
$this->getUserControl()->checkRateLimit();
$this->getUserControl()->checkGenericAccess(__FUNCTION__);
$format = $this->app->make(TranslationsConverterProvider::class)->getByHandle($formatHandle);
if ($format === null) {
throw new UserMessageException(t('Unable to find the specified translations format'), Response::HTTP_NOT_FOUND);
}
/* @var \CommunityTranslation\TranslationsConverter\ConverterInterface $format */
if (!$format->canUnserializeTranslations()) {
throw new UserMessageException(t('The specified translations format does not support unserialization'), Response::HTTP_NOT_ACCEPTABLE);
}
if (!$format->canSerializeTranslations()) {
throw new UserMessageException(t('The specified translations format does not support serialization'), Response::HTTP_NOT_ACCEPTABLE);
}
if (!$format->supportLanguageHeader()) {
throw new UserMessageException(t('The specified translations format does not support a language header'), Response::HTTP_NOT_ACCEPTABLE);
}
$file = $this->request->files->get('file');
if ($file === null) {
throw new UserMessageException(t('The file with strings to be translated has not been specified'), Response::HTTP_NOT_ACCEPTABLE);
}
if (!$file->isValid()) {
throw new UserMessageException(t('The file with strings to be translated has not been received correctly: %s', $file->getErrorMessage()), Response::HTTP_NOT_ACCEPTABLE);
}
$translations = $format->loadTranslationsFromFile($file->getPathname());
$localeID = (string) $translations->getLanguage();
if ($localeID === '') {
throw new UserMessageException(t('The file with strings to be translated does not specify a language ID'));
}
$locale = $this->app->make(LocaleRepository::class)->findApproved($localeID);
if ($locale === null) {
throw new UserMessageException(t('The file with strings to be translated specifies an unknown language ID (%s)', $localeID));
}
$translationExporter = $this->app->make(TranslationExporter::class);
/* @var TranslationExporter $translationExporter */
$translations = $translationExporter->fromPot($translations, $locale);
$result = $this->getResponseFactory()->create(
$format->convertTranslationsToString($translations),
Response::HTTP_OK,
[
'Content-Type' => 'application/octet-stream',
'Content-Transfer-Encoding' => 'binary',
'Content-Disposition' => 'attachment; filename="translations.' . $format->getFileExtension() . '"',
]
);
} catch (Exception $x) {
$result = $this->buildErrorResponse($x);
} catch (Throwable $x) {
$result = $this->buildErrorResponse($x);
}
return $this->finish($result);
} | Fill-in translations that we already know.
@param string $formatHandle
@return Response
@example POST a file (field name: file) to http://www.example.com/api/fill-translations/po/ | entailment |
public function importPackage()
{
$this->start();
try {
$this->getUserControl()->checkRateLimit();
$this->getUserControl()->checkGenericAccess(__FUNCTION__);
$args = $this->getRequestJson();
$package_handle = (isset($args['package_handle']) && is_string($args['package_handle'])) ? trim($args['package_handle']) : '';
if ($package_handle === '') {
throw new UserMessageException(t('Missing argument: %s', 'package_handle'), Response::HTTP_NOT_ACCEPTABLE);
}
$package_version = (isset($args['package_version']) && is_string($args['package_version'])) ? trim($args['package_version']) : '';
if ($package_version === '') {
throw new UserMessageException(t('Missing argument: %s', 'package_version'), Response::HTTP_NOT_ACCEPTABLE);
}
$archive_url = (isset($args['archive_url']) && is_string($args['archive_url'])) ? trim($args['archive_url']) : '';
if ($archive_url === '') {
throw new UserMessageException(t('Missing argument: %s', 'archive_url'), Response::HTTP_NOT_ACCEPTABLE);
}
$entity = RemotePackageEntity::create($package_handle, $package_version, $archive_url);
if (isset($args['package_name'])) {
if (!is_string($args['package_name'])) {
throw new UserMessageException(t('Invalid type of argument: %s', 'package_name'), Response::HTTP_NOT_ACCEPTABLE);
}
$entity->setName(trim($args['package_name']));
}
if (isset($args['package_url'])) {
if (!is_string($args['package_url'])) {
throw new UserMessageException(t('Invalid type of argument: %s', 'package_url'), Response::HTTP_NOT_ACCEPTABLE);
}
$entity->setUrl(trim($args['package_url']));
}
if (isset($args['approved'])) {
if (!is_bool($args['approved'])) {
throw new UserMessageException(t('Invalid type of argument: %s', 'approved'), Response::HTTP_NOT_ACCEPTABLE);
}
$entity->setIsApproved($args['approved']);
}
if (isset($args['immediate'])) {
if (!is_bool($args['immediate'])) {
throw new UserMessageException(t('Invalid type of argument: %s', 'immediate'), Response::HTTP_NOT_ACCEPTABLE);
}
$immediate = $args['immediate'];
} else {
$immediate = false;
}
$em = $this->app->make(EntityManager::class);
/* @var EntityManager $em */
$repo = $this->app->make(RemotePackageRepository::class);
/* @var RemotePackageRepository $repo */
$connection = $em->getConnection();
$connection->beginTransaction();
try {
// Remove duplicated packages still to be processed
$qb = $repo->createQueryBuilder('rp');
$qb
->delete()
->where('rp.handle = :handle')->setParameter('handle', $entity->getHandle())
->andWhere('rp.version = :version')->setParameter('version', $entity->getVersion())
->andWhere($qb->expr()->isNull('rp.processedOn'))
->getQuery()->execute();
if ($entity->isApproved()) {
// Approve previously queued packages that were'nt approved
$qb = $repo->createQueryBuilder('rp');
$qb
->update()
->set('rp.approved', true)
->where('rp.handle = :handle')->setParameter('handle', $entity->getHandle())
->andWhere('rp.approved = :approved')->setParameter('approved', false)
->andWhere($qb->expr()->isNull('rp.processedOn'))
->getQuery()->execute();
}
if ($immediate === false) {
$em->persist($entity);
$em->flush($entity);
}
$connection->commit();
} catch (Exception $x) {
try {
$connection->rollBack();
} catch (Exception $foo) {
}
throw $x;
}
if ($immediate) {
if ($entity->isApproved()) {
$importer = $this->app->make(RemotePackageImporter::class);
/* @var RemotePackageImporter $importer */
$importer->import($entity);
$result = $this->buildJsonResponse('imported');
} else {
$result = $this->buildJsonResponse('skipped');
}
} else {
$result = $this->buildJsonResponse('queued');
}
} catch (Exception $x) {
$result = $this->buildErrorResponse($x);
} catch (Throwable $x) {
$result = $this->buildErrorResponse($x);
}
return $this->finish($result);
} | Accept a package version to be imported and queue it for later processing.
@return Response
@example PUT Request to http://www.example.com/api/import/package/ with this JSON data:
{
"package_handle": "...", // Required
"package_version": "...", // Required
"archive_url": "...", // Required
"package_name": "...", // Optional
"package_url": "...", // Optional
"approved": true/false // Optional
"immediate": true/false // Optional
} | entailment |
public function importPackageVersionTranslatables($packageHandle, $packageVersion, $formatHandle)
{
$this->start();
try {
$this->getUserControl()->checkRateLimit();
$this->getUserControl()->checkGenericAccess(__FUNCTION__);
$em = $this->app->make(EntityManager::class);
$post = $this->request->request;
$packageName = $post->get('packageName', '');
if (!is_string($packageName)) {
$packageName = '';
}
$packageVersion = is_string($packageVersion) ? trim($packageVersion) : '';
if ($packageVersion === '') {
throw new UserMessageException(t('Package version not specified'), Response::HTTP_NOT_ACCEPTABLE);
}
$format = $this->app->make(TranslationsConverterProvider::class)->getByHandle($formatHandle);
if ($format === null) {
throw new UserMessageException(t('Unable to find the specified translations format'), 404);
}
$package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageHandle]);
if ($package === null) {
$package = PackageEntity::create($packageHandle, $packageName);
$em->persist($package);
$em->flush($package);
$version = null;
} else {
if ($packageName !== '' && $package->getName() !== $packageName) {
$package->setName($packageName);
$em->persist($package);
$em->flush($package);
}
$version = $this->app->make(PackageVersionRepository::class)->findByOneBy(['package' => $package, 'version' => $packageVersion]);
}
if ($version === null) {
$version = PackageVersionEntity::create($package, $packageVersion);
$em->persist($version);
$em->flush($version);
}
$file = $this->request->files->get('file');
if ($file === null) {
throw new UserMessageException(t('The file with translatable strings has not been specified'), Response::HTTP_NOT_ACCEPTABLE);
}
if (!$file->isValid()) {
throw new UserMessageException(t('The file with translatable strings has not been received correctly: %s', $file->getErrorMessage()), Response::HTTP_NOT_ACCEPTABLE);
}
$translations = $format->loadTranslationsFromFile($file->getPathname());
if (count($translations) < 1) {
throw new UserMessageException(t('No translatable strings found in uploaded file'));
}
$importer = $this->app->make(TranslatableImporter::class);
$changed = $importer->importTranslations($translations, $package->getHandle(), $packageVersion->getVersion());
$result = $this->buildJsonResponse(['changed' => $changed]);
} catch (Exception $x) {
$result = $this->buildErrorResponse($x);
} catch (Throwable $x) {
$result = $this->buildErrorResponse($x);
}
return $this->finish($result);
} | Set the translatable strings of a package version.
@param string $packageHandle
@param string $packageVersion
@param string $formatHandle
@return Response
@example http://www.example.com/api/package/concrete5/8.2/translatables/po/ | entailment |
public function importTranslations($localeID, $formatHandle, $approve)
{
$this->start();
try {
$this->getUserControl()->checkRateLimit();
$approve = $approve ? true : false;
$accessibleLocales = $this->getUserControl()->checkLocaleAccess(__FUNCTION__ . ($approve ? '_approve' : ''));
$locale = $this->app->make(LocaleRepository::class)->findApproved($localeID);
if ($locale === null) {
throw new UserMessageException(t('Unable to find the specified locale'), Response::HTTP_NOT_FOUND);
}
if (!in_array($locale, $accessibleLocales, true)) {
throw AccessDeniedException::create(t('Access denied to the specified locale'));
}
$format = $this->app->make(TranslationsConverterProvider::class)->getByHandle($formatHandle);
if ($format === null) {
throw new UserMessageException(t('Unable to find the specified translations format'), 404);
}
$file = $this->request->files->get('file');
if ($file === null) {
throw new UserMessageException(t('The file with translated strings has not been specified'), Response::HTTP_NOT_ACCEPTABLE);
}
if (!$file->isValid()) {
throw new UserMessageException(t('The file with translated strings has not been received correctly: %s', $file->getErrorMessage()), Response::HTTP_NOT_ACCEPTABLE);
}
$translations = $format->loadTranslationsFromFile($file->getPathname());
if (count($translations) < 1) {
throw new UserMessageException(t('No translations found in uploaded file'));
}
if (!$translations->getLanguage()) {
throw new UserMessageException(t('The translation file does not contain a language header'));
}
if (strcasecmp($translations->getLanguage(), $locale->getID()) !== 0) {
throw new UserMessageException(t("The translation file is for the '%1\$s' language, not for '%2\$s'", $translations->getLanguage(), $locale->getID()));
}
$pf = $translations->getPluralForms();
if ($pf === null) {
throw new UserMessageException(t('The translation file does not define the plural rules'));
}
if ($pf[0] !== $locale->getPluralCount()) {
throw new UserMessageException(t('The translation file defines %1$s plural forms instead of %2$s', $pf[0], $locale->getPluralCount()));
}
$importer = $this->app->make(TranslationImporter::class);
$me = $this->getUserControl()->getAssociatedUserEntity();
$imported = $importer->import($translations, $locale, $me, $approve ? TranslationImportOptions::forAdministrators() : TranslationImportOptions::forTranslators());
if ($imported->newApprovalNeeded > 0) {
$this->app->make(NotificationRepository::class)->translationsNeedApproval(
$locale,
$imported->newApprovalNeeded,
$me->getUserID(),
null
);
}
$result = $this->buildJsonResponse($imported);
} catch (Exception $x) {
$result = $this->buildErrorResponse($x);
} catch (Throwable $x) {
$result = $this->buildErrorResponse($x);
}
return $this->finish($result);
} | Import the translations for a specific locale.
@param string $localeID
@param string $formatHandle
@param string|int|bool $approve
@return Response
@example http://www.example.com/api/translations/it_IT/po/0/ | entailment |
public function unrecognizedCall($unrecognizedPath = '')
{
$this->start();
if ($unrecognizedPath === '') {
$message = t('Resource not specified');
} else {
$message = t(/*i18n: %1$s is a path, %2$s is an HTTP method*/'Unknown resource %1$s for %2$s method', $unrecognizedPath, $this->request->getMethod());
}
$result = $this->buildErrorResponse(
$message,
Response::HTTP_NOT_FOUND
);
return $this->finish($result);
} | What to do if the entry point is not recognized.
@param string $unrecognizedPath
@return Response | entailment |
private function getDefaultProviders()
{
$defaultProviders = array();
foreach ($this->defaultProviders as $provider) {
$defaultProviders[$provider] = $this->getProvider($provider);
}
return $defaultProviders;
} | Retrieves array of default providers objects.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface[] | entailment |
public function getProvider($label)
{
if (!isset($this->providers[$label])) {
throw new InvalidArgumentException(sprintf('Unknown share button provider `%s`', $label));
}
return $this->providers[$label];
} | Retrieves a share button provider from collection by its label.
@param string $label
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface
@throws \InvalidArgumentException | entailment |
public function render(array $options = array())
{
if (!empty($options['providers'])) {
$outputProviders = array();
foreach ($options['providers'] as $provider) {
$outputProviders[] = $this->getProvider($provider);
}
} else {
$outputProviders = $this->getDefaultProviders();
}
unset($options['providers']);
$renderedProviders = array();
foreach ($outputProviders as $label => $provider) {
$provider->setTemplateEngine($this->templateEngine);
$provider->setTemplateName($options['template']);
$provider->setLabel($label);
$renderedProviders[$label] = $provider->render($options);
}
return $renderedProviders;
} | Renders the share buttons list.
@param array $options
@return string[] | entailment |
public function getUnreviewedInitialTranslations(LocaleEntity $locale)
{
$rs = $this->app->make(TranslationExporter::class)->getUnreviewedSelectQuery($locale);
return $this->buildInitialTranslations($locale, $rs);
} | Returns the initial translations to be reviewed for the online editor, for a specific locale.
@param LocaleEntity $locale
@return array | entailment |
public function getInitialTranslations(PackageVersionEntity $packageVersion, LocaleEntity $locale)
{
$rs = $this->app->make(TranslationExporter::class)->getPackageSelectQuery($packageVersion, $locale, false);
return $this->buildInitialTranslations($locale, $rs);
} | Returns the initial translations for the online editor, for a specific package version.
@param PackageVersionEntity $packageVersion
@param LocaleEntity $locale
@return array | entailment |
protected function buildInitialTranslations(LocaleEntity $locale, \Concrete\Core\Database\Driver\PDOStatement $rs)
{
$approvedSupport = $this->app->make(Access::class)->getLocaleAccess($locale) >= Access::ADMIN;
$result = [];
$numPlurals = $locale->getPluralCount();
while (($row = $rs->fetch()) !== false) {
$item = [
'id' => (int) $row['id'],
'original' => $row['text'],
];
if ($approvedSupport && $row['approved']) {
$item['isApproved'] = true;
}
if ($row['context'] !== '') {
$item['context'] = $row['context'];
}
$isPlural = $row['plural'] !== '';
if ($isPlural) {
$item['originalPlural'] = $row['plural'];
}
if ($row['text0'] !== null) {
$translations = [];
switch ($isPlural ? $numPlurals : 1) {
case 6:
$translations[] = $row['text5'];
/* @noinspection PhpMissingBreakStatementInspection */
case 5:
$translations[] = $row['text4'];
/* @noinspection PhpMissingBreakStatementInspection */
case 4:
$translations[] = $row['text3'];
/* @noinspection PhpMissingBreakStatementInspection */
case 3:
$translations[] = $row['text2'];
/* @noinspection PhpMissingBreakStatementInspection */
case 2:
$translations[] = $row['text1'];
/* @noinspection PhpMissingBreakStatementInspection */
case 1:
$translations[] = $row['text0'];
break;
}
$item['translations'] = array_reverse($translations);
}
$result[] = $item;
}
$rs->closeCursor();
return $result;
} | Builds the initial translations array.
@param \Concrete\Core\Database\Driver\PDOStatement $rs
@return array | entailment |
public function getTranslatableData(LocaleEntity $locale, TranslatableEntity $translatable, PackageVersionEntity $packageVersion = null, $initial = false)
{
$result = [
'id' => $translatable->getID(),
'translations' => $this->getTranslations($locale, $translatable),
];
if ($initial) {
$place = ($packageVersion === null) ? null : $this->app->make(TranslatablePlaceRepository::class)->findOneBy(['packageVersion' => $packageVersion, 'translatable' => $translatable]);
if ($place !== null) {
$extractedComments = $place->getComments();
$references = $this->expandReferences($place->getLocations(), $packageVersion);
} else {
$extractedComments = [];
$references = [];
}
$result['extractedComments'] = $extractedComments;
$result['references'] = $references;
$result['extractedComments'] = ($place === null) ? [] : $place->getComments();
$result['comments'] = $this->getComments($locale, $translatable);
$result['suggestions'] = $this->getSuggestions($locale, $translatable);
$result['glossary'] = $this->getGlossaryTerms($locale, $translatable);
}
return $result;
} | Returns the data to be used in the editor when editing a string.
@param LocaleEntity $locale the current editor locale
@param TranslatableEntity $translatable the source string that's being translated
@param PackageVersionEntity $packageVersion the package version where this string is used
@param bool $initial set to true when a string is first loaded, false after it has been saved
@return array | entailment |
public function getTranslations(LocaleEntity $locale, TranslatableEntity $translatable)
{
$numPlurals = $locale->getPluralCount();
$result = [
'current' => null,
'others' => [],
];
$translations = $this->app->make(TranslationRepository::class)->findBy(['translatable' => $translatable, 'locale' => $locale], ['createdOn' => 'DESC']);
$dh = $this->app->make('helper/date');
$uh = $this->app->make(UserService::class);
foreach ($translations as $translation) {
/* @var \CommunityTranslation\Entity\Translation $translation */
$texts = [];
switch (($translatable->getPlural() === '') ? 1 : $numPlurals) {
case 6:
$texts[] = $translation->getText5();
/* @noinspection PhpMissingBreakStatementInspection */
case 5:
$texts[] = $translation->getText4();
/* @noinspection PhpMissingBreakStatementInspection */
case 4:
$texts[] = $translation->getText3();
/* @noinspection PhpMissingBreakStatementInspection */
case 3:
$texts[] = $translation->getText2();
/* @noinspection PhpMissingBreakStatementInspection */
case 2:
$texts[] = $translation->getText1();
/* @noinspection PhpMissingBreakStatementInspection */
case 1:
default:
$texts[] = $translation->getText0();
break;
}
$item = [
'id' => $translation->getID(),
'createdOn' => $dh->formatPrettyDateTime($translation->getCreatedOn(), false, true),
'createdBy' => $uh->format($translation->getCreatedBy()),
'approved' => $translation->isApproved(),
'translations' => array_reverse($texts),
];
if ($translation->isCurrent()) {
$item['currentSince'] = $dh->formatPrettyDateTime($translation->getCurrentSince(), false, true);
$result['current'] = $item;
} else {
$result['others'][] = $item;
}
}
return $result;
} | Search all the translations associated to a translatable string.
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@return array | entailment |
public function getComments(LocaleEntity $locale, TranslatableEntity $translatable, TranslatableCommentEntity $parentComment = null)
{
$repo = $this->app->make(TranslatableCommentRepository::class);
if ($parentComment === null) {
$qb = $repo->createQueryBuilder('c');
$qb
->where('c.translatable = :translatable')
->andWhere('c.parentComment is null')
->andWhere($qb->expr()->orX(
'c.locale = :locale',
'c.locale is null'
))
->orderBy('c.postedOn', 'ASC')
->setParameter('translatable', $translatable)
->setParameter('locale', $locale)
;
$comments = $qb->getQuery()->getResult();
} else {
$comments = $repo->findBy(
['parentComment' => $parentComment],
['postedOn' => 'ASC']
);
}
$result = [];
$uh = $this->app->make(UserService::class);
$dh = $this->app->make('helper/date');
$me = new \User();
$myID = $me->isRegistered() ? (int) $me->getUserID() : null;
foreach ($comments as $comment) {
$result[] = [
'id' => $comment->getID(),
'date' => $dh->formatPrettyDateTime($comment->getPostedOn(), true, true),
'mine' => $myID && $myID === $comment->getPostedBy(),
'by' => $uh->format($comment->getPostedBy()),
'text' => $comment->getText(),
'comments' => $this->getComments($locale, $translatable, $comment),
'isGlobal' => $comment->getLocale() === null,
];
}
return $result;
} | Get the comments associated to a translatable strings.
@param LocaleEntity $locale
@param TranslatableEntity $translatable | entailment |
public function getSuggestions(LocaleEntity $locale, TranslatableEntity $translatable)
{
$result = [];
$connection = $this->app->make(EntityManager::class)->getConnection();
$rs = $connection->executeQuery(
'
select distinct
CommunityTranslationTranslatables.text,
CommunityTranslationTranslations.text0,
match(CommunityTranslationTranslatables.text) against (:search in natural language mode) as relevance
from
CommunityTranslationTranslations
inner join CommunityTranslationTranslatables on CommunityTranslationTranslations.translatable = CommunityTranslationTranslatables.id and 1 = CommunityTranslationTranslations.current and :locale = CommunityTranslationTranslations.locale
where
CommunityTranslationTranslatables.id <> :currentTranslatableID
and length(CommunityTranslationTranslatables.text) between :minLength and :maxLength
having
relevance > 0
order by
relevance desc,
text asc
limit
0, ' . ((int) self::MAX_SUGGESTIONS) . '
',
[
'search' => $translatable->getText(),
'locale' => $locale->getID(),
'currentTranslatableID' => $translatable->getID(),
'minLength' => (int) floor(strlen($translatable->getText()) * 0.75),
'maxLength' => (int) ceil(strlen($translatable->getText()) * 1.33),
]
);
while ($row = $rs->fetch()) {
$result[] = [
'source' => $row['text'],
'translation' => $row['text0'],
];
}
$rs->closeCursor();
return $result;
} | Search for similar translations.
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@return array | entailment |
public function getGlossaryTerms(LocaleEntity $locale, TranslatableEntity $translatable)
{
$result = [];
$connection = $this->app->make(EntityManager::class)->getConnection();
$rs = $connection->executeQuery(
'
select
CommunityTranslationGlossaryEntries.id,
CommunityTranslationGlossaryEntries.term,
CommunityTranslationGlossaryEntries.type,
CommunityTranslationGlossaryEntries.comments as commentsE,
CommunityTranslationGlossaryEntriesLocalized.translation,
CommunityTranslationGlossaryEntriesLocalized.comments as commentsEL,
match(CommunityTranslationGlossaryEntries.term) against (:search in natural language mode) as relevance
from
CommunityTranslationGlossaryEntries
left join CommunityTranslationGlossaryEntriesLocalized on CommunityTranslationGlossaryEntries.id = CommunityTranslationGlossaryEntriesLocalized.entry and :locale = CommunityTranslationGlossaryEntriesLocalized.locale
having
relevance > 0
order by
relevance desc,
CommunityTranslationGlossaryEntries.term asc
limit
0, ' . ((int) self::MAX_GLOSSARY_ENTRIES) . '
',
[
'search' => $translatable->getText(),
'locale' => $locale->getID(),
]
);
while ($row = $rs->fetch()) {
$result[] = [
'id' => (int) $row['id'],
'term' => $row['term'],
'type' => $row['type'],
'termComments' => $row['commentsE'],
'translation' => ($row['translation'] === null) ? '' : $row['translation'],
'translationComments' => ($row['commentsEL'] === null) ? '' : $row['commentsEL'],
];
}
$rs->closeCursor();
return $result;
} | Search the glossary entries to show when translating a string in a specific locale.
@param LocaleEntity $locale the current editor locale
@param TranslatableEntity $translatable the source string that's being translated
@return array | entailment |
public function expandReferences(array $references, PackageVersionEntity $packageVersion)
{
if (empty($references)) {
return $references;
}
$gitRepositories = $this->app->make(GitRepositoryRepository::class)->findBy(['packageHandle' => $packageVersion->getPackage()->getHandle()]);
$applicableRepository = null;
$foundVersionData = null;
foreach ($gitRepositories as $gitRepository) {
$d = $gitRepository->getDetectedVersion($packageVersion->getVersion());
if ($d !== null) {
$applicableRepository = $gitRepository;
$foundVersionData = $d;
break;
}
}
$pattern = null;
$lineFormat = null;
if ($applicableRepository !== null) {
$matches = null;
switch (true) {
case 1 == preg_match('/^(?:\w+:\/\/|\w+@)github.com[:\/]([a-z0-9_.\-]+\/[a-z0-9_.\-]+)\.git$/i', $applicableRepository->getURL(), $matches):
switch ($foundVersionData['kind']) {
case 'tag':
$pattern = 'https://github.com/' . $matches[1] . '/blob/' . $foundVersionData['repoName'] . '/<<FILE>><<LINE>>';
$lineFormat = '#L%s';
break;
case 'branch':
$pattern = 'https://github.com/' . $matches[1] . '/blob/' . $foundVersionData['repoName'] . '/<<FILE>><<LINE>>';
$lineFormat = '#L%s';
break;
}
break;
}
}
$result = $references;
if ($pattern !== null) {
$prefix = $applicableRepository->getDirectoryToParse();
if ($prefix !== '') {
$prefix .= '/';
}
$stripSuffix = $applicableRepository->getDirectoryForPlaces();
if ($stripSuffix !== '') {
$stripSuffix .= '/';
}
$m = null;
foreach ($result as $index => $reference) {
if (!preg_match('/^\w*:\/\//', $reference)) {
if (preg_match('/^(.+):(\d+)$/', $reference, $m)) {
$file = $m[1];
$line = $m[2];
} else {
$file = $reference;
$line = null;
}
$file = ltrim($file, '/');
$line = ($line === null || $lineFormat === null) ? '' : sprintf($lineFormat, $line);
if ($stripSuffix !== '' && strpos($file, $stripSuffix) === 0) {
$file = $prefix . substr($file, strlen($stripSuffix));
}
$result[$index] = [
str_replace(['<<FILE>>', '<<LINE>>'], [$file, $line], $pattern),
$reference,
];
}
}
}
return $result;
} | Expand translatable string references by adding a link to the online repository where they are defined.
@param string[] $references
@param PackageVersionEntity $packageVersion
@return string[] | entailment |
protected function getRecipientIDs(NotificationEntity $notification)
{
$result = [];
$notificationData = $notification->getNotificationData();
$result[] = $notificationData['requestedBy'];
$group = $this->getGroupsHelper()->getGlobalAdministrators();
$result = array_merge($result, $group->getGroupMemberIDs());
return $result;
} | {@inheritdoc}
@see Category::getRecipientIDs() | entailment |
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient)
{
$notificationData = $notification->getNotificationData();
$uir = $this->app->make(UserInfoRepository::class);
$requestedBy = $notificationData['requestedBy'] ? $uir->getByID($notificationData['requestedBy']) : null;
$deniedBy = $notificationData['by'] ? $uir->getByID($notificationData['by']) : null;
return [
'localeName' => Language::getName($notificationData['localeID']),
'requestedBy' => $requestedBy,
'deniedBy' => $deniedBy,
'teamsUrl' => $this->getBlockPageURL('CommunityTranslation Team List'),
] + $this->getCommonMailParameters($notification, $recipient);
} | {@inheritdoc}
@see Category::getMailParameters() | entailment |
public function getMailTemplate()
{
$chunks = explode('\\', get_class($this));
$className = array_pop($chunks);
return [
uncamelcase($className),
'community_translation',
];
} | {@inheritdoc}
@see CategoryInterface::getMailTemplate() | entailment |
public function getRecipients(NotificationEntity $notification)
{
$ids = $this->getRecipientIDs($notification);
// be sure we have integers
$ids = array_map('intval', $ids);
// remove problematic IDs
$ids = array_filter($ids);
// remove duplicated
$ids = array_unique($ids, SORT_REGULAR);
if (!empty($ids)) {
$repo = $this->app->make(UserInfoRepository::class);
/* @var UserInfoRepository $repo */
foreach ($ids as $id) {
$userInfo = $repo->getByID($id);
if ($userInfo !== null && $userInfo->isActive()) {
yield $userInfo;
}
}
}
} | {@inheritdoc}
@see CategoryInterface::getRecipients() | entailment |
protected function getCommonMailParameters(NotificationEntity $notification, UserInfo $recipient)
{
$site = $this->app->make('site')->getSite();
/* @var \Concrete\Core\Entity\Site\Site $site */
return [
'siteName' => $site->getSiteName(),
'siteUrl' => (string) $site->getSiteCanonicalURL(),
'recipientName' => $recipient->getUserName(),
'recipientAccountUrl' => URL::to('/account/edit_profile'),
'usersHelper' => $this->app->make(\CommunityTranslation\Service\User::class),
];
} | @param NotificationEntity $notification
@param UserInfo $recipient
@return array | entailment |
protected function getBlockPageURL($blockName, $blockAction = '', $isBlockActionInstanceSpecific = false)
{
if (!isset($this->blockPageURLs[$blockName])) {
$page = null;
if ($blockName) {
$block = Block::getByName($blockName);
if ($block && $block->getBlockID()) {
$page = $block->getOriginalCollection();
}
}
$this->blockPageURLs[$blockName] = [
'foundBlockID' => ($page === null) ? null : $block->getBlockID(),
'url' => (string) ($page ? URL::to($page) : URL::to('/')),
];
}
$url = $this->blockPageURLs[$blockName]['url'];
if ($blockAction !== '' && $this->blockPageURLs[$blockName]['foundBlockID'] !== null) {
$url = rtrim($url, '/') . '/' . trim($blockAction, '/');
if ($isBlockActionInstanceSpecific) {
$url .= '/' . $this->blockPageURLs[$blockName]['foundBlockID'];
}
}
return $url;
} | @param string $blockName
@param string $blockAction
@param bool $isBlockActionInstanceSpecific
@return string | entailment |
public function values(): array
{
$ret = [];
foreach (array_keys($this->__data) as $key) {
$ret[$key] = $this->innerGet($key);
}
return $ret;
} | Returns array of all object's stored values
@return array | entailment |
public function searchSame($element)
{
$key = array_search($element, $this->values(), true);
return false === $key ? null : $key;
} | Returns index of first found same (===) element
MUST returns null if the same element is not found
@param mixed $element
@return int|string|bool|null | entailment |
protected function needCasting($key, $value): bool
{
if (is_null($value) || is_scalar($value) || is_object($value)) {
return false;
}
return true;
} | Does value need cast to this (or another) class?
@param mixed $key
@param mixed $value
@return bool | entailment |
public function findByHandleAndVersion($packageHandle, $packageVersion)
{
$result = null;
$packageHandle = (string) $packageHandle;
if ($packageHandle !== '') {
$packageVersion = (string) $packageVersion;
if ($packageVersion !== '') {
$list = $this->createQueryBuilder('v')
->innerJoin(Package::class, 'p', Expr\Join::WITH, 'v.package = p.id')
->where('p.handle = :handle')->setParameter('handle', $packageHandle)
->andWhere('v.version = :version')->setParameter('version', $packageVersion)
->setMaxResults(1)
->getQuery()->execute();
if (!empty($list)) {
$result = $list[0];
}
}
}
return $result;
} | Find a version given the package handle and the version.
@param string $packageHandle
@param string $packageVersion
@return \CommunityTranslation\Entity\Package\Version|null | entailment |
public function addProduct($itemCode, $itemPrice, $itemUrl, $itemQuantity, $itemTotal = 0, $itemName = '', $itemImage = '', $properties = [])
{
$product = new Product($itemCode, $itemPrice, $itemUrl, $itemQuantity, $itemTotal, $itemName, $itemImage, $properties);
array_push($this->order, $product);
return $product;
} | Adds a new product to order collection
@param string $itemCode
@param number $itemPrice
@param string $itemUrl
@param int $itemQuantity
@param int $itemTotal
@param string $itemName
@param string $itemImage
@param array $properties
@return \Moosend\Models\Product | entailment |
public function getSelect()
{
$data = [];
if (!empty($this->select)) {
foreach ($this->select as $field => $item) {
$data[] = $field . ' as ' . $item;
}
}
return $data;
} | @return mixed | entailment |
public function getRequestUrl($url)
{
if ($this->getPerPage() && $this->getPage()) {
return $url . $this->getRequestPageInfo();
}
return $url;
} | @param $url
@return string | entailment |
public function getInputsFromResult($inputResult)
{
$input_array = [];
if (!isset($inputResult['inputs'])) {
throw new \Exception('Inputs Not Found');
}
foreach ($inputResult['inputs'] as $rawInput) {
$input = new Input($rawInput);
$input_array[] = $input;
}
return $input_array;
} | Parses Request Result and gets Inputs
@param $inputResult
@return array
@throws \Exception | entailment |
public function init($siteId = '', $force = false)
{
$siteId = !empty($siteId) ? $siteId : $this->payload->getSiteId();
$hasUserId = $this->cookie->getCookie(CookieNames::USER_ID);
$hasUserId = !empty($hasUserId);
//store siteId on cookies
$this->cookie->setCookie(CookieNames::SITE_ID, $siteId);
//store campaignId on cookies
$this->storeCampaignIdIfExists();
if (!$hasUserId || $force) {
$newUserId = $this->replace_dashes(Uuid::v4());
$this->cookie->setCookie(CookieNames::USER_ID, $newUserId, time() + 60 * 60 * 24 * 3650);
return;
}
} | Stores a cookie that tells if a user is a new one or returned
@param string $siteId
@param bool $force | entailment |
public function storeCampaignId($campaignId)
{
if (!preg_match('/^\{?[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}\}?$/', $campaignId)) {
throw new \InvalidArgumentException('$campaignId should be a valid uuid');
}
$this->cookie->setCookie(CookieNames::CAMPAIGN_ID, $campaignId);
} | Store $campaignId on cookies
@param $campaignId | entailment |
public function create($siteId, $userAgent = '', $requestIPAddress = '')
{
if (empty($siteId)) {
throw new \Exception('Cannot create an instance without a site id');
}
$cookie = new Cookie();
$userId = $cookie->getCookie(CookieNames::USER_ID);
$userId = ! empty($userId) ? $userId : Uuid::v4();
$payload = new Payload(new Cookie(), $siteId, $userId);
$requestHeaders = [];
$browserUserAgent = !empty($userAgent) ? $userAgent : Browser::getUserAgent();
$browserIPAddress = !empty($requestIPAddress) ? $requestIPAddress : Browser::getRequestIPAddress();
if (! empty($browserUserAgent)) {
$requestHeaders['X-Original-User-Agent'] = $browserUserAgent;
}
if (! empty($browserIPAddress)) {
$requestHeaders['X-Original-Request-IP-Address'] = $browserIPAddress;
}
$client = new Client([
'base_uri' => API::ENDPOINT,
RequestOptions::HEADERS => $requestHeaders,
RequestOptions::HTTP_ERRORS => false,
RequestOptions::VERIFY => false
]);
return new Tracker($cookie, $payload, $client);
} | Creates a Tracker instance
@param string $siteId
@param string $userAgent
@param string $requestIPAddress
@throws \Exception
@return Tracker | entailment |
public function install()
{
parent::install();
$this->installXml();
$this->registerServiceProvider();
$this->configureSourceLocale();
$this->refreshLatestPackageVersions();
} | {@inheritdoc}
@see \Concrete\Core\Package\Package::install() | entailment |
public function upgradeCoreData()
{
$e = $this->getPackageEntity();
if ($e !== null) {
$this->upgradingFromVersion = $e->getPackageVersion();
}
parent::upgradeCoreData();
} | {@inheritdoc}
@see \Concrete\Core\Package\Package::upgradeCoreData() | entailment |
public function upgrade()
{
parent::upgrade();
$this->installXml();
if ($this->upgradingFromVersion !== null && version_compare($this->upgradingFromVersion, '0.4.0') < 0) {
$this->refreshLatestPackageVersions();
}
} | {@inheritdoc}
@see \Concrete\Core\Package\Package::upgrade() | entailment |
private function installXml()
{
$contentImporter = $this->app->make(ContentImporter::class);
$contentImporter->importContentFile($this->getPackagePath() . '/install.xml');
} | Install/refresh stuff from the XML installation file. | entailment |
private function configureSourceLocale()
{
$em = $this->app->make(EntityManager::class);
/* @var EntityManager $em */
$repo = $this->app->make(LocaleRepository::class);
if ($repo->findOneBy(['isSource' => true]) === null) {
$locale = LocaleEntity::create('en_US');
$locale
->setIsApproved(true)
->setIsSource(true)
;
$em->persist($locale);
$em->flush($locale);
}
} | Configure the source locale. | entailment |
public function on_start()
{
$this->registerServiceProvider();
$this->registerParsers();
$this->app->make('director')->addSubscriber($this->app->make(EventSubscriber::class));
if ($this->app->isRunThroughCommandLineInterface()) {
$this->registerCLICommands();
} else {
$this->registerAssets();
$this->registerRoutes();
}
} | Initialize the package. | entailment |
private function registerCLICommands()
{
$console = $this->app->make('console');
$console->add(new TransifexTranslationsCommand());
$console->add(new TransifexGlossaryCommand());
$console->add(new ProcessGitRepositoriesCommand());
$console->add(new AcceptPendingJoinRequestsCommand());
$console->add(new SendNotificationsCommand());
$console->add(new RemoveLoggedIPAddressesCommand());
$console->add(new NotifyPackageVersionsCommand());
$console->add(new ProcessRemotePackagesCommand());
} | Register the CLI commands. | entailment |
private function registerAssets()
{
$al = AssetList::getInstance();
$al->registerMultiple([
'jquery/scroll-to' => [
['javascript', 'js/jquery.scrollTo.min.js', ['minify' => true, 'combine' => true, 'version' => '2.1.2'], $this],
],
'community_translation/online_translation/bootstrap' => [
['javascript', 'js/bootstrap.min.js', ['minify' => false, 'combine' => true], $this],
],
'community_translation/online_translation/markdown-it' => [
['javascript', 'js/markdown-it.min.js', ['minify' => false, 'combine' => true], $this],
],
'community_translation/online_translation/core' => [
['css', 'css/online-translation.css', ['minify' => false, 'combine' => true], $this],
['javascript', 'js/online-translation.js', ['minify' => true, 'combine' => true], $this],
],
'jquery/comtraSortable' => [
['css', 'css/jquery.comtraSortable.css', ['minify' => true, 'combine' => true], $this],
['javascript', 'js/jquery.comtraSortable.js', ['minify' => true, 'combine' => true], $this],
],
]);
$al->registerGroupMultiple([
'jquery/scroll-to' => [
[
['javascript', 'jquery'],
['javascript', 'jquery/scroll-to'],
],
],
'community_translation/online_translation' => [
[
['css', 'community_translation/online_translation/core'],
['javascript', 'community_translation/online_translation/bootstrap'],
['javascript', 'community_translation/online_translation/markdown-it'],
['javascript', 'community_translation/online_translation/core'],
],
],
'jquery/comtraSortable' => [
[
['css', 'font-awesome'],
['css', 'jquery/comtraSortable'],
['javascript', 'jquery/comtraSortable'],
],
],
]);
} | Register the assets. | entailment |
private function registerRoutes()
{
$config = $this->app->make('community_translation/config');
$onlineTranslationPath = $config->get('options.onlineTranslationPath');
$apiEntryPoint = $config->get('options.api.entryPoint');
$handleRegex = '[A-Za-z0-9]([A-Za-z0-9\_]*[A-Za-z0-9])?';
$localeRegex = '[a-zA-Z]{2,3}([_\-][a-zA-Z0-9]{2,3})?';
$this->app->make(Router::class)->registerMultiple([
// Online Translation
"$onlineTranslationPath/{packageVersionID}/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::view',
null,
['packageVersionID' => 'unreviewed|[1-9][0-9]*', 'localeID' => $localeRegex],
[],
'',
[],
['GET'],
],
"$onlineTranslationPath/action/save_comment/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::save_comment',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/delete_comment/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::delete_comment',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/load_all_places/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::load_all_places',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/process_translation/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::process_translation',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/load_translation/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::load_translation',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/save_glossary_term/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::save_glossary_term',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/delete_glossary_term/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::delete_glossary_term',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/download/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::download',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/upload/{localeID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::upload',
null,
['localeID' => $localeRegex],
[],
'',
[],
['POST'],
],
"$onlineTranslationPath/action/save_notifications/{packageID}" => [
'Concrete\Package\CommunityTranslation\Controller\Frontend\OnlineTranslation::save_notifications',
null,
['packageID' => '\d+'],
[],
'',
[],
['POST'],
],
// API Entry Points
"$apiEntryPoint/rate-limit/" => [
'CommunityTranslation\Api\EntryPoint::getRateLimit',
null,
[],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/locales/" => [
'CommunityTranslation\Api\EntryPoint::getLocales',
null,
[],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/packages/" => [
'CommunityTranslation\Api\EntryPoint::getPackages',
null,
[],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/package/{packageHandle}/versions/" => [
'CommunityTranslation\Api\EntryPoint::getPackageVersions',
null,
['packageHandle' => $handleRegex],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/package/{packageHandle}/{packageVersion}/locales/{minimumLevel}/" => [
'CommunityTranslation\Api\EntryPoint::getPackageVersionLocales',
null,
['packageHandle' => $handleRegex, 'minimumLevel' => '[0-9]{1,3}'],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/package/{packageHandle}/{packageVersion}/translations/{localeID}/{formatHandle}/" => [
'CommunityTranslation\Api\EntryPoint::getPackageVersionTranslations',
null,
['packageHandle' => $handleRegex, 'localeID' => $localeRegex, 'formatHandle' => $handleRegex],
[],
'',
[],
['GET'],
],
"$apiEntryPoint/fill-translations/{formatHandle}/" => [
'CommunityTranslation\Api\EntryPoint::fillTranslations',
null,
['formatHandle' => $handleRegex],
[],
'',
[],
['POST'],
],
"$apiEntryPoint/package/{packageHandle}/{packageVersion}/translatables/{formatHandle}/" => [
'CommunityTranslation\Api\EntryPoint::importPackageVersionTranslatables',
null,
['packageHandle' => $handleRegex, 'formatHandle' => $handleRegex],
[],
'',
[],
['POST'],
],
"$apiEntryPoint/translations/{localeID}/{formatHandle}/{approve}/" => [
'CommunityTranslation\Api\EntryPoint::importTranslations',
null,
['localeID' => $localeRegex, 'formatHandle' => $handleRegex, 'approve' => '[01]'],
[],
'',
[],
['POST'],
],
"$apiEntryPoint/import/package/" => [
'CommunityTranslation\Api\EntryPoint::importPackage',
null,
[],
[],
'',
[],
['PUT'],
],
"$apiEntryPoint/{unrecognizedPath}" => [
'CommunityTranslation\Api\EntryPoint::unrecognizedCall',
null,
['unrecognizedPath' => '.*'],
],
"$apiEntryPoint" => [
'CommunityTranslation\Api\EntryPoint::unrecognizedCall',
],
]);
} | Register the routes. | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
if ($this->replace || '' === $request->getUri()->getHost()) {
$uri = $request->getUri()->withHost($this->host->getHost());
$uri = $uri->withScheme($this->host->getScheme());
$request = $request->withUri($uri);
}
return $next($request);
} | {@inheritdoc} | entailment |
public function getPhpExcelObject(SS_List $set)
{
// Get the first object. We'll need it to know what type of objects we
// are dealing with
$first = $set->first();
// Get the Excel object
$excel = $this->setupExcel($first);
$sheet = $excel->setActiveSheetIndex(0);
// Make sure we have at lease on item. If we don't, we'll be returning
// an empty spreadsheet.
if ($first) {
// Set up the header row
$fields = $this->getFieldsForObj($first);
$this->headerRow($sheet, $fields, $first);
// Add a new row for each DataObject
foreach ($set as $item) {
$this->addRow($sheet, $item, $fields);
}
// Freezing the first column and the header row
$sheet->freezePane("B2");
// Auto sizing all the columns
$col = sizeof($fields);
for ($i = 0; $i < $col; $i++) {
$sheet
->getColumnDimension(
PHPExcel_Cell::stringFromColumnIndex($i)
)
->setAutoSize(true);
}
}
return $excel;
} | Generate a {@link PHPExcel} for the provided DataObject List
@param SS_List $set List of DataObjects
@return PHPExcel | entailment |
protected function setupExcel(DataObjectInterface $do)
{
// Try to get the current user
$member = Member::currentUser();
$creator = $member ? $member->getName() : '';
// Get information about the current Model Class
$singular = $do ? $do->i18n_singular_name() : '';
$plural = $do ? $do->i18n_plural_name() : '';
// Create the Spread sheet
$excel = new PHPExcel();
$excel->getProperties()
->setCreator($creator)
->setTitle(_t(
'firebrandhq.EXCELEXPORT',
'{singular} export',
'Title for the spread sheet export',
array('singular' => $singular)
))
->setDescription(_t(
'firebrandhq.EXCELEXPORT',
'List of {plural} exported out of a SilverStripe website',
'Description for the spread sheet export',
array('plural' => $plural)
));
// Give a name to the sheet
if ($plural) {
$excel->getActiveSheet()->setTitle($plural);
}
return $excel;
} | Initialize a new {@link PHPExcel} object based on the provided
{@link DataObjectInterface} interface.
@param DataObjectInterface $do
@return PHPExcel | entailment |
protected function headerRow(PHPExcel_Worksheet &$sheet, array $fields, DataObjectInterface $do)
{
// Counter
$row = 1;
$col = 0;
$useLabelsAsHeaders = $this->getUseLabelsAsHeaders();
// Add each field to the first row
foreach ($fields as $field => $type) {
$header = $useLabelsAsHeaders ? $do->fieldLabel($field) : $field;
$sheet->setCellValueByColumnAndRow($col, $row, $header);
$col++;
}
// Get the last column
$col--;
$endcol = PHPExcel_Cell::stringFromColumnIndex($col);
// Set Autofilters and Header row style
$sheet->setAutoFilter("A1:{$endcol}1");
$sheet->getStyle("A1:{$endcol}1")->getFont()->setBold(true);
return $sheet;
} | Add an header row to a {@link PHPExcel_Worksheet}.
@param PHPExcel_Worksheet $sheet
@param array $fields List of fields
@param DataObjectInterface $do
@return PHPExcel_Worksheet | entailment |
protected function addRow(
PHPExcel_Worksheet &$sheet,
DataObjectInterface $item,
array $fields
) {
$row = $sheet->getHighestRow() + 1;
$col = 0;
foreach ($fields as $field => $type) {
if ($item->hasField($field) || $item->hasMethod("get{$field}")) {
$value = $item->$field;
} else {
$viewer = SSViewer::fromString('$' . $field . '.RAW');
$value = $item->renderWith($viewer, true);
}
$sheet->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
return $sheet;
} | Add a new row to a {@link PHPExcel_Worksheet} based of a
{@link DataObjectInterface}
@param PHPExcel_Worksheet $sheet
@param DataObjectInterface $item
@param array $fields List of fields to include
@return PHPExcel_Worksheet | entailment |
protected function getFileData(PHPExcel $excel, $format)
{
$writer = PHPExcel_IOFactory::createWriter($excel, $format);
ob_start();
$writer->save('php://output');
$fileData = ob_get_clean();
return $fileData;
} | Generate a string representation of an {@link PHPExcel} spread sheet
suitable for output to the browser.
@param PHPExcel $excel
@param string $format Format to use when outputting the spreadsheet.
Must be compatible with the format expected by
{@link PHPExcel_IOFactory::createWriter}.
@return string | entailment |
public function getUseLabelsAsHeaders()
{
if ($this->useLabelsAsHeaders !== null) {
return $this->useLabelsAsHeaders;
}
$useLabelsAsHeaders = static::config()->UseLabelsAsHeaders;
if ($useLabelsAsHeaders !== null) {
return $useLabelsAsHeaders;
}
return false;
} | Accessor for UseLabelsAsHeaders. If this is `true`, the data formatter will call {@link DataObject::fieldLabel()} to pick the header strings. If it's set to false, it will use the raw field name.
You can define this for a specific ExcelDataFormatter instance with `setUseLabelsAsHeaders`. You can set the default for all ExcelDataFormatter instance in your YML config file:
```
ExcelDataFormatter:
UseLabelsAsHeaders: true
```
Otherwise, the data formatter will default to false.
@return bool | entailment |
public function store(FormRequest $request)
{
$data = $request->all();
$model = $this->repository->create($data);
return $this->redirect($request, $model);
} | Store a newly created resource in storage.
@param \TypiCMS\Modules\News\Http\Requests\FormRequest $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function update(News $news, FormRequest $request)
{
$data = $request->all();
$this->repository->update($news->id, $data);
return $this->redirect($request, $news);
} | Update the specified resource in storage.
@param \TypiCMS\Modules\News\Models\News $news
@param \TypiCMS\Modules\News\Http\Requests\FormRequest $request
@return \Illuminate\Http\RedirectResponse | entailment |
public static function create(TranslatableEntity $translatable, UserEntity $postedBy, LocaleEntity $locale = null, Comment $parentComment = null)
{
$result = new static();
$result->translatable = $translatable;
$result->locale = $locale;
$result->parentComment = $parentComment;
$result->postedOn = new DateTime();
$result->postedBy = $postedBy;
$result->text = null;
return $result;
} | Create a new (unsaved) entity.
@param TranslatableEntity $translatable The associated translatable string
@param UserEntity $postedBy The user that posted the comment
@param LocaleEntity $locale NULL if it's a global comment, the locale instance if it's translation-specific
@param Comment $parentComment The parent comment (if this is a followup) or null
@return static | entailment |
public function getRootComment()
{
$result = $this;
while (($parent = $result->getParentComment()) !== null) {
$result = $parent;
}
return $result;
} | Get the root comment (this instance itself if it's the root one).
@return Comment | entailment |
public function run(Factory $factory, Generator $faker)
{
$factory->define(\App\Http\Node\Model\ArticleExampleModel::class, function () use ($faker) {
return [
'title' => $faker->sentence($nbWords = 6, $variableNbWords = true),
'description' => $faker->text($maxNbChars = 150),
'date' => $faker->date($format = 'Y-m-d', $max = 'now')
];
});
factory(\App\Http\Node\Model\ArticleExampleModel::class, 50)->create();
} | Run the database seeds.
@return void | entailment |
public function set($id, callable $resolver)
{
$this->innerSet($id, $resolver);
unset($this->resolved[$id]);
unset($this->singletons[$id]);
return $this;
} | Sets a resolver for entry of the container by its identifier.
@param string $id Identifier of the entry to look for.
@param callable $resolver Function that resolves the entry and returns it.
@return $this. | entailment |
public function singleton($id, callable $resolver)
{
$this->innerSet($id, $resolver);
unset($this->resolved[$id]);
$this->singletons[$id] = true;
return $this;
} | Sets a resolver for entry of the container by its identifier as singleton.
@param string $id Identifier of the entry to look for.
@param callable $resolver Function that resolves the entry and returns it.
@return $this. | entailment |
public function get($id)
{
if (!$this->has($id)) {
throw new ContainerEntryNotFoundException($id);
}
try {
if (isset($this->singletons[$id])) {
if (!isset($this->resolved[$id])) {
$this->resolved[$id] = $this->innerGet($id)();
}
return $this->resolved[$id];
}
return $this->innerGet($id)();
} catch (\Throwable $e) {
throw new ContainerException($e);
}
} | Finds an entry of the container by its identifier and returns it.
@param string $id Identifier of the entry to look for.
@throws ContainerEntryNotFoundException No entry was found for **this** identifier.
@throws ContainerException Error while retrieving the entry.
@return mixed Entry. | entailment |
public function handleRequest(string $method, string $uri = '', array $options = [], array $parameters = [])
{
// Are we going a GET or a POST?
if (!empty($parameters)) {
if ($method === 'GET') {
// Send as get params
$options['query'] = $parameters;
}
if ($method === 'POST' || $method === 'PATCH' || $method === 'DELETE') {
// Otherwise send JSON in the body
$options['json'] = (object)$parameters;
}
}
// Let's go
try {
$response = $this->client->request($method, $uri, $options);
// All good
return json_decode($response->getBody(), true);
} catch (RequestException $exception) {
$message = $exception->getMessage();
throw new ApiException($message, $exception->getCode(), $exception);
}
} | Makes a request using Guzzle
@param string $method The HTTP request method (GET/POST/etc)
@param string $uri The resource
@param array $options Request options
@param array $parameters Request parameters
@see RequestHandler::request()
@return array
@throws ApiException | entailment |
public function request(string $method, string $path, array $parameters = [])
{
$options = [
'headers' => [
'Authorization' => sprintf('Key %s', $this->apiKey),
'User-Agent' => sprintf(
'Clarifai PHP (https://github.com/darrynten/clarifai-php);v%s;%s',
\DarrynTen\Clarifai\Clarifai::VERSION,
phpversion()
),
],
];
// TODO check for batch operation
return $this->handleRequest(
$method,
sprintf('%s/%s/%s', $this->url, $this->version, $path),
$options,
$parameters
);
} | Makes a request to Clarifai
@param string $method The API method
@param string $path The path
@param array $parameters The request parameters
@return array
@throws ApiException | entailment |
public function generateRawData()
{
$rawData = ['id' => $this->getId()];
if ($this->getCreatedAt()) {
$rawData['created_at'] = $this->getCreatedAt();
}
if ($this->getStatusDescription() || $this->getStatusCode()) {
$rawData['status'] = $this->getStatus();
}
return $rawData;
} | Generates rawData from modelVersion
@return array | entailment |
public function sendRequest(RequestInterface $request)
{
try {
return $this->pluginClient->sendRequest($request);
} catch (\Http\Client\Common\Exception\LoopException $e) {
throw new LoopException($e->getMessage(), $e->getRequest(), $e);
}
} | {@inheritdoc} | entailment |
protected function getRecipientIDs(NotificationEntity $notification)
{
$result = [];
$notificationData = $notification->getNotificationData();
$locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']);
if ($locale === null) {
throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID']));
}
$group = $this->getGroupsHelper()->getAdministrators($locale);
$result = array_merge($result, $group->getGroupMemberIDs());
if (empty($result)) {
$group = $this->getGroupsHelper()->getGlobalAdministrators();
$result = $group->getGroupMemberIDs();
}
return $result;
} | {@inheritdoc}
@see Category::getRecipientIDs() | entailment |
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient)
{
$notificationData = $notification->getNotificationData();
$locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']);
if ($locale === null) {
throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID']));
}
$uir = $this->app->make(UserInfoRepository::class);
$packageVersion = $notificationData['packageVersionID'] ? $this->app->make(PackageVersionRepository::class)->find($notificationData['packageVersionID']) : null;
$translations = [];
foreach ($notificationData['numTranslations'] as $userID => $numTranslations) {
$translations[] = [
'user' => $uir->getByID($userID),
'numTranslations' => $numTranslations,
];
}
return [
'localeName' => $locale->getDisplayName(),
'translations' => $translations,
'approvalURL' => (string) URL::to(
$this->app->make('community_translation/config')->get('options.onlineTranslationPath'),
$packageVersion ? $packageVersion->getID() : 'unreviewed',
$locale->getID()
),
] + $this->getCommonMailParameters($notification, $recipient);
} | {@inheritdoc}
@see Category::getMailParameters() | entailment |
public function findApproved($localeID)
{
$result = null;
if (is_string($localeID) && $localeID !== '') {
$l = $this->find($localeID);
if ($l !== null && $l->isApproved() && !$l->isSource()) {
$result = $l;
}
}
return $result;
} | Search an approved locale given its ID (excluding the source one).
@param string $localeID
@return LocaleEntity|null | entailment |
public function getApprovedLocales()
{
$locales = $this->findBy(['isSource' => null, 'isApproved' => true]);
$comparer = new Comparer();
usort($locales, function (LocaleEntity $a, LocaleEntity $b) use ($comparer) {
return $comparer->compare($a->getDisplayName(), $b->getDisplayName());
});
return $locales;
} | Get the list of the approved locales (excluding the source one).
@return LocaleEntity[] | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$this->logger->info(sprintf('Emit request: "%s"', $this->formatter->formatRequest($request)), ['request' => $request]);
return $next($request)->then(function (ResponseInterface $response) use ($request) {
$this->logger->info(
sprintf('Receive response: "%s" for request: "%s"', $this->formatter->formatResponse($response), $this->formatter->formatRequest($request)),
[
'request' => $request,
'response' => $response,
]
);
return $response;
}, function (Exception $exception) use ($request) {
if ($exception instanceof Exception\HttpException) {
$this->logger->error(
sprintf('Error: "%s" with response: "%s" when emitting request: "%s"', $exception->getMessage(), $this->formatter->formatResponse($exception->getResponse()), $this->formatter->formatRequest($request)),
[
'request' => $request,
'response' => $exception->getResponse(),
'exception' => $exception,
]
);
} else {
$this->logger->error(
sprintf('Error: "%s" when emitting request: "%s"', $exception->getMessage(), $this->formatter->formatRequest($request)),
[
'request' => $request,
'exception' => $exception,
]
);
}
throw $exception;
});
} | {@inheritdoc} | entailment |
public static function getClassMethodArgs($class, string $method)
{
static $cache = null;
if (null !== $cache && isset($cache[$class][$method])) {
return $cache[$class][$method];
}
$reflector = new \ReflectionMethod($class, $method);
$params = $reflector->getParameters();
if (empty($params)) {
$cache[$class][$method] = [];
return [];
}
$args = [];
foreach ($params as $param) {
$args[$param->name] = [
'optional' => $param->isOptional(),
'variadic' => $param->isVariadic(),
];
if ($param->isOptional() && $param->isDefaultValueAvailable()) {
$args[$param->name]['default'] = $param->getDefaultValue();
}
if ($param->hasType()) {
$args[$param->name]['type'] = (string)$param->getType();
}
}
$cache[$class][$method] = $args;
return $args;
} | Returns the argument list by object and its method name
@param string $class
@param string $method
@return array
@throws \ReflectionException | entailment |
public static function getObjectMethodArgs($obj, string $method)
{
if (!is_object($obj)) {
throw new Exception('$obj is not an object');
}
return static::getClassMethodArgs(get_class($obj), $method);
} | Returns the argument list by object and its method name
@param object $obj
@param string $method
@return array
@throws \Runn\Reflection\Exception | entailment |
public function get($key, $default = null)
{
list($baseKey, $searchKey) = $this->fetchKey($key);
$value = $this->fetchValue($baseKey, $searchKey);
return (! is_null($value)) ? $value : $default;
} | Get value from registry
@param string $key
@param string $default
@return mixed | entailment |
public function set($key, $value)
{
list($baseKey, $searchKey) = $this->fetchKey($key);
$registry = $this->get($baseKey);
if ($registry === null) {
$registry = $this->cache->get($baseKey);
}
if (! is_null($registry)) {
return $this->overwrite($key, $value);
}
if ($baseKey != $searchKey)
{
$object = array();
$level = '';
$keys = explode('.', $searchKey);
foreach ($keys as $key)
{
$level .= '.'.$key;
(trim($level, '.') == $searchKey) ? array_set($object, trim($level, '.'), $value) : array_set($object, trim($level, '.'), array());
}
$this->database->table($this->config['table'])->insert(array('key' => $baseKey, 'value' => json_encode($object)));
// Add to cache
$this->cache->add($baseKey, $object);
}
else
{
$this->database->table($this->config['table'])->insert(array('key' => $baseKey, 'value' => json_encode($value)));
// Add to cache
$this->cache->add($baseKey, $value);
}
return true;
} | Store value into registry
@param string $key
@param mixed $value
@return bool | entailment |
protected function forceTypes($data)
{
if (in_array($data, array('true', 'false')))
{
$data = ($data === 'true' ? 1 : 0);
}
else if (is_numeric($data))
{
$data = (int) $data;
}
else if (gettype($data) === 'array')
{
foreach($data as $key=>$value)
{
$data[$key] = $this->forceTypes($value);
}
}
return $data;
} | Cast values to native PHP variable types.
@param mixed $data
@return mixed | entailment |
protected function fetchKey($key)
{
if (str_contains($key, '.'))
{
$keys = explode('.', $key);
$search = array_except($keys, 0);
return array(array_get($keys, 0), implode('.', $search));
}
return array($key, null);
} | Get registry key
@param string $key
@return array | entailment |
protected function fetchValue($key, $searchKey = null)
{
$object = $this->cache->get($key);
if (is_null($object)) {
return null;
}
return $searchKey ? array_get($object, $searchKey, null) : $object;
} | Get key value
@param string $key
@param string $searchKey
@return mixed | entailment |
protected function setCache()
{
// Check if cache has expired
if ($this->cache->expired() === false) {
return;
}
// Instantiate values
$values = array();
// Get values from database
foreach($this->database->table($this->config['table'])->get() as $setting)
{
$values[$setting->key] = json_decode($setting->value, true);
}
// Cache values
$this->cache->set($values);
} | Set cache
@return array | entailment |
public function getPaginationHTML()
{
if ($this->pagination->haveToPaginate()) {
$view = new TwitterBootstrap3View();
$me = $this;
$result = $view->render(
$this->pagination,
function ($page) use ($me) {
$list = $me->getItemListObject();
$result = (string) $me->getBaseURL();
$result .= strpos($result, '?') === false ? '?' : '&';
$result .= ltrim($list->getQueryPaginationPageParameter(), '&') . '=' . $page;
return $result;
},
[
'prev_message' => tc('Pagination', '← Previous'),
'next_message' => tc('Pagination', 'Next →'),
'active_suffix' => '<span class="sr-only">' . tc('Pagination', '(current)') . '</span>',
]
);
} else {
$result = '';
}
return $result;
} | Builds the HTML to be used to control the pagination.
@return string | entailment |
public function send(IRequest $request, IResponse $response): void
{
// Set response headers for the file download
$response->setHeader('Content-Length', $this->stream->getSize());
$response->setHeader('Content-Type', $this->contentType);
$response->setHeader('Content-Disposition', 'attachment; filename="'.$this->name.'";');
while (!$this->stream->eof()) {
echo $this->stream->read(4e6);
}
$this->stream->close();
} | Sends response to output.
@param IRequest $request
@param IResponse $response | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->logger = $this->createLogger($input, $output);
$error = null;
try {
$result = $this->executeWithLogger($input);
} catch (Exception $x) {
$error = $x;
} catch (Throwable $x) {
$error = $x;
}
if ($error !== null) {
$this->logger->error($this->formatThrowable($error));
return static::RETURN_CODE_ON_FAILURE;
}
return $result;
} | {@inheritdoc}
@see \Symfony\Component\Console\Command\Command::execute() | entailment |
private function createLogger(InputInterface $input, OutputInterface $output)
{
$logger = new MonologLogger('CommunityTranslation');
if (!$input->isInteractive()) {
$config = $this->app->make('community_translation/config');
if ($config->get('options.nonInteractiveCLICommands.notify')) {
$to = $config->get('options.nonInteractiveCLICommands.to');
if ($to && is_array($to)) {
$site = $this->app->make('site')->getSite()->getSiteName();
foreach ($to as $toConfig) {
$handler = null;
if (is_array($toConfig) && isset($toConfig['handler'])) {
switch ($toConfig['handler']) {
case 'slack':
if (isset($toConfig['apiToken']) && $toConfig['apiToken'] && isset($toConfig['channel']) && $toConfig['channel']) {
$handler = new SlackHandler($toConfig['apiToken'], $toConfig['channel'], 'CommunityTranslation@' . $site);
$lineFormatter = new LineFormatter('%message%');
if (method_exists($lineFormatter, 'allowInlineLineBreaks')) {
$lineFormatter->allowInlineLineBreaks(true);
}
$handler->setFormatter($lineFormatter);
}
break;
case 'telegram':
if (isset($toConfig['botToken']) && $toConfig['botToken'] && isset($toConfig['chatID']) && $toConfig['chatID']) {
$handler = new TelegramHandler($toConfig['botToken'], $toConfig['chatID']);
}
break;
}
}
if ($handler !== null) {
$handler->setLevel(MonologLogger::ERROR);
$logger->pushHandler($handler);
}
}
}
}
}
$logger->pushHandler(new ConsoleHandler($output));
return $logger;
} | @param OutputInterface $output
@return MonologLogger | entailment |
protected function formatThrowable($error)
{
$message = trim($error->getMessage()) . "\n";
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$file = $error->getFile();
if ($file) {
$message .= "\nFile:\n$file";
$line = $error->getLine();
if ($line) {
$message .= ':' . $line;
}
$message .= "\n";
}
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
$trace = $error->getTraceAsString();
if ($trace) {
$message .= "\nTrace:\n$trace\n";
}
}
}
return $message;
} | @param Exception|Throwable $error
@return string | entailment |
private function getLockFilename($lockHandle = null)
{
$lockHandle = (string) $lockHandle;
if ($lockHandle === '') {
$myClass = new ReflectionClass($this);
$myFilename = $myClass->getFileName();
$lockHandle = $myClass->getShortName() . '-' . sha1($myFilename . DIR_APPLICATION);
}
$config = $this->app->make('community_translation/config');
$tempDir = $config->get('options.tempDir');
$tempDir = is_string($tempDir) ? rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $tempDir), '/') : '';
if ($tempDir === '') {
$fh = $this->app->make('helper/file');
$tempDir = $fh->getTemporaryDirectory();
$tempDir = is_string($tempDir) ? rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $tempDir), '/') : '';
if ($tempDir === '') {
throw new Exception(t('Unable to retrieve the temporary directory.'));
}
}
$locksDir = $tempDir . '/command-locks';
if (!@is_dir($locksDir)) {
@mkdir($locksDir, DIRECTORY_PERMISSIONS_MODE_COMPUTED, true);
if (!@is_dir($locksDir)) {
throw new Exception(t('Unable to create a temporary directory.'));
}
}
return $locksDir . "/$lockHandle.lock";
} | @param string|null $lockHandle
@throws Exception
@return string | entailment |
protected function acquireLock($maxWaitSeconds = 5, $lockHandle = null)
{
$lockFile = $this->getLockFilename($lockHandle);
if (isset($this->lockHandles[$lockFile])) {
$result = true;
} else {
$startTime = time();
$result = false;
$fd = null;
while ($result === false) {
$fd = @fopen($lockFile, 'w');
if ($fd !== false) {
if (@flock($fd, LOCK_EX | LOCK_NB) === true) {
$result = true;
break;
} else {
@fclose($fd);
}
}
$elapsedTime = time() - $startTime;
if ($elapsedTime >= $maxWaitSeconds) {
break;
}
sleep(1);
}
if ($result === true) {
$this->lockHandles[$lockFile] = $fd;
}
}
return $result;
} | @param int $maxWaitSeconds
@param string|null $lockHandle
@return bool | entailment |
public function generateRawData()
{
$rawData = ['id' => $this->getId()];
$rawData['data'] = [];
$rawData['data']['image'] = [];
if ($this->getCreatedAt()) {
$rawData['created_at'] = $this->getCreatedAt();
}
if ($this->getStatusDescription() || $this->getStatusCode()) {
$rawData['status'] = $this->getStatus();
}
if ($this->getImage()) {
$rawData['data']['image'][$this->getImageMethod()] = $this->getImage();
}
if ($this->getCrop()) {
$rawData['data']['image']['crop'] = $this->getCrop();
}
if ($this->getConcepts()) {
$rawData['data']['concepts'] = [];
foreach ($this->getConcepts() as $concept) {
$rawData['data']['concepts'][] = $concept->generateRawData();
}
}
if ($this->getMetaData()) {
$rawData['data']['metadata'] = $this->getMetaData();
}
return $rawData;
} | Generates rawData from Input
@return array | entailment |
public function splitTimeWindow($timeWindow, $default = 3600)
{
$timeWindow = (int) $timeWindow;
if ($timeWindow <= 0) {
$timeWindow = (int) $default;
}
foreach (array_keys($this->getTimeWindowUnits()) as $u) {
if (($timeWindow % $u) === 0) {
$unit = $u;
} else {
break;
}
}
return [
(int) ($timeWindow / $unit),
$unit,
];
} | Get the representation of a time window expressed in seconds.
@param int $timeWindow
@param int $default the value to use if $timeWindow is not valid
@return int[] Index 0: value, index 1: units | entailment |
public function joinTimeWindow($value, $unit, $required = false)
{
if (is_int($value)) {
$v = $value;
} elseif (is_string($value) && trim($value) !== '' && is_numeric(trim($value))) {
$v = (int) $value;
} else {
$v = null;
}
if ($v === null) {
if ($required) {
throw new UserMessageException(t('The value of the time window is missing'));
}
$result = null;
} elseif ($v <= 0) {
throw new UserMessageException(t('The value of the time window must be greater than zero'));
} else {
if (is_int($unit)) {
$u = $unit;
} elseif (is_string($unit) && trim($unit) !== '' && is_numeric(trim($unit))) {
$u = (int) $unit;
} else {
$u = null;
}
if ($u === null || !array_key_exists($u, $this->getTimeWindowUnits())) {
throw new UserMessageException(t('The value of the time window units is not valid'));
}
$result = $u * $v;
if (!is_int($result)) {
throw new UserMessageException(t('The value of the time window units is too big'));
}
}
return $result;
} | Parse a value and a unit and returns the seconds (or an Error instance in case of errors).
@param int|mixed $value
@param int|mixed $unit
@param bool $required
@throws UserMessageException
@return int|null|Error | entailment |
public function getWidgetHtml($name, $maxRequests, $timeWindow)
{
list($timeWindowValue, $timeWindowUnit) = $this->splitTimeWindow($timeWindow);
$html = '<div class="input-group" id="' . $name . '_container">';
$html .= $this->form->number($name . '_maxRequests', $maxRequests, ['min' => '1']);
$html .= '<span class="input-group-addon">' . tc('TimeInterval', 'requests every') . '</span>';
$html .= $this->form->number($name . '_timeWindow_value', $timeWindowValue, ['min' => '1']);
$html .= '<div class="input-group-btn">';
$timeWindowUnits = $this->getTimeWindowUnits();
$u = $this->form->getRequestValue($name . '_timeWindow_unit');
if (isset($timeWindowUnits[$u])) {
$timeWindowUnit = $u;
}
$html .= '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="' . $name . '_timeWindow_unitlabel">' . h($timeWindowUnits[$timeWindowUnit]) . '</span> <span class="caret"></span></button>';
$html .= '<ul class="dropdown-menu dropdown-menu-right">';
foreach ($timeWindowUnits as $unitValue => $unitName) {
$html .= '<li><a href="#" data-unit-value="' . $unitValue . '" data-max-value="' . floor(PHP_INT_MAX / $unitValue) . '">' . h($unitName) . '</a></li>';
}
$html .= '</ul>';
$html .= '</div>';
$html .= $this->form->hidden($name . '_timeWindow_unit', $timeWindowUnit);
$html .= '</div>';
$html .= <<<EOT
<script>
$(document).ready(function() {
var twValue = $('#{$name}_timeWindow_value'), twUnitLabel = $('#{$name}_timeWindow_unitlabel'), twUnit = $('#{$name}_timeWindow_unit'), twUnitLinks = $('#{$name}_container a[data-unit-value]');
twUnit
.on('change', function() {
var a = twUnitLinks.filter('[data-unit-value="' + twUnit.val() + '"]');
twUnitLabel.text(a.text());
twValue.attr('max', a.data('max-value'));
})
.trigger('change')
;
twUnitLinks.on('click', function(e) {
e.preventDefault();
twUnit.val($(this).data('unit-value')).trigger('change');
});
});
</script>
EOT
;
return $html;
} | Create the HTML for a rate limit.
@param string $name
@param int|null $maxRequests
@param int $timeWindow
@return string | entailment |
public function fromWidgetHtml($name, $defaultTimeWindow = 3600)
{
$post = $this->request->request;
$s = $post->get($name . '_maxRequests');
$maxRequests = (is_scalar($s) && is_numeric($s)) ? (int) $s : null;
if ($maxRequests !== null && $maxRequests <= 0) {
throw new UserMessageException(t('Please specify a positive integer for the maximum number of requests (or leave it empty)'));
}
try {
$timeWindow = $this->joinTimeWindow($post->get($name . '_timeWindow_value'), $post->get($name . '_timeWindow_unit'), true);
} catch (UserMessageException $x) {
if ($maxRequests === null) {
$timeWindow = $defaultTimeWindow;
} else {
throw $x;
}
}
return [$maxRequests, $timeWindow];
} | Get the rate limit values from the values of the widget.
@param string $name
@param int $defaultTimeWindow the value of the time window if the max requests is empty and the received time window is invalid
@throws UserMessageException
@return array | entailment |
public function describeRate($maxRequests, $timeWindow)
{
if ($maxRequests && $timeWindow) {
list($value, $unit) = $this->splitTimeWindow($timeWindow);
switch ($unit) {
case 60:
$duration = Unit::format($value, 'duration/minute', 'long');
break;
case 3600:
$duration = Unit::format($value, 'duration/hour', 'long');
break;
case 86400:
$duration = Unit::format($value, 'duration/day', 'long');
break;
case 604800:
$duration = Unit::format($value, 'duration/week', 'long');
break;
default:
$duration = Unit::format($timeWindow, 'duration/second', 'long');
break;
}
$result = t2('%1$d request every %2$s', '%1$d requests every %2$s', $maxRequests, $duration);
} else {
$result = '';
}
return $result;
} | Format a rate limit.
@param int|null $maxRequests
@param int|null $timeWindow
@return string
@example: '2 requests every 1 hour' | entailment |
public function getSourceStrings($buildIfNotSet = false)
{
$result = $this->sourceStrings;
if ($result === null && $buildIfNotSet) {
$result = new Translations();
$result->setLanguage($this->app->make('community_translation/sourceLocale'));
foreach ($this->translations as $translations) {
foreach ($translations[1] as $key => $translation) {
if (!$result->offsetExists($key)) {
$newTranslation = $result->insert($translation->getContext(), $translation->getOriginal(), $translation->getPlural());
foreach ($translation->getExtractedComments() as $comment) {
$newTranslation->addExtractedComment($comment);
}
}
}
}
$this->sourceStrings = $result;
}
return $result;
} | Get the source (untranslated) strings (representing a .pot file).
@param bool $buildIfNotSet set to true to build the string list if it's not set
@return Translations|null | entailment |
public function setTranslations(Locale $locale, Translations $translations)
{
$this->translations[$locale->getID()] = [$locale, $translations];
} | Set the translations for a specific locale.
@param Locale $locale
@param Translations $translations | entailment |
public function getTranslations(Locale $locale)
{
$localeID = $locale->getID();
$translations = isset($this->translations[$localeID]) ? $this->translations[$localeID][1] : null;
if ($translations === null) {
$translations = clone $this->getSourceStrings(true);
$translations->setLanguage($locale->getID());
$this->setTranslations($locale, $translations);
}
return $translations;
} | Get the translations for a specific locale.
@param Locale $locale | entailment |
public function mergeWith(Parsed $other)
{
$mergeMethod = Translations::MERGE_ADD | Translations::MERGE_PLURAL;
if ($other->sourceStrings !== null) {
if ($this->sourceStrings === null) {
$this->sourceStrings = $other->sourceStrings;
} else {
$this->sourceStrings->mergeWith($other->sourceStrings, $mergeMethod);
}
}
foreach ($other->translations as $key => $data) {
if (isset($this->translations[$key])) {
$this->translations[$key][1]->mergeWith($data[1], $mergeMethod);
} else {
$this->translations[$key] = $data;
}
}
} | Merge another instance into this one.
@param Parsed $other | entailment |
protected function cast($value, $castTo)
{
if (\DateTime::class == $castTo) {
if (null === $value) {
return null;
} elseif (is_numeric($value)) {
$value = \DateTime::createFromFormat('U', $value);
} elseif (is_array($value)) {
if (isset($value['tz'])) {
$value = \DateTime::createFromFormat('Y-m-d\TH:i:s', $value['time'], new \DateTimeZone($value['tz']));
} else {
// bc
$value = \DateTime::createFromFormat('U', $value['unix']);
}
} else {
$value = new \DateTime($value);
}
} else if (\DateInterval::class == $castTo) {
if (null === $value) {
return null;
} elseif (is_array($value)) {
$value = new \DateInterval($value['interval']);
} else {
$value = new \DateInterval($value);
}
} else if (\DateTimeZone::class == $castTo) {
if (null === $value) {
return null;
} else {
$value = new \DateTimeZone($value['tz']);
}
} else {
settype($value, $castTo);
}
return $value;
} | @param mixed $value
@param string $castTo
@return mixed | entailment |
protected function castValue($value)
{
if ($value instanceof \DateTime) {
$value = [
'unix' => (int) $value->format('U'),
'time' => (string) $value->format('Y-m-d\TH:i:s'),
'tz' => $value->getTimezone()->getName(),
];
} elseif ($value instanceof \DateInterval) {
$value = [
'interval' => $value->format('P%yY%mM%dDT%HH%IM%SS'),
'days' => $value->days,
'y' => $value->y,
'm' => $value->m,
'd' => $value->d,
'h' => $value->h,
'i' => $value->i,
's' => $value->s,
];
} elseif ($value instanceof \DateTimeZone) {
$value = [
'tz' => $value->getName(),
];
}
return $value;
} | @param mixed $value
@return mixed | entailment |
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient)
{
$notificationData = $notification->getNotificationData();
$pr = $this->app->make(PackageRepository::class);
$qb = $pr->createQueryBuilder('p');
$or = $qb->expr()->orX();
foreach ($notificationData['packageIDs'] as $packageID) {
$or->add('p.id = ' . (int) $packageID);
}
$packages = [];
if ($or->count() > 0) {
foreach ($qb->where($or)->getQuery()->iterate() as $packageRow) {
$package = $packageRow[0];
$packageURL = $this->getBlockPageURL('CommunityTranslation Search Packages', 'package/' . $package->getHandle());
$packages[] = [
'url' => $packageURL,
'name' => $package->getDisplayName(),
];
$qb->getEntityManager()->detach($package);
}
}
if (count($packages) === 0) {
throw new Exception(t('Unable to find any package'));
}
return [
'packages' => $packages,
] + $this->getCommonMailParameters($notification, $recipient);
} | {@inheritdoc}
@see Category::getMailParameters() | entailment |
public function run(Factory $factory, Generator $faker)
{
$factory->define(\App\Http\Node\Model\CategoryExampleModel::class, function () use ($faker) {
return [
'url' => $faker->domainWord,
'title' => $faker->text($maxNbChars = 20),
'description' => $faker->text($maxNbChars = 50),
'name' => $faker->jobTitle
];
});
factory(\App\Http\Node\Model\CategoryExampleModel::class, 10)->create();
} | Run the database seeds.
@return void | entailment |
public function generate()
{
$pickChars = str_repeat(static::DICTIONARY, static::LENGTH);
for (; ;) {
$value = substr(str_shuffle($pickChars), 0, static::LENGTH);
if (preg_match(static::TOKEN_GENERATION_REGEX, $value)) {
$this->insertQuery->execute([$value]);
if ($this->insertQuery->rowCount() === 1) {
break;
}
}
}
return $value;
} | Generate a new API token.
@return string | entailment |
public function isGenerated($token)
{
$result = false;
$token = (string) $token;
if ($token !== '') {
$this->searchQuery->execute([$token]);
$row = $this->searchQuery->fetch();
$this->searchQuery->closeCursor();
if ($row !== false) {
$result = true;
}
}
return $result;
} | Check if a token has been generated.
@param string $token
@return bool | entailment |
public function setIsCurrent($value)
{
if ($value) {
$this->current = true;
} else {
$this->current = null;
}
return $this;
} | Is this the current translation?
@param bool $value
@return static | entailment |
public function setIsApproved($value)
{
if ($value === null || $value === '') {
$this->approved = null;
} else {
$this->approved = (bool) $value;
}
return $this;
} | Is the translation approved? (true: yes, false: no, null: pending review).
@param bool|null $value
@return static | 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.