コード例 #1
0
 /**
  * Test ModuleRefreshCommand
  */
 public function testModuleRefreshCommand()
 {
     $moduleManagement = new ModuleManagement();
     $moduleManagement->updateModules();
     $module = ModuleQuery::create()->filterByType(1)->orderByPosition(Criteria::DESC)->findOne();
     if ($module !== null) {
         $module->delete();
         $application = new Application($this->getKernel());
         $moduleRefresh = new ModuleRefreshCommand();
         $moduleRefresh->setContainer($this->getContainer());
         $application->add($moduleRefresh);
         $command = $application->find('module:refresh');
         $commandTester = new CommandTester($command);
         $commandTester->execute(['command' => $command->getName()]);
         $expected = $module;
         $actual = ModuleQuery::create()->filterByType(1)->orderByPosition(Criteria::DESC)->findOne();
         $this->assertEquals($expected->getCode(), $actual->getCode(), 'Last standard module code must be same after deleting this one and calling module:refresh');
         $this->assertEquals($expected->getType(), $actual->getType(), 'Last standard module type must be same after deleting this one and calling module:refresh');
         $this->assertEquals($expected->getFullNamespace(), $actual->getFullNamespace(), 'Last standard module namespace must be same after deleting this one and calling module:refresh');
         // Restore activation status
         $actual->setActivate($expected->getActivate())->save();
     } else {
         $this->markTestIncomplete('This test cannot be complete without at least one standard module.');
     }
 }
コード例 #2
0
ファイル: ModuleHook.php プロジェクト: alex63530/thelia
 protected function isModuleActive($module_id)
 {
     if (null !== ($module = ModuleQuery::create()->findPk($module_id))) {
         return $module->getActivate();
     }
     return false;
 }
コード例 #3
0
ファイル: Hook.php プロジェクト: badelas/thelia
 /**
  * Generates the content of the hook
  *
  * {hook name="hook_code" var1="value1" var2="value2" ... }
  *
  * This function create an event, feed it with the custom variables passed to the function (var1, var2, ...) and
  * dispatch it to the hooks that respond to it.
  *
  * The name of the event is `hook.{context}.{hook_code}` where :
  *      * context : the id of the context of the smarty render : 1: frontoffice, 2: backoffice, 3: email, 4: pdf
  *      * hook_code : the code of the hook
  *
  * The event collects all the fragments of text rendered in each modules functions that listen to this event.
  * Finally, this fragments are concatenated and injected in the template
  *
  * @param array        $params the params passed in the smarty function
  * @param \TheliaSmarty\Template\SmartyParser $smarty the smarty parser
  *
  * @return string the contents generated by modules
  */
 public function processHookFunction($params, &$smarty)
 {
     $hookName = $this->getParam($params, 'name');
     $module = intval($this->getParam($params, 'module', 0));
     $moduleCode = $this->getParam($params, 'modulecode', "");
     $type = $smarty->getTemplateDefinition()->getType();
     $event = new HookRenderEvent($hookName, $params);
     $event->setArguments($this->getArgumentsFromParams($params));
     $eventName = sprintf('hook.%s.%s', $type, $hookName);
     // this is a hook specific to a module
     if (0 === $module && "" !== $moduleCode) {
         if (null !== ($mod = ModuleQuery::create()->findOneByCode($moduleCode))) {
             $module = $mod->getId();
         }
     }
     if (0 !== $module) {
         $eventName .= '.' . $module;
     }
     $this->getDispatcher()->dispatch($eventName, $event);
     $content = trim($event->dump());
     if ($this->debug && $smarty->getRequest()->get('SHOW_HOOK')) {
         $content = sprintf('<div style="background-color: #C82D26; color: #fff; border-color: #000000; border: solid;">%s</div>%s', $hookName, $content);
     }
     $this->hookResults[$hookName] = $content;
     // support for compatibility with module_include
     if ($type === TemplateDefinition::BACK_OFFICE) {
         $content .= $this->moduleIncludeCompat($params, $smarty);
     }
     return $content;
 }
