public function addLineItemAction(Request $request)
 {
     $locale = $this->get('commercetools.locale.converter')->convert($request->getLocale());
     $session = $this->get('session');
     $form = $this->createForm(AddToCartType::class, ['variantIdText' => true]);
     $form->handleRequest($request);
     if ($form->isValid() && $form->isSubmitted()) {
         $productId = $form->get('productId')->getData();
         $variantId = (int) $form->get('variantId')->getData();
         $quantity = (int) $form->get('quantity')->getData();
         $slug = $form->get('slug')->getData();
         $cartId = $session->get(CartRepository::CART_ID);
         $country = \Locale::getRegion($locale);
         $currency = $this->getParameter('commercetools.currency.' . $country);
         /**
          * @var CartRepository $repository
          */
         $repository = $this->get('commercetools.repository.cart');
         $repository->addLineItem($request->getLocale(), $cartId, $productId, $variantId, $quantity, $currency, $country, $this->getCustomerId());
         $redirectUrl = $this->generateUrl('_ctp_example_product', ['slug' => $slug]);
     } else {
         $redirectUrl = $this->generateUrl('_ctp_example');
     }
     return new RedirectResponse($redirectUrl);
 }
예제 #2
0
 /**
  * Get options array for locale dropdown
  *
  * @param   bool $translatedName translation flag
  * @return  array
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function _getOptionLocales($translatedName = false)
 {
     $currentLocale = $this->localeResolver->getLocale();
     $locales = \ResourceBundle::getLocales('') ?: [];
     $languages = (new LanguageBundle())->get($currentLocale)['Languages'];
     $countries = (new RegionBundle())->get($currentLocale)['Countries'];
     $options = [];
     $allowedLocales = $this->_config->getAllowedLocales();
     foreach ($locales as $locale) {
         if (!in_array($locale, $allowedLocales)) {
             continue;
         }
         $language = \Locale::getPrimaryLanguage($locale);
         $country = \Locale::getRegion($locale);
         if (!$languages[$language] || !$countries[$country]) {
             continue;
         }
         if ($translatedName) {
             $label = ucwords(\Locale::getDisplayLanguage($locale, $locale)) . ' (' . \Locale::getDisplayRegion($locale, $locale) . ') / ' . $languages[$language] . ' (' . $countries[$country] . ')';
         } else {
             $label = $languages[$language] . ' (' . $countries[$country] . ')';
         }
         $options[] = ['value' => $locale, 'label' => $label];
     }
     return $this->_sortOptionArray($options);
 }
 public function add(Request $request)
 {
     $session = $this->get('session');
     // TODO: enable if product add form has a csrf token
     //        if (!$this->validateCsrfToken(static::CSRF_TOKEN_FORM, $request->get(static::CSRF_TOKEN_NAME))) {
     //            throw new \InvalidArgumentException('CSRF Token invalid');
     //        }
     $productId = $request->get('productId');
     $variantId = (int) $request->get('variantId');
     $quantity = (int) $request->get('quantity');
     $sku = $request->get('productSku');
     $slug = $request->get('productSlug');
     $cartId = $session->get('cartId');
     $country = \Locale::getRegion($this->locale);
     $currency = $this->config->get('currencies.' . $country);
     $cart = $this->get('app.repository.cart')->addLineItem($cartId, $productId, $variantId, $quantity, $currency, $country);
     $session->set('cartId', $cart->getId());
     $session->set('cartNumItems', $this->getItemCount($cart));
     $session->save();
     if (empty($sku)) {
         $redirectUrl = $this->generateUrl('pdp-master', ['slug' => $slug]);
     } else {
         $redirectUrl = $this->generateUrl('pdp', ['slug' => $slug, 'sku' => $sku]);
     }
     return new RedirectResponse($redirectUrl);
 }
 /**
  * Returns a carrier name for the given phone number, in the language provided. The carrier name
  * is the one the number was originally allocated to, however if the country supports mobile
  * number portability the number might not belong to the returned carrier anymore. If no mapping
  * is found an empty string is returned.
  *
  * <p>This method assumes the validity of the number passed in has already been checked, and that
  * the number is suitable for carrier lookup. We consider mobile and pager numbers possible
  * candidates for carrier lookup.
  *
  * @param PhoneNumber $number a valid phone number for which we want to get a carrier name
  * @param string $languageCode the language code in which the name should be written
  * @return string a carrier name for the given phone number
  */
 public function getNameForValidNumber(PhoneNumber $number, $languageCode)
 {
     $languageStr = \Locale::getPrimaryLanguage($languageCode);
     $scriptStr = "";
     $regionStr = \Locale::getRegion($languageCode);
     return $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr);
 }
 public function geocode($ipAddress)
 {
     $region = \Locale::getRegion($this->getLocale());
     $countryName = \Locale::getDisplayRegion($this->getLocale(), 'en');
     $countryCode = \Locale::getRegion($this->getLocale());
     if ($countryCode == '') {
         throw new NoResult(sprintf('No results found for IP address "%s".', $ipAddress));
     }
     return $this->returnResults([$this->fixEncoding(array_merge($this->getDefaults(), array('country' => $countryName, 'countryCode' => $countryCode)))]);
 }
