* @copyright 2020 DIGITAL RETAIL TECHNOLOGIES SL * @license https://opensource.org/licenses/MIT The MIT License * * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ class RetailcrmContextSwitcher { /** * @var int */ private static $contextShopType; /** * @var Shop */ private static $contextShop; /** * Runs given callback function in all context shops * * @param callable $callback * @param array $arguments Arguments that will be passed to callback function * @return array */ public static function runInContext($callback, $arguments = array()) { $result = array(); self::storeContext(); foreach (self::getShops() as $shop) { self::setShopContext(intval($shop['id_shop'])); $result[intval($shop['id_shop'])] = call_user_func_array($callback, $arguments); } self::restoreContext(); return $result; } private static function storeContext() { static::$contextShopType = Shop::getContext(); static::$contextShop = Context::getContext()->shop; } private static function restoreContext() { switch (static::$contextShopType) { case Shop::CONTEXT_GROUP: $contextShopId = static::$contextShop->id_shop_group; break; case Shop::CONTEXT_SHOP: $contextShopId = static::$contextShop->id; break; default: $contextShopId = null; break; } try { Shop::setContext(static::$contextShopType, $contextShopId); } catch (PrestaShopException $e) { RetailcrmLogger::writeCaller(__METHOD__, 'Unable to set shop context'); } Context::getContext()->shop = static::$contextShop; } /** * * Change shop in the context * * @param $id_shop */ public static function setShopContext($id_shop) { try { Shop::setContext(Shop::CONTEXT_SHOP, $id_shop); } catch (PrestaShopException $e) { RetailcrmLogger::writeCaller(__METHOD__, 'Unable to set shop context'); } Context::getContext()->shop = new Shop($id_shop); } /** * @return array */ public static function getShops() { $idShop = Shop::getContextShopID(); if (Shop::isFeatureActive() && $idShop === null) { return Shop::getShops(true, Shop::getContextShopGroupID(true)); } else { return array(Shop::getShop($idShop)); } } }