コード例 #4
0
 protected function processHook(ContainerBuilder $container, $definition)
 {
     foreach ($container->findTaggedServiceIds('hook.event_listener') as $id => $events) {
         $class = $container->getDefinition($id)->getClass();
         // the class must extends BaseHook
         $implementClass = HookDefinition::BASE_CLASS;
         if (!is_subclass_of($class, $implementClass)) {
             throw new \InvalidArgumentException(sprintf('Hook class "%s" must extends class "%s".', $class, $implementClass));
         }
         // retrieve the module id
         $properties = $container->getDefinition($id)->getProperties();
         $module = null;
         if (array_key_exists('module', $properties)) {
             $moduleCode = explode(".", $properties['module'])[1];
             if (null !== ($module = ModuleQuery::create()->findOneByCode($moduleCode))) {
                 $module = $module->getId();
             }
         }
         foreach ($events as $event) {
             $this->registerHook($class, $module, $id, $event);
         }
     }
     // now we can add listeners for active hooks and active module
     $this->addHooksMethodCall($definition);
 }
コード例 #5
0
ファイル: ModuleManagement.php プロジェクト: fachriza/thelia
 public function updateModules()
 {
     $finder = new Finder();
     $finder->name('module.xml')->in($this->baseModuleDir . '/*/Config');
     $descriptorValidator = new ModuleDescriptorValidator();
     foreach ($finder as $file) {
         $content = $descriptorValidator->getDescriptor($file->getRealPath());
         $reflected = new \ReflectionClass((string) $content->fullnamespace);
         $code = basename(dirname($reflected->getFileName()));
         $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME);
         $con->beginTransaction();
         try {
             $module = ModuleQuery::create()->filterByCode($code)->findOne();
             if (null === $module) {
                 $module = new Module();
                 $module->setCode($code)->setFullNamespace((string) $content->fullnamespace)->setType($this->getModuleType($reflected))->setActivate(0)->save($con);
             }
             $this->saveDescription($module, $content, $con);
             $con->commit();
         } catch (PropelException $e) {
             $con->rollBack();
             throw $e;
         }
     }
 }
コード例 #6
0
 protected function checkValidInvoice()
 {
     $order = $this->getSession()->getOrder();
     if (null === $order || null === $order->getChoosenInvoiceAddress() || null === $order->getPaymentModuleId() || null === AddressQuery::create()->findPk($order->getChoosenInvoiceAddress()) || null === ModuleQuery::create()->findPk($order->getPaymentModuleId())) {
         throw new RedirectException($this->retrieveUrlFromRouteId('order.invoice'));
     }
 }
コード例 #7
0
 /**
  * @param  string                    $itemName the modume code
  * @return Module                    the module object
  * @throws \InvalidArgumentException if module was not found
  */
 protected function getModule($itemName)
 {
     if (null !== ($module = ModuleQuery::create()->findPk($itemName))) {
         return $module;
     }
     throw new \InvalidArgumentException($this->getTranslator()->trans("No module found for code '%item'", ['%item' => $itemName]));
 }
コード例 #8
0
 public function verifyModuleId($value, ExecutionContextInterface $context)
 {
     $module = ModuleQuery::create()->findPk($value);
     if (null === $module) {
         $context->addViolation(Translator::getInstance()->trans("Module ID not found"));
     }
 }