예제 #6
0
 /**
  * Retrieve list of locales
  *
  * @return  array
  */
 public function getLocaleList()
 {
     $languages = (new LanguageBundle())->get(Resolver::DEFAULT_LOCALE)['Languages'];
     $countries = (new RegionBundle())->get(Resolver::DEFAULT_LOCALE)['Countries'];
     $locales = \ResourceBundle::getLocales('') ?: [];
     $list = [];
     foreach ($locales as $locale) {
         if (!in_array($locale, $this->allowedLocales)) {
             continue;
         }
         $language = \Locale::getPrimaryLanguage($locale);
         $country = \Locale::getRegion($locale);
         if (!$languages[$language] || !$countries[$country]) {
             continue;
         }
         $list[$locale] = $languages[$language] . ' (' . $countries[$country] . ')';
     }
     asort($list);
     return $list;
 }
 /**
  * Validates a Locale
  *
  * @param string     $locale     The locale to be validated
  * @param Constraint $constraint Locale Constraint
  *
  * @throws \Symfony\Component\Validator\Exception\UnexpectedTypeException
  */
 public function validate($locale, Constraint $constraint)
 {
     if (null === $locale || '' === $locale) {
         return;
     }
     if (!is_scalar($locale) && !(is_object($locale) && method_exists($locale, '__toString'))) {
         throw new UnexpectedTypeException($locale, 'string');
     }
     $locale = (string) $locale;
     if ($this->intlExtension) {
         $primary = \Locale::getPrimaryLanguage($locale);
         $region = \Locale::getRegion($locale);
         $locales = Intl::getLocaleBundle()->getLocales();
         if (null !== $region && strtolower($primary) != strtolower($region) && !in_array($locale, $locales) && !in_array($primary, $locales)) {
             $this->context->addViolation($constraint->message, array('%string%' => $locale));
         }
     } else {
         $splittedLocale = explode('_', $locale);
         $splitCount = count($splittedLocale);
         if ($splitCount == 1) {
             $primary = $splittedLocale[0];
             if (!in_array($primary, $this->iso639)) {
                 $this->context->addViolation($constraint->message, array('%string%' => $locale));
             }
         } elseif ($splitCount == 2) {
             $primary = $splittedLocale[0];
             $region = $splittedLocale[1];
             if (!in_array($primary, $this->iso639) && !in_array($region, $this->iso3166)) {
                 $this->context->addViolation($constraint->message, array('%string%' => $locale));
             }
         } elseif ($splitCount > 2) {
             $primary = $splittedLocale[0];
             $script = $splittedLocale[1];
             $region = $splittedLocale[2];
             if (!in_array($primary, $this->iso639) && !in_array($region, $this->iso3166) && !in_array($script, $this->script)) {
                 $this->context->addViolation($constraint->message, array('%string%' => $locale));
             }
         }
     }
 }
