PHP Break Line Character For Function Arguments - coda

I have this code :
public function registerNew ($first_name, $last_name, $email, $phone, $password, $bank_name, $bank_account_number, $bank_account_name, $gender, $birthday, $address, $area, $signup_date, $activated, $first_login, $token, $referred_by, $referral_id, $default_type) {
//some code here
}
and I want to make it pretty like this :
public function registerNew ($first_name, $last_name, $email, $phone, $password,
$bank_name, $bank_account_number, $bank_account_name,
$gender, $birthday, $address, $area, $signup_date,
$activated, $first_login, $token, $referred_by,
$referral_id, $default_type) {
//some code here
}
but, since I just hit enter button at the end of the line, then every time I tried to fold this function, my code editor fold everything until only the class name appears like this :
class User {...}
I'm expecting an output like this :
class User {
public function registerNew ($first_name, $last_name, $email, $phone, $password,
$bank_name, $bank_account_number, $bank_account_name,
$gender, $birthday, $address, $area, $signup_date,
$activated, $first_login, $token, $referred_by,
$referral_id, $default_type) {...}
}
do I have to put some character to break the lines instead of just hit enter button? or this just my code editor's problem?
thank you

Related

Problems with twig in cyrillic

I'm trying to use twig template that contains my native language characters and receive this error
object(Twig_Error_Syntax)[173]
private 'lineno' (Twig_Error) => int 1
private 'name' (Twig_Error) => string 'sms' (length=3)
private 'sourceCode' (Twig_Error) => string 'Привет, {{name}}' (length=22)
protected 'message' => string 'Unexpected token "end of template" of value "" in "sms" at line 1.' (length=66)
private 'string' (Exception) => string '' (length=0)
protected 'code' => int 0
protected 'file' => string '/var/www/bitrix/vendor/twig/twig/lib/Twig/ExpressionParser.php' (length=62)
protected 'line' => int 201
However the same code works fine with Latin characters.
The code I use follows:
$loader = new Twig_Loader_Array(['sms' => $arTemplate['PROPERTY_SMS_VALUE']['TEXT'], 'mail' => $arTemplate['PROPERTY_EMAIL_VALUE']['TEXT']]);
$twig = new Twig_Environment($loader);
try {
$sms_text = $twig->render('sms', ['name' => $_REQUEST[FIELD_NAME]]);
It basically takes twig from database and applies simple render. I use twig without Symfony (only basic requirements installed)
It would be better to use tools.twig for bitrix CMS.
composer req maximaster/tools.twig
Then you should delete template.php and create template.twig file in component folder.
In the docs you can find bitrix variables available in the twig template and rule for template inheritance.

Kohana auth model

I'm new to kohana 3.2 and i couldnt find any answer regrading the auth module.
this is my code and forsome reason ever since i changed the user model to extend model_auth_user
the validation isnt being done prooperly. The password field can be inserted empty and no excpetion will be caught and same if the password_confirm and password fields are different:
public function action_new()
{
if ($_POST){
try
{
$user = ORM::factory('user')
->values(array(
'username' => $_POST['username'],
'email' => $_POST['email'],
'password' => $_POST['password'],
'password_confirm' => $_POST['password_confirm']));
$user->save();
$user->add('roles', ORM::factory('role', array('name' => 'login')));
$this->request->redirect('user/index');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
}
}
$view = View::factory('user/new')
->bind('errors',$errors); //pass the info to the view
$this->response->body($view); //show the view
}
thanks
You can override run_filter() method to force Kohana ignore password filtering in case of empty value. For example, put this code to your User_Model:
protected function run_filter($field, $value)
{
if ($field === "password" AND $value === "")
return "";
parent::run_filter($field, $value);
}
Try code sample from Model_Auth_User::create_user();
$user->save(Model_User::get_password_validation($_POST)->rule('password', 'not_empty'));
This validation execute before filters(hashing password). After hashing - blank password becomes not empty string.

Symfony2 Entity form type with a specific query_buider

Context
In my case, I've some orders with "discount vouchers" (discount). A discount can be use on under different conditions. For instance, discounts have an expired date, can be used by a limited number of customers, can be dedicated to a user, ...
Each discount can be attached to several order.
In my backoffice, I want to add to order create form a field "Discount" with a list of discount available but only right discounts.
What I made
An entity "order" with a field manyToMany
/**
* #ORM\ManyToMany(targetEntity="PATH\MyBundle\Entity\Discount", inversedBy="orders")
* #ORM\JoinTable(name="shop_discounts_orders",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="discount_id", referencedColumnName="id")}
* )
*/
private $discounts;
An entity "discounts" with a field manyToMany
/**
* #ORM\ManyToMany(targetEntity="PATH\MyBundle\Entity\Order", mappedBy="discounts")
*/
private $orders;
A form OrderType with a field discounts
$builder->add('discounts', 'entity',
array( 'label' => 'Discount vouchers',
'required' => false,
'expanded' => true,
'class' => 'PATH\MyBundle\Entity\Discount',
'property' => 'title',
'multiple' => true,
'query_builder' => function(EntityRepository $er) use ($params) {
return $er->getQuerySelectType($params);
},
));
With this solution, I can return specific discount defined by my request in my entity repository. It's good for expired date condition for instance.
What I would like
I'd like to filter results in the checkbox list. In fact, I want limit usage of the discount to a dedicated user, limit to a list of products, or limit the number of usage... And these condition cannot be done by a simple sql request.
I try to create special Type. My idea is to have an array of entities Discount and load a choice list... After that, I create a dataTransformer but It doesn't work !
Thank's for your ideas !
You could use the $options from public function buildForm(FormBuilderInterface $builder, array $options) to pass your user and product for instance. With those 2 informations you could refine your list of discount (in your query)
if you do so you need to add them in the setDefaultValue
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'user_discount' => null,
'product_discount' => null,
));
}
and in your controller:
$form = $this->formFactory->create(new YourFormType(), $entity, array(
'user_discount' => $this->getUser(),
'product_discount' => $product,
));
I found a solution and explain it if someone have the same issue as me.
Create a custom Type
My custom type is inspired by Symfony\Bridge\Doctrine\Form\Type\DoctrineType
class DiscountOrderType extends AbstractType
{
// overide choiceList callback
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$choiceListCache =& $this->choiceListCache;
$type = $this;
$choiceList = function (Options $options) use (&$choiceListCache, &$time, $container) {
[[ Copy paste same as Doctrine type ]]
// Create your own choiceList class (EntityChoiceList)
if (!isset($choiceListCache[$hash])) {
$choiceListCache[$hash] = new DiscountChoiceList(
$options['em'],
$options['class'],
$options['property'],
$options['loader'],
$options['choices'],
$options['group_by']
);
// If you want add container
$choiceListCache[$hash]->setContainer($container);
}
return $choiceListCache[$hash];
};
$resolver->setDefaults(array(
'choice_list' => $choiceList,
));
}
Create a custom EntityChoiceList
My custom type is inspired by Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList
class EntityChoiceList extends ObjectChoiceList
{
protected function load()
{
if ($this->entityLoader) {
$entities = $this->entityLoader->getEntities();
} else {
$entities = $this->em->getRepository($this->class)->findAll();
}
// You have access to the entities in the choice list
// Add your custom code here to manipulate the choice list
// you can do some check not properly possible with sql request (http requests on each result, ...) before add it in choice list
// you can add some custom cache rules, ...
// if you use gedmon and want apply a "join" with translate table, you can add $query->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'); before playing request...
// Possibilities are infinite
// FOR INSTANCE : you already want unset first entity of the result
if (isset($entities[0])) {
unset($entities[0]);
}
// END OF CUSTOM CODE
try {
// The second parameter $labels is ignored by ObjectChoiceList
// The third parameter $preferredChoices is currently not supported
parent::initialize($entities, array(), array());
} catch (StringCastException $e) {
throw new StringCastException(str_replace('argument $labelPath', 'option "property"', $e->getMessage()), null, $e);
}
$this->loaded = true;
}
Of course you can try to extend symfony class for beautyfull code ;).
Thank's to #maxwell2022 for your help !

