/** * Get name format based on locale, if locale is not passed locale from system configuration will be used. * * @param string|null $locale * @throws \RuntimeException */ public function getNameFormat($locale = null) { if (!$locale) { $locale = $this->localeSettings->getLocale(); } $nameFormats = $this->localeSettings->getNameFormats(); // match by locale (for example - "fr_CA") if (isset($nameFormats[$locale])) { return $nameFormats[$locale]; } // match by locale language (for example - "fr") $localeParts = \Locale::parseLocale($locale); if (isset($localeParts[\Locale::LANG_TAG])) { $match = $localeParts[\Locale::LANG_TAG]; if (isset($match, $nameFormats[$match])) { return $nameFormats[$match]; } } // match by default locale in system configuration settings $match = $this->localeSettings->getLocale(); if ($match !== $locale && isset($nameFormats[$match])) { return $nameFormats[$match]; } // fallback to default constant locale $match = LocaleConfiguration::DEFAULT_LOCALE; if (isset($nameFormats[$match])) { return $nameFormats[$match]; } throw new \RuntimeException(sprintf('Cannot get name format for "%s"', $locale)); }
/** * @param array $tokens * * @throws \LogicException * @return mixed */ public function parse($tokens) { $this->validate($tokens); $RPNTokens = $this->convertExprToRPN($tokens); $stack = []; foreach ($RPNTokens as $token) { if ($token instanceof Token && $token->is(Token::TYPE_OPERATOR)) { $a = array_shift($stack); $b = array_shift($stack); $method = $token->getValue() === '-' ? 'subtract' : 'add'; $result = $a->{$method}($b); array_push($stack, $result); } else { $stack[] = new ExpressionResult($token, $this->localeSettings->getTimeZone()); } } /** @var ExpressionResult $result */ $result = array_pop($stack); if (count($stack) > 0) { foreach ($stack as $stackedResult) { $result->merge($stackedResult); } } return $result === null ? $result : $result->getValue(); }
/** * @param User $user * @param Period $period * @return Timesheet */ private function timesheet(User $user, Period $period) { $worklogs = $this->workLogRepository->listAllByUserAndPeriod($user, $period); $taskList = new TaskList($period, $worklogs, new \DateTimeZone($this->localeSettings->getTimeZone())); $timeSheet = new Timesheet($user, $taskList); return $timeSheet; }
protected function setUp() { MockAnnotations::init($this); $this->localeSettings->expects($this->any())->method('getTimeZone')->will($this->returnValue('UTC')); $this->periodFactory = new PeriodFactory($this->localeSettings); $this->service = new TimeSheetServiceImpl($this->worklogRepository, $this->periodFactory, $this->localeSettings); }
public function testSetOrderCurrency() { $currency = 'USD'; $this->localeSettings->expects($this->once())->method('getCurrency')->willReturn($currency); $order = new Order(); $this->handler->setOrderCurrency($order); $this->assertEquals($currency, $order->getCurrency()); }
/** * @param Period $period * @return CalendarPeriod */ public function createCalendarPeriod(Period $period) { $begin = $period->getBegin(); $end = $period->getEnd(); $begin->setTimezone(new \DateTimeZone($this->localeSettings->getTimeZone())); $end->setTimezone(new \DateTimeZone($this->localeSettings->getTimeZone())); return new CalendarPeriod($begin, $end); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', 'text', ['label' => 'orob2b.rfp.requeststatus.name.label', 'required' => true])->add('sortOrder', 'integer', ['label' => 'orob2b.rfp.requeststatus.sort_order.label', 'required' => true]); $lang = $this->localeSettings->getLanguage(); $notificationLangs = $this->userConfig->get('oro_locale.languages'); $notificationLangs = array_unique(array_merge($notificationLangs, [$lang])); $localeLabels = $this->localeSettings->getLocalesByCodes($notificationLangs, $lang); $builder->add('translations', 'orob2b_rfp_request_status_translation', ['label' => 'orob2b.rfp.requeststatus.label.label', 'required' => false, 'locales' => $notificationLangs, 'labels' => $localeLabels]); }
/** * Get address formats converted to simplified structure. * * @param LocaleSettings $localeSettings * @return array */ protected function getAddressFormats(LocaleSettings $localeSettings) { $result = array(); $formats = $localeSettings->getAddressFormats(); foreach ($formats as $country => $formatData) { $result[$country] = $formatData[LocaleSettings::ADDRESS_FORMAT_KEY]; } return $result; }
/** * @param Request $request */ public function setRequest(Request $request = null) { if (!$request) { return; } if (!$request->attributes->get('_locale')) { $request->setLocale($this->localeSettings->getLanguage()); } $this->setPhpDefaultLocale($this->localeSettings->getLocale()); }
/** * {@inheritdoc} */ public function initialize(array $options) { if (empty($options['date'])) { // as a default value should be used local timezone date $localDate = new \DateTime(null, new \DateTimeZone($this->localeSettings->getTimeZone())); $options['date'] = $localDate->format('Y-m-d'); } elseif (!is_string($options['date'])) { throw new InvalidParameterException(sprintf('Option "date" must be a string, %s given.', $this->getClassOrType($options['date']))); } return parent::initialize($options); }
/** * @param \DateTime|null $date * @return array */ public function getTimezoneOffset(\DateTime $date = null) { $timezone = $this->localeSettings->getTimeZone(); $timezoneObj = new \DateTimeZone($timezone); if ($date === null) { $date = new \DateTime('now', $timezoneObj); } else { $date->setTimezone($timezoneObj); } $timezoneOffset = $timezoneObj->getOffset($date) / 60; return $timezoneOffset; }
/** * Get the absolute filepath for JS translations. * If the file doesn't exist, it creates it. * * @return string */ public function getTranslationsFile() { $localeCode = $this->localeSettings->getLanguage(); $translationFilePath = sprintf('%s/js/translation/%s.js', $this->asseticRoot, $localeCode); $translationFilePath = realpath($translationFilePath); if (!file_exists($translationFilePath)) { $result = $this->commandLauncher->executeForeground(sprintf('oro:translation:dump %s', $localeCode)); if ($result->getCommandStatus() > 0) { throw new \RuntimeException(sprintf('Error during translations file generation for locale "%s"', $localeCode)); } } return $translationFilePath; }
/** * @param integer $weeksDiff * * @return \DateTime[] */ public function getLastWeekPeriod($weeksDiff = 0) { $end = new \DateTime('last Saturday', new \DateTimeZone($this->localeSettings->getTimeZone())); $start = clone $end; $start->modify('-7 days'); $end->setTime(23, 59, 59); if ($weeksDiff) { $days = $weeksDiff * 7; $start->modify("{$days} days"); $end->modify("{$days} days"); } return ['start' => $start, 'end' => $end]; }
/** * Gets instance of intl date formatter by parameters * * @param string|int|null $dateType * @param string|int|null $timeType * @param string|null $locale * @param string|null $timeZone * @param string|null $pattern * @return \IntlDateFormatter */ protected function getFormatter($dateType, $timeType, $locale, $timeZone, $pattern) { if (!$pattern) { $pattern = $this->getPattern($dateType, $timeType, $locale); } return new \IntlDateFormatter($this->localeSettings->getLanguage(), null, null, $timeZone, \IntlDateFormatter::GREGORIAN, $pattern); }
/** * @dataProvider submitDataProvider * * @param array $allowedCurrencies * @param string $localeCurrency * @param array $inputOptions * @param array $expectedOptions * @param string $submittedData */ public function testSubmit(array $allowedCurrencies, $localeCurrency, array $inputOptions, array $expectedOptions, $submittedData) { $hasCustomCurrencies = isset($inputOptions['currencies_list']) || !empty($inputOptions['full_currency_list']); $this->configManager->expects($hasCustomCurrencies ? $this->never() : $this->once())->method('get')->with('oro_currency.allowed_currencies')->willReturn($allowedCurrencies); $this->localeSettings->expects(count($allowedCurrencies) ? $this->never() : $this->once())->method('getCurrency')->willReturn($localeCurrency); $form = $this->factory->create($this->formType, null, $inputOptions); $formConfig = $form->getConfig(); foreach ($expectedOptions as $key => $value) { $this->assertTrue($formConfig->hasOption($key)); $this->assertEquals($value, $formConfig->getOption($key)); } $this->assertNull($form->getData()); $form->submit($submittedData); $this->assertTrue($form->isValid()); $this->assertEquals($submittedData, $form->getData()); }
public function testGetLocaleByCode() { $locales = $this->localeSettings->getLocalesByCodes(['en', 'fr']); $this->assertCount(2, $locales); $this->configManager->expects($this->once())->method('get')->with('test'); $this->localeSettings->get('test'); }
/** * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ protected function setUp() { $this->formatter = $this->getMockBuilder('Oro\\Bundle\\LocaleBundle\\Formatter\\DateTimeFormatter')->disableOriginalConstructor()->setMethods(array('getPattern'))->getMock(); $this->formatter->expects($this->any())->method('getPattern')->will($this->returnValueMap($this->localFormatMap)); $this->translator = $this->getMockBuilder('Symfony\\Bundle\\FrameworkBundle\\Translation\\Translator')->disableOriginalConstructor()->getMock(); $this->translator->method('trans')->will($this->returnCallback(function ($one, $two, $tree, $locale) { if ($locale == self::LOCALE_EN) { return 'MMM d'; } if ($locale == self::LOCALE_RU) { return 'd.MMM'; } return ''; })); $this->converter = $this->createFormatConverter(); }
/** * Get address format based on locale or region, if argument is not passed locale from * system configuration will be used. * * @param string|null $localeOrRegion * @throws \RuntimeException */ public function getAddressFormat($localeOrRegion = null) { if (!$localeOrRegion) { $localeOrRegion = $this->localeSettings->getLocale(); } $addressFormats = $this->localeSettings->getAddressFormats(); // matched by country (for example - "RU") if (isset($addressFormats[$localeOrRegion][LocaleSettings::ADDRESS_FORMAT_KEY])) { return $addressFormats[$localeOrRegion][LocaleSettings::ADDRESS_FORMAT_KEY]; } // matched by locale region - "CA" $localeParts = \Locale::parseLocale($localeOrRegion); if (isset($localeParts[\Locale::REGION_TAG])) { $match = $localeParts[\Locale::REGION_TAG]; if (isset($match, $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) { return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY]; } } // match by default country in system configuration settings $match = $this->localeSettings->getCountry(); if ($match !== $localeOrRegion && isset($addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) { return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY]; } // fallback to default country $match = LocaleConfiguration::DEFAULT_COUNTRY; if (isset($addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) { return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY]; } throw new \RuntimeException(sprintf('Cannot get address format for "%s"', $localeOrRegion)); }
/** * @param BuildAfter $event */ public function onBuildAfter(BuildAfter $event) { $datagrid = $event->getDatagrid(); $datasource = $datagrid->getDatasource(); if ($datasource instanceof OrmDatasource) { $parameters = $datagrid->getParameters(); $entityClass = $this->entityRoutingHelper->decodeClassName($parameters->get('entityClass')); $entityId = $parameters->get('entityId'); $qb = $datasource->getQueryBuilder(); // apply activity filter $this->activityManager->addFilterByTargetEntity($qb, $entityClass, $entityId); // apply filter by date $start = new \DateTime('now', new \DateTimeZone($this->localeSettings->getTimeZone())); $start->setTime(0, 0, 0); $qb->andWhere('event.start >= :date OR event.end >= :date')->setParameter('date', $start); } }
/** * Get current timezone offset * * @return string */ private function getTimeZoneOffset() { if (null === $this->offset) { $time = new \DateTime('now', new \DateTimeZone($this->localeSettings->getTimeZone())); $this->offset = $time->format('P'); } return $this->offset; }
/** * Gets translated locale name by its code * * @param string|null $locale The locale code. NULL means default locale * * @return string */ protected function getLocaleName($locale) { $currentLang = $this->localeSettings->getLanguage(); if (empty($locale)) { $locale = $currentLang; } $localeNames = $this->localeSettings->getLocalesByCodes([$locale], $currentLang); return $localeNames[$locale]; }
/** * @dataProvider testDenormalizeProvider * * @param \DateTime $expected * @param string $data * @param string $locale * @param string $timezone * @param array $context */ public function testDenormalize($expected, $data, $locale, $timezone, $context) { if ($locale !== null) { $this->localeSettings->expects($this->any())->method('getLocale')->willReturn($locale); } if ($timezone !== null) { $this->localeSettings->expects($this->any())->method('getTimezone')->willReturn($timezone); } $this->assertEquals($expected, $this->normalizer->denormalize($data, 'DateTime', null, $context)); }
/** * @param ConsoleCommandEvent $event */ public function onConsoleCommand(ConsoleCommandEvent $event) { $isForced = $event->getInput()->hasParameterOption('--force'); if ($isForced) { $this->isInstalled = false; return; } if ($this->isInstalled) { try { $locale = $this->localeSettings->getLocale(); $language = $this->localeSettings->getLanguage(); } catch (DBALException $exception) { // application is not installed return; } $this->setPhpDefaultLocale($locale); $this->translatableListener->setTranslatableLocale($language); } }
public function testGetCurrencySymbolByCurrency() { $existingCurrencyCode = 'USD'; $existingCurrencySymbol = '$'; $notExistingCurrencyCode = 'UAK'; $currencyData = [$existingCurrencyCode => ['symbol' => $existingCurrencySymbol]]; $this->localeSettings->addCurrencyData($currencyData); $this->assertEquals($existingCurrencySymbol, $this->localeSettings->getCurrencySymbolByCurrency($existingCurrencyCode)); $this->assertEquals($notExistingCurrencyCode, $this->localeSettings->getCurrencySymbolByCurrency($notExistingCurrencyCode)); }
/** * @dataProvider getAddressFormatDataProvider * * @param array $addressFormats * @param string $localeOrRegion * @param string $expectedFormat * @param string $defaultCountry */ public function testGetAddressFormat(array $addressFormats, $localeOrRegion, $expectedFormat, $defaultCountry = null) { $this->localeSettings->expects($this->once())->method('getAddressFormats')->will($this->returnValue($addressFormats)); if (!$localeOrRegion) { $this->localeSettings->expects($this->once())->method('getLocale')->will($this->returnValue('en_US')); } if ($defaultCountry) { $this->localeSettings->expects($this->once())->method('getCountry')->will($this->returnValue($defaultCountry)); } $this->assertEquals($expectedFormat, $this->addressFormatter->getAddressFormat($localeOrRegion)); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', 'text', array('label' => 'oro.email.emailtemplate.name.label', 'required' => true)); $builder->add('type', 'choice', array('label' => 'oro.email.emailtemplate.type.label', 'multiple' => false, 'expanded' => true, 'choices' => array('html' => 'oro.email.datagrid.emailtemplate.filter.type.html', 'txt' => 'oro.email.datagrid.emailtemplate.filter.type.txt'), 'required' => true)); $builder->add('entityName', 'oro_entity_choice', array('label' => 'oro.email.emailtemplate.entity_name.label', 'tooltip' => 'oro.email.emailtemplate.entity_name.tooltip', 'required' => false, 'configs' => ['allowClear' => true])); $lang = $this->localeSettings->getLanguage(); $notificationLangs = $this->userConfig->get('oro_locale.languages'); $notificationLangs = array_merge($notificationLangs, [$lang]); $localeLabels = $this->localeSettings->getLocalesByCodes($notificationLangs, $lang); $builder->add('translations', 'oro_email_emailtemplate_translatation', array('label' => 'oro.email.emailtemplate.translations.label', 'required' => false, 'locales' => $notificationLangs, 'labels' => $localeLabels)); $builder->add('parentTemplate', 'hidden', array('label' => 'oro.email.emailtemplate.parent.label', 'property_path' => 'parent')); // disable some fields for non editable email template $setDisabled = function (&$options) { if (isset($options['auto_initialize'])) { $options['auto_initialize'] = false; } $options['disabled'] = true; }; $factory = $builder->getFormFactory(); $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($factory, $setDisabled) { $data = $event->getData(); if ($data && $data->getId() && $data->getIsSystem()) { $form = $event->getForm(); // entityName field $options = $form->get('entityName')->getConfig()->getOptions(); $setDisabled($options); $form->add($factory->createNamed('entityName', 'oro_entity_choice', null, $options)); // name field $options = $form->get('name')->getConfig()->getOptions(); $setDisabled($options); $form->add($factory->createNamed('name', 'text', null, $options)); if (!$data->getIsEditable()) { // name field $options = $form->get('type')->getConfig()->getOptions(); $setDisabled($options); $form->add($factory->createNamed('type', 'choice', null, $options)); } } }); }
/** * @param array $currencies * @throws LogicException */ protected function checkCurrencies(array $currencies) { $invalidCurrencies = []; foreach ($currencies as $currency) { $name = Intl::getCurrencyBundle()->getCurrencyName($currency, $this->localeSettings->getLocale()); if (!$name) { $invalidCurrencies[] = $currency; } } if ($invalidCurrencies) { throw new LogicException(sprintf('Found unknown currencies: %s.', implode(', ', $invalidCurrencies))); } }
/** * Prepare locale system settings default values. * * @param array $config * @param ContainerBuilder $container */ protected function prepareSettings(array $config, ContainerBuilder $container) { $locale = LocaleSettings::getValidLocale($this->getFinalizedParameter($config['settings']['locale']['value'], $container)); $config['settings']['locale']['value'] = $locale; if (empty($config['settings']['language']['value'])) { $config['settings']['language']['value'] = $locale; } if (empty($config['settings']['country']['value'])) { $config['settings']['country']['value'] = LocaleSettings::getCountryByLocale($locale); } $country = $config['settings']['country']['value']; if (empty($config['settings']['currency']['value']) && isset($config['locale_data'][$country]['currency_code'])) { $config['settings']['currency']['value'] = $config['locale_data'][$country]['currency_code']; } $container->prependExtensionConfig('oro_locale', $config); }
/** * @param string $currency * @param string|null $locale * @return bool|null Null means that there are no currency symbol in string */ public function isCurrencySymbolPrepend($currency, $locale = null) { if (!$locale) { $locale = $this->localeSettings->getLocale(); } if (empty($this->currencySymbolPrepend[$locale]) || !array_key_exists($currency, $this->currencySymbolPrepend)) { $formatter = $this->getFormatter($locale, \NumberFormatter::CURRENCY); $pattern = $formatter->formatCurrency('123', $currency); preg_match('/^([^\\s\\xc2\\xa0]*)[\\s\\xc2\\xa0]*123(?:[,.]0+)?[\\s\\xc2\\xa0]*([^\\s\\xc2\\xa0]*)$/u', $pattern, $matches); if (!empty($matches[1])) { $this->currencySymbolPrepend[$locale][$currency] = true; } elseif (!empty($matches[2])) { $this->currencySymbolPrepend[$locale][$currency] = false; } else { $this->currencySymbolPrepend[$locale][$currency] = null; } } return $this->currencySymbolPrepend[$locale][$currency]; }
/** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $currencyCode = $this->localeSettings->getCurrency(); $currencySymbol = $this->localeSettings->getCurrencySymbolByCurrency($currencyCode); $resolver->setDefaults(array('currency' => $currencyCode, 'currency_symbol' => $currencySymbol, 'grouping' => (bool) $this->numberFormatter->getAttribute(\NumberFormatter::GROUPING_USED), 'constraints' => array(new LessThan(array('value' => pow(10, 15)))))); }