Merge branch 'master' into loops

Conflicts:
	core/lib/Thelia/Core/Template/Loop/Category.php
	core/lib/Thelia/Core/Template/Loop/FeatureValue.php
	core/lib/Thelia/Core/Template/Loop/Folder.php
	core/lib/Thelia/Core/Template/Loop/Product.php
	core/lib/Thelia/Core/Template/Smarty/Plugins/TheliaLoop.php
	install/faker.php
This commit is contained in:
Etienne Roudeix
2013-08-21 09:19:56 +02:00
3275 changed files with 929970 additions and 274940 deletions

View File

@@ -28,6 +28,7 @@ use Symfony\Component\DependencyInjection\Scope;
use Thelia\Core\DependencyInjection\Compiler\RegisterListenersPass;
use Thelia\Core\DependencyInjection\Compiler\RegisterParserPluginPass;
use Thelia\Core\DependencyInjection\Compiler\RegisterRouterPass;
/**
* First Bundle use in Thelia
@@ -55,7 +56,11 @@ class TheliaBundle extends Bundle
$container->addScope(new Scope('request'));
$container->addCompilerPass(new RegisterListenersPass());
$container->addCompilerPass(new RegisterParserPluginPass());
$container
->addCompilerPass(new RegisterListenersPass())
->addCompilerPass(new RegisterParserPluginPass())
->addCompilerPass(new RegisterRouterPass())
;
}
}

6
core/lib/Thelia/Core/Context.php Normal file → Executable file
View File

@@ -23,7 +23,6 @@
namespace Thelia\Core;
class Context
{
const CONTEXT_FRONT_OFFICE = 'front';
@@ -43,8 +42,7 @@ class Context
public function setContext($context)
{
if($this->isValidContext($context))
{
if ($this->isValidContext($context)) {
$this->currentContext = $context;
}
}
@@ -53,4 +51,4 @@ class Context
{
return $this->currentContext;
}
}
}

View File

@@ -0,0 +1,85 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
class RegisterRouterPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*
* @api
*/
public function process(ContainerBuilder $container)
{
try {
$chainRouter = $container->getDefinition("router.chainRequest");
} catch (InvalidArgumentException $e) {
return;
}
foreach ($container->findTaggedServiceIds("router.register") as $id => $attributes) {
$priority = isset($attributes[0]["priority"]) ? $attributes[0]["priority"] : 0;
$router = $container->getDefinition($id);
$router->addMethodCall("setOption", array("matcher_cache_class", $container::camelize("ProjectUrlMatcher".$id)));
$chainRouter->addMethodCall("add", array(new Reference($id), $priority));
}
if (defined("THELIA_INSTALL_MODE") === false) {
$modules = \Thelia\Model\ModuleQuery::getActivated();
foreach ($modules as $module) {
$moduleCode = ucfirst($module->getCode());
if (file_exists(THELIA_MODULE_DIR . "/" . $moduleCode . "/Config/routing.xml")) {
$definition = new Definition(
$container->getParameter("router.class"),
array(
new Reference("router.module.xmlLoader"),
ucfirst($module->getCode()) . "/Config/routing.xml",
array(
"cache_dir" => $container->getParameter("kernel.cache_dir"),
"debug" => $container->getParameter("kernel.debug"),
"matcher_cache_class" => $container::camelize("ProjectUrlMatcher".$moduleCode)
),
new Reference("request.context")
)
);
$container->setDefinition("router.".$moduleCode, $definition);
$chainRouter->addMethodCall("add", array(new Reference("router.".$moduleCode), -1));
}
}
}
}
}

View File

@@ -16,6 +16,7 @@
<xsd:element name="parameters" type="parameters"/>
<xsd:element name="commands" type="commands"/>
<xsd:element name="forms" type="forms" />
<xsd:element name="routing" type="routing" />
</xsd:choice>
</xsd:complexType>
@@ -54,6 +55,16 @@
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="routing">
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="file" type="file"/>
</xsd:choice>
</xsd:complexType>
<xsd:complexType name="file">
<xsd:attribute name="path" type="xsd:string" use="required" />
</xsd:complexType>
<xsd:complexType name="loops">
<xsd:choice minOccurs="0" maxOccurs="unbounded" >
<xsd:element name="loop" type="loop"/>

View File

@@ -26,7 +26,6 @@ namespace Thelia\Core\Event;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Form\BaseForm;
use Thelia\Core\Security\SecurityContext;
/**
*
* Class thrown on Thelia.action event
@@ -43,7 +42,6 @@ abstract class ActionEvent extends Event
*/
protected $request;
protected $errorForm = null;
protected $parameters = array();
@@ -58,7 +56,6 @@ abstract class ActionEvent extends Event
$this->request = $request;
}
public function __set($name, $value)
{
$this->parameters[$name] = $value;
@@ -82,17 +79,20 @@ abstract class ActionEvent extends Event
return $this->request;
}
public function setErrorForm(BaseForm $form) {
$this->errorForm = $form;
public function setErrorForm(BaseForm $form)
{
$this->errorForm = $form;
if ($form != null) $this->stopPropagation();
if ($form != null) $this->stopPropagation();
}
public function getErrorForm() {
return $this->errorForm;
public function getErrorForm()
{
return $this->errorForm;
}
public function hasErrorForm() {
return $this->errorForm != null ? true : false;
public function hasErrorForm()
{
return $this->errorForm != null ? true : false;
}
}

118
core/lib/Thelia/Core/Event/CartEvent.php Normal file → Executable file
View File

@@ -23,21 +23,127 @@
namespace Thelia\Core\Event;
use Thelia\Core\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Model\Cart;
class CartEvent extends ActionEvent {
class CartEvent extends Event
{
protected $cart;
protected $quantity;
protected $append;
protected $newness;
protected $productSaleElementsId;
protected $product;
protected $cartItem;
public function __construct(Request $request, Cart $cart)
public function __construct(Cart $cart)
{
parent::__construct($request);
$this->cart = $cart;
}
/**
* @param mixed $append
*/
public function setAppend($append)
{
$this->append = $append;
}
/**
* @return mixed
*/
public function getAppend()
{
return $this->append;
}
/**
* @param mixed $cartItem
*/
public function setCartItem($cartItem)
{
$this->cartItem = $cartItem;
}
/**
* @return mixed
*/
public function getCartItem()
{
return $this->cartItem;
}
/**
* @param mixed $newness
*/
public function setNewness($newness)
{
$this->newness = $newness;
}
/**
* @return mixed
*/
public function getNewness()
{
return $this->newness;
}
/**
* @param mixed $product
*/
public function setProduct($product)
{
$this->product = $product;
}
/**
* @return mixed
*/
public function getProduct()
{
return $this->product;
}
/**
* @param mixed $productSaleElementsId
*/
public function setProductSaleElementsId($productSaleElementsId)
{
$this->productSaleElementsId = $productSaleElementsId;
}
/**
* @return mixed
*/
public function getProductSaleElementsId()
{
return $this->productSaleElementsId;
}
/**
* @param mixed $quantity
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
}
/**
* @return mixed
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* @return \Thelia\Model\Cart
*/
public function getCart()
{
return $this->cart;
}
}
}

7
core/lib/Thelia/Core/Event/CartItemEvent.php Normal file → Executable file
View File

@@ -23,11 +23,10 @@
namespace Thelia\Core\Event;
use Thelia\Model\CartItem;
class CartItemEvent extends InternalEvent {
class CartItemEvent extends InternalEvent
{
protected $cartItem;
public function __construct(CartItem $cartItem)
@@ -39,4 +38,4 @@ class CartItemEvent extends InternalEvent {
{
return $this->cartItem;
}
}
}

7
core/lib/Thelia/Core/Event/CategoryEvent.php Normal file → Executable file
View File

@@ -23,15 +23,14 @@
namespace Thelia\Core\Event;
use Thelia\Model\Category;
class CategoryEvent extends InternalEvent {
class CategoryEvent extends InternalEvent
{
public $category;
public function __construct(Category $category)
{
$this->category = $category;
}
}
}

View File

@@ -0,0 +1,237 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: manu
* Date: 16/08/13
* Time: 10:24
* To change this template use File | Settings | File Templates.
*/
namespace Thelia\Core\Event;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Model\Customer;
class CustomerCreateOrUpdateEvent extends Event {
//base parameters for creating new customer
protected $title;
protected $firstname;
protected $lastname;
protected $address1;
protected $address2;
protected $address3;
protected $phone;
protected $cellphone;
protected $zipcode;
protected $city;
protected $country;
protected $email;
protected $password;
protected $lang;
protected $reseller;
protected $sponsor;
protected $discount;
/**
* @var \Thelia\Model\Customer
*/
protected $customer;
/**
* @param int $title the title customer id
* @param string $firstname
* @param string $lastname
* @param string $address1
* @param string $address2
* @param string $address3
* @param string $phone
* @param string $cellphone
* @param string $zipcode
* @param string $city
* @param int $country the country id
* @param string $email
* @param string $password plain password, don't put hash password, it will hashes again
* @param $lang
* @param int $reseller if customer is a reseller
* @param int $sponsor customer's id sponsor
* @param float $discount
*/
function __construct($title, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $country, $email, $password, $lang, $reseller, $sponsor, $discount)
{
$this->address1 = $address1;
$this->address2 = $address2;
$this->address3 = $address3;
$this->country = $country;
$this->email = $email;
$this->firstname = $firstname;
$this->lang = $lang;
$this->lastname = $lastname;
$this->password = $password;
$this->phone = $phone;
$this->cellphone = $cellphone;
$this->title = $title;
$this->zipcode = $zipcode;
$this->reseller = $reseller;
$this->sponsor = $sponsor;
$this->discount = $discount;
}
/**
* @return string
*/
public function getAddress1()
{
return $this->address1;
}
/**
* @return string
*/
public function getAddress2()
{
return $this->address2;
}
/**
* @return string
*/
public function getAddress3()
{
return $this->address3;
}
/**
* @return int
*/
public function getCountry()
{
return $this->country;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* @return mixed
*/
public function getLang()
{
return $this->lang;
}
/**
* @return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* @return string
*/
public function getCellphone()
{
return $this->cellphone;
}
/**
* @return int
*/
public function getTitle()
{
return $this->title;
}
/**
* @return string
*/
public function getZipcode()
{
return $this->zipcode;
}
/**
* @return string
*/
public function getCity()
{
return $this->city;
}
/**
* @return float
*/
public function getDiscount()
{
return $this->discount;
}
/**
* @return int
*/
public function getReseller()
{
return $this->reseller;
}
/**
* @return int
*/
public function getSponsor()
{
return $this->sponsor;
}
/**
* @param Customer $customer
*/
public function setCustomer(Customer $customer)
{
$this->customer = $customer;
}
/**
* @return Customer
*/
public function getCustomer()
{
return $this->customer;
}
}

View File

@@ -21,33 +21,22 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\DependencyInjection;
namespace Thelia\Core\Event;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Thelia\Core\Context;
use Thelia\Model\Customer;
class ContainerAwareAdmin implements ContainerAwareInterface {
class CustomerLoginEvent {
/**
* @var ContainerInterface
*
* @api
*/
protected $container;
protected $customer;
/**
* Sets the Container.
*
* @param ContainerInterface|null $container A ContainerInterface instance or null
*
* @api
*/
public function setContainer(ContainerInterface $container = null)
public function __construct(Customer $customer)
{
$container->get('thelia.envContext')->setContext(Context::CONTEXT_BACK_OFFICE);
$this->container = $container;
$this->customer = $customer;
}
public function getCustomer()
{
return $this->customer;
}
}

View File

@@ -0,0 +1,257 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Model\Cart;
class ImageEvent extends ActionEvent
{
/**
* @var string The complete file name (with path) of the source image
*/
protected $source_filepath = null;
/**
* @var string The target subdirectory in the image cache
*/
protected $cache_subdirectory = null;
/**
* @var string The absolute URL of the cached image (in the web space)
*/
protected $file_url = null;
/**
* @var string The absolute path of the cached image file
*/
protected $cache_filepath = null;
/**
* @var string The absolute URL of the cached version of the original image (in the web space)
*/
protected $original_file_url = null;
/**
* @var string The absolute path of the cached version of the original image file
*/
protected $cache_original_filepath = null;
/**
* @var string The image category (i.e. the subdirectory in image cache)
*/
protected $category = null;
/**
* @var integer the required image width
*/
protected $width = null;
/**
* @var int the required image height
*/
protected $height = null;
/**
* @var string the resize mode, either crop, bands, none
*/
protected $resize_mode = null;
/**
* @var string the background color in RGB format (eg. #ff8000)
*/
protected $background_color = null;
/**
* @var array a list of effects (grayscale, negative, mirror...), applied in the specified order.
*/
protected $effects = array();
/**
* @var int the rotation angle in degrees, none if zero or null
*/
protected $rotation = null;
/**
* @var int the quality of the result image, from 0 (!) to 100
*/
protected $quality = null;
/**
* @return boolean true if the required image is the original image (resize_mode and background_color are not significant)
*/
public function isOriginalImage()
{
return empty($this->width) && empty($this->height) /* && empty($this->resize_mode) && empty($this->background_color) not significant */
&& empty($this->effects) && empty($this->rotation) && empty($this->quality);
}
/**
* @return string a hash identifiying the processing options
*/
public function getOptionsHash()
{
return md5(
$this->width . $this->height . $this->resize_mode . $this->background_color . implode(',', $this->effects)
. $this->rotation);
}
public function getCategory()
{
return $this->category;
}
public function setCategory($category)
{
$this->category = $category;
}
public function getWidth()
{
return $this->width;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getHeight()
{
return $this->height;
}
public function setHeight($height)
{
$this->height = $height;
}
public function getResizeMode()
{
return $this->resize_mode;
}
public function setResizeMode($resize_mode)
{
$this->resize_mode = $resize_mode;
}
public function getBackgroundColor()
{
return $this->background_color;
}
public function setBackgroundColor($background_color)
{
$this->background_color = $background_color;
}
public function getEffects()
{
return $this->effects;
}
public function setEffects(array $effects)
{
$this->effects = $effects;
}
public function getRotation()
{
return $this->rotation;
}
public function setRotation($rotation)
{
$this->rotation = $rotation;
}
public function getFileUrl()
{
return $this->file_url;
}
public function setFileUrl($file_url)
{
$this->file_url = $file_url;
}
public function getCacheFilepath()
{
return $this->cache_filepath;
}
public function setCacheFilepath($cache_filepath)
{
$this->cache_filepath = $cache_filepath;
}
public function getSourceFilepath()
{
return $this->source_filepath;
}
public function setSourceFilepath($source_filepath)
{
$this->source_filepath = $source_filepath;
}
public function getCacheSubdirectory()
{
return $this->cache_subdirectory;
}
public function setCacheSubdirectory($cache_subdirectory)
{
$this->cache_subdirectory = $cache_subdirectory;
}
public function getQuality()
{
return $this->quality;
}
public function setQuality($quality)
{
$this->quality = $quality;
}
public function getOriginalFileUrl()
{
return $this->original_file_url;
}
public function setOriginalFileUrl($original_file_url)
{
$this->original_file_url = $original_file_url;
}
public function getCacheOriginalFilepath()
{
return $this->cache_original_filepath;
}
public function setCacheOriginalFilepath($cache_original_filepath)
{
$this->cache_original_filepath = $cache_original_filepath;
}
}

10
core/lib/Thelia/Core/Event/Internal/CartEvent.php Normal file → Executable file
View File

@@ -21,14 +21,12 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event\Internal;
use Thelia\Model\Cart;
class CartEvent extends InternalEvent {
class CartEvent extends InternalEvent
{
public $cart;
public function __construct(Cart $cart)
@@ -36,6 +34,4 @@ class CartEvent extends InternalEvent {
$this->cart = $cart;
}
}
}

16
core/lib/Thelia/Core/Event/Internal/CustomerEvent.php Normal file → Executable file
View File

@@ -23,11 +23,10 @@
namespace Thelia\Core\Event\Internal;
use Thelia\Model\Customer;
class CustomerEvent extends InternalEvent {
class CustomerEvent extends InternalEvent
{
public $customer;
public function __construct(Customer $customer)
@@ -35,4 +34,13 @@ class CustomerEvent extends InternalEvent {
$this->customer = $customer;
}
}
/**
* @return \Thelia\Model\Customer
*/
public function getCustomer()
{
return $this->customer;
}
}

7
core/lib/Thelia/Core/Event/Internal/InternalEvent.php Normal file → Executable file
View File

@@ -23,7 +23,6 @@
namespace Thelia\Core\Event\Internal;
use Symfony\Component\EventDispatcher\Event;
/**
@@ -32,6 +31,6 @@ use Symfony\Component\EventDispatcher\Event;
* Class InternalEvent
* @package Thelia\Core\Event
*/
abstract class InternalEvent extends Event {
}
abstract class InternalEvent extends Event
{
}

View File

@@ -56,6 +56,16 @@ final class TheliaEvents
*/
const CUSTOMER_LOGIN = "action.customer_login";
/**
* sent on customer account creation
*/
const CUSTOMER_CREATEACCOUNT = "action.createCustomer";
/**
* sent on customer account update
*/
const CUSTOMER_UPDATEACCOUNT = "action.modifyCustomer";
/**
* Sent before the logout of the administrator.
*/
@@ -65,8 +75,6 @@ final class TheliaEvents
*/
const ADMIN_LOGIN = "action.admin_login";
/**
* Sent once the customer creation form has been successfully validated, and before customer insertion in the database.
*/
@@ -86,8 +94,6 @@ final class TheliaEvents
*/
const AFTER_CHANGECUSTOMER = "action.after_changecustomer";
/**
* Sent once the category creation form has been successfully validated, and before category insertion in the database.
*/
@@ -112,7 +118,6 @@ final class TheliaEvents
*/
const AFTER_CHANGECATEGORY = "action.after_changecategory";
/**
* sent when a new existing cat id duplicated. This append when current customer is different from current cart
*/
@@ -121,7 +126,7 @@ final class TheliaEvents
/**
* sent when a new item is added to current cart
*/
const AFTER_CARTADDITEM = "cart.addItem";
const AFTER_CARTADDITEM = "cart.after.addItem";
/**
* sent when a cart item is modify
@@ -136,5 +141,18 @@ final class TheliaEvents
/**
* sent on modify article action
*/
const CART_CHANGEARTICLE = "action.changeArticle";
}
const CART_CHANGEITEM = "action.changeArticle";
const CART_DELETEITEM = "action.deleteArticle";
/**
* Sent on image processing
*/
const IMAGE_PROCESS = "action.processImage";
/**
* Sent on cimage cache clear request
*/
const IMAGE_CLEAR_CACHE = "action.clearImageCache";
}

View File

@@ -39,14 +39,15 @@ use Thelia\Core\Template\ParserContext;
*/
class ControllerListener implements EventSubscriberInterface
{
/**
* @var ParserContext the parser context
*/
protected $parserContext;
/**
* @var ParserContext the parser context
*/
protected $parserContext;
public function __construct(ParserContext $parserContext) {
$this->parserContext = $parserContext;
}
public function __construct(ParserContext $parserContext)
{
$this->parserContext = $parserContext;
}
public function onKernelController(FilterControllerEvent $event)
{
@@ -61,7 +62,7 @@ class ControllerListener implements EventSubscriberInterface
// Process form errors
if ($actionEvent->hasErrorForm()) {
$this->parserContext->setErrorForm($actionEvent->getErrorForm());
$this->parserContext->setErrorForm($actionEvent->getErrorForm());
}
}
}

View File

@@ -81,14 +81,12 @@ class ViewListener implements EventSubscriberInterface
} else {
$event->setResponse(new Response($content, $parser->getStatus() ?: 200));
}
}
catch (ResourceNotFoundException $e) {
} catch (ResourceNotFoundException $e) {
$event->setResponse(new Response($e->getMessage(), 404));
}
catch (AuthenticationException $ex) {
} catch (AuthenticationException $ex) {
// Redirect to the login template
$event->setResponse(Redirect::exec(URL::viewUrl($ex->getLoginTemplate())));
// Redirect to the login template
$event->setResponse(Redirect::exec(URL::viewUrl($ex->getLoginTemplate())));
}
}

View File

@@ -23,7 +23,6 @@
namespace Thelia\Core\HttpFoundation;
use Symfony\Component\HttpFoundation\Request as BaseRequest;
use Thelia\Core\Context;
class Request extends BaseRequest
{
@@ -46,6 +45,7 @@ class Request extends BaseRequest
if ('' == $this->getQueryString()) {
$additionalQs = '?'. ltrim($additionalQs, '&');
}
return $uri . $additionalQs;
}
}
}

