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($formatHandl... | 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_strin... | 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": "...", // ... | entailment |
public function importPackageVersionTranslatables($packageHandle, $packageVersion, $formatHandle)
{
$this->start();
try {
$this->getUserControl()->checkRateLimit();
$this->getUserControl()->checkGenericAccess(__FUNCTION__);
$em = $this->app->make(EntityManager::cl... | 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 ?... | 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', $unrecogn... | 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 {
$outputPro... | 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 = $r... | 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),
];
... | 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 ... | entailment |
public function getTranslations(LocaleEntity $locale, TranslatableEntity $translatable)
{
$numPlurals = $locale->getPluralCount();
$result = [
'current' => null,
'others' => [],
];
$translations = $this->app->make(TranslationRepository::class)->findBy(['trans... | 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
... | 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
CommunityTranslatio... | 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
CommunityTranslationGlossa... | 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()])... | 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($re... | {@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['requeste... | {@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... | {@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-... | @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->get... | @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->cr... | 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);... | 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[]... | 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(CookieName... | 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(CookieNam... | 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(... | 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');
... | 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();
} el... | 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 AcceptPendingJoinRequestsCo... | 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_trans... | 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])?';
... | 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());
$requ... | {@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);
... | 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() : '';
$... | 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) {
... | 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}")) {
... | 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;
}
... | 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 al... | 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;
... | 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 com... | 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($maxN... | 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)();
... | 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;
... | 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%... | 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();
... | 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 n... | {@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... | {@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->getDisplayNam... | 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) {
... | {@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->getPar... | 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->overw... | 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')
{
... | 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']... | 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->get... | 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="'.$th... | 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 (Exc... | {@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... | @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 = ... | @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... | @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;
... | @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->getSt... | 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) {
$... | 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... | 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']... | 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 Us... | 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');
... | 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->transla... | 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);
$transl... | 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 {
$t... | 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)) {
... | @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 (... | @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 ($notif... | {@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' ... | 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]);
... | 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) {
... | 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 community queries yet
The top public SQL queries from the community will appear here once available.