コード例 #9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $moduleCode = $this->formatModuleName($input->getArgument("module"));
     $module = ModuleQuery::create()->findOneByCode($moduleCode);
     if (null === $module) {
         throw new \RuntimeException(sprintf("module %s not found", $moduleCode));
     }
     if ($module->getActivate() == BaseModule::IS_NOT_ACTIVATED) {
         throw new \RuntimeException(sprintf("module %s is already deactivated", $moduleCode));
     }
     try {
         $event = new ModuleToggleActivationEvent($module->getId());
         $module = ModuleQuery::create()->findPk($module->getId());
         if ($module->getMandatory() == BaseModule::IS_MANDATORY) {
             if (!$this->askConfirmation($input, $output)) {
                 return;
             }
             $event->setAssumeDeactivate(true);
         }
         if ($input->getOption("with-dependencies")) {
             $event->setRecursive(true);
         }
         $this->getDispatcher()->dispatch(TheliaEvents::MODULE_TOGGLE_ACTIVATION, $event);
     } catch (\Exception $e) {
         throw new \RuntimeException(sprintf("Deactivation fail with Exception : [%d] %s", $e->getCode(), $e->getMessage()));
     }
     //impossible to change output class in CommandTester...
     if (method_exists($output, "renderBlock")) {
         $output->renderBlock(array('', sprintf("Deactivation succeed for module %s", $moduleCode), ''), "bg=green;fg=black");
     }
 }
コード例 #10
0
 public function setUp()
 {
     $stubContainer = $this->getMockBuilder('\\Symfony\\Component\\DependencyInjection\\ContainerInterface')->disableOriginalConstructor()->getMock();
     $this->action = new ModuleHook($stubContainer, $this->getMockEventDispatcher());
     $this->module = ModuleQuery::create()->findOneByActivate(1);
     $this->hook = HookQuery::create()->findOneByActivate(true);
 }
コード例 #11
0
 protected function buildForm($change_mode = false)
 {
     $this->formBuilder->add("id", "hidden", array("required" => true, "constraints" => array(new Constraints\NotBlank(), new Constraints\Callback(array("methods" => array(array($this, "verifyProfileId")))))));
     foreach (ModuleQuery::create()->find() as $module) {
         $this->formBuilder->add(self::MODULE_ACCESS_FIELD_PREFIX . ':' . str_replace(".", ":", $module->getCode()), "choice", array("choices" => array(AccessManager::VIEW => AccessManager::VIEW, AccessManager::CREATE => AccessManager::CREATE, AccessManager::UPDATE => AccessManager::UPDATE, AccessManager::DELETE => AccessManager::DELETE), "attr" => array("tag" => "modules", "module_code" => $module->getCode()), "multiple" => true, "constraints" => array()));
     }
 }
コード例 #12
0
 public function process(ContainerBuilder $container)
 {
     if (!$container->hasDefinition('event_dispatcher')) {
         return;
     }
     $definition = $container->getDefinition('event_dispatcher');
     foreach ($container->findTaggedServiceIds('kernel.event_listener') as $id => $events) {
         foreach ($events as $event) {
             $priority = isset($event['priority']) ? $event['priority'] : 0;
             if (!isset($event['event'])) {
                 throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "kernel.event_listener" tags.', $id));
             }
             if (!isset($event['method'])) {
                 $event['method'] = 'on' . preg_replace_callback(array('/(?<=\\b)[a-z]/i', '/[^a-z0-9]/i'), function ($matches) {
                     return strtoupper($matches[0]);
                 }, $event['event']);
                 $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
             }
             $definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
         }
     }
     foreach ($container->findTaggedServiceIds('kernel.event_subscriber') as $id => $attributes) {
         // We must assume that the class value has been correctly filled, even if the service is created by a factory
         $class = $container->getDefinition($id)->getClass();
         $refClass = new \ReflectionClass($class);
         $interface = 'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface';
         if (!$refClass->implementsInterface($interface)) {
             throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
         }
         $definition->addMethodCall('addSubscriberService', array($id, $class));
     }
     // We have to check if Propel is initialized before registering hooks
     $managers = Propel::getServiceContainer()->getConnectionManagers();
     if (!array_key_exists('thelia', $managers)) {
         return;
     }
     foreach ($container->findTaggedServiceIds('hook.event_listener') as $id => $events) {
         $class = $container->getDefinition($id)->getClass();
         // the class must extends BaseHook
         $implementClass = HookDefinition::BASE_CLASS;
         if (!is_subclass_of($class, $implementClass)) {
             throw new \InvalidArgumentException(sprintf('Hook class "%s" must extends class "%s".', $class, $implementClass));
         }
         // retrieve the module id
         $properties = $container->getDefinition($id)->getProperties();
         $module = null;
         if (array_key_exists('module', $properties)) {
             $moduleCode = explode(".", $properties['module'])[1];
             if (null !== ($module = ModuleQuery::create()->findOneByCode($moduleCode))) {
                 $module = $module->getId();
             }
         }
         foreach ($events as $event) {
             $this->registerHook($class, $module, $id, $event);
         }
     }
     // now we can add listeners for active hooks and active module
     $this->addHooksMethodCall($definition);
 }