View File

@@ -120,7 +120,7 @@ class Session extends BaseSession
/**
*
*
* @param \Thelia\Model\Cart $cart
* @param \Thelia\Model\Cart $cart
* @throws \Thelia\Exception\InvalidCartException
*/
protected function verifyValidCart(Cart $cart)
@@ -128,7 +128,7 @@ class Session extends BaseSession
$customer = $this->getCustomerUser();
if ($customer && $cart->getCustomerId() != $customer->getId()) {
throw new InvalidCartException("customer in session and customer_id in cart are not the same");
} else if($customer === null && $cart->getCustomerId() !== null) {
} elseif ($customer === null && $cart->getCustomerId() !== null) {
throw new InvalidCartException("Customer exists in cart and not in session");
}
}

View File

@@ -31,13 +31,14 @@ use Thelia\Core\Security\UserProvider\AdminUserProvider;
use Thelia\Core\Security\Authentication\UsernamePasswordFormAuthenticator;
use Thelia\Form\AdminLogin;
class AdminUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator {
public function __construct(Request $request, AdminLogin $loginForm) {
parent::__construct(
$request,
$loginForm,
new AdminUserProvider()
);
}
}
class AdminUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator
{
public function __construct(Request $request, AdminLogin $loginForm)
{
parent::__construct(
$request,
$loginForm,
new AdminUserProvider()
);
}
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Core\Security\Authentication;
interface AuthenticatorInterface {
/**
* Returns a UserInterface instance, authentified using the authenticator specific method
*/
public function getAuthentifiedUser();
}
interface AuthenticatorInterface
{
/**
* Returns a UserInterface instance, authentified using the authenticator specific method
*/
public function getAuthentifiedUser();
}

View File

@@ -29,16 +29,17 @@ use Thelia\Core\Security\Authentication\UsernamePasswordFormAuthenticator;
use Thelia\Form\CustomerLogin;
use Thelia\Core\Security\UserProvider\CustomerUserProvider;
class CustomerUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator {
public function __construct(Request $request, CustomerLogin $loginForm) {
parent::__construct(
$request,
$loginForm,
new CustomerUserProvider(),
array(
'username_field_name' => 'email'
)
);
}
}
class CustomerUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator
{
public function __construct(Request $request, CustomerLogin $loginForm)
{
parent::__construct(
$request,
$loginForm,
new CustomerUserProvider(),
array(
'username_field_name' => 'email'
)
);
}
}

View File

@@ -32,64 +32,65 @@ use Thelia\Core\Security\Exception\UsernameNotFoundException;
use Symfony\Component\Validator\Exception\ValidatorException;
use Thelia\Form\BaseForm;
class UsernamePasswordFormAuthenticator implements AuthenticatorInterface {
class UsernamePasswordFormAuthenticator implements AuthenticatorInterface
{
protected $request;
protected $loginForm;
protected $userProvider;
protected $options;
protected $request;
protected $loginForm;
protected $userProvider;
protected $options;
protected $baseLoginForm;
protected $baseLoginForm;
public function __construct(Request $request, BaseForm $loginForm, UserProviderInterface $userProvider, array $options = array())
{
$this->request = $request;
$this->baseLoginForm = $loginForm;
$this->loginForm = $this->baseLoginForm->getForm();
$this->userProvider = $userProvider;
public function __construct(Request $request, BaseForm $loginForm, UserProviderInterface $userProvider, array $options = array()) {
$this->request = $request;
$this->baseLoginForm = $loginForm;
$this->loginForm = $this->baseLoginForm->getForm();
$this->userProvider = $userProvider;
$defaults = array(
'required_method' => 'POST',
'username_field_name' => 'username',
'password_field_name' => 'password'
);
$defaults = array(
'required_method' => 'POST',
'username_field_name' => 'username',
'password_field_name' => 'password'
);
$this->options = array_merge($defaults, $options);
$this->options = array_merge($defaults, $options);
$this->loginForm->bind($this->request);
}
$this->loginForm->bind($this->request);
}
/**
* @return string the username value
*/
public function getUsername()
{
return $this->loginForm->get($this->options['username_field_name'])->getData();
}
/**
* @return string the username value
*/
public function getUsername() {
return $this->loginForm->get($this->options['username_field_name'])->getData();
}
/**
* @see \Thelia\Core\Security\Authentication\AuthenticatorInterface::getAuthentifiedUser()
*/
public function getAuthentifiedUser()
{
if ($this->request->isMethod($this->options['required_method'])) {
/**
* @see \Thelia\Core\Security\Authentication\AuthenticatorInterface::getAuthentifiedUser()
*/
public function getAuthentifiedUser() {
if (! $this->loginForm->isValid()) throw new ValidatorException("Form is not valid.");
if ($this->request->isMethod($this->options['required_method'])) {
// Retreive user
$username = $this->getUsername();
$password = $this->loginForm->get($this->options['password_field_name'])->getData();
if (! $this->loginForm->isValid()) throw new ValidatorException("Form is not valid.");
$user = $this->userProvider->getUser($username);
// Retreive user
$username = $this->getUsername();
$password = $this->loginForm->get($this->options['password_field_name'])->getData();
if ($user === null) throw new UsernameNotFoundException(sprintf("Username '%s' was not found.", $username));
$user = $this->userProvider->getUser($username);
// Check user password
$authOk = $user->checkPassword($password) === true;
if ($user === null) throw new UsernameNotFoundException(sprintf("Username '%s' was not found.", $username));
if ($authOk !== true) throw new WrongPasswordException(sprintf("Wrong password for user '%s'.", $username));
return $user;
}
// Check user password
$authOk = $user->checkPassword($password) === true;
if ($authOk !== true) throw new WrongPasswordException(sprintf("Wrong password for user '%s'.", $username));
return $user;
}
throw new \RuntimeException("Invalid method.");
}
}
throw new \RuntimeException("Invalid method.");
}
}

View File

@@ -25,24 +25,26 @@ namespace Thelia\Core\Security\Exception;
class AuthenticationException extends \Exception
{
/**
* @var string The login template name
*/
protected $loginTemplate = "login";
/**
* @var string The login template name
*/
protected $loginTemplate = "login";
/**
* @return string the login template name
*/
public function getLoginTemplate() {
return $this->loginTemplate;
}
/**
* @return string the login template name
*/
public function getLoginTemplate()
{
return $this->loginTemplate;
}
/**
* Set the login template name
*
* @param string $loginPath the login template name
*/
public function setLoginTemplate($loginTemplate) {
$this->loginTemplate = $loginTemplate;
}
/**
* Set the login template name
*
* @param string $loginPath the login template name
*/
public function setLoginTemplate($loginTemplate)
{
$this->loginTemplate = $loginTemplate;
}
}

View File

View File

View File

View File

@@ -39,7 +39,8 @@ class Role implements RoleInterface
return $this->role;
}
public function __toString() {
return $this->role;
public function __toString()
{
return $this->role;
}
}