예제 #8
0
 /**
  * @return array
  */
 public function getValueOptions()
 {
     if (empty($this->valueOptions)) {
         $this->valueOptions = array();
         $enabledLocales = $this->getServiceLocator()->get('Locale')->getAvailableFlags();
         if ($this->onlyEnabledLocales) {
             $enabledLocales = array_filter($enabledLocales);
         }
         foreach ($enabledLocales as $locale => $enabled) {
             $main = IntlLocale::getPrimaryLanguage($locale);
             $sub = IntlLocale::getRegion($locale);
             $mainKey = 'locale.main.' . $main;
             $localeKey = 'locale.sub.' . $locale;
             if (!empty($this->valueOptions[$mainKey])) {
                 $this->valueOptions[$mainKey]['options'][$locale] = $localeKey;
             } elseif (!$sub && empty($this->valueOptions[$locale])) {
                 $this->valueOptions[$locale] = $mainKey;
             } else {
                 if ($sub && !empty($this->valueOptions[$main])) {
                     $this->valueOptions[$mainKey]['options'] = array($main => 'locale.sub.' . $main);
                     unset($this->valueOptions[$main]);
                 }
                 $this->valueOptions[$mainKey]['options'][$locale] = $localeKey;
                 $this->valueOptions[$mainKey]['label'] = $mainKey;
             }
         }
         foreach ($this->valueOptions as &$valueGroup) {
             if (is_array($valueGroup) && isset($valueGroup['options']) && is_array($valueGroup['options'])) {
                 ksort($valueGroup['options']);
             }
         }
         $first = reset($this->valueOptions);
         if (count($this->valueOptions) === 1 && is_array($first) && !empty($first['options'])) {
             $this->valueOptions = $first['options'];
         }
     }
     return parent::getValueOptions();
 }
예제 #9
0
 /**
  * Returns the ISO code of the country according to locale
  *
  * @return Locale 2-letter ISO code
  */
 public function getCountryCode()
 {
     $localeIso = $this->locale->getIso();
     if (isset($this->localeCountryAssociations[$localeIso])) {
         return Locale::create($this->localeCountryAssociations[$localeIso]);
     }
     $regionLocale = \Locale::getRegion($localeIso);
     return $regionLocale ? Locale::create($regionLocale) : $this->locale;
 }
예제 #10
0
 /**
  * Returns the country/region code of a locale.
  *
  * @return CUStringObject The locale's two-letter country/region code (always uppercased).
  */
 public function regionCode()
 {
     assert('$this->hasRegionCode()', vs(isset($this), get_defined_vars()));
     return Locale::getRegion($this->m_name);
 }
 /**
  * Returns a text description for the given phone number, in the language provided. The
  * description might consist of the name of the country where the phone number is from, or the
  * name of the geographical area the phone number is from if more detailed information is
  * available.
  *
  * <p>This method assumes the validity of the number passed in has already been checked, and that
  * the number is suitable for geocoding. We consider fixed-line and mobile numbers possible
  * candidates for geocoding.
  *
  * <p>If $userRegion is set, we also consider the region of the user. If the phone number is from
  * the same region as the user, only a lower-level description will be returned, if one exists.
  * Otherwise, the phone number's region will be returned, with optionally some more detailed
  * information.
  *
  * <p>For example, for a user from the region "US" (United States), we would show "Mountain View,
  * CA" for a particular number, omitting the United States from the description. For a user from
  * the United Kingdom (region "GB"), for the same number we may show "Mountain View, CA, United
  * States" or even just "United States".
  *
  * @param PhoneNumber $number a valid phone number for which we want to get a text description
  * @param string $locale the language code for which the description should be written
  * @param string $userRegion the region code for a given user. This region will be omitted from the
  *     description if the phone number comes from this region. It is a two-letter uppercase ISO
  *     country code as defined by ISO 3166-1.
  * @return string a text description for the given language code for the given phone number
  */
 public function getDescriptionForValidNumber(PhoneNumber $number, $locale, $userRegion = null)
 {
     // If the user region matches the number's region, then we just show the lower-level
     // description, if one exists - if no description exists, we will show the region(country) name
     // for the number.
     $regionCode = $this->phoneUtil->getRegionCodeForNumber($number);
     if ($userRegion == null || $userRegion == $regionCode) {
         $languageStr = Locale::getPrimaryLanguage($locale);
         $scriptStr = "";
         $regionStr = Locale::getRegion($locale);
         $mobileToken = $this->phoneUtil->getCountryMobileToken($number->getCountryCode());
         $nationalNumber = $this->phoneUtil->getNationalSignificantNumber($number);
         if ($mobileToken !== "" && !strncmp($nationalNumber, $mobileToken, strlen($mobileToken))) {
             // In some countries, eg. Argentina, mobile numbers have a mobile token before the national
             // destination code, this should be removed before geocoding.
             $nationalNumber = substr($nationalNumber, strlen($mobileToken));
             $region = $this->phoneUtil->getRegionCodeForCountryCode($number->getCountryCode());
             try {
                 $copiedNumber = $this->phoneUtil->parse($nationalNumber, $region);
             } catch (NumberParseException $e) {
                 // If this happens, just reuse what we had.
                 $copiedNumber = $number;
             }
             $areaDescription = $this->prefixFileReader->getDescriptionForNumber($copiedNumber, $languageStr, $scriptStr, $regionStr);
         } else {
             $areaDescription = $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr);
         }
         return strlen($areaDescription) > 0 ? $areaDescription : $this->getCountryNameForNumber($number, $locale);
     }
     // Otherwise, we just show the region(country) name for now.
     return $this->getRegionDisplayName($regionCode, $locale);
     // TODO: Concatenate the lower-level and country-name information in an appropriate
     // way for each language.
 }