コード例 #13
0
ファイル: Loyalty.php プロジェクト: gillesbourgeat/Loyalty
 /**
  *
  * return false if CreditAccount module is not present
  *
  * @param ConnectionInterface $con
  * @return bool|void
  */
 public function preActivation(ConnectionInterface $con = null)
 {
     $module = ModuleQuery::create()->filterByCode('CreditAccount')->filterByActivate(self::IS_ACTIVATED)->findOne();
     if (null === $module) {
         throw new \RuntimeException(Translator::getInstance()->trans('CreditAccount must be installed and activated', [], 'loyalty'));
     }
     return true;
 }
コード例 #14
0
ファイル: OrderDelivery.php プロジェクト: margery/thelia
 public function verifyDeliveryModule($value, ExecutionContextInterface $context)
 {
     $module = ModuleQuery::create()->filterActivatedByTypeAndId(BaseModule::DELIVERY_MODULE_TYPE, $value)->findOne();
     if (null === $module) {
         $context->addViolation(Translator::getInstance()->trans("Delivery module ID not found"));
     } elseif (!$module->isDeliveryModule()) {
         $context->addViolation(sprintf(Translator::getInstance()->trans("delivery module %s is not a Thelia\\Module\\DeliveryModuleInterface"), $module->getCode()));
     }
 }
コード例 #15
0
 private function getModule(InputInterface $input)
 {
     $module = null;
     $moduleCode = $input->getArgument("module");
     if (!empty($moduleCode)) {
         if (null === ($module = ModuleQuery::create()->findOneByCode($moduleCode))) {
             throw new \RuntimeException(sprintf("Module %s does not exist.", $moduleCode));
         }
     }
     return $module;
 }
コード例 #16
0
 /**
  * Update module information, and invoke install() for new modules (e.g. modules
  * just discovered), or update() modules for which version number ha changed.
  *
  * @param SplFileInfo $file the module.xml file descriptor
  * @param ContainerInterface $container the container
  *
  * @return Module
  *
  * @throws \Exception
  * @throws \Propel\Runtime\Exception\PropelException
  */
 public function updateModule($file, ContainerInterface $container)
 {
     $descriptorValidator = $this->getDescriptorValidator();
     $content = $descriptorValidator->getDescriptor($file->getRealPath());
     $reflected = new \ReflectionClass((string) $content->fullnamespace);
     $code = basename(dirname($reflected->getFileName()));
     $version = (string) $content->version;
     $mandatory = intval($content->mandatory);
     $hidden = intval($content->hidden);
     $module = ModuleQuery::create()->filterByCode($code)->findOne();
     if (null === $module) {
         $module = new Module();
         $module->setActivate(0);
         $action = 'install';
     } elseif ($version !== $module->getVersion()) {
         $currentVersion = $module->getVersion();
         $action = 'update';
     } else {
         $action = 'none';
     }
     $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME);
     $con->beginTransaction();
     try {
         $module->setCode($code)->setVersion($version)->setFullNamespace((string) $content->fullnamespace)->setType($this->getModuleType($reflected))->setCategory((string) $content->type)->setMandatory($mandatory)->setHidden($hidden)->save($con);
         // Update the module images, title and description when the module is installed, but not after
         // as these data may have been modified byt the administrator
         if ('install' === $action) {
             $this->saveDescription($module, $content, $con);
             if (isset($content->{"images-folder"}) && !$module->isModuleImageDeployed($con)) {
                 /** @var \Thelia\Module\BaseModule $moduleInstance */
                 $moduleInstance = $reflected->newInstance();
                 $imagesFolder = THELIA_MODULE_DIR . $code . DS . (string) $content->{"images-folder"};
                 $moduleInstance->deployImageFolder($module, $imagesFolder, $con);
             }
         }
         // Tell the module to install() or update()
         $instance = $module->createInstance();
         $instance->setContainer($container);
         if ($action == 'install') {
             $instance->install($con);
         } elseif ($action == 'update') {
             $instance->update($currentVersion, $version, $con);
         }
         if ($action !== 'none') {
             $instance->registerHooks();
         }
         $con->commit();
     } catch (\Exception $ex) {
         Tlog::getInstance()->addError("Failed to update module " . $module->getCode(), $ex);
         $con->rollBack();
         throw $ex;
     }
     return $module;
 }