ZF2 CurrencyFormat on Default locale not working

In my application I use serval languages. I'n my module.php I set the locale of a user by the follow methode:
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator ->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))
->setFallbackLocale($this->setDomainLocale());
There are running server domain.tdl's on this application (different languages) so I use a function in my fallback to set the fallback locale per domain, anyway...
I want to make use of currencyFormat but I don't get it work to use it with the locale by user. I tried the code below with and without '\Locale::getDefault())';
A number like '1509053' and should be returned as '€ 1.509.053.00' or ',' depends on locale, I get just '€ 1509053.00'.
$this->plugin("currencyformat")->setCurrencyCode("EUR")->setLocale(\Locale::getDefault());
output of \Locale::getDefault())
string(11) "en_US_POSIX"
output of module.php $translator
class Zend\I18n\Translator\Translator#193 (8) { protected $messages => array(0) { }
protected $files => array(0) { } protected $patterns => array(1) { 'default' => array(1) { [0] => array(3) { 'type' => string(7) "gettext" 'baseDir' => string(119) "..../module/.../config/../language" 'pattern' => string(5) "%s.mo" } } } protected $remote => array(0) { } protected $locale => string(35) "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4" protected $fallbackLocale => string(5) "nl_NL" protected $cache => NULL protected $pluginManager => NULL }
Hope someone can put me in the right direction :) Thnx
To use the function '\Locale::getDefault();' we need to set first '\Locale::setDefault(language_code);' $translate->setLocale doesn't set Locale::getDefault();.

Kohana 3.2: Custom error message for a custom validation rule?

I am using a custom method for a validation rule in my model (using Kohana 3.2). I am following the format listed on the documentation.
// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),
But I can't seem to figure out how to add a custom error message if the rule fails.
Any help?
For this example we will assume a modal "user" and validating the field "username"
/application/classes/model/user.php
class Model_User extends ORM
{
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('A_Class::a_method', array(':value')),
)
);
}
}
A_Class
public static function a_method($value)
{
// Validate and return TRUE or FALSE
}
/application/messages/forms/user.php
Added a forms folder so show we can select message file to load with errors. Message file matches model name (user)
return array(
'username' => array(
'not_empty' => 'Custom error message for not_empty method',
'A_Class::a_method' => 'Custom error message for you own validation rule...'
),
);
Now in your controller to validate and display the error messages
class Controller_User extends Controller
{
// User model instance
$model = ORM::factory('user');
// Set some data to the model
$model->username - 'bob';
// Try to validate and save
try
{
$model->save()
}
catch (ORM_Validation_Exception $e)
{
// Loads messages from forms/user.php
$errors = $e->errors('forms');
// See the custom error messages
echo Debug::vars($errors);
)
)

Resources