예제 #12
0
 private function prepareDisplayProperties($lang)
 {
     $locale = $this->config->findLocaleByLanguage($lang);
     $nameOfLanguage = \Locale::getDisplayName($lang, $locale);
     $nameOfCountry = \Locale::getDisplayLanguage($lang, \Locale::getDefault());
     $countryCode = \Locale::getRegion($locale);
     return [$nameOfLanguage, $nameOfCountry, $countryCode];
 }
예제 #13
0
 /**
  * Gets the region for the input locale
  *
  * @return string The region subtag for the locale or NULL if not present
  */
 public function getRegion()
 {
     return IntlLocale::getRegion($this->getLocale());
 }
예제 #14
0
 public function getDefaultCountry()
 {
     $defaultCountry = $this->container->getParameter('form.type.location.defaultCountry');
     if (false === $defaultCountry) {
         $defaultCountry = '';
     } else {
         if (empty($defaultCountry)) {
             $defaultCountry = \Locale::getRegion($this->container->get('request')->getLocale());
         }
     }
     return $defaultCountry;
 }
예제 #15
0
foreach ($translatedLocales as $translatedLocale) {
    // Don't include ICU's root resource bundle
    if ($translatedLocale === 'root') {
        continue;
    }
    $langBundle = load_resource_bundle($translatedLocale, $langDir);
    $regionBundle = load_resource_bundle($translatedLocale, $regionDir);
    $localeNames = array();
    foreach ($supportedLocales as $supportedLocale) {
        // Don't include ICU's root resource bundle
        if ($supportedLocale === 'root') {
            continue;
        }
        $lang = \Locale::getPrimaryLanguage($supportedLocale);
        $script = \Locale::getScript($supportedLocale);
        $region = \Locale::getRegion($supportedLocale);
        $variants = \Locale::getAllVariants($supportedLocale);
        // Currently the only available variant is POSIX, which we don't want
        // to include in the list
        if (count($variants) > 0) {
            continue;
        }
        $langName = $langBundle->get('Languages')->get($lang);
        $extras = array();
        // Some languages are simply not translated
        // Example: "az" (Azerbaijani) has no translation in "af" (Afrikaans)
        if (!$langName) {
            continue;
        }
        // "af" (Afrikaans) has no "Scripts" block
        if (!$langBundle->get('Scripts')) {
예제 #16
0
 /**
  * Sets some options
  *
  * @param string $locale
  * @return boolean
  */
 private function _setOptions()
 {
     $this->language = \Locale::getPrimaryLanguage($this->_currentLocale);
     $this->_setTimezoneCandidates(\Locale::getRegion($this->_currentLocale));
     return true;
 }
 private function generateLocaleName($locale, $displayLocale)
 {
     $name = null;
     $lang = \Locale::getPrimaryLanguage($locale);
     $script = \Locale::getScript($locale);
     $region = \Locale::getRegion($locale);
     $variants = \Locale::getAllVariants($locale);
     // Currently the only available variant is POSIX, which we don't want
     // to include in the list
     if (count($variants) > 0) {
         return null;
     }
     // Some languages are translated together with their region,
     // i.e. "en_GB" is translated as "British English"
     // we don't include these languages though because they mess up
     // the name sorting
     // $name = $this->langBundle->getLanguageName($displayLocale, $lang, $region);
     // Some languages are simply not translated
     // Example: "az" (Azerbaijani) has no translation in "af" (Afrikaans)
     if (null === ($name = $this->languageBundle->getLanguageName($lang, null, $displayLocale))) {
         return null;
     }
     // "as" (Assamese) has no "Variants" block
     //if (!$langBundle->get('Variants')) {
     //    continue;
     //}
     $extras = array();
     // Discover the name of the script part of the locale
     // i.e. in zh_Hans_MO, "Hans" is the script
     if ($script) {
         // Some scripts are not translated into every language
         if (null === ($scriptName = $this->languageBundle->getScriptName($script, $lang, $displayLocale))) {
             return null;
         }
         $extras[] = $scriptName;
     }
     // Discover the name of the region part of the locale
     // i.e. in de_AT, "AT" is the region
     if ($region) {
         // Some regions are not translated into every language
         if (null === ($regionName = $this->regionBundle->getCountryName($region, $displayLocale))) {
             return null;
         }
         $extras[] = $regionName;
     }
     if (count($extras) > 0) {
         // Remove any existing extras
         // For example, in German, zh_Hans is "Chinesisch (vereinfacht)".
         // The latter is the script part which is already included in the
         // extras and will be appended again with the other extras.
         if (preg_match('/^(.+)\\s+\\([^\\)]+\\)$/', $name, $matches)) {
             $name = $matches[1];
         }
         $name .= ' (' . implode(', ', $extras) . ')';
     }
     return $name;
 }
예제 #18
0
 /**
  * Get the region from a locale code
  *
  * @param string $code
  *
  * @return string
  */
 public function getRegion($code)
 {
     return \Locale::getRegion($code);
 }
예제 #19
0
 /**
  *
  *
  * @param string $Path
  * @param Gdn_Controller $Controller
  */
 public function init($Path, $Controller)
 {
     $Smarty = $this->smarty();
     // Get a friendly name for the controller.
     $ControllerName = get_class($Controller);
     if (StringEndsWith($ControllerName, 'Controller', true)) {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     // Get an ID for the body.
     $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod)));
     $Smarty->assign('BodyID', htmlspecialchars($BodyIdentifier));
     //$Smarty->assign('Config', Gdn::Config());
     // Assign some information about the user.
     $Session = Gdn::session();
     if ($Session->isValid()) {
         $User = array('Name' => htmlspecialchars($Session->User->Name), 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true);
         $Photo = $Session->User->Photo;
         if ($Photo) {
             if (!isUrl($Photo)) {
                 $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
             }
         } else {
             $Photo = UserModel::getDefaultAvatarUrl($Session->User);
         }
         $User['Photo'] = $Photo;
     } else {
         $User = false;
         /*array(
           'Name' => '',
           'CountNotifications' => 0,
           'SignedIn' => FALSE);*/
     }
     $Smarty->assign('User', $User);
     // Make sure that any datasets use arrays instead of objects.
     foreach ($Controller->Data as $Key => $Value) {
         if ($Value instanceof Gdn_DataSet) {
             $Controller->Data[$Key] = $Value->resultArray();
         } elseif ($Value instanceof stdClass) {
             $Controller->Data[$Key] = (array) $Value;
         }
     }
     $BodyClass = val('CssClass', $Controller->Data, '', true);
     $Sections = Gdn_Theme::section(null, 'get');
     if (is_array($Sections)) {
         foreach ($Sections as $Section) {
             $BodyClass .= ' Section-' . $Section;
         }
     }
     $Controller->Data['BodyClass'] = $BodyClass;
     // Set the current locale for themes to take advantage of.
     $Locale = Gdn::locale()->Locale;
     $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', Gdn::locale()->language(true)));
     if (class_exists('Locale')) {
         $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale);
         $CurrentLocale['Region'] = Locale::getRegion($Locale);
         $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale);
         $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale);
         $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale);
     }
     $Smarty->assign('CurrentLocale', $CurrentLocale);
     $Smarty->assign('Assets', (array) $Controller->Assets);
     // 2016-07-07 Linc: Request used to return blank for homepage.
     // Now it returns defaultcontroller. This restores BC behavior.
     $isHomepage = val('isHomepage', $Controller->Data);
     $Path = $isHomepage ? "" : Gdn::request()->path();
     $Smarty->assign('Path', $Path);
     $Smarty->assign('Homepage', $isHomepage);
     // true/false
     // Assign the controller data last so the controllers override any default data.
     $Smarty->assign($Controller->Data);
     $security = new SmartySecurityVanilla($Smarty);
     $security->php_handling = Smarty::PHP_REMOVE;
     $security->allow_constants = false;
     $security->allow_super_globals = false;
     $security->streams = null;
     $security->setPhpFunctions(array_merge($security->php_functions, ['array', 'category', 'checkPermission', 'inSection', 'inCategory', 'ismobile', 'multiCheckPermission', 'getValue', 'setValue', 'url', 'useragenttype']));
     $security->php_modifiers = array_merge($security->php_functions, array('sprintf'));
     $Smarty->enableSecurity($security);
 }
 /**
  * Get country by locale if country is supported, otherwise return default country (US)
  *
  * @param string $locale
  * @return string
  */
 public static function getCountryByLocale($locale)
 {
     $region = \Locale::getRegion($locale);
     $countries = Intl::getRegionBundle()->getCountryNames();
     if (array_key_exists($region, $countries)) {
         return $region;
     }
     return LocaleConfiguration::DEFAULT_COUNTRY;
 }
 /**
  * Get "What Is PayPal" localized URL
  * Supposed to be used with "mark" as popup window
  *
  * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
  * @return string
  */
 public function getPaymentMarkWhatIsPaypalUrl(\Magento\Framework\Locale\ResolverInterface $localeResolver = null)
 {
     $countryCode = 'US';
     if (null !== $localeResolver) {
         $shouldEmulate = null !== $this->_storeId && $this->_storeManager->getStore()->getId() != $this->_storeId;
         if ($shouldEmulate) {
             $localeResolver->emulate($this->_storeId);
         }
         $countryCode = \Locale::getRegion($localeResolver->getLocale());
         if ($shouldEmulate) {
             $localeResolver->revert();
         }
     }
     return sprintf('https://www.paypal.com/%s/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside', strtolower($countryCode));
 }