コード例 #17
0
ファイル: ModuleConfig.php プロジェクト: fachriza/thelia
 /**
  * @param LoopResult $loopResult
  *
  * @return LoopResult
  */
 public function parseResults(LoopResult $loopResult)
 {
     $moduleCode = $this->getModule();
     if (null === ($module = ModuleQuery::create()->filterByCode($moduleCode, Criteria::LIKE)->findOne())) {
         throw new \InvalidArgumentException("Module with code '{$moduleCode}' does not exists.");
     }
     $configValue = ModuleConfigQuery::create()->getConfigValue($module->getId(), $this->getVariable(), $this->getDefaultValue(), $this->getLocale());
     $loopResultRow = new LoopResultRow();
     $loopResultRow->set("VARIABLE", $this->getVariable())->set("VALUE", $configValue);
     $loopResult->addRow($loopResultRow);
     return $loopResult;
 }
コード例 #18
0
ファイル: VirtualProductHook.php プロジェクト: margery/thelia
 public function onMainBeforeContent(HookRenderEvent $event)
 {
     if ($this->securityContext->isGranted(["ADMIN"], [AdminResources::PRODUCT], [], [AccessManager::VIEW])) {
         $products = ProductQuery::create()->filterByVirtual(1)->filterByVisible(1)->count();
         if ($products > 0) {
             $deliveryModule = ModuleQuery::create()->retrieveVirtualProductDelivery();
             if (false === $deliveryModule) {
                 $event->add($this->render('virtual-delivery-warning.html'));
             }
         }
     }
 }
コード例 #19
0
 public function manageAcl(ModuleToggleActivationEvent $event)
 {
     if (null === ($module = ModuleQuery::create()->findPk($event->getModuleId()))) {
         return;
     }
     //In case of deactivation do nothing
     if ($module->getActivate() == BaseModule::IS_ACTIVATED) {
         return;
     }
     //In case of activation update acls
     $this->aclXmlFileloader->load($module);
 }
コード例 #20
0
 /**
  * @covers ModuleListener::load()
  */
 public function testModuleConfigurationIsNotLoadedOnDeactivation()
 {
     // use this module for testing
     $testModule = ModuleQuery::create()->findOneByCode(CustomerGroupAcl::getModuleCode());
     // activate it
     $testModule->reload();
     $testModule->setActivate(true)->save();
     // we expect the ACL configuration for our module to NOT be loaded
     $this->aclXmlFileloader->expects($this->never())->method("load")->with($this->equalTo($testModule));
     // toggle the module
     $activationEvent = new ModuleToggleActivationEvent($testModule->getId());
     $this->dispatcher->dispatch(TheliaEvents::MODULE_TOGGLE_ACTIVATION, $activationEvent);
 }
コード例 #21
0
ファイル: Security.php プロジェクト: alex63530/thelia
 public function checkValidDeliveryFunction($params, &$smarty)
 {
     $order = $this->request->getSession()->getOrder();
     /* Does address and module still exists ? We assume address owner can't change neither module type */
     if ($order !== null) {
         $checkAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress());
         $checkModule = ModuleQuery::create()->findPk($order->getDeliveryModuleId());
     }
     if (null === $order || null == $checkAddress || null === $checkModule) {
         throw new OrderException('Delivery must be defined', OrderException::UNDEFINED_DELIVERY, array('missing' => 1));
     }
     return "";
 }
