sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function processLocale(LocaleEntity $locale) { $result = 0; $this->logger->info(sprintf('Processing %s (%s)', $locale->getName(), $locale->getID())); $aspiringGroup = $this->groupsHelper->getAspiringTranslators($locale); $aspiringGroupMemberIDs = $aspiringGroup->getGroupMembe...
@param LocaleEntity $locale @return int The number of accepted join requests
entailment
private function processAspiring(LocaleEntity $locale, CoreGroup $aspiringGroup, $memberID) { $result = false; if ($this->dateLimit === null) { $dateLimitReached = true; } else { $enteredOnString = $aspiringGroup->getGroupDateTimeEntered($memberID); if ($e...
@param LocaleEntity $locale @param CoreGroup $aspiringGroup @param int $memberID @return bool Returns true if the user has been promoted to the translators group
entailment
private function predict(array $image, $modelType, $language = null) { $data['inputs'] = [ [ 'data' => [ 'image' => $image, ], ], ]; if ($language) { $data['model'] = [ 'output_info' => [...
The actual predict call @param array $image @param $modelType @param string|null $language Language to return results in @return array
entailment
public function predictUrl($url, $modelType, $language = null) { return $this->predict(['url' => $url], $modelType, $language); }
Predict by url @param string $url Url of image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function predictPath($path, $modelType, $language = null) { if (!file_exists($path)) { throw new FileNotFoundException($path); } return $this->predict( [ 'base64' => base64_encode(file_get_contents($path)), ], $modelType...
Predict by image path @param string $path Path to image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function predictEncoded($hash, $modelType, $language = null) { return $this->predict( [ 'base64' => $hash, ], $modelType, $language ); }
Predict base64 encoded image @param string $hash base64 encoded image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function train(string $id) { $modelResult = $this->getRequest()->request( 'POST', $this->getRequestUrl(sprintf('models/%s/versions', $id)) ); return $this->getModelFromResult($modelResult); }
Train the model @param string $id @return Model
entailment
public function create(Model $model) { $data['model'] = $this->createModelData($model); $modelResult = $this->getRequest()->request( 'POST', $this->getRequestUrl('models'), $data ); return $this->getModelFromResult($modelResult); }
Create new Model @param Model $model @return Model @throws \Exception
entailment
public function update(Model $model) { $data['models'] = []; $data['models'][] = $this->createModelData($model); $data['action'] = 'merge'; $modelResult = $this->getRequest()->request( 'PATCH', $this->getRequestUrl('models'), $data ); ...
Update the model @param Model $model @return Model[]
entailment
public function createModelData(Model $model) { $data = []; if ($model->getId()) { $data['id'] = $model->getId(); } if ($model->getName()) { $data['name'] = $model->getName(); } if ($model->getConcepts()) { $data['output_info']['da...
Create Model data for Request @param Model $model @return array
entailment
public function get() { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl('models') ); return $this->getModelsFromResult($modelResult); }
Gets All Models @return array @throws \Exception
entailment
public function getById($id) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s', $id)) ); return $this->getModelFromResult($modelResult); }
Gets Model By Id @param $id @return Model @throws \Exception
entailment
public function getModelVersions($id) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions', $id)) ); if (!isset($modelResult['model_versions'])) { throw new \Exception('Model Versions Not Found'); ...
Gets Model Versions @param $id @return array @throws \Exception
entailment
public function getModelVersionById($modelId, $versionId) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions/%s', $modelId, $versionId)) ); if (isset($modelResult['model_version'])) { $modelVersion = new...
Gets Model Version By Id @param string $modelId @param string $versionId @return ModelVersion @throws \Exception
entailment
public function updateModelConcepts(array $modelsArray, $action) { $data['models'] = []; foreach ($modelsArray as $modelId => $modelConcepts) { $model = []; $model['id'] = (string)$modelId; $model['output_info'] = []; $model['output_info']['data'] = [...
Common Model's Concepts Update Method @param array $modelsArray @param $action @return array
entailment
public function getModelsFromResult($modelResult) { $modelsArray = []; if (isset($modelResult['models'])) { foreach ($modelResult['models'] as $model) { $model = new Model($model); $modelsArray[] = $model; } } else { throw ...
Parses Request Result and gets Models @param $modelResult @return Model[] @throws \Exception
entailment
public function addModelConcepts(array $data, array $concepts) { $data['concepts'] = []; foreach ($concepts as $concept) { $data['concepts'][] = [ 'id' => $concept->getId(), ]; } return $data; }
Adds Model's Concepts to Model's Data @param array $data @param array $concepts @return array
entailment
public function deleteById(string $modelId) { $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl(sprintf('models/%s', $modelId)) ); return $deleteResult['status']; }
Delete Model By Id @param string $modelId @return array
entailment
public function deleteVersionById(string $modelId, string $versionId) { $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl(sprintf('models/%s/versions/%s', $modelId, $versionId)) ); return $deleteResult['status']; }
Delete Model Version By Id @param string $modelId @param string $versionId @return array
entailment
public function getTrainingInputsById(string $modelId) { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/inputs', $modelId)) ); return $this->getInputsFromResult($inputResult); }
Get Model Training Inputs By Model Id @param string $modelId @return array
entailment
public function getTrainingInputsByVersion(string $modelId, string $versionId) { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions/%s/inputs', $modelId, $versionId)) ); return $this->getInputsFromResult($inputResult)...
Get Model Training Inputs By Model Id @param string $modelId @param string $versionId @return array
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { foreach ($this->headers as $header) { if ($request->hasHeader($header)) { $request = $request->withoutHeader($header); } } return $next($request); }
{@inheritdoc}
entailment
public static function generateTitleFromRoute($path) { $path = str_replace([':', '*', '$'], '', $path); $path = preg_replace('/\<(.*)\>/iU', '', $path); $path = str_replace(' ', '', ucwords(str_replace('/', ' ', $path))); return $path; }
Generates an title "BarFoo" based on an PSX route "/bar/:foo" @param string $path @return string
entailment
public function searchByNameAndType($name = null, $type = null) { $searchResult = $this->getRequest()->request( 'POST', $this->getRequestUrl('models/searches'), [ 'model_query' => [ 'name' => $name, 'type' => $type, ...
Searches Models by It's name and type @param string $name @param string $type @return Model[] array
entailment
public function setString($context, $text, $plural = '') { $this->context = (string) $context; $this->text = (string) $text; $this->plural = (string) $plural; $this->hash = md5($this->plural ? $this->context . "\004" . $this->text . "\005" . $this->plural : $this->context . "\004" . ...
Set the translatable text. @param string $context The string context @param string $text The string text (singular form) @param string $plural The string text (plural form)
entailment
protected function innerSet($key, $val) { $setMethod = 'set' . ucfirst($key); if ( !in_array($key, $this->notsetters()) && method_exists($this, $setMethod) ) { $this->$setMethod($val); } else { $validateMethod = 'validate' . ucfirst($key); if (method_exi...
This method is reloaded for on-set validation and sanitizing @param string $key @param mixed $val @throws \Runn\Core\Exceptions
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { // Check in storage if (array_key_exists($request->getRequestTarget(), $this->redirectStorage)) { $uri = $this->redirectStorage[$request->getRequestTarget()]['uri']; $statusCode = $thi...
{@inheritdoc}
entailment
protected function buildRedirectRequest(RequestInterface $request, UriInterface $uri, $statusCode) { $request = $request->withUri($uri); if (false !== $this->redirectCodes[$statusCode]['switch'] && !in_array($request->getMethod(), $this->redirectCodes[$statusCode]['switch']['unless'])) { ...
Builds the redirect request. @param RequestInterface $request Original request @param UriInterface $uri New uri @param int $statusCode Status code from the redirect response @return MessageInterface|RequestInterface
entailment
private function createUri(ResponseInterface $response, RequestInterface $request) { if ($this->redirectCodes[$response->getStatusCode()]['multiple'] && (!$this->useDefaultForMultiple || !$response->hasHeader('Location'))) { throw new MultipleRedirectionException('Cannot choose a redirection', $...
Creates a new Uri from the old request and the location header. @param ResponseInterface $response The redirect response @param RequestInterface $request The original request @throws HttpException If location header is not usable (missing or incorrect) @throws MultipleRedirectionException If a 300 st...
entailment
public function invalidateResourceIndex(FilterInterface $filter = null) { $this->cache->deleteItem($this->getResourceIndexKey($filter)); }
Invalidates the cached resource index
entailment
public function invalidateResource($sourcePath, $version = null) { $this->cache->deleteItem($this->getResourceKey($sourcePath, $version)); }
Invalidates a cached resource @param string $sourcePath @param integer|null $version
entailment
public function invalidateResourceCollection($version = null, FilterInterface $filter = null) { $this->cache->deleteItem($this->getResourceCollectionKey($version, $filter)); }
Invalidates the cached resource collection @param integer|null $version
entailment
protected function materializeResource(Resource $resource) { foreach ($resource as $method) { $request = $method->getRequest(); if ($request) { $method->setRequest(new Schema($request->getDefinition())); } $responses = $method->getResponses();...
A resource can contain schema definitions which are only resolved if we actual call the getDefinition method i.e. the schema is stored in a database. So before we cache the documentation we must get the actual definition object which we can serialize @param \PSX\Api\Resource $resource
entailment
public function getSynopsis($short = false) { $key = $short ? 'short' : 'long'; if (!isset($this->synopsis[$key])) { $this->synopsis[$key] = trim(sprintf( '%s %s', $_SERVER['PHP_SELF'], $this->getDefinition()->getSynopsis($short) ...
{@inheritdoc} @SuppressWarnings(PHPMD.Superglobals)
entailment
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient) { $notificationData = $notification->getNotificationData(); $pvr = $this->app->make(PackageVersionRepository::class); $qb = $pvr->createQueryBuilder('pv'); $or = $qb->expr()->orX(); forea...
{@inheritdoc} @see Category::getMailParameters()
entailment
public function feed() { $page = TypiCMS::getPageLinkedToModule('news'); if (!$page) { return; } $feed = app('feed'); if (config('typicms.cache')) { $feed->setCache(60, 'typicmsNewsFeed'); } if (!$feed->isCached()) { $models...
Generate Atom feed.
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { $promise = $next($request); return $promise->then(function (ResponseInterface $response) use ($request) { return $this->transformResponseToException($request, $response); }); }
{@inheritdoc}
entailment
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response) { if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) { throw new ClientErrorException($response->getReasonPhrase(), $request, $response); } if ($respon...
Transform response to an error if possible. @param RequestInterface $request Request of the call @param ResponseInterface $response Response of the call @throws ClientErrorException If response status code is a 4xx @throws ServerErrorException If response status code is a 5xx @return ResponseInterface If status co...
entailment
protected function getRecipientIDs(NotificationEntity $notification) { $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->find($notificationData['localeID']); if ($locale === null && $locale->isApproved()) { // The reque...
{@inheritdoc} @see Category::getRecipientIDs()
entailment
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient) { $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->find($notificationData['localeID']); if ($locale === null) { throw new Excepti...
{@inheritdoc} @see Category::getMailParameters()
entailment
public function register() { $this->registerCommands(); $this->app->singleton(AdminInterface::class, function () { return new Admin($this->nodes(), $this->navigation(), $this->app, $this->app->make(Route::class)); }); //$this->app->singleton(ModelRouterInterface::class,...
Register the application services. @return void
entailment
public function parseDirectory($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { if (!$this->filesystem->isDirectory($path)) { throw new UserMessageException(t('Unable to find the directory %s', $path)); } if ('' === (str...
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseDirectory()
entailment
public function parseDictionaryFile($packageHandle, $packageVersion, $path, $kinds) { if (!$this->filesystem->isFile($path)) { throw new UserMessageException(t('Unable to find the file %s', $path)); } $translations = null; if ($kinds & (self::DICTIONARY_SOURCE | self::DIC...
{@inheritdoc} @see \CommunityTranslation\Parser\Parser::parseDictionaryFile()
entailment
public function parseSourceFile($packageHandle, $packageVersion, $path, $relDirectory = '') { if (!$this->filesystem->isFile($path)) { throw new UserMessageException(t('Unable to find the file %s', $path)); } $tmp = $this->app->make(VolatileDirectory::class); $workDir = $...
{@inheritdoc} @see \CommunityTranslation\Parser\Parser::parseSourceFile()
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { foreach ($this->cookieJar->getCookies() as $cookie) { if ($cookie->isExpired()) { continue; } if (!$cookie->matchDomain($request->getUri()->getHost())) { ...
{@inheritdoc}
entailment
private function createCookie(RequestInterface $request, $setCookie) { $parts = array_map('trim', explode(';', $setCookie)); if (empty($parts) || !strpos($parts[0], '=')) { return; } list($name, $cookieValue) = $this->createValueKey(array_shift($parts)); $maxAg...
Creates a cookie from a string. @param RequestInterface $request @param $setCookie @return Cookie|null @throws \Http\Client\Exception\TransferException
entailment
public function parse($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { if (is_object($path) && ($path instanceof DecompressedPackage)) { $result = $this->parseDirectory($packageHandle, $packageVersion, $path->getExtractedWorkDir(), $rel...
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parse()
entailment
public function parseFile($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { $zip = $this->app->make(DecompressedPackage::class, ['packageArchive' => $path, 'volatileDirectory' => null]); try { $zip->extract(); } catch (Us...
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseFile()
entailment
public function parseZip($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { $zip = $this->app->make(DecompressedPackage::class, ['packageArchive' => $path, 'volatileDirectory' => null]); $zip->extract(); $result = $this->parseDirector...
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseZip()
entailment
public function convertTranslationsToString(Translations $translations) { \Gettext\Generators\Mo::$includeEmptyTranslations = true; return $translations->toMoString(); }
{@inheritdoc} @see ConverterInterface::convertTranslationsToString()
entailment
public function mapConfig(array &$scopeSettings, $currentScope, ContextualizerInterface $contextualizer) { // common settings if (isset($scopeSettings['providers'])) { $contextualizer->setContextualParameter('providers', $currentScope, $scopeSettings['providers']); } if (...
{@inheritdoc}
entailment
public function setRawConcepts(array $rawConcepts) { $concepts = []; foreach ($rawConcepts as $rawConcept) { $concept = new Concept($rawConcept); $concepts[] = $concept; } $this->concepts = $concepts; return $this; }
Sets concepts from Raw Data @param array $rawConcepts @return $this
entailment
public function generateRawData() { $rawData = ['id' => $this->getId()]; $rawData['output_info'] = []; $rawData['output_info']['data'] = []; if ($this->getName()) { $rawData['name'] = $this->getName(); } if ($this->getAppId()) { $rawData['app_i...
Generates rawData from Model @return array
entailment
public static function create(Version $packageVersion, Locale $locale) { $result = new static(); $result->packageVersion = $packageVersion; $result->locale = $locale; $result->lastUpdated = null; $result->total = 0; $result->translated = 0; return $result; ...
@param Version $packageVersion @param Locale $locale @return static
entailment
public function getPercentage($round = true) { if ($this->translated === 0 || $this->total === 0) { $result = $round ? 0 : 0.0; } elseif ($this->translated === $this->total) { $result = $round ? 100 : 100.0; } else { $result = $this->translated * 100.0 / $...
Get the translation percentage. @param bool $round Set to true to get a rounded value (0 if no translations at all, 100 if all strings are translated, 1...99 otherwise), @return int|float
entailment
private function getCurrentUserID($required) { $result = null; if (User::isLoggedIn()) { $u = new User(); if ($u->isRegistered()) { $uID = (int) $u->getUserID(); if ($uID !== 0) { $result = $uID; } ...
@param bool $required @return int|null
entailment
private function getCurrentUser($required) { $result = null; $id = $this->getCurrentUserID($required); if ($id !== null) { $result = $this->getEntityManager()->find(UserEntity::class, $id); } if ($result === null && $required) { throw new UserMessageE...
@param bool $required @return UserEntity|null
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { if (!$request->hasHeader('Content-Length')) { $stream = $request->getBody(); // Cannot determine the size so we use a chunk stream if (null === $stream->getSize()) { ...
{@inheritdoc}
entailment
public static function getTypesInfo() { $locale = Localization::activeLocale(); if (!isset(self::$typesInfo[$locale])) { $list = [ self::ADJECTIVE => [ 'name' => tc('TermType', 'Adjective'), 'short' => tc('TermType_short', 'adj.'), ...
Get all the allowed type names, short names and descriptions. @return array
entailment
public static function isValidType($type) { if ($type === '') { $result = true; } else { $valid = self::getTypesInfo(); $result = isset($valid[$type]); } return $result; }
Check if a term type is valid. @param string $type @return bool
entailment
protected function configure() { $this ->setName(self::COMMAND_NAME) ->setDescription('lint an xml file') ->addArgument( self::ARGUMENT_FILE, InputArgument::REQUIRED, 'the path/to/file.xml to lint a single file or a path/to/...
{@inheritdoc}
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $this->start = microtime(true); $this->output = $output; $this->input = $input; if ($input->getOption(self::OPTION_NO_XSD)) { $this->validator = ValidationFactory::createLintOnlyValidation(); ...
{@inheritdoc}
entailment
private function lintDir($dir) { $finder = Finder::create(); $finder->files() ->in($dir); $patterns = $this->input->getOption(self::OPTION_PATTERN); if (!empty($patterns)) { $patterns = explode(',', $patterns); foreach ($patterns as $pattern) { ...
lint the content of a directory, recursive if defined. @param string $dir path/to/dir @return bool
entailment
private function printReportsOfFilesWithProblems() { $this->output->writeln(PHP_EOL . '<error>errors:</error>'); foreach ($this->reports as $report) { if (false === $report->hasProblems()) { continue; } $file = $report->getFile(); $th...
format and print the errors from the queue to the output.
entailment
private function lintFile(\SplFileInfo $file) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->write('lint file ' . $file . ' ... '); } $report = FileReport::create($file); $this->reports[] = $report; $status = $this->va...
lint a file, pass errors to the queue. @param \SplFileInfo $file @return bool
entailment
public function setTypeField(array $arrTypeField) { foreach ($arrTypeField as $nameField => $item) { if (is_array($item)) { //проверяем подключена ли к полю другая таблица if (!empty($item[3]) and $item[2] === 'multiple') { $this->setOtherTabl...
@param array $arrTypeField todo выбор поля который будет отображатся в форме например input select file с настройками
entailment
public function getIdentify($email, $name = '', $properties = []) { if (!$email) { throw new InvalidArgumentException('E-mail cannot be empty or null'); } //props that we will combine with default props $props = [ PayloadProperties::EMAIL => Encryption::decod...
Generates payload for identify events @param $email @param string $name @param array $properties @return array @throws InvalidArgumentException
entailment
public function getPageView($url, $properties = []) { if (empty($url)) { throw new Exception('url cannot be empty'); } $props = [ PayloadProperties::URL => $url ]; if ($properties) { $props[PayloadProperties::PROPERTIES] = $properties; ...
Generates payload for page view events @param $url @param array $properties @return array @throws Exception
entailment
public function getAddToOrder(Models\Product $product) { return $this->getTrackPayload(ActionTypes::ADDED_TO_ORDER, [ PayloadProperties::PROPERTIES => [ [ PayloadProperties::PRODUCT => $product->toArray() ] ...
Generates payload for add to order events @param Models\Product $product @return array
entailment
public function getOrderCompleted(Models\Order $order) { if (!$order->hasProducts()) { throw new \Exception('$order should have at least one product'); } return $this->getTrackPayload(ActionTypes::ORDER_COMPLETED, [ PayloadProperties::PROPERTIES => [ ...
Generates payload for order completed events @param Models\Order $order @throws Exception @return array
entailment
public function getCustom($event, $properties = []) { $properties = empty($properties) ? [] : [PayloadProperties::PROPERTIES => $properties]; return $this->getTrackPayload($event, $properties); }
Generates payload for custom events @param $event @param array $properties @return array
entailment
public static function create(Entry $entry, Locale $locale) { $result = new static(); $result->entry = $entry; $result->locale = $locale; $result->comments = ''; return $result; }
@param Entry $entry @param Locale $locale @param string $text @param string $comments @return static
entailment
private function getTransifexAccount(InputInterface $input, OutputInterface $output) { $this->transifexUsername = trim((string) $input->getOption('username')); if ($this->transifexUsername === '') { if (!$input->isInteractive()) { throw new Exception('Please specify the T...
@param InputInterface $input @param OutputInterface $output @throws Exception
entailment
private function fetchTransifexLocales($transifexProject) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/languages/") ->setMethod('GET') ->send() ; if ($response->getStat...
@param string $transifexProject @throws Exception @return string[]
entailment
private function fetchTransifexResources($transifexProject) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/resources/") ->setMethod('GET') ->send() ; if ($response->getSt...
@param string $transifexProject @throws Exception @return string[]
entailment
private function fetchTransifexTranslations($transifexProject, $transifexResource, $transifexLocale) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/resource/$transifexResource/translation/$transifexLocale/") ...
@param string $transifexProject @param string $transifexResource @param string $transifexLocale @throws Exception @return string
entailment
private function parseTranslations($translationsData) { $translations = Translations::fromPoString($translationsData); if (count($translations) < 1) { throw new Exception('No translations downloaded'); } return $translations; }
@param string $translationsData @throws Exception @return Translations
entailment
private function translationsNeedsPluralFix(Translations $translations, LocaleEntity $locale, &$translationsPluralCount) { $txPlurals = $translations->getPluralForms(); $translationsPluralCount = isset($txPlurals) ? $txPlurals[0] : null; return $translationsPluralCount !== $locale->getPlura...
@param Translations $translations @param LocaleEntity $locale @return bool
entailment
public function generateRawData() { $rawData = ['id' => $this->getId()]; if ($this->getValue()) { $rawData['value'] = $this->getValue(); } if ($this->getName()) { $rawData['name'] = $this->getName(); } if ($this->getAppId()) { $rawD...
Generates rawData from Concept @return array
entailment
public static function create(Locale $locale, $numTranslatable, $numApprovedTranslations) { $result = new static(); $result->locale = $locale; $result->numTranslatable = (int) $numTranslatable; $result->numApprovedTranslations = (int) $numApprovedTranslations; return $result...
Create a new (unsaved) instance. @param Locale $locale @param int $numTranslatable @param int $numApprovedTranslations @return static
entailment
public function getPercentage($round = true) { if ($this->numApprovedTranslations === 0 || $this->numTranslatable === 0) { $result = $round ? 0 : 0.0; } elseif ($this->numApprovedTranslations === $this->numTranslatable) { $result = $round ? 100 : 100.0; } else { ...
Get the translation progress. @param bool $round @return int|float
entailment
private function getPackageHandlesToTry(RemotePackageRepository $repo, DateTime $dateLimit) { $qb = $repo->createQueryBuilder('rp'); $expr = $qb->expr(); $qb ->distinct() ->select('rp.handle') ->where($expr->isNull('rp.processedOn')) ->andWhere...
@param RemotePackageRepository $repo @param DateTime $dateLimit @return string[]|\Generator
entailment
private function processRemotePackage(Connection $connection, RemotePackageRepository $repo, RemotePackageImporter $importer, RemotePackageEntity $remotePackage, $recordFailures) { $this->logger->debug(sprintf('Processing package %s v%s', $remotePackage->getHandle(), $remotePackage->getVersion())); ...
@param Connection $connection @param RemotePackageRepository $repo @param RemotePackageImporter $importer @param RemotePackageEntity $remotePackage @param bool $recordFailures @throws Exception @throws Throwable
entailment
private function tryProcessRemotePackage(Connection $connection, RemotePackageRepository $repo, RemotePackageImporter $importer, $remotePackageHandle) { $result = false; $this->logger->debug(sprintf('Trying unapproved package with handle %s', $remotePackageHandle)); $remotePackage = $repo->f...
@param Connection $connection @param RemotePackageRepository $repo @param RemotePackageImporter $importer @param string $remotePackageHandle @return bool
entailment
protected function registerRegistry() { $this->app['registry'] = $this->app->share(function($app) { $config = $app->config->get('registry', array()); return new Registry($app['db'], $app['registry.cache'], $config); }); }
Register the collection repository. @return void
entailment
public function import(Translations $translations, LocaleEntity $locale, UserEntity $user, ImportOptions $options = null) { if ($options === null) { $options = ImportOptions::forTranslators(); } $allFuzzy = $options->getAllFuzzy(); $unapproveFuzzy = $options->getUnapprove...
Import translations into the database. This function works directly with the database, not with entities (so that working on thousands of strings requires seconds instead of minutes). This implies that entities related to translations may become invalid. @param Translations $translations The translations to be import...
entailment
private function buildInsertTranslationsSQL(Connection $connection, LocaleEntity $locale, $numRecords, UserEntity $user) { $fields = '(locale, createdOn, createdBy, current, currentSince, approved, translatable, text0, text1, text2, text3, text4, text5)'; $values = ' (' . implode(', ', [ ...
@param Connection $connection @param int $numRecords @param UserEntity $user @return string
entailment
private function rowSameAsTranslation(array $row, GettextTranslation $translation, $isPlural, $pluralCount) { if ($row['text0'] !== $translation->getTranslation()) { return false; } if ($isPlural === false) { return true; } $same = true; switch...
Is a database row the same as the translation? @param array $row @param GettextTranslation $translation @param bool $isPlural @param int $pluralCount @return bool
entailment
private function checkXSS(GettextTranslation $translation) { $sourceText = $translation->getOriginal(); $translatedText = $translation->getTranslation(); if ($translation->hasPlural()) { $sourceText .= "\n" . $translation->getPlural(); $translatedText .= "\n" . implod...
Check that translated text doesn't contain potentially harmful code. @param \Gettext\Translation $translation @throws \Concrete\Core\Error\UserMessageException
entailment
private function checkFormat(GettextTranslation $translation) { // placeholder := %[position][flags][width][.precision]specifier // position := \d+$ // flags := ([\-+ 0]|('.))* // width := \d* // precision := (\.\d*)? // specifier := [bcdeEfFgGosuxX] // $place...
Check that translated text doesn't contain potentially harmful code. @param \Gettext\Translation $translation @throws \Concrete\Core\Error\UserMessageException
entailment
protected function buildErrorResponse($error, $code = null) { if ($code !== null && (!is_int($code) || $code < 400)) { $code = null; } if (is_object($error)) { if ($error instanceof AccessDeniedException) { $error = $error->getMessage(); ...
Build an error response. @param string|Exception|Throwable $error @param int $code @return Response
entailment
protected function getRequestJson() { if ($this->request->getContentType() !== 'json') { throw new UserMessageException(t('Invalid request Content-Type: %s', $this->request->headers->get('Content-Type', '')), Response::HTTP_NOT_ACCEPTABLE); } $contentBody = $this->request->getCon...
Check if the request is a JSON request and returns the posted parameters. @throws UserMessageException @return array
entailment
protected function getPackageVersion(PackageEntity $package, $packageVersion, &$isBastMatch = null) { if ($packageVersion === 'best-match-version') { $isBastMatch = true; $result = null; if ($this->request->query->has('v')) { $v = $this->request->query->ge...
@param PackageEntity $package @param string $packageVersionID @param bool $isBastMatch [out] @param string $packageVersion @return \CommunityTranslation\Entity\Package\Version|null
entailment
protected function finish(Response $response) { if ($this->requestedResultsLocale !== '') { $this->getLocalization()->popActiveContext(); } if (!$response->headers->has('X-Frame-Options')) { $response->headers->set('X-Frame-Options', 'DENY'); } if (!$r...
@param Response $response @return Response
entailment
public function getRateLimit() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $rateLimit = $this->getUserControl()->getRateLimit(); if ($rateLimit === null) { ...
Get the current rate limit status. @return Response @example http://www.example.com/api/rate-limit/
entailment
public function getLocales() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $locales = $this->app->make(LocaleRepository::class)->getApprovedLocales(); $result = $this->buil...
Get the list of approved locales. @return Response @example http://www.example.com/api/locales/
entailment
public function getPackages() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $repo = $this->app->make(PackageRepository::class); $packages = $repo->createQueryBuilder('p') ...
Get the list of packages. @return Response @example http://www.example.com/api/packages/
entailment
public function getPackageVersions($packageHandle) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageH...
Get the list of versions of a package. @param string $packageHandle @return Response @example http://www.example.com/api/package/concrete5/versions/
entailment
public function getPackageVersionLocales($packageHandle, $packageVersion, $minimumLevel = null) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $accessibleLocales = $this->getUserControl()->checkLocaleAccess(__FUNCTION__); $package = $this->app-...
Get some stats about the translations of a package version. @param string $packageHandle @param string $packageVersion @param null|int $minimumLevel @return Response @example http://www.example.com/api/package/concrete5/8.2/locales/80/ @example http://www.example.com/api/package/concrete5/best-match-version/locales...
entailment
public function getPackageVersionTranslations($packageHandle, $packageVersion, $localeID, $formatHandle) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $accessibleLocales = $this->getUserControl()->checkLocaleAccess(__FUNCTION__); $locale = $th...
Get the translations of a package version. @param string $packageHandle @param string $packageVersion @param string $localeID @param string $formatHandle @return Response @example http://www.example.com/api/package/concrete5/8.2/translations/it_IT/mo/ @example http://www.example.com/api/package/concrete5/best-match...
entailment