예제 #22
0
 /**
  * Get payment request data as array
  *
  * @param \Magento\Paypal\Model\Hostedpro $paymentMethod
  * @return array
  */
 protected function _getPaymentData(\Magento\Paypal\Model\Hostedpro $paymentMethod)
 {
     $request = ['paymentaction' => strtolower($paymentMethod->getConfigData('payment_action')), 'notify_url' => $paymentMethod->getNotifyUrl(), 'cancel_return' => $paymentMethod->getCancelUrl(), 'return' => $paymentMethod->getReturnUrl(), 'lc' => \Locale::getRegion($this->localeResolver->getLocale()), 'template' => 'mobile-iframe', 'showBillingAddress' => 'false', 'showShippingAddress' => 'true', 'showBillingEmail' => 'false', 'showBillingPhone' => 'false', 'showCustomerName' => 'false', 'showCardInfo' => 'true', 'showHostedThankyouPage' => 'false'];
     return $request;
 }
 protected function getProducts(Request $request)
 {
     $country = \Locale::getRegion($this->locale);
     $currency = $this->config->get('currencies.' . $country);
     $itemsPerPage = $this->getItemsPerPage($request);
     $currentPage = $this->getCurrentPage($request);
     $sort = $this->getSort($request, 'sunrise.products.sort')['searchParam'];
     /**
      * @var ProductProjectionCollection $products
      * @var PagedSearchResponse $response
      */
     list($products, $facets, $offset, $total) = $this->get('app.repository.product')->getProducts($itemsPerPage, $currentPage, $sort, $currency, $country, $this->getFilters($request), $this->getFacetDefinitions());
     $this->applyPagination(new Uri($request->getRequestUri()), $offset, $total, $itemsPerPage);
     $this->pagination->currentPage = $products->count();
     // @todo this is actually the count of products
     $this->pagination->totalPages = $total;
     // @todo this is actually the total count of products
     $this->facets = $facets;
     return $products;
 }