コード例 #22
0
ファイル: Profile.php プロジェクト: margery/thelia
 /**
  * @param ProfileEvent $event
  */
 public function updateModuleAccess(ProfileEvent $event)
 {
     if (null !== ($profile = ProfileQuery::create()->findPk($event->getId()))) {
         ProfileModuleQuery::create()->filterByProfileId($event->getId())->delete();
         foreach ($event->getModuleAccess() as $moduleCode => $accesses) {
             $manager = new AccessManager(0);
             $manager->build($accesses);
             $profileModule = new ProfileModule();
             $profileModule->setProfileId($event->getId())->setModule(ModuleQuery::create()->findOneByCode($moduleCode))->setAccess($manager->getAccessValue());
             $profileModule->save();
         }
         $event->setProfile($profile);
     }
 }
コード例 #23
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage module Letshopethismoduledoesnotexists not found
  */
 public function testModuleActivateCommandUnknownModule()
 {
     $testedModule = ModuleQuery::create()->findOneByCode('Letshopethismoduledoesnotexists');
     if (null == $testedModule) {
         $application = new Application($this->getKernel());
         $moduleActivate = new ModuleActivateCommand();
         $moduleActivate->setContainer($this->getContainer());
         $application->add($moduleActivate);
         $command = $application->find("module:activate");
         $commandTester = new CommandTester($command);
         $commandTester->execute(array("command" => $command->getName(), "module" => "letshopethismoduledoesnotexists"));
         $out = true;
     }
 }
コード例 #24
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $moduleCode = $this->formatModuleName($input->getArgument("module"));
     $module = ModuleQuery::create()->findOneByCode($moduleCode);
     if (null === $module) {
         throw new \RuntimeException(sprintf("module %s not found", $moduleCode));
     }
     try {
         $moduleInstance = $module->createInstance();
         $moduleInstance->activate();
     } catch (\Exception $e) {
         throw new \RuntimeException(sprintf("Activation fail with Exception : [%d] %s", $e->getCode(), $e->getMessage()));
     }
     //impossible to change output class in CommandTester...
     if (method_exists($output, "renderBlock")) {
         $output->renderBlock(array('', sprintf("Activation succeed for module %s", $moduleCode), ''), "bg=green;fg=black");
     }
 }
コード例 #25
0
 protected function getModulesData()
 {
     $moduleData = ModuleQuery::create()->orderByType()->addAsColumn("code", ModuleTableMap::CODE)->addAsColumn("active", "IF(" . ModuleTableMap::ACTIVATE . ", \"Yes\", \"No\")")->addAsColumn("type", ModuleTableMap::TYPE)->addAsColumn("version", ModuleTableMap::VERSION)->select(["code", "active", "type", "version"])->find()->toArray();
     foreach ($moduleData as &$row) {
         switch ($row["type"]) {
             case BaseModule::CLASSIC_MODULE_TYPE:
                 $row["type"] = "classic";
                 break;
             case BaseModule::DELIVERY_MODULE_TYPE:
                 $row["type"] = "delivery";
                 break;
             case BaseModule::PAYMENT_MODULE_TYPE:
                 $row["type"] = "payment";
                 break;
         }
     }
     return $moduleData;
 }
コード例 #26
0
 /**
  * @covers AclListener::aclUpdate()
  */
 public function testUpdateNonExistingAcl()
 {
     // get an ACL id not yet used
     $initialAclId = 1;
     while (null !== AclQuery::create()->findPk($initialAclId)) {
         ++$initialAclId;
     }
     $testAclCode = $this->makeUniqueAclCode("-customer-group-acl-unit-test-new-acl-code-");
     $anotherModuleId = ModuleQuery::create()->findOneByCode(CustomerGroup::getModuleCode())->getId();
     $updateEvent = new AclEvent($testAclCode, $anotherModuleId, "en_US", "New title", "New description", $initialAclId);
     $this->dispatcher->dispatch(CustomerGroupAclEvents::ACL_UPDATE, $updateEvent);
     $finalAcl = AclQuery::create()->findOneByCode($testAclCode);
     $this->assertNotNull($finalAcl);
     $this->assertEquals($finalAcl->getModuleId(), $anotherModuleId);
     $finalAcl->setLocale("en_US");
     $this->assertEquals($finalAcl->getTitle(), "New title");
     $this->assertEquals($finalAcl->getDescription(), "New description");
 }