View File

@@ -32,4 +32,4 @@ interface RoleInterface
* @return string|null A string representation of the role, or null
*/
public function getRole();
}
}

View File

@@ -23,9 +23,6 @@
namespace Thelia\Core\Security;
use Thelia\Core\Security\Authentication\AuthenticationProviderInterface;
use Thelia\Core\Security\Exception\AuthenticationTokenNotFoundException;
use Thelia\Core\Security\Token\TokenInterface;
use Thelia\Core\Security\User\UserInterface;
use Thelia\Core\HttpFoundation\Request;
@@ -34,73 +31,77 @@ use Thelia\Core\HttpFoundation\Request;
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class SecurityContext {
class SecurityContext
{
const CONTEXT_FRONT_OFFICE = 'front';
const CONTEXT_BACK_OFFICE = 'admin';
const CONTEXT_FRONT_OFFICE = 'front';
const CONTEXT_BACK_OFFICE = 'admin';
private $request;
private $context;
private $request;
private $context;
public function __construct(Request $request)
{
$this->request = $request;
public function __construct(Request $request) {
$this->context = null;
}
$this->request = $request;
public function setContext($context)
{
if ($context !== self::CONTEXT_FRONT_OFFICE && $context !== self::CONTEXT_BACK_OFFICE) {
throw new \InvalidArgumentException(sprintf("Invalid or empty context identifier '%s'", $context));
}
$this->context = null;
}
$this->context = $context;
public function setContext($context) {
if ($context !== self::CONTEXT_FRONT_OFFICE && $context !== self::CONTEXT_BACK_OFFICE) {
throw new \InvalidArgumentException(sprintf("Invalid or empty context identifier '%s'", $context));
}
return $this;
}
$this->context = $context;
public function getContext($exception_if_context_undefined = false)
{
if (null === $this->context && $exception_if_context_undefined === true)
throw new \LogicException("No context defined. Please use setContext() first.");
return $this;
}
return $this->context;
}
public function getContext($exception_if_context_undefined = false) {
if (null === $this->context && $exception_if_context_undefined === true)
throw new \LogicException("No context defined. Please use setContext() first.");
private function getSession()
{
$session = $this->request->getSession();
return $this->context;
}
if ($session === null)
throw new \LogicException("No session found.");
private function getSession() {
$session = $this->request->getSession();
if ($session === null)
throw new \LogicException("No session found.");
return $session;
}
return $session;
}
/**
* Gets the currently authenticated user in the current context, or null if none is defined
*
* @return UserInterface|null A UserInterface instance or null if no user is available
*/
public function getUser() {
$context = $this->getContext(true);
public function getUser()
{
$context = $this->getContext(true);
if ($context === self::CONTEXT_FRONT_OFFICE)
$user = $this->getSession()->getCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$user = $this->getSession()->getAdminUser();
else
$user = null;
if ($context === self::CONTEXT_FRONT_OFFICE)
$user = $this->getSession()->getCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$user = $this->getSession()->getAdminUser();
else
$user = null;
return $user;
}
return $user;
}
final public function isAuthenticated()
{
if (null !== $this->getUser()) {
return true;
}
final public function isAuthenticated()
{
if (null !== $this->getUser()) {
return true;
}
return false;
}
return false;
}
/**
* Checks if the current user is allowed
@@ -111,51 +112,51 @@ class SecurityContext {
{
if ($this->isAuthenticated() === true) {
$user = $this->getUser();
$user = $this->getUser();
// Check if user's roles matches required roles
$userRoles = $user->getRoles();
// Check if user's roles matches required roles
$userRoles = $user->getRoles();
$roleFound = false;
$roleFound = false;
foreach($userRoles as $role) {
if (in_array($role, $roles)) {
$roleFound = true;
foreach ($userRoles as $role) {
if (in_array($role, $roles)) {
$roleFound = true;
break;
}
}
break;
}
}
if ($roleFound) {
if ($roleFound) {
if (empty($permissions)) {
return true;
}
if (empty($permissions)) {
return true;
}
// Get permissions from profile
// $userPermissions = $user->getPermissions(); FIXME
// Get permissions from profile
// $userPermissions = $user->getPermissions(); FIXME
// TODO: Finalize permissions system !;
// TODO: Finalize permissions system !;
$userPermissions = array('*'); // FIXME !
$userPermissions = array('*'); // FIXME !
$permissionsFound = true;
$permissionsFound = true;
// User have all permissions ?
if (in_array('*', $userPermissions))
return true;
// User have all permissions ?
if (in_array('*', $userPermissions))
return true;
// Check that user's permissions matches required permissions
foreach($permissions as $permission) {
if (! in_array($permission, $userPermissions)) {
$permissionsFound = false;
// Check that user's permissions matches required permissions
foreach ($permissions as $permission) {
if (! in_array($permission, $userPermissions)) {
$permissionsFound = false;
break;
}
}
break;
}
}
return $permissionsFound;
}
return $permissionsFound;
}
}
return false;
@@ -168,25 +169,26 @@ class SecurityContext {
*/
public function setUser(UserInterface $user)
{
$context = $this->getContext(true);
$context = $this->getContext(true);
$user->eraseCredentials();
$user->eraseCredentials();
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->setCustomerUser($user);
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->setAdminUser($user);
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->setCustomerUser($user);
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->setAdminUser($user);
}
/**
* Clear the user from the security context
*/
public function clear() {
$context = $this->getContext(true);
public function clear()
{
$context = $this->getContext(true);
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->clearCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->clearAdminUser();
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->clearCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->clearAdminUser();
}
}
}

View File

@@ -8,8 +8,8 @@ namespace Thelia\Core\Security\User;
* @author Franck Allimant <franck@cqfdev.fr>
*
*/
interface UserInterface {
interface UserInterface
{
/**
* Return the user unique name
*/
@@ -48,4 +48,4 @@ interface UserInterface {
* @return void
*/
public function eraseCredentials();
}
}

View File

@@ -4,14 +4,14 @@ namespace Thelia\Core\Security\UserProvider;
use Thelia\Model\Admin;
use Thelia\Model\AdminQuery;
class AdminUserProvider implements UserProviderInterface {
public function getUser($key) {
class AdminUserProvider implements UserProviderInterface
{
public function getUser($key)
{
$admin = AdminQuery::create()
->filterByLogin($key)
->findOne();
return $admin;
}
}
}

View File

@@ -1,17 +1,16 @@
<?php
namespace Thelia\Core\Security\UserProvider;
use Thelia\Action\Customer;
use Thelia\Model\CustomerQuery;
class CustomerUserProvider implements UserProviderInterface {
public function getUser($key) {
class CustomerUserProvider implements UserProviderInterface
{
public function getUser($key)
{
$customer = CustomerQuery::create()
->filterByEmail($key)
->findOne();
return $customer;
}
}
}

View File

@@ -2,7 +2,8 @@
namespace Thelia\Core\Security\UserProvider;
interface UserProviderInterface {
interface UserProviderInterface
{
/**
* Returns a UserInterface instance
*
@@ -11,4 +12,3 @@ interface UserProviderInterface {
*/
public function getUser($key);
}
?>

View File

@@ -51,7 +51,6 @@ abstract class BaseLoop
*/
protected $securityContext;
protected $args;
/**
@@ -77,11 +76,11 @@ abstract class BaseLoop
*/
protected function getDefaultArgs()
{
return array(
return array(
Argument::createIntTypeArgument('offset', 0),
Argument::createIntTypeArgument('page'),
Argument::createIntTypeArgument('limit', PHP_INT_MAX),
);
);
}
/**
@@ -93,17 +92,17 @@ abstract class BaseLoop
* @return null
* @throws \InvalidArgumentException if the parameter is unknown or the method name is not supported.
*/
public function __call($name, $arguments) {
public function __call($name, $arguments)
{
if (substr($name, 0, 3) == 'get') {
if (substr($name, 0, 3) == 'get') {
// camelCase to underscore: getNotEmpty -> not_empty
$argName = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", substr($name, 3)));
// camelCase to underscore: getNotEmpty -> not_empty
$argName = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", substr($name, 3)));
return $this->getArg($argName)->getValue();
}
return $this->getArg($argName)->getValue();
}
throw new \InvalidArgumentException(sprintf("Unsupported magic method %s. only getArgname() is supported.", $name));
throw new \InvalidArgumentException(sprintf("Unsupported magic method %s. only getArgname() is supported.", $name));
}
/**
@@ -113,8 +112,8 @@ abstract class BaseLoop
*
* @throws \InvalidArgumentException if somùe argument values are missing, or invalid
*/
public function initializeArgs(array $nameValuePairs) {
public function initializeArgs(array $nameValuePairs)
{
$faultActor = array();
$faultDetails = array();
@@ -127,29 +126,26 @@ abstract class BaseLoop
$value = isset($nameValuePairs[$argument->name]) ? $nameValuePairs[$argument->name] : null;
/* check if mandatory */
if($value === null && $argument->mandatory) {
if ($value === null && $argument->mandatory) {
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('"%s" parameter is missing in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else if($value === '' && !$argument->empty) {
/* check if empty */
} else if ($value === '' && !$argument->empty) {
/* check if empty */
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('"%s" parameter cannot be empty in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else if($value !== null && !$argument->type->isValid($value)) {
/* check type */
} elseif ($value !== null && !$argument->type->isValid($value)) {
/* check type */
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('Invalid value for "%s" argument in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else {
/* set default */
/* did it as last checking for we consider default value is acceptable no matter type or empty restriction */
if($value === null) {
$value = $argument->default;
}
} else {
/* set default */
/* did it as last checking for we consider default value is acceptable no matter type or empty restriction */
if ($value === null) {
$value = $argument->default;
}
$argument->setValue($value);
}
$argument->setValue($value);
}
}
if (!empty($faultActor)) {
@@ -165,16 +161,16 @@ abstract class BaseLoop
* @param string $argumentName the argument name
*
* @throws \InvalidArgumentException if argument is not found in loop argument list
* @return Argument the loop argument.
* @return Argument the loop argument.
*/
public function getArg($argumentName) {
protected function getArg($argumentName)
{
$arg = $this->args->get($argumentName);
$arg = $this->args->get($argumentName);
if ($arg === null)
throw new \InvalidArgumentException("Undefined loop argument '$argumentName'");
if ($arg === null)
throw new \InvalidArgumentException("Undefined loop argument '$argumentName'");
return $arg;
return $arg;
}
/**
@@ -183,11 +179,11 @@ abstract class BaseLoop
* @param string $argumentName the argument name
*
* @throws \InvalidArgumentException if argument is not found in loop argument list
* @return Argument the loop argument.
* @return Argument the loop argument.
*/
public function getArgValue($argumentName) {
return $this->getArg($argumentName)->getValue();
protected function getArgValue($argumentName)
{
return $this->getArg($argumentName)->getValue();
}
/**
@@ -196,9 +192,9 @@ abstract class BaseLoop
*
* @return array|mixed|\PropelModelPager|\PropelObjectCollection
*/
public function search(ModelCriteria $search, &$pagination = null)
protected function search(ModelCriteria $search, &$pagination = null)
{
if($this->getArgValue('page') !== null) {
if ($this->getArgValue('page') !== null) {
return $this->searchWithPagination($search, $pagination);
} else {
return $this->searchWithOffset($search);
@@ -210,9 +206,9 @@ abstract class BaseLoop
*
* @return array|mixed|\PropelObjectCollection
*/
public function searchWithOffset(ModelCriteria $search)
protected function searchWithOffset(ModelCriteria $search)
{
if($this->getArgValue('limit') >= 0) {
if ($this->getArgValue('limit') >= 0) {
$search->limit($this->getArgValue('limit'));
}
$search->offset($this->getArgValue('offset'));
@@ -226,11 +222,11 @@ abstract class BaseLoop
*
* @return array|\PropelModelPager
*/
public function searchWithPagination(ModelCriteria $search, &$pagination)
protected function searchWithPagination(ModelCriteria $search, &$pagination)
{
$pagination = $search->paginate($this->getArgValue('page'), $this->getArgValue('limit'));
if($this->getArgValue('page') > $pagination->getLastPage()) {
if ($this->getArgValue('page') > $pagination->getLastPage()) {
return array();
} else {
return $pagination;

View File

@@ -46,7 +46,7 @@ class LoopResultRow
public function getVars()
{
return array_keys($this->substitution);
return array_keys($this->substitution);
}
}

View File

@@ -26,19 +26,12 @@ namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Loop\Product;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\ProductQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
@@ -86,12 +79,12 @@ class Accessory extends Product
$order = $this->getOrder();
$orderByAccessory = array_search('accessory', $order);
$orderByAccessoryReverse = array_search('accessory_reverse', $order);
if($orderByAccessory !== false) {
if ($orderByAccessory !== false) {
$search->orderByPosition(Criteria::ASC);
$order[$orderByAccessory] = 'given_id';
$this->args->get('order')->setValue( implode(',', $order) );
}
if($orderByAccessoryReverse !== false) {
if ($orderByAccessoryReverse !== false) {
$search->orderByPosition(Criteria::DESC);
$order[$orderByAccessoryReverse] = 'given_id';
$this->args->get('order')->setValue( implode(',', $order) );
@@ -107,7 +100,7 @@ class Accessory extends Product
$receivedIdList = $this->getId();
/* if an Id list is receive, loop will only match accessories from this list */
if($receivedIdList === null) {
if ($receivedIdList === null) {
$this->args->get('id')->setValue( implode(',', $accessoryIdList) );
} else {
$this->args->get('id')->setValue( implode(',', array_intersect($receivedIdList, $accessoryIdList)) );

View File

@@ -30,10 +30,8 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\AddressQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
@@ -77,7 +75,7 @@ class Address extends BaseLoop
{
$search = AddressQuery::create();
$id = $this->getId();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
@@ -87,7 +85,7 @@ class Address extends BaseLoop
if ($customer === 'current') {
$currentCustomer = $this->request->getSession()->getCustomerUser();
if($currentCustomer === null) {
if ($currentCustomer === null) {
return new LoopResult();
} else {
$search->filterByCustomerId($currentCustomer->getId(), Criteria::EQUAL);
@@ -100,7 +98,7 @@ class Address extends BaseLoop
if ($default === true) {
$search->filterByIsDefault(1, Criteria::EQUAL);
} elseif($default === false) {
} elseif ($default === false) {
$search->filterByIsDefault(1, Criteria::NOT_EQUAL);
}
@@ -138,4 +136,4 @@ class Address extends BaseLoop
return $loopResult;
}
}
}

View File

@@ -51,12 +51,14 @@ class Argument
$this->setValue($value);
}
public function getValue() {
return $this->type->getFormattedValue($this->value);
public function getValue()
{
return $this->type->getFormattedValue($this->value);
}
public function setValue($value) {
$this->value = $value === null ? null : (string)$value;
public function setValue($value)
{
$this->value = $value === null ? null : (string) $value;
}
public static function createAnyTypeArgument($name, $default=null, $mandatory=false, $empty=true)
@@ -113,15 +115,15 @@ class Argument
public static function createBooleanOrBothTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\BooleanOrBothType()
),
$default,
$mandatory,
$empty
);
return new Argument(
$name,
new TypeCollection(
new Type\BooleanOrBothType()
),
$default,
$mandatory,
$empty
);
}
public static function createIntListTypeArgument($name, $default=null, $mandatory=false, $empty=true)

View File

@@ -37,12 +37,14 @@ class ArgumentCollection implements \Iterator
$this->addArguments(func_get_args(), true);
}
public function hasKey($key) {
return isset($this->arguments[$key]);
public function hasKey($key)
{
return isset($this->arguments[$key]);
}
public function get($key) {
return $this->hasKey($key) ? $this->arguments[$key] : null;
public function get($key)
{
return $this->hasKey($key) ? $this->arguments[$key] : null;
}
public function isEmpty()
@@ -51,14 +53,14 @@ class ArgumentCollection implements \Iterator
}
/**
* @param array $argumentList
* @param $force
* @param array $argumentList
* @param $force
*
* @return ArgumentCollection
*/
public function addArguments(array $argumentList, $force = true)
{
foreach($argumentList as $argument) {
foreach ($argumentList as $argument) {
$this->addArgument($argument, $force);
}
@@ -73,7 +75,7 @@ class ArgumentCollection implements \Iterator
*/
public function addArgument(Argument $argument, $force = true)
{
if(isset($this->arguments[$argument->name]) && ! $force) {
if (isset($this->arguments[$argument->name]) && ! $force) {
return $this;
}

View File

@@ -30,11 +30,6 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
*
* @package Thelia\Core\Template\Loop
@@ -46,24 +41,24 @@ class Auth extends BaseLoop
public function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createAnyTypeArgument('roles', null, true),
Argument::createAnyTypeArgument('permissions'),
Argument::createAnyTypeArgument('context', 'front', false)
Argument::createAnyTypeArgument('roles', null, true),
Argument::createAnyTypeArgument('permissions'),
Argument::createAnyTypeArgument('context', 'front', false)
);
}
private function _explode($commaSeparatedValues)
{
$array = explode(',', $commaSeparatedValues);
$array = explode(',', $commaSeparatedValues);
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
return array();
return array();
}
/**
@@ -73,25 +68,24 @@ class Auth extends BaseLoop
*/
public function exec(&$pagination)
{
$context = $this->getContext();
$roles = $this->_explode($this->getRoles());
$permissions = $this->_explode($this->getPermissions());
$context = $this->getContext();
$roles = $this->_explode($this->getRoles());
$permissions = $this->_explode($this->getPermissions());
$loopResult = new LoopResult();
$loopResult = new LoopResult();
try {
$this->securityContext->setContext($context);
try {
$this->securityContext->setContext($context);
if (true === $this->securityContext->isGranted($roles, $permissions == null ? array() : $permissions)) {
if (true === $this->securityContext->isGranted($roles, $permissions == null ? array() : $permissions)) {
// Create an empty row: loop is no longer empty :)
$loopResult->addRow(new LoopResultRow());
}
}
catch (\Exception $ex) {
// Not granted, loop is empty
}
// Create an empty row: loop is no longer empty :)
$loopResult->addRow(new LoopResultRow());
}
} catch (\Exception $ex) {
// Not granted, loop is empty
}
return $loopResult;
return $loopResult;
}
}
}

10
core/lib/Thelia/Core/Template/Loop/Cart.php Normal file → Executable file
View File

@@ -9,13 +9,13 @@
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
class Cart extends BaseLoop {
class Cart extends BaseLoop
{
use \Thelia\Cart\CartTrait;
/**
*
@@ -74,11 +74,10 @@ class Cart extends BaseLoop {
$result = new LoopResult();
$cart = $this->getCart($this->request);
if($cart === null) {
if ($cart === null) {
return $result;
}
$cartItems = $cart->getCartItems();
foreach ($cartItems as $cartItem) {
@@ -99,5 +98,4 @@ class Cart extends BaseLoop {
return $result;
}
}
}

67
core/lib/Thelia/Core/Template/Loop/CategoryPath.php Normal file → Executable file
View File

@@ -23,18 +23,14 @@
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Type\BooleanOrBothType;
@@ -69,7 +65,7 @@ class CategoryPath extends BaseLoop
Argument::createIntTypeArgument('category', null, true),
Argument::createIntTypeArgument('depth'),
Argument::createIntTypeArgument('level'),
Argument::createBooleanOrBothTypeArgument('visible', true, false)
Argument::createBooleanOrBothTypeArgument('visible', true, false)
);
}
@@ -80,50 +76,49 @@ class CategoryPath extends BaseLoop
*/
public function exec(&$pagination)
{
$id = $this->getCategory();
$visible = $this->getVisible();
$id = $this->getCategory();
$visible = $this->getVisible();
$search = CategoryQuery::create();
$search->filterById($id);
if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible);
$search->filterById($id);
if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible);
$results = array();
$results = array();
$ids = array();
$ids = array();
do {
$category = $search->findOne();
do {
$category = $search->findOne();
if ($category != null) {
if ($category != null) {
$loopResultRow = new LoopResultRow();
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("TITLE",$category->getTitle())
->set("URL", $category->getUrl())
->set("ID", $category->getId())
;
$loopResultRow
->set("TITLE",$category->getTitle())
->set("URL", $category->getUrl())
->set("ID", $category->getId())
;
$results[] = $loopResultRow;
$results[] = $loopResultRow;
$parent = $category->getParent();
$parent = $category->getParent();
if ($parent > 0) {
if ($parent > 0) {
// Prevent circular refererences
if (in_array($parent, $ids)) {
throw new \LogicException(sprintf("Circular reference detected in category ID=%d hierarchy (category ID=%d appears more than one times in path)", $id, $parent));
}
// Prevent circular refererences
if (in_array($parent, $ids)) {
throw new \LogicException(sprintf("Circular reference detected in category ID=%d hierarchy (category ID=%d appears more than one times in path)", $id, $parent));
}
$ids[] = $parent;
$ids[] = $parent;
$search = CategoryQuery::create();
$search->filterById($parent);
if ($visible == true) $search->filterByVisible($visible);
}
}
}
while ($category != null && $parent > 0);
$search = CategoryQuery::create();
$search->filterById($parent);
if ($visible == true) $search->filterByVisible($visible);
}
}
} while ($category != null && $parent > 0);
// Reverse list and build the final result
$results = array_reverse($results);
@@ -134,4 +129,4 @@ class CategoryPath extends BaseLoop
return $loopResult;
}
}
}

67
core/lib/Thelia/Core/Template/Loop/CategoryTree.php Normal file → Executable file
View File

@@ -30,11 +30,8 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Type\BooleanOrBothType;
@@ -59,45 +56,45 @@ class CategoryTree extends BaseLoop
return new ArgumentCollection(
Argument::createIntTypeArgument('category', null, true),
Argument::createIntTypeArgument('depth', PHP_INT_MAX),
Argument::createBooleanOrBothTypeArgument('visible', true, false),
Argument::createIntListTypeArgument('exclude', array())
Argument::createBooleanOrBothTypeArgument('visible', true, false),
Argument::createIntListTypeArgument('exclude', array())
);
}
// changement de rubrique
protected function buildCategoryTree($parent, $visible, $level, $max_level, array $exclude, LoopResult &$loopResult) {
protected function buildCategoryTree($parent, $visible, $level, $max_level, array $exclude, LoopResult &$loopResult)
{
if ($level > $max_level) return;
if ($level > $max_level) return;
$search = CategoryQuery::create();
$search = CategoryQuery::create();
$search->filterByParent($parent);
$search->filterByParent($parent);
if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible);
if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible);
$search->filterById($exclude, Criteria::NOT_IN);
$search->filterById($exclude, Criteria::NOT_IN);
$search->orderByPosition(Criteria::ASC);
$search->orderByPosition(Criteria::ASC);
$results = $search->find();
$results = $search->find();
foreach ($results as $result) {
foreach($results as $result) {
$loopResultRow = new LoopResultRow();
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("ID", $result->getId())
->set("TITLE",$result->getTitle())
->set("PARENT", $result->getParent())
->set("URL", $result->getUrl())
->set("VISIBLE", $result->getVisible() ? "1" : "0")
->set("LEVEL", $level)
;
$loopResultRow
->set("ID", $result->getId())
->set("TITLE",$result->getTitle())
->set("PARENT", $result->getParent())
->set("URL", $result->getUrl())
->set("VISIBLE", $result->getVisible() ? "1" : "0")
->set("LEVEL", $level)
;
$loopResult->addRow($loopResultRow);
$loopResult->addRow($loopResultRow);
$this->buildCategoryTree($result->getId(), $visible, 1 + $level, $max_level, $exclude, $loopResult);
}
$this->buildCategoryTree($result->getId(), $visible, 1 + $level, $max_level, $exclude, $loopResult);
}
}
/**
@@ -107,17 +104,17 @@ class CategoryTree extends BaseLoop
*/
public function exec(&$pagination)
{
$id = $this->getCategory();
$depth = $this->getDepth();
$visible = $this->getVisible();
$exclude = $this->getExclude();
$id = $this->getCategory();
$depth = $this->getDepth();
$visible = $this->getVisible();
$exclude = $this->getExclude();
//echo "exclude=".print_r($exclude);
//echo "exclude=".print_r($exclude);
$loopResult = new LoopResult();
$loopResult = new LoopResult();
$this->buildCategoryTree($id, $visible, 0, $depth, $exclude, $loopResult);
$this->buildCategoryTree($id, $visible, 0, $depth, $exclude, $loopResult);
return $loopResult;
}
}
}

View File

@@ -24,16 +24,13 @@
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureContentQuery;
use Thelia\Model\FolderQuery;
use Thelia\Model\Map\ContentTableMap;
use Thelia\Model\ContentFolderQuery;
@@ -69,7 +66,7 @@ class Content extends BaseLoop
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse', 'random', 'given_id'))
new Type\EnumListType(array('alpha', 'alpha-reverse', 'manual', 'manual_reverse', 'random', 'given_id'))
),
'alpha'
),
@@ -101,8 +98,8 @@ class Content extends BaseLoop
$depth = $this->getDepth();
if(null !== $depth) {
foreach(FolderQuery::findAllChild($folder, $depth) as $subFolder) {
if (null !== $depth) {
foreach (FolderQuery::findAllChild($folder, $depth) as $subFolder) {
$folders->prepend($subFolder);
}
}
@@ -117,7 +114,7 @@ class Content extends BaseLoop
if ($current === true) {
$search->filterById($this->request->get("content_id"));
} elseif($current === false) {
} elseif ($current === false) {
$search->filterById($this->request->get("content_id"), Criteria::NOT_IN);
}
@@ -134,7 +131,7 @@ class Content extends BaseLoop
)->find(),
Criteria::IN
);
} elseif($current_folder === false) {
} elseif ($current_folder === false) {
$search->filterByFolder(
FolderQuery::create()->filterByContent(
ContentFolderQuery::create()->filterByContentId(
@@ -153,12 +150,12 @@ class Content extends BaseLoop
$orders = $this->getOrder();
foreach($orders as $order) {
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\ContentI18nTableMap::TITLE);
break;
case "alpha_reverse":
case "alpha-reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\ContentI18nTableMap::TITLE);
break;
case "manual":
@@ -174,7 +171,7 @@ class Content extends BaseLoop
case "given_id":
if(null === $id)
throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
foreach($id as $singleId) {
foreach ($id as $singleId) {
$givenIdMatched = 'given_id_matched_' . $singleId;
$search->withColumn(ContentTableMap::ID . "='$singleId'", $givenIdMatched);
$search->orderBy($givenIdMatched, Criteria::DESC);
@@ -223,12 +220,12 @@ class Content extends BaseLoop
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $content->getId())
->set("TITLE",$content->getTitle())
->set("CHAPO", $content->getChapo())
->set("DESCRIPTION", $content->getDescription())
->set("POSTSCRIPTUM", $content->getPostscriptum())
->set("POSITION", $content->getPosition())
;
->set("TITLE",$content->getTitle())
->set("CHAPO", $content->getChapo())
->set("DESCRIPTION", $content->getDescription())
->set("POSTSCRIPTUM", $content->getPostscriptum())
->set("POSITION", $content->getPosition())
;
$loopResult->addRow($loopResultRow);
}

View File

@@ -30,12 +30,9 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CountryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
@@ -71,7 +68,7 @@ class Country extends BaseLoop
{
$search = CountryQuery::create();
$id = $this->getId();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
@@ -131,4 +128,4 @@ class Country extends BaseLoop
return $loopResult;
}
}
}

View File

@@ -30,10 +30,8 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CustomerQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
@@ -76,18 +74,18 @@ class Customer extends BaseLoop
{
$search = CustomerQuery::create();
$current = $this->getCurrent();
$current = $this->getCurrent();
if ($current === true) {
$currentCustomer = $this->request->getSession()->getCustomerUser();
if($currentCustomer === null) {
if ($currentCustomer === null) {
return new LoopResult();
} else {
$search->filterById($currentCustomer->getId(), Criteria::EQUAL);
}
}
$id = $this->getId();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
@@ -103,7 +101,7 @@ class Customer extends BaseLoop
if ($reseller === true) {
$search->filterByReseller(1, Criteria::EQUAL);
} else if($reseller === false) {
} elseif ($reseller === false) {
$search->filterByReseller(0, Criteria::EQUAL);
}
@@ -134,4 +132,4 @@ class Customer extends BaseLoop
return $loopResult;
}
}
}

View File

@@ -24,14 +24,12 @@
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\CategoryQuery;
use Thelia\Model\Base\ProductCategoryQuery;
@@ -67,7 +65,7 @@ class Feature extends BaseLoop
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse'))
new Type\EnumListType(array('alpha', 'alpha-reverse', 'manual', 'manual_reverse'))
),
'manual'
)
@@ -102,17 +100,17 @@ class Feature extends BaseLoop
$product = $this->getProduct();
$category = $this->getCategory();
if(null !== $product) {
if (null !== $product) {
$productCategories = ProductCategoryQuery::create()->select(array(ProductCategoryTableMap::CATEGORY_ID))->filterByProductId($product, Criteria::IN)->find()->getData();
if(null === $category) {
if (null === $category) {
$category = $productCategories;
} else {
$category = array_merge($category, $productCategories);
}
}
if(null !== $category) {
if (null !== $category) {
$search->filterByCategory(
CategoryQuery::create()->filterById($category)->find(),
Criteria::IN
@@ -121,12 +119,12 @@ class Feature extends BaseLoop
$orders = $this->getOrder();
foreach($orders as $order) {
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "alpha_reverse":
case "alpha-reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "manual":
@@ -166,4 +164,4 @@ class Feature extends BaseLoop
return $loopResult;
}
}
}

View File

@@ -24,14 +24,12 @@
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureAvQuery;
use Thelia\Model\ConfigQuery;
@@ -60,7 +58,7 @@ class FeatureAvailability extends BaseLoop
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse'))
new Type\EnumListType(array('alpha', 'alpha-reverse', 'manual', 'manual_reverse'))
),
'manual'
)
@@ -90,18 +88,18 @@ class FeatureAvailability extends BaseLoop
$feature = $this->getFeature();
if(null !== $feature) {
if (null !== $feature) {
$search->filterByFeatureId($feature, Criteria::IN);
}
$orders = $this->getOrder();
foreach($orders as $order) {
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FeatureAvI18nTableMap::TITLE);
break;
case "alpha_reverse":
case "alpha-reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FeatureAvI18nTableMap::TITLE);
break;
case "manual":
@@ -141,4 +139,4 @@ class FeatureAvailability extends BaseLoop
return $loopResult;
}
}
}

View File

@@ -30,9 +30,6 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
@@ -44,8 +41,8 @@ class Feed extends BaseLoop
public function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createAnyTypeArgument('url', null, true),
Argument::createIntTypeArgument('timeout', 10)
Argument::createAnyTypeArgument('url', null, true),
Argument::createIntTypeArgument('timeout', 10)
);
}
@@ -56,13 +53,13 @@ class Feed extends BaseLoop
*/
public function exec(&$pagination)
{
$cachedir = THELIA_ROOT . 'cache/feeds';
$cachedir = THELIA_ROOT . 'cache/feeds';
if (! is_dir($cachedir)) {
if (! mkdir($cachedir)) {
throw new \Exception(sprintf("Failed to create cache directory '%s'", $cachedir));
}
}
if (! is_dir($cachedir)) {
if (! mkdir($cachedir)) {
throw new \Exception(sprintf("Failed to create cache directory '%s'", $cachedir));
}
}
$feed = new \SimplePie($this->getUrl(), THELIA_ROOT . 'cache/feeds');
@@ -78,29 +75,29 @@ class Feed extends BaseLoop
$loopResult = new LoopResult();
for($idx = 0; $idx < $limit; $idx++) {
for ($idx = 0; $idx < $limit; $idx++) {
$item = $items[$idx];
$item = $items[$idx];
$link = $item->get_permalink();
$link = $item->get_permalink();
$title = $item->get_title();
$author = $item->get_author();
$description = $item->get_description();
$title = $item->get_title();
$author = $item->get_author();
$description = $item->get_description();
$date = $item->get_date('d/m/Y');
$date = $item->get_date('d/m/Y');
$loopResultRow = new LoopResultRow();
$loopResultRow = new LoopResultRow();
$loopResultRow->set("URL", $item->get_permalink());
$loopResultRow->set("TITLE", $item->get_title());
$loopResultRow->set("AUTHOR", $item->get_author());
$loopResultRow->set("DESCRIPTION", $item->get_description());
$loopResultRow->set("DATE", $item->get_date('d/m/Y')); // FIXME - date format should be an intl parameter
$loopResultRow->set("URL", $item->get_permalink());
$loopResultRow->set("TITLE", $item->get_title());
$loopResultRow->set("AUTHOR", $item->get_author());
$loopResultRow->set("DESCRIPTION", $item->get_description());
$loopResultRow->set("DATE", $item->get_date('d/m/Y')); // FIXME - date format should be an intl parameter
$loopResult->addRow($loopResultRow);
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}
}

View File

@@ -0,0 +1,336 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Event\ImageEvent;
use Thelia\Model\CategoryImageQuery;
use Thelia\Model\ProductImageQuery;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Type\TypeCollection;
use Thelia\Type\EnumListType;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Type\EnumType;
use Thelia\Log\Tlog;
/**
* The image loop
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class Image extends BaseLoop
{
/**
* @var array Possible image sources
*/
protected $possible_sources = array('category', 'product', 'folder', 'content');
/**
* Dynamically create the search query, and set the proper filter and order
*
* @param string $source a valid source identifier (@see $possible_sources)
* @param int $object_id the source object ID
* @return ModelCriteria the propel Query object
*/
protected function createSearchQuery($source, $object_id) {
$object = ucfirst($source);
$queryClass = sprintf("\Thelia\Model\%sImageQuery", $object);
$filterMethod = sprintf("filterBy%sId", $object);
$mapClass = sprintf("\Thelia\Model\Map\%sI18nTableMap", $object);
// xxxImageQuery::create()
$method = new \ReflectionMethod($queryClass, 'create');
$search = $method->invoke(null); // Static !
// $query->filterByXXX(id)
$method = new \ReflectionMethod($queryClass, $filterMethod);
$method->invoke($search, $object_id);
$map = new \ReflectionClass($mapClass);
$title_map = $map->getConstant('TITLE');
$orders = $this->getOrder();
// Results ordering
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn($title_map);
break;
case "alpha-reverse":
$search->addDescendingOrderByColumn($title_map);
break;
case "manual-reverse":
$search->orderByPosition(Criteria::DESC);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
break;
}
}
return $search;
}
/**
* Dynamically create the search query, and set the proper filter and order
*
* @param string $object_type (returned) the a valid source identifier (@see $possible_sources)
* @param string $object_id (returned) the ID of the source object
* @return ModelCriteria the propel Query object
*/
protected function getSearchQuery(&$object_type, &$object_id) {
$search = null;
// Check form source="product" source_id="123" style arguments
$source = $this->getSource();
if (! is_null($source)) {
$source_id = $this->getSourceId();
// echo "source = ".$this->getSource().", id=".$id."<br />";
if (is_null($source_id)) {
throw new \InvalidArgumentException("'source_id' argument cannot be null if 'source' argument is specified.");
}
$search = $this->createSearchQuery($source, $source_id);
$object_type = $source;
$object_id = $source_id;
}
else {
// Check for product="id" folder="id", etc. style arguments
foreach($this->possible_sources as $source) {
$argValue = intval($this->getArgValue($source));
if ($argValue > 0) {
$search = $this->createSearchQuery($source, $argValue);
$object_type = $source;
$object_id = $argValue;
break;
}
}
}
if ($search == null)
throw new \InvalidArgumentException(sprintf("Unable to find image source. Valid sources are %s", implode(',', $this->possible_sources)));
return $search;
}
/**
* @param unknown $pagination
*/
public function exec(&$pagination)
{
// Select the proper query to use, and get the object type
$object_type = $object_id = null;
$search = $this->getSearchQuery($object_type, $object_id);
$id = $this->getId();
if (! is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$exclude = $this->getExclude();
if (!is_null($exclude))
$search->filterById($exclude, Criteria::NOT_IN);
// Create image processing event
$event = new ImageEvent($this->request);
// Prepare tranformations
$width = $this->getWidth();
$height = $this->getHeight();
$rotation = $this->getRotation();
$background_color = $this->getBackgroundColor();
$quality = $this->getQuality();
$effects = $this->getEffects();
$effects = $this->getEffects();
if (! is_null($effects)) {
$effects = explode(',', $effects);
}
switch($this->getResizeMode()) {
case 'crop' :
$resize_mode = \Thelia\Action\Image::EXACT_RATIO_WITH_CROP;
break;
case 'borders' :
$resize_mode = \Thelia\Action\Image::EXACT_RATIO_WITH_BORDERS;
break;
case 'none' :
default:
$resize_mode = \Thelia\Action\Image::KEEP_IMAGE_RATIO;
}
/**
* \Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$results = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($results as $result) {
// Create image processing event
$event = new ImageEvent($this->request);
// Setup required transformations
if (! is_null($width)) $event->setWidth($width);
if (! is_null($height)) $event->setHeight($height);
$event->setResizeMode($resize_mode);
if (! is_null($rotation)) $event->setRotation($rotation);
if (! is_null($background_color)) $event->setBackgroundColor($background_color);
if (! is_null($quality)) $event->setQuality($quality);
if (! is_null($effects)) $event->setEffects($effects);
// Put source image file path
$source_filepath = sprintf("%s%s/%s/%s",
THELIA_ROOT,
ConfigQuery::read('documents_library_path', 'local/media/images'),
$object_type,
$result->getFile()
);
$event->setSourceFilepath($source_filepath);
$event->setCacheSubdirectory($object_type);
try {
// Dispatch image processing event
$this->dispatcher->dispatch(TheliaEvents::IMAGE_PROCESS, $event);
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("ID", $result->getId())
->set("IMAGE_URL", $event->getFileUrl())
->set("ORIGINAL_IMAGE_URL", $event->getOriginalFileUrl())
->set("IMAGE_PATH", $event->getCacheFilepath())
->set("ORIGINAL_IMAGE_PATH", $source_filepath)
->set("TITLE", $result->getTitle())
->set("CHAPO", $result->getChapo())
->set("DESCRIPTION", $result->getDescription())
->set("POSTSCRIPTUM", $result->getPostscriptum())
->set("POSITION", $result->getPosition())
->set("OBJECT_TYPE", $object_type)
->set("OBJECT_ID", $object_id)
;
$loopResult->addRow($loopResultRow);
}
catch (\Exception $ex) {
// Ignore the result and log an error
Tlog::getInstance()->addError("Failed to process image in image loop: ", $this->args);
}
}
return $loopResult;
}
/**
* @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection
*/
protected function getArgDefinitions()
{
$collection = new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('exclude'),
new Argument(
'order',
new TypeCollection(
new EnumListType(array('alpha', 'alpha-reverse', 'manual', 'manual-reverse', 'random'))
),
'manual'
),
Argument::createIntTypeArgument('width'),
Argument::createIntTypeArgument('height'),
Argument::createIntTypeArgument('rotation', 0),
Argument::createAnyTypeArgument('background_color'),
Argument::createIntTypeArgument('quality'),
new Argument(
'resize_mode',
new TypeCollection(
new EnumType(array('crop', 'borders', 'none'))
),
'none'
),
Argument::createAnyTypeArgument('effects'),
Argument::createIntTypeArgument('category'),
Argument::createIntTypeArgument('product'),
Argument::createIntTypeArgument('folder'),
Argument::createIntTypeArgument('content'),
new Argument(
'source',
new TypeCollection(
new EnumType($this->possible_sources)
)
),
Argument::createIntTypeArgument('source_id'),
Argument::createIntListTypeArgument('lang')
);
// Add possible image sources
foreach($this->possible_sources as $source) {
$collection->addArgument(Argument::createIntTypeArgument($source));
}
return $collection;
}
}

44
core/lib/Thelia/Core/Template/Loop/Lang.php Normal file → Executable file
View File

@@ -30,8 +30,6 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Model\LangQuery;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
@@ -66,20 +64,20 @@ class Lang extends BaseLoop
*/
public function exec(&$pagination)
{
$id = $this->getId();
$exclude = $this->getExclude();
$default_only = $this->getDefaultOnly();
$id = $this->getId();
$exclude = $this->getExclude();
$default_only = $this->getDefaultOnly();
$search = LangQuery::create();
if (! is_null($id))
$search->filterById($id);
$search->filterById($id);
if ($default_only)
$search->filterByByDefault(true);
$search->filterByByDefault(true);
if (! is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
$search->filterById($exclude, Criteria::NOT_IN);
}
$search->orderByPosition(Criteria::ASC);
@@ -90,25 +88,25 @@ class Lang extends BaseLoop
foreach ($results as $result) {
$loopResultRow = new LoopResultRow();
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("ID", $result->getId())
->set("TITLE",$result->getTitle())
->set("CODE", $result->getCode())
->set("LOCALE", $result->getLocale())
->set("URL", $result->getUrl())
->set("IS_DEFAULT", $result->getByDefault())
->set("URL", $result->getUrl())
->set("POSITION", $result->getPosition())
$loopResultRow
->set("ID", $result->getId())
->set("TITLE",$result->getTitle())
->set("CODE", $result->getCode())
->set("LOCALE", $result->getLocale())
->set("URL", $result->getUrl())
->set("IS_DEFAULT", $result->getByDefault())
->set("URL", $result->getUrl())
->set("POSITION", $result->getPosition())
->set("CREATE_DATE", $result->getCreatedAt())
->set("UPDATE_DATE", $result->getUpdatedAt())
;
->set("CREATE_DATE", $result->getCreatedAt())
->set("UPDATE_DATE", $result->getUpdatedAt())
;
$loopResult->addRow($loopResultRow);
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}
}

8
core/lib/Thelia/Core/Template/Loop/Order.php Normal file → Executable file
View File

@@ -25,14 +25,10 @@ namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
@@ -53,7 +49,7 @@ class Order extends BaseLoop
*/
public function exec(&$pagination)
{
// TODO : a coder !
// TODO : a coder !
return new LoopResult();
}
}
}

8
core/lib/Thelia/Core/Template/Loop/OrderStatus.php Normal file → Executable file
View File

@@ -25,14 +25,10 @@ namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
@@ -53,7 +49,7 @@ class OrderStatus extends BaseLoop
*/
public function exec(&$pagination)
{
// TODO : a coder !
// TODO : a coder !
return new LoopResult();
}
}
}

View File

@@ -30,12 +30,9 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CustomerTitleQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
@@ -67,7 +64,7 @@ class Title extends BaseLoop
{
$search = CustomerTitleQuery::create();
$id = $this->getId();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
@@ -102,4 +99,4 @@ class Title extends BaseLoop
return $loopResult;
}
}
}

95
core/lib/Thelia/Core/Template/ParserContext.php Normal file → Executable file
View File

@@ -35,62 +35,67 @@ use Thelia\Form\BaseForm;
*/
class ParserContext implements \IteratorAggregate
{
private $store = array();
private $store = array();
public function __construct(Request $request) {
public function __construct(Request $request)
{
// Setup basic variables
$this
->set('BASE_URL' , ConfigQuery::read('base_url', '/'))
->set('INDEX_PAGE' , URL::getIndexPage())
->set('RETURN_TO_URL' , URL::absoluteUrl($request->getSession()->getReturnToUrl()))
->set('THELIA_VERSION' , ConfigQuery::read('thelia_version', 'undefined'))
;
}
// Setup basic variables
$this
->set('BASE_URL' , ConfigQuery::read('base_url', '/'))
->set('INDEX_PAGE' , URL::getIndexPage())
->set('RETURN_TO_URL' , URL::absoluteUrl($request->getSession()->getReturnToUrl()))
->set('THELIA_VERSION' , ConfigQuery::read('thelia_version', 'undefined'))
;
}
// -- Error form -----------------------------------------------------------
// -- Error form -----------------------------------------------------------
/**
* @param BaseForm $form the errored form
*/
public function setErrorForm(BaseForm $form)
{
$this->set('error_form', $form);
}
/**
* @param BaseForm $form the errored form
*/
public function setErrorForm(BaseForm $form)
{
$this->set('error_form', $form);
}
public function setGeneralError($error)
{
$this->set('general_error', $error);
}
public function getErrorForm()
{
return $this->get('error_form', null);
}
public function getErrorForm()
{
return $this->get('error_form', null);
}
public function clearErrorForm()
{
return $this->remove('error_form');
}
public function clearErrorForm()
{
return $this->remove('error_form');
}
// -- Internal table manipulation ------------------------------------------
// -- Internal table manipulation ------------------------------------------
public function set($name, $value)
{
$this->store[$name] = $value;
public function set($name, $value)
{
$this->store[$name] = $value;
return $this;
}
return $this;
}
public function remove($name)
{
unset($this->store[$name]);
public function remove($name)
{
unset($this->store[$name]);
return $this;
}
return $this;
}
public function get($name, $default = null)
{
return isset($this->store[$name]) ? $this->store[$name] : $default;
}
public function get($name, $default = null)
{
return isset($this->store[$name]) ? $this->store[$name] : $default;
}
public function getIterator()
{
return new \ArrayIterator( $this->store );
}
public function getIterator()
{
return new \ArrayIterator( $this->store );
}
}

View File

@@ -32,69 +32,67 @@ namespace Thelia\Core\Template\Smarty;
*/
abstract class AbstractSmartyPlugin
{
/**
* Explode a comma separated list in a array, trimming all array elements
*
* @param unknown $commaSeparatedValues
* @return multitype:
*/
protected function _explode($commaSeparatedValues)
{
$array = explode(',', $commaSeparatedValues);
/**
* Explode a comma separated list in a array, trimming all array elements
*
* @param unknown $commaSeparatedValues
* @return multitype:
*/
protected function _explode($commaSeparatedValues)
{
$array = explode(',', $commaSeparatedValues);
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
return array();
}
return array();
}
/**
* Get a function or block parameter value, and normalize it, trimming balnks and
* making it lowercase
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getNormalizedParam($params, $name, $default = null)
{
$value = $this->getParam($params, $name, $default);
/**
* Get a function or block parameter value, and normalize it, trimming balnks and
* making it lowercase
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getNormalizedParam($params, $name, $default = null)
{
$value = $this->getParam($params, $name, $default);
if (is_string($value)) $value = strtolower(trim($value));
if (is_string($value)) $value = strtolower(trim($value));
return $value;
}
return $value;
}
/**
* Get a function or block parameter value
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getParam($params, $name, $default = null)
{
if (is_array($name)) {
foreach ($name as $test) {
if (isset($params[$test])) {
return $params[$test];
}
}
} elseif (isset($params[$name])) {
return $params[$name];
}
/**
* Get a function or block parameter value
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getParam($params, $name, $default = null)
{
if (is_array($name)) {
foreach($name as $test) {
if (isset($params[$test])) {
return $params[$test];
}
}
}
else if (isset($params[$name])) {
return $params[$name];
}
return $default;
}
return $default;
}
/**
* @return an array of SmartyPluginDescriptor
*/
public abstract function getPluginDescriptors();
abstract public function getPluginDescriptors();
}

View File

@@ -24,7 +24,6 @@
namespace Thelia\Core\Template\Smarty\Assets;
use Thelia\Core\Template\Assets\AsseticHelper;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\URL;
class SmartyAssetsManager
@@ -50,7 +49,8 @@ class SmartyAssetsManager
$this->assetic_manager = new AsseticHelper();
}
public function computeAssetUrl($assetType, $params, \Smarty_Internal_Template $template) {
public function computeAssetUrl($assetType, $params, \Smarty_Internal_Template $template)
{
$file = $params['file'];
$filters = isset($params['filters']) ? $params['filters'] : '';
$debug = isset($params['debug']) ? trim(strtolower($params['debug'])) == 'true' : false;
@@ -70,7 +70,7 @@ class SmartyAssetsManager
$url = $this->assetic_manager->asseticize(
$asset_dir.'/'.$asset_file,
$this->web_root."/".$this->path_relative_to_web_root,
URL::absoluteUrl($this->path_relative_to_web_root, array(), true /* path only */),
URL::absoluteUrl($this->path_relative_to_web_root, null, URL::PATH_TO_FILE /* path only */),
$assetType,
$filters,
$debug
@@ -83,7 +83,7 @@ class SmartyAssetsManager
{
// Opening tag (first call only)
if ($repeat) {
$url = $this->computeAssetUrl($assetType, $params, $template);
$url = $this->computeAssetUrl($assetType, $params, $template);
$template->assign('asset_url', $url);

View File

@@ -58,7 +58,7 @@ class Assetic extends AbstractSmartyPlugin
public function functionImage($params, \Smarty_Internal_Template $template)
{
return $this->assetManager->computeAssetUrl(SmartyAssetsManager::ASSET_TYPE_AUTO, $params, $template);
return $this->assetManager->computeAssetUrl(SmartyAssetsManager::ASSET_TYPE_AUTO, $params, $template);
}
/**

View File

@@ -35,24 +35,24 @@ use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
*/
class DataAccessFunctions extends AbstractSmartyPlugin
{
private $securityContext;
protected $parserContext;
private $securityContext;
protected $parserContext;
public function __construct(SecurityContext $securityContext, ParserContext $parserContext)
{
$this->securityContext = $securityContext;
}
public function __construct(SecurityContext $securityContext, ParserContext $parserContext)
{
$this->securityContext = $securityContext;
}
/**
* Provides access to the current logged administrator attributes using the accessors.
*
* @param array $params
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
* @return string the value of the requested attribute
*/
public function adminDataAccess($params, &$smarty)
{
return $this->userDataAccess("Admin User", SecurityContext::CONTEXT_BACK_OFFICE, $params);
return $this->userDataAccess("Admin User", SecurityContext::CONTEXT_BACK_OFFICE, $params);
}
/**
@@ -64,38 +64,37 @@ class DataAccessFunctions extends AbstractSmartyPlugin
*/
public function customerDataAccess($params, &$smarty)
{
return $this->userDataAccess("Customer User", SecurityContext::CONTEXT_FRONT_OFFICE, $params);
return $this->userDataAccess("Customer User", SecurityContext::CONTEXT_FRONT_OFFICE, $params);
}
/**
* Provides access to user attributes using the accessors.
*
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
* @throws InvalidArgumentException if the object does not have the requested attribute.
*/
protected function userDataAccess($objectLabel, $context, $params)
{
$attribute = $this->getNormalizedParam($params, array('attribute', 'attrib', 'attr'));
$attribute = $this->getNormalizedParam($params, array('attribute', 'attrib', 'attr'));
if (! empty($attribute)) {
$user = $this->securityContext->setContext($context)->getUser();
if (! empty($attribute)) {
$user = $this->securityContext->setContext($context)->getUser();
if (null != $user) {
$getter = sprintf("get%s", ucfirst($attribute));
if (null != $user) {
$getter = sprintf("get%s", ucfirst($attribute));
if (method_exists($user, $getter)) {
return $user->$getter();
}
if (method_exists($user, $getter)) {
return $user->$getter();
}
throw new \InvalidArgumentException(sprintf("%s has no '%s' attribute", $objectLabel, $attribute));
throw new \InvalidArgumentException(sprintf("%s has no '%s' attribute", $objectLabel, $attribute));
}
}
}
}
return '';
return '';
}
/**
* Define the various smarty plugins hendled by this class

View File

@@ -28,7 +28,6 @@ use Thelia\Core\Template\Element\Exception\ElementNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Log\Tlog;
use Thelia\Core\Template\ParserContext;
/**
@@ -85,7 +84,7 @@ class Form extends AbstractSmartyPlugin
{
if ($repeat) {
$name = $this->getParam($params, 'name');
$name = $this->getParam($params, 'name');
if (null == $name) {
throw new \InvalidArgumentException("Missing 'name' parameter in form arguments");
@@ -98,11 +97,11 @@ class Form extends AbstractSmartyPlugin
if (null != $errorForm && $errorForm->getName() == $instance->getName()) {
// Re-use the errored form
$instance = $errorForm;
// Re-use the errored form
$instance = $errorForm;
// Don't do that, as we may want to use this form firther in the template code
//$this->parserContext->clearErrorForm();
// Don't do that, as we may want to use this form firther in the template code
//$this->parserContext->clearErrorForm();
}
$instance->createView();
@@ -111,8 +110,7 @@ class Form extends AbstractSmartyPlugin
$template->assign("form_error", $instance->hasError() ? true : false);
$template->assign("form_error_message", $instance->getErrorMessage());
}
else {
} else {
return $content;
}
}
@@ -121,7 +119,7 @@ class Form extends AbstractSmartyPlugin
{
if ($repeat) {
$formFieldView = $this->getFormFieldView($params);
$formFieldView = $this->getFormFieldView($params);
$template->assign("options", $formFieldView->vars);
$template->assign("name", $formFieldView->vars["full_name"]);
@@ -133,7 +131,7 @@ class Form extends AbstractSmartyPlugin
$template->assign("error", empty($errors) ? false : true);
if (! empty($errors)) {
$this->assignFieldErrorVars($template, $errors);
$this->assignFieldErrorVars($template, $errors);
}
$attr = array();
@@ -145,8 +143,7 @@ class Form extends AbstractSmartyPlugin
$template->assign("attr", implode(" ", $attr));
$formFieldView->setRendered();
}
else {
} else {
return $content;
}
}
@@ -155,7 +152,7 @@ class Form extends AbstractSmartyPlugin
{
$field = '<input type="hidden" name="%s" value="%s">';
$instance = $this->getInstanceFromParams($params);
$instance = $this->getInstanceFromParams($params);
$formView = $instance->getView();
@@ -172,7 +169,7 @@ class Form extends AbstractSmartyPlugin
public function formEnctype($params, \Smarty_Internal_Template $template)
{
$instance = $this->getInstanceFromParams($params);
$instance = $this->getInstanceFromParams($params);
$formView = $instance->getForm();
@@ -183,18 +180,17 @@ class Form extends AbstractSmartyPlugin
public function formError($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
$formFieldView = $this->getFormFieldView($params);
$formFieldView = $this->getFormFieldView($params);
$errors = $formFieldView->vars["errors"];
$errors = $formFieldView->vars["errors"];
if (empty($errors)) {
return "";
}
if ($repeat) {
$this->assignFieldErrorVars($template, $errors);
}
else {
$this->assignFieldErrorVars($template, $errors);
} else {
return $content;
}
}
@@ -202,45 +198,46 @@ class Form extends AbstractSmartyPlugin
protected function assignFieldErrorVars(\Smarty_Internal_Template $template, array $errors)
{
$template->assign("message", $errors[0]->getMessage());
$template->assign("parameters", $errors[0]->getMessageParameters());
$template->assign("pluralization", $errors[0]->getMessagePluralization());
$template->assign("message", $errors[0]->getMessage());
$template->assign("parameters", $errors[0]->getMessageParameters());
$template->assign("pluralization", $errors[0]->getMessagePluralization());
}
protected function isHidden(FormView $formView)
{
return array_search("hidden", $formView->vars["block_prefixes"]);
return array_search("hidden", $formView->vars["block_prefixes"]);
}
protected function getFormFieldView($params) {
$instance = $this->getInstanceFromParams($params);
protected function getFormFieldView($params)
{
$instance = $this->getInstanceFromParams($params);
$fieldName = $this->getParam($params, 'field');
$fieldName = $this->getParam($params, 'field');
if (null == $fieldName)
throw new \InvalidArgumentException("'field' parameter is missing");
if (null == $fieldName)
throw new \InvalidArgumentException("'field' parameter is missing");
if (empty($instance->getView()[$fieldName]))
throw new \InvalidArgumentException(sprintf("Field name '%s' not found in form %s", $fieldName, $instance->getName()));
throw new \InvalidArgumentException(sprintf("Field name '%s' not found in form %s", $fieldName, $instance->getName()));
return $instance->getView()[$fieldName];
}
protected function getInstanceFromParams($params) {
protected function getInstanceFromParams($params)
{
$instance = $this->getParam($params, 'form');
$instance = $this->getParam($params, 'form');
if (null == $instance) {
throw new \InvalidArgumentException("Missing 'form' parameter in form arguments");
}
if (null == $instance) {
throw new \InvalidArgumentException("Missing 'form' parameter in form arguments");
}
if (! $instance instanceof \Thelia\Form\BaseForm) {
throw new \InvalidArgumentException(sprintf("form parameter in form_field block must be an instance of
if (! $instance instanceof \Thelia\Form\BaseForm) {
throw new \InvalidArgumentException(sprintf("form parameter in form_field block must be an instance of
\Thelia\Form\BaseForm, instance of %s found", get_class($instance)));
}
}
return $instance;
return $instance;
}
protected function createInstance($name)

View File

@@ -25,54 +25,53 @@ namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Smarty\Assets\SmartyAssetsManager;
use Thelia\Core\Security\SecurityContext;
use Thelia\Core\Security\Exception\AuthenticationException;
class Security extends AbstractSmartyPlugin
{
private $securityContext;
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* Process security check function
*
* @param array $params
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
* @return string no text is returned.
*/
public function checkAuthFunction($params, &$smarty)
{
// Context: 'front' or 'admin'
$context = $this->getNormalizedParam($params, 'context');
// Context: 'front' or 'admin'
$context = $this->getNormalizedParam($params, 'context');
$this->securityContext->setContext($context);
$this->securityContext->setContext($context);
$roles = $this->_explode($this->getParam($params, 'roles'));
$permissions = $this->_explode($this->getParam($params, 'permissions'));
$roles = $this->_explode($this->getParam($params, 'roles'));
$permissions = $this->_explode($this->getParam($params, 'permissions'));
if (! $this->securityContext->isGranted($roles, $permissions)) {
if (! $this->securityContext->isGranted($roles, $permissions)) {
$ex = new AuthenticationException(
sprintf("User not granted for roles '%s', permissions '%s' in context '%s'.",
implode(',', $roles), implode(',', $permissions), $context
)
);
$ex = new AuthenticationException(
sprintf("User not granted for roles '%s', permissions '%s' in context '%s'.",
implode(',', $roles), implode(',', $permissions), $context
)
);
$loginTpl = $this->getParam($params, 'login_tpl');
$loginTpl = $this->getParam($params, 'login_tpl');
if (null != $loginTpl) {
$ex->setLoginTemplate($loginTpl);
}
if (null != $loginTpl) {
$ex->setLoginTemplate($loginTpl);
}
throw $ex;
}
throw $ex;
}
return '';
return '';
}
/**

View File

@@ -73,7 +73,7 @@ class TheliaLoop extends AbstractSmartyPlugin
*/
public function theliaCount($params, $template)
{
$type = $this->getParam($params, 'type');
$type = $this->getParam($params, 'type');
if (null == $type) {
throw new \InvalidArgumentException("Missing 'type' parameter in count arguments");
@@ -83,9 +83,9 @@ class TheliaLoop extends AbstractSmartyPlugin
$dummy = null;
$loopResults = $loop->exec($dummy);
$loopResults = $loop->exec($dummy);
return $loopResults->valid() ? $loopResults->getCount() : 0;
return $loopResults->valid() ? $loopResults->getCount() : 0;
}
/**
@@ -100,7 +100,7 @@ class TheliaLoop extends AbstractSmartyPlugin
*/
public function theliaLoop($params, $content, $template, &$repeat)
{
$name = $this->getParam($params, 'name');
$name = $this->getParam($params, 'name');
if (null == $name) {
throw new \InvalidArgumentException("Missing 'name' parameter in loop arguments");
@@ -112,194 +112,6 @@ class TheliaLoop extends AbstractSmartyPlugin
throw new \InvalidArgumentException("Missing 'type' parameter in loop arguments");
}
if ($content === null) {
// Check if a loop with the same name exists in the current scope, and abort if it's the case.
if (array_key_exists($name, $this->varstack)) {
throw new \InvalidArgumentException("A loop named '$name' already exists in the current scope.");
}
$loop = $this->createLoopInstance($params);
self::$pagination[$name] = null;
$loopResults = $loop->exec(self::$pagination[$name]);
$this->loopstack[$name] = $loopResults;
// Pas de résultat ? la boucle est terminée, ne pas évaluer le contenu.
if ($loopResults->isEmpty()) $repeat = false;
} else {
$loopResults = $this->loopstack[$name];
$loopResults->next();
}
if ($loopResults->valid()) {
$loopResultRow = $loopResults->current();
// On first iteration, save variables that may be overwritten by this loop
if (! isset($this->varstack[$name])) {
$saved_vars = array();
$varlist = $loopResultRow->getVars();
$varlist[] = 'LOOP_COUNT';
$varlist[] = 'LOOP_TOTAL';
foreach($varlist as $var) {
$saved_vars[$var] = $template->getTemplateVars($var);
}
$this->varstack[$name] = $saved_vars;
}
foreach($loopResultRow->getVarVal() as $var => $val) {
$template->assign($var, $val);
}
$repeat = true;
}
// Assign meta information
$template->assign('LOOP_COUNT', 1 + $loopResults->key());
$template->assign('LOOP_TOTAL', $loopResults->getCount());
// Loop is terminated. Cleanup.
if (! $repeat) {
// Restore previous variables values before terminating
if (isset($this->varstack[$name])) {
foreach($this->varstack[$name] as $var => $value) {
$template->assign($var, $value);
}
unset($this->varstack[$name]);
}
}
if ($content !== null) {
if ($loopResults->isEmpty()) {
$content = "";
}
return $content;
}
}
/**
* Process {elseloop rel="loopname"} ... {/elseloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaElseloop($params, $content, $template, &$repeat)
{
// When encoutering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? $content : '';
}
}
/**
* Process {ifloop rel="loopname"} ... {/ifloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaIfLoop($params, $content, $template, &$repeat)
{
// When encountering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? '' : $content;
}
}
/**
* Process {pageloop rel="loopname"} ... {/pageloop} block
*
* @param $params
* @param $content
* @param $template
* @param $repeat
*
* @return string
* @throws \InvalidArgumentException
*/
public function theliaPageLoop($params, $content, $template, &$repeat)
{
$loopName = $this->getParam($params, 'rel');
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in page loop");
// Find loop results in the current template vars
/* $loopResults = $template->getTemplateVars($loopName);
if (empty($loopResults)) {
throw new \InvalidArgumentException("Loop $loopName is not defined.");
}*/
// Find pagination
$pagination = self::getPagination($loopName);
if ($pagination === null) {
throw new \InvalidArgumentException("Loop $loopName is not defined");
}
if($pagination->getNbResults() == 0) {
return '';
}
if ($content === null) {
$page = 1;
} else {
$page = $template->getTemplateVars('PAGE');
$page++;
}
if ($page <= $pagination->getLastPage()) {
$template->assign('PAGE', $page);
$template->assign('CURRENT', $pagination->getPage());
$template->assign('LAST', $pagination->getLastPage());
$repeat = true;
}
if ($content !== null) {
return $content;
}
}
/**
* Process {unionloop name="loop name" type="loop type" ... } ... {/unionloop} block
*
* @param $params
* @param $content
* @param $template
* @param $repeat
*
* @return string
* @throws \InvalidArgumentException
*/
public function theliaUnion($params, $content, $template, &$repeat)
{
return;
$name = $this->getParam($params, 'name');
if (null == $name)
throw new \InvalidArgumentException("Missing 'name' parameter in unionloop arguments");
$type = $this->getParam($params, 'type');
if (null == $type)
throw new \InvalidArgumentException("Missing 'type' parameter in unionloop arguments");
if ($content === null) {
// Check if a loop with the same name exists in the current scope, and abort if it's the case.
if (array_key_exists($name, $this->varstack)) {
@@ -335,14 +147,14 @@ class TheliaLoop extends AbstractSmartyPlugin
$varlist[] = 'LOOP_COUNT';
$varlist[] = 'LOOP_TOTAL';
foreach($varlist as $var) {
foreach ($varlist as $var) {
$saved_vars[$var] = $template->getTemplateVars($var);
}
$this->varstack[$name] = $saved_vars;
}
foreach($loopResultRow->getVarVal() as $var => $val) {
foreach ($loopResultRow->getVarVal() as $var => $val) {
$template->assign($var, $val);
}
@@ -357,7 +169,7 @@ class TheliaLoop extends AbstractSmartyPlugin
if (! $repeat) {
// Restore previous variables values before terminating
if (isset($this->varstack[$name])) {
foreach($this->varstack[$name] as $var => $value) {
foreach ($this->varstack[$name] as $var => $value) {
$template->assign($var, $value);
}
@@ -374,6 +186,95 @@ class TheliaLoop extends AbstractSmartyPlugin
}
}
/**
* Process {elseloop rel="loopname"} ... {/elseloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaElseloop($params, $content, $template, &$repeat)
{
// When encoutering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? $content : '';
}
}
/**
* Process {ifloop rel="loopname"} ... {/ifloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaIfLoop($params, $content, $template, &$repeat)
{
// When encountering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? '' : $content;
}
}
/**
* Process {pageloop rel="loopname"} ... {/pageloop} block
*
* @param $params
* @param $content
* @param $template
* @param $repeat
*
* @return string
* @throws \InvalidArgumentException
*/
public function theliaPageLoop($params, $content, $template, &$repeat)
{
$loopName = $this->getParam($params, 'rel');
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in page loop");
// Find loop results in the current template vars
/* $loopResults = $template->getTemplateVars($loopName);
if (empty($loopResults)) {
throw new \InvalidArgumentException("Loop $loopName is not defined.");
}*/
// Find pagination
$pagination = self::getPagination($loopName);
if ($pagination === null) {
throw new \InvalidArgumentException("Loop $loopName is not defined");
}
if ($pagination->getNbResults() == 0) {
return '';
}
if ($content === null) {
$page = 1;
} else {
$page = $template->getTemplateVars('PAGE');
$page++;
}
if ($page <= $pagination->getLastPage()) {
$template->assign('PAGE', $page);
$template->assign('CURRENT', $pagination->getPage());
$template->assign('LAST', $pagination->getLastPage());
$repeat = true;
}
if ($content !== null) {
return $content;
}
}
/**
* Check if a loop has returned results. The loop shoud have been executed before, or an
* InvalidArgumentException is thrown
@@ -384,10 +285,10 @@ class TheliaLoop extends AbstractSmartyPlugin
*/
protected function checkEmptyLoop($params, $template)
{
$loopName = $this->getParam($params, 'rel');
$loopName = $this->getParam($params, 'rel');
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in ifloop/elseloop arguments");
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in ifloop/elseloop arguments");
if (! isset($this->loopstack[$loopName])) {
throw new \InvalidArgumentException("Loop $loopName is not defined.");
@@ -400,14 +301,14 @@ class TheliaLoop extends AbstractSmartyPlugin
*
* find the loop class with his name and construct an instance of this class
*
* @param string $name
* @param string $name
* @return \Thelia\Core\Template\Element\BaseLoop
* @throws InvalidElementException
* @throws ElementNotFoundException
*/
protected function createLoopInstance($smartyParams)
{
$type = strtolower($smartyParams['type']);
$type = strtolower($smartyParams['type']);
if (! isset($this->loopDefinition[$type])) {
throw new ElementNotFoundException(sprintf("%s loop does not exists", $type));
@@ -423,7 +324,7 @@ class TheliaLoop extends AbstractSmartyPlugin
$loop = $class->newInstance(
$this->request,
$this->dispatcher,
$this->securityContext
$this->securityContext
);
$loop->initializeArgs($smartyParams);
@@ -469,12 +370,11 @@ class TheliaLoop extends AbstractSmartyPlugin
{
return array(
new SmartyPluginDescriptor('function', 'count', $this, 'theliaCount'),
new SmartyPluginDescriptor('block' , 'loop', $this, 'theliaLoop'),
new SmartyPluginDescriptor('block' , 'elseloop', $this, 'theliaElseloop'),
new SmartyPluginDescriptor('block' , 'ifloop', $this, 'theliaIfLoop'),
new SmartyPluginDescriptor('block' , 'pageloop', $this, 'theliaPageLoop'),
new SmartyPluginDescriptor('block' , 'union', $this, 'theliaUnion'),
new SmartyPluginDescriptor('function', 'count' , $this, 'theliaCount'),
new SmartyPluginDescriptor('block' , 'loop' , $this, 'theliaLoop'),
new SmartyPluginDescriptor('block' , 'elseloop' , $this, 'theliaElseloop'),
new SmartyPluginDescriptor('block' , 'ifloop' , $this, 'theliaIfLoop'),
new SmartyPluginDescriptor('block' , 'pageloop' , $this, 'theliaPageLoop'),
);
}
}

View File

@@ -35,7 +35,7 @@ class TheliaSyntax extends AbstractSmartyPlugin
{
public function dieseCancel($value, $diese)
{
if($value === null) {
if ($value === null) {
return $diese;
}

View File

@@ -29,11 +29,12 @@ use Symfony\Component\Translation\TranslatorInterface;
class Translation extends AbstractSmartyPlugin
{
protected $translator;
protected $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* Process translate function
@@ -44,15 +45,15 @@ class Translation extends AbstractSmartyPlugin
*/
public function translate($params, &$smarty)
{
// All parameters other than 'l' are supposed to be variables. Build an array of var => value pairs
// and pass it to the translator
$vars = array();
// All parameters other than 'l' are supposed to be variables. Build an array of var => value pairs
// and pass it to the translator
$vars = array();
foreach($params as $name => $value) {
if ($name != 'l') $vars["%$name"] = $value;
}
foreach ($params as $name => $value) {
if ($name != 'l') $vars["%$name"] = $value;
}
return $this->translator->trans($this->getParam($params, 'l'), $vars);
return $this->translator->trans($this->getParam($params, 'l'), $vars);
}
/**

View File

@@ -37,25 +37,24 @@ class UrlGenerator extends AbstractSmartyPlugin
$this->request = $request;
}
/**
/**
* Process url generator function
*
* @param array $params
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
* @return string no text is returned.
*/
public function generateUrlFunction($params, &$smarty)
{
// the path to process
$path = $this->getParam($params, 'path');
// the path to process
$path = $this->getParam($params, 'path');
$target = $this->getParam($params, 'target', null);
$target = $this->getParam($params, 'target', null);
$url = URL::absoluteUrl($path, $this->getArgsFromParam($params, array('path', 'target')));
$url = URL::absoluteUrl($path, $this->getArgsFromParam($params, array('path', 'target')));
if ($target != null) $url .= '#'.$target;
return $url;
if ($target != null) $url .= '#'.$target;
return $url;
}
/**
@@ -67,7 +66,7 @@ class UrlGenerator extends AbstractSmartyPlugin
*/
public function generateFrontViewUrlFunction($params, &$smarty)
{
return $this->generateViewUrlFunction($params, false);
return $this->generateViewUrlFunction($params, false);
}
/**
@@ -79,22 +78,21 @@ class UrlGenerator extends AbstractSmartyPlugin
*/
public function generateAdminViewUrlFunction($params, &$smarty)
{
return $this->generateViewUrlFunction($params, true);
return $this->generateViewUrlFunction($params, true);
}
protected function generateViewUrlFunction($params, $forAdmin)
{
// the view name (without .html)
$view = $this->getParam($params,'view');
// the view name (without .html)
$view = $this->getParam($params,'view');
// the related action (optionale)
$action = $this->getParam($params, 'action');
// the related action (optionale)
$action = $this->getParam($params, 'action');
$args = $this->getArgsFromParam($params, array('view', 'action', 'target'));
$args = $this->getArgsFromParam($params, array('view', 'action', 'target'));
if (! empty($action)) $args['action'] = $action;
return $forAdmin ? URL::adminViewUrl($view, $args) : URL::viewUrl($view, $args);
if (! empty($action)) $args['action'] = $action;
return $forAdmin ? URL::adminViewUrl($view, $args) : URL::viewUrl($view, $args);
}
/**
@@ -103,18 +101,18 @@ class UrlGenerator extends AbstractSmartyPlugin
* @param array $params Smarty function params
* @return array the parameters array (either emply, of valued)
*/
private function getArgsFromParam($params, $exclude = array()) {
private function getArgsFromParam($params, $exclude = array())
{
$pairs = array();
$pairs = array();
foreach ($params as $name => $value) {
foreach($params as $name => $value) {
if (in_array($name, $exclude)) continue;
if (in_array($name, $exclude)) continue;
$pairs[$name] = $value;
}
$pairs[$name] = $value;
}
return $pairs;
return $pairs;
}
/**

View File

@@ -41,8 +41,8 @@ class SmartyParser extends Smarty implements ParserInterface
* @param bool $debug
*/
public function __construct(
Request $request, EventDispatcherInterface $dispatcher, ParserContext $parserContext,
$template = false, $env = "prod", $debug = false)
Request $request, EventDispatcherInterface $dispatcher, ParserContext $parserContext,
$template = false, $env = "prod", $debug = false)
{
parent::__construct();
@@ -69,7 +69,7 @@ class SmartyParser extends Smarty implements ParserInterface
$this->error_reporting = E_ALL ^ E_NOTICE;
// Si on n'est pas en mode debug, activer le cache, avec une lifetime de 15mn, et en vérifiant que les templates sources n'ont pas été modifiés.
if($debug === false) {
if ($debug === false) {
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->cache_lifetime = 300;
$this->compile_check = true;
@@ -87,15 +87,15 @@ class SmartyParser extends Smarty implements ParserInterface
public function preThelia($tpl_source, \Smarty_Internal_Template $template)
{
$new_source = preg_replace('`{#([a-zA-Z][a-zA-Z0-9\-_]*)(.*)}`', '{\$$1$2}', $tpl_source);
$new_source = preg_replace('`#([a-zA-Z][a-zA-Z0-9\-_]*)`', '{\$$1|dieseCanceller:\'#$1\'}', $new_source);
$new_source = preg_replace('`{#([a-zA-Z][a-zA-Z0-9\-_]*)(.*)}`', '{\$$1$2}', $tpl_source);
$new_source = preg_replace('`#([a-zA-Z][a-zA-Z0-9\-_]*)`', '{\$$1|dieseCanceller:\'#$1\'}', $new_source);
return $new_source;
return $new_source;
}
public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source);
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source);
}
public function setTemplate($template_path_from_template_base)
@@ -119,10 +119,10 @@ class SmartyParser extends Smarty implements ParserInterface
*/
public function render($realTemplateName, array $parameters = array())
{
// Assign the parserContext variables
foreach($this->parserContext as $var => $value) {
$this->assign($var, $value);
}
// Assign the parserContext variables
foreach ($this->parserContext as $var => $value) {
$this->assign($var, $value);
}
$this->assign($parameters);
@@ -138,8 +138,7 @@ class SmartyParser extends Smarty implements ParserInterface
{
try {
$templateFile = $this->getTemplateFilePath();
}
catch(\RuntimeException $e) {
} catch (\RuntimeException $e) {
return new Response($e->getMessage(), "404");
}
@@ -219,7 +218,7 @@ class SmartyParser extends Smarty implements ParserInterface
if (!file_exists($fileName)) {
$fileName .= ".html";
if(!file_exists($fileName)) {
if (!file_exists($fileName)) {
throw new ResourceNotFoundException(sprintf("%s file not found in %s template", $file, $this->template));
}
}

View File

@@ -196,6 +196,7 @@ class Thelia extends Kernel
$parameters["thelia.root_dir"] = THELIA_ROOT;
$parameters["thelia.core_dir"] = THELIA_ROOT . "core/lib/Thelia";
$parameters["thelia.module_dir"] = THELIA_MODULE_DIR;
return $parameters;
}

View File

@@ -131,17 +131,17 @@ class TheliaHttpKernel extends HttpKernel
}
/**
* @param Request $request
* @param Request $request
* @return null|\Thelia\Model\Lang
*/
protected function detectLang(Request $request)
{
$lang = null;
//first priority => lang parameter present in request (get or post)
if($request->query->has("lang")) {
if ($request->query->has("lang")) {
$lang = Model\LangQuery::create()->findOneByCode($request->query->get("lang"));
if(is_null($lang)) {
if (is_null($lang)) {
return;
}

42
core/lib/Thelia/Core/Translation/Translator.php Normal file → Executable file
View File

@@ -3,26 +3,26 @@ namespace Thelia\Core\Translation;
use Symfony\Component\Translation\Translator as BaseTranslator;
class Translator extends BaseTranslator {
class Translator extends BaseTranslator
{
/**
* {@inheritdoc}
*
* @api
*/
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
{
if (null === $locale) {
$locale = $this->getLocale();
}
/**
* {@inheritdoc}
*
* @api
*/
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
{
if (null === $locale) {
$locale = $this->getLocale();
}
if (!isset($this->catalogues[$locale])) {
$this->loadCatalogue($locale);
}
if (!isset($this->catalogues[$locale])) {
$this->loadCatalogue($locale);
}
if ($this->catalogues[$locale]->has((string) $id, $domain))
return parent::trans($id, $parameters, $domain = 'messages', $locale = null);
else
return strtr($id, $parameters);
}
}
if ($this->catalogues[$locale]->has((string) $id, $domain))
return parent::trans($id, $parameters, $domain = 'messages', $locale = null);
else
return strtr($id, $parameters);
}
}