예제 #24
0
 /**
  * Get country code.
  *
  * If param $case is not set the result will be in UPPER case (e. g. "DE") by default.
  *
  * @param string $case [optional] Convert value to case (Text::LOWER, Text::UPPER or Text::NONE)
  *
  * @return string
  */
 public function getCountry($case = Text::NONE)
 {
     return Text::toCase(\Locale::getRegion($this->locale), $case);
 }
 protected function getProductData($cachePrefix, ProductProjection $product, ProductVariant $productVariant, $locale, $includeDetails, $selectSku = null)
 {
     $cacheKey = $cachePrefix . '-' . $productVariant->getSku() . $selectSku . '-' . $locale;
     if ($this->config['cache.products'] && $this->cache->has($cacheKey)) {
         return unserialize($this->cache->fetch($cacheKey));
     }
     $country = \Locale::getRegion($locale);
     $currency = $this->config['currencies.' . $country];
     $productModel = new ViewData();
     $productModelProduct = new ViewData();
     $productModelVariant = new ViewData();
     if (!is_null($productVariant->getPrice())) {
         $price = $productVariant->getPrice();
     } else {
         $price = PriceFinder::findPriceFor($productVariant->getPrices(), $currency, $country);
     }
     if (empty($selectSku)) {
         $productUrl = $this->generator->generate('pdp-master', ['slug' => (string) $product->getSlug()]);
     } else {
         $productUrl = $this->generator->generate('pdp', ['slug' => (string) $product->getSlug(), 'sku' => $productVariant->getSku()]);
     }
     $productModelProduct->variantId = $productVariant->getId();
     $productModelVariant->url = $productUrl;
     $productModelProduct->productId = $product->getId();
     $productModelProduct->slug = (string) $product->getSlug();
     $productModelVariant->name = (string) $product->getName();
     if (!is_null($price->getDiscounted())) {
         $productModelVariant->price = (string) $price->getDiscounted()->getValue();
         $productModelVariant->priceOld = (string) $price->getValue();
     } else {
         $productModelVariant->price = (string) $price->getValue();
     }
     $productModel->sale = isset($productModelVariant->priceOld);
     $productModelProduct->gallery = new ViewData();
     $productModelVariant->image = (string) $productVariant->getImages()->current()->getUrl();
     $productModelProduct->gallery->list = new ViewDataCollection();
     foreach ($productVariant->getImages() as $image) {
         $imageData = new ViewData();
         $imageData->thumbImage = $image->getUrl();
         $imageData->bigImage = $image->getUrl();
         $productModelProduct->gallery->list->add($imageData);
     }
     if ($includeDetails) {
         $productModelVariant->description = (string) $product->getDescription();
         $productType = $this->productTypeRepository->getById($product->getProductType()->getId());
         list($attributes, $variantKeys, $variantIdentifiers) = $this->getVariantSelectors($product, $productType, $selectSku);
         $productModelProduct->variants = $variantKeys;
         $productModelProduct->variantIdentifiers = $variantIdentifiers;
         if ($selectSku || count($variantIdentifiers) == 0) {
             $productModelVariant->variantId = $productVariant->getId();
             $productModelVariant->sku = $productVariant->getSku();
         }
         $productModelProduct->attributes = $attributes;
         $productModelProduct->details = new ViewData();
         $productModelProduct->details->list = new ViewDataCollection();
         $productVariant->getAttributes()->setAttributeDefinitions($productType->getAttributes());
         if (isset($this->config['sunrise.products.details.attributes'][$productType->getName()])) {
             $attributeList = $this->config['sunrise.products.details.attributes.' . $productType->getName()];
             foreach ($attributeList as $attributeName) {
                 $attribute = $productVariant->getAttributes()->getByName($attributeName);
                 if ($attribute) {
                     $attributeDefinition = $productType->getAttributes()->getByName($attributeName);
                     $attributeData = new ViewData();
                     $attributeData->text = (string) $attributeDefinition->getLabel() . ': ' . (string) $attribute->getValue();
                     $productModelProduct->details->list->add($attributeData);
                 }
             }
         }
     }
     $productModel->product = $productModelProduct;
     $productModel->product->variant = $productModelVariant;
     $productModel = $productModel->toArray();
     $this->cache->store($cacheKey, serialize($productModel));
     return $productModel;
 }