コード例 #27
0
 /**
  * Build Coupon form
  *
  * @return void
  */
 protected function buildForm()
 {
     // Create countries and shipping modules list
     $countries = [0 => '   '];
     $list = CountryQuery::create()->find();
     /** @var Country $item */
     foreach ($list as $item) {
         $countries[$item->getId()] = $item->getTitle();
     }
     asort($countries);
     $countries[0] = Translator::getInstance()->trans("All countries");
     $modules = [0 => '   '];
     $list = ModuleQuery::create()->filterByActivate(BaseModule::IS_ACTIVATED)->filterByType(BaseModule::DELIVERY_MODULE_TYPE)->find();
     /** @var Module $item */
     foreach ($list as $item) {
         $modules[$item->getId()] = $item->getTitle();
     }
     asort($modules);
     $modules[0] = Translator::getInstance()->trans("All shipping methods");
     $this->formBuilder->add('code', 'text', array('constraints' => array(new NotBlank())))->add('title', 'text', array('constraints' => array(new NotBlank())))->add('shortDescription', 'text')->add('description', 'textarea')->add('type', 'text', array('constraints' => array(new NotBlank(), new NotEqualTo(array('value' => -1)))))->add('isEnabled', 'text', array())->add('expirationDate', 'text', array('constraints' => array(new NotBlank(), new Callback(array("methods" => array(array($this, "checkLocalizedDate")))))))->add('isCumulative', 'text', array())->add('isRemovingPostage', 'text', array())->add('freeShippingForCountries', 'choice', array('multiple' => true, 'choices' => $countries))->add('freeShippingForModules', 'choice', array('multiple' => true, 'choices' => $modules))->add('isAvailableOnSpecialOffers', 'text', array())->add('maxUsage', 'text', array('constraints' => array(new NotBlank(), new GreaterThanOrEqual(['value' => -1]))))->add('perCustomerUsageCount', 'choice', array('multiple' => false, 'required' => true, 'choices' => [1 => Translator::getInstance()->trans('Per customer'), 0 => Translator::getInstance()->trans('Overall')]))->add('locale', 'hidden', array('constraints' => array(new NotBlank())))->add('coupon_specific', 'collection', array('allow_add' => true, 'allow_delete' => true));
 }
コード例 #28
0
 /**
  *
  * in this function you add all the fields you need for your Form.
  * Form this you have to call add method on $this->formBuilder attribute :
  *
  * $this->formBuilder->add("name", "text")
  *   ->add("email", "email", array(
  *           "attr" => array(
  *               "class" => "field"
  *           ),
  *           "label" => "email",
  *           "constraints" => array(
  *               new \Symfony\Component\Validator\Constraints\NotBlank()
  *           )
  *       )
  *   )
  *   ->add('age', 'integer');
  *
  * @return null
  */
 protected function buildForm()
 {
     /**
      * Get information
      */
     if (ShoppingFluxConfigQuery::getDefaultLang() !== null) {
         $langId = ShoppingFluxConfigQuery::getDefaultLang()->getId();
     } else {
         $langId = Lang::getDefaultLanguage()->getId();
     }
     $langsId = LangQuery::create()->select("Id")->find()->toArray();
     $langsId = array_flip($langsId);
     $deliveryModulesId = ModuleQuery::create()->filterByType(AbstractDeliveryModule::DELIVERY_MODULE_TYPE)->filterByActivate(1)->select("Id")->find()->toArray();
     $deliveryModulesId = array_flip($deliveryModulesId);
     $taxesId = TaxQuery::create()->filterByType("Thelia\\TaxEngine\\TaxType\\FixAmountTaxType")->select("Id")->find()->toArray();
     $taxesId = array_flip($taxesId);
     $translator = Translator::getInstance();
     /**
      * Then build the form
      */
     $this->formBuilder->add("token", "text", array("label" => $translator->trans("ShoppingFlux Token", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_token"], "constraints" => [], "required" => true, "data" => ShoppingFluxConfigQuery::getToken()))->add("prod", "checkbox", array("label" => $translator->trans("In production", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_prod"], "required" => false, "data" => ShoppingFluxConfigQuery::getProd()))->add("delivery_module_id", "choice", array("label" => $translator->trans("Delivery module", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_delivery_module_id"], "required" => true, "multiple" => false, "choices" => $deliveryModulesId, "data" => ShoppingFluxConfigQuery::getDeliveryModuleId()))->add("lang_id", "choice", array("label" => $translator->trans("Language", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_lang"], "required" => true, "multiple" => false, "choices" => $langsId, "data" => $langId))->add("ecotax_id", "choice", array("label" => $translator->trans("Ecotax rule", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_ecotax"], "required" => true, "choices" => $taxesId, "multiple" => false, "data" => ShoppingFluxConfigQuery::getEcotaxRuleId()))->add("action_type", "choice", array("required" => true, "choices" => ["save" => 0, "export" => 1], "multiple" => false));
 }
コード例 #29
0
 public function buildModelCriteria()
 {
     $search = ModuleQuery::create();
     $search->filterByActivate(1);
     if (null !== ($id = $this->getId())) {
         $search->filterById($id);
     }
     if (null !== ($exclude = $this->getExclude())) {
         $search->filterById($exclude, Criteria::NOT_IN);
     }
     if (null !== ($code = $this->getCode())) {
         $search->filterByCode($code);
     }
     $this->configureI18nProcessing($search);
     $search->filterByType($this->getModuleType(), Criteria::EQUAL);
     $order = $this->getOrder();
     switch ($order) {
         case "id":
             $search->orderById(Criteria::ASC);
             break;
         case "id_reverse":
             $search->orderById(Criteria::DESC);
             break;
         case "alpha":
             $search->addAscendingOrderByColumn('i18n_TITLE');
             break;
         case "alpha_reverse":
             $search->addDescendingOrderByColumn('i18n_TITLE');
             break;
         case "manual_reverse":
             $search->orderByPosition(Criteria::DESC);
             break;
         case "manual":
         default:
             $search->orderByPosition(Criteria::ASC);
             break;
     }
     return $search;
 }
コード例 #30
0
ファイル: CartPostage.php プロジェクト: alex63530/thelia
 /**
  * Retrieve the cheapest delivery for country
  *
  * @param  \Thelia\Model\Country   $country
  * @return DeliveryModuleInterface
  */
 protected function getCheapestDelivery(Country $country)
 {
     $deliveryModules = ModuleQuery::create()->filterByActivate(1)->filterByType(BaseModule::DELIVERY_MODULE_TYPE, Criteria::EQUAL)->find();
     foreach ($deliveryModules as $deliveryModule) {
         /** @var DeliveryModuleInterface $moduleInstance */
         $moduleInstance = $deliveryModule->getModuleInstance($this->container);
         if (false === $moduleInstance instanceof DeliveryModuleInterface) {
             throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\\Module\\DeliveryModuleInterface", $deliveryModule->getCode()));
         }
         try {
             // Check if module is valid, by calling isValidDelivery(),
             // or catching a DeliveryException.
             if ($moduleInstance->isValidDelivery($country)) {
                 $postage = $moduleInstance->getPostage($country);
                 if (null === $this->postage || $this->postage > $postage) {
                     $this->postage = $postage;
                     $this->deliveryId = $deliveryModule->getId();
                 }
             }
         } catch (DeliveryException $ex) {
             // Module is not available
         }
     }
 }