예제 #26
0
 /**
  *
  *
  * @param $Path
  * @param $Controller
  */
 public function init($Path, $Controller)
 {
     $Smarty = $this->smarty();
     // Get a friendly name for the controller.
     $ControllerName = get_class($Controller);
     if (StringEndsWith($ControllerName, 'Controller', true)) {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     // Get an ID for the body.
     $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod)));
     $Smarty->assign('BodyID', $BodyIdentifier);
     //$Smarty->assign('Config', Gdn::Config());
     // Assign some information about the user.
     $Session = Gdn::session();
     if ($Session->isValid()) {
         $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true);
         $Photo = $Session->User->Photo;
         if ($Photo) {
             if (!IsUrl($Photo)) {
                 $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));
             }
         } else {
             if (function_exists('UserPhotoDefaultUrl')) {
                 $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto');
             } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) {
                 $Photo = Gdn_Upload::url($ConfigPhoto);
             } else {
                 $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', true);
             }
         }
         $User['Photo'] = $Photo;
     } else {
         $User = false;
         /*array(
           'Name' => '',
           'CountNotifications' => 0,
           'SignedIn' => FALSE);*/
     }
     $Smarty->assign('User', $User);
     // Make sure that any datasets use arrays instead of objects.
     foreach ($Controller->Data as $Key => $Value) {
         if ($Value instanceof Gdn_DataSet) {
             $Controller->Data[$Key] = $Value->resultArray();
         } elseif ($Value instanceof stdClass) {
             $Controller->Data[$Key] = (array) $Value;
         }
     }
     $BodyClass = val('CssClass', $Controller->Data, '', true);
     $Sections = Gdn_Theme::section(null, 'get');
     if (is_array($Sections)) {
         foreach ($Sections as $Section) {
             $BodyClass .= ' Section-' . $Section;
         }
     }
     $Controller->Data['BodyClass'] = $BodyClass;
     // Set the current locale for themes to take advantage of.
     $Locale = Gdn::locale()->Locale;
     $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', $Locale));
     if (class_exists('Locale')) {
         $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale);
         $CurrentLocale['Region'] = Locale::getRegion($Locale);
         $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale);
         $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale);
         $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale);
     }
     $Smarty->assign('CurrentLocale', $CurrentLocale);
     $Smarty->assign('Assets', (array) $Controller->Assets);
     $Smarty->assign('Path', Gdn::request()->path());
     // Assign the controller data last so the controllers override any default data.
     $Smarty->assign($Controller->Data);
     $Smarty->Controller = $Controller;
     // for smarty plugins
     $Smarty->security = true;
     $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('Category', 'CheckPermission', 'InSection', 'InCategory', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url'));
     $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf'));
     $Smarty->secure_dir = array($Path);
 }
예제 #27
0
    echo Locale::getPrimaryLanguage($locale) ?: '<em>none</em>';
    ?>
</td>
        <td><?php 
    echo Locale::getDisplayLanguage($locale, Yii::$app->language) ?: '<em>none</em>';
    ?>
</td>
        <td><?php 
    echo Locale::getDisplayLanguage($locale, $locale) ?: '<em>none</em>';
    ?>
</td>
    </tr>
    <tr>
        <th>Region</th>
        <td><?php 
    echo Locale::getRegion($locale) ?: '<em>none</em>';
    ?>
</td>
        <td><?php 
    echo Locale::getDisplayRegion($locale, Yii::$app->language) ?: '<em>none</em>';
    ?>
</td>
        <td><?php 
    echo Locale::getDisplayRegion($locale, $locale) ?: '<em>none</em>';
    ?>
</td>
    </tr>
    <tr>
        <th>Script</th>
        <td><?php 
    echo Locale::getScript($locale) ?: '<em>none</em>';