Return validator messages in custom Rule - php

A problem that we probably didn't know about when switching to PHP 8+:
Very often, in the rules we created earlier, we returned a message like this:
public function message(): array
{
return [$this->validator->errors()->messages()];
}
When using PHP 7.4 - this isn't a problem, but not for PHP 8+
Since looking "deeper" into how the laravel framework forms messages, we get an error in the replaceAttributePlaceholder method of the FormatsMessages class:
/**
* Replace the : attribute placeholder in the given message.
*
* #param string $message
* #param string $value
* #return string
*/
protected function replaceAttributePlaceholder($message, $value)
{
return str_replace(
[':attribute', ':ATTRIBUTE', ':Attribute'],
[$value, Str::upper($value), Str::ucfirst($value)],
$message
);
}
And indeed, if we open any editor and run the same code, but for two different versions, we'll get:
If you return the message like this:
public function message(): array
{
return $this->validator->errors()->messages();
}
We will avoid the error, but accordingly, the format of the message will be different - this doesn't suit me, and the format of the message should remain the same.
Does anyone have any ideas on how to save the format and fix the error?

Related

PyroCMS user registration error

So I'm a newbie at laravel framework and PyroCMS, I recently install PyroCMS and go to mydomain.com/register to try the registration function and I got the following error, but no idea how to solve it.
Error code:
}
/**
* Convert the given string to upper-case.
*
* #param string $value
* #return string
*/
public static function upper($value)
{
return mb_strtoupper($value, 'UTF-8');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Highlighted line
}
/**
* Convert the given string to title case.
*
* #param string $value
* #return string
*/
public static function title($value)
{
return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
}
And
public static function substr($string, $start, $length = null)
{
return mb_substr($string, $start, $length, 'UTF-8');
}
Which the line return mb_strtoupper($value, 'UTF-8'); and return mb_substr($string, $start, $length, 'UTF-8'); is highlighted with an error log expects parameter 1 to be string, array given.
How can I solve it?
More info:
Error file: pyrocms/vendor/laravel/framework/src/Illuminate/Support/Str.php
Error screenshot:
You may or may not want to do something like this
public static function upper($value)
{
if(is_array($value)){
foreach($value as &$item){
$item = self::upper($item); //recursive
}
return $value;
}
return mb_strtoupper($value, 'UTF-8');
}
This will recursively call upper when it's an array and the effect will be that it will uppercase everything in $value. This may or may not be what you want.
Chances are you are passing the wrong data to this method.
To pass the right data you would do something like
$value['key'] = Class::upper($value['key']);
But I have no idea what value key should be, and I don't even know what class these methods reside in Class. I don't use laravel and I never heard of PyroCMS before.
If I used every framework that came along i would spend my days learning frameworks and not building them. I don't use laravel because I don't like the syntax blade uses, I am not a fan of query builders, probably these can be replaced but we already have everything build in a different framework. So there is no need to customize it to work the way I want it to when we already have a solution that works just fine.
That said, I do know PHP, I know it quite well in fact.

How to retrieve the same message twice or more in RabbitMQ with php

I have some broblems with php + RabbitMQ + MySQL.
I have worker on php, that update one record in DB. Now I trying to make correct
work if server MySQL gone away.
What I am doing:
I'm trying reconnect to DB 10 times, if I can't - need to return this massage back to the RabbitMQ.
For accepting message I use basic_ack, for rejecting I use basic_nack.
Example:
if ($can_accept_message) {
$message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
} else {
$message->delivery_info['channel']->basic_nack($message->delivery_info['delivery_tag']);
}
But basic_nack delete this message from queue and I can't repeat it again ;(
Trying like this: https://github.com/php-amqplib/php-amqplib/blob/d2b8a292f709b79b1615bef87b1b89bde4c7c347/demo/basic_nack.php
Reading this: https://github.com/php-amqplib/php-amqplib/issues/221
But it still not working.
What's wrong? Maybe you have any other ideas?
It seems the function basic_nack is defined as follow:
/**
* Rejects one or several received messages
*
* #param string $delivery_tag
* #param bool $multiple
* #param bool $requeue
*/
public function basic_nack($delivery_tag, $multiple = false, $requeue = false)
As you can see, the third parameter is $requeue = false
You should try
else {
$message->delivery_info['channel']->basic_nack($message->delivery_info['delivery_tag'], false, true);
}

How to create a custom error view in codeigniter

I have a same problem with this How to change an error displayed in codeigniter
I tried the solution from Jordan Arseno, because that was the most logically answer that could be, but the problem is the class that he suggested can't be loaded so it stuck with the default error from Codeigniter.
I want to make a custom error view, so I tried to change file system/core/URI.php directly but it can't use redirect function because :
autoload['helper']="url";can't be loaded in this URI file.
Can anybody know how to solve this?
Change on system/core/Input.php , try this this must work let me know if doesn't work , this works for me
<?php
class MY_Input extends CI_Input {
/**
* Clean Keys
*
* This is a helper function. To prevent malicious users
* from trying to exploit keys we make sure that keys are
* only named with alpha-numeric text and a few other items.
*
* Extended to allow:
* - '.' (dot),
* - '[' (open bracket),
* - ']' (close bracket)
*
* #access private
* #param string
* #return string
*/
function _clean_input_keys($str) {
if (!preg_match("/^[a-z0-9:_\/\.\[\]-]+$/i", $str)) {
/**
* Check for Development enviroment - Non-descriptive
* error so show me the string that caused the problem
*/
if (getenv('ENVIRONMENT') && getenv('ENVIRONMENT') == 'DEVELOPMENT')
var_dump($str);
exit('Disallowed Key Characters.');
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE) {
$str = $this->uni->clean_string($str);
}
return $str;
}
}
// /?/> /* Should never close php file - if you have a space after can mess your life up */

Magento - Blank white screen search results. Many things broken

Whenever a user searches, I get this error:
2012-06-26 11:05:21.671 [NOTICE] [208.69.120.120:48175-0#hostname] [STDERR] PHP Fatal error: Call to undefined method Mage_Catalog_Model_Resource_Product_Flat::getEntityTablePrefix() in /chroot/home/SITENAME/DOMAIN.COM/html/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php on line 505
And instead of the user's results appearing, they get a blank white page- no error on their end, no UI, just white. This was the first issue I noticed, but on the same day the following issues started coming up:
White Search Results
Sub-category product count for all sub-categories in layered nav is showing 0.
Some customers can not view orders from their front-end UI when logged in.
Our order export script is returning blank fields (1.7mb instead of 4.3).
Our "Made-in-the-usa" and "best sellers" pages are returning more products than they should.
Now, I know these are all incorrect because if I reindex the entire site, for some period while it is processing the index, all of the above works. However, when the index is complete, it all breaks again. The same day this happened we had an error page appear that stated one of the tables had broken and should be repaired. We ran PHPMyAdmin's repair and optimize functions on all tables and it fixed that error- but all of these are still broken.
Any ideas at all? Any ideas of what could be tried to fix this? I cant find this error anywhere- and the guys over at Nexcess haven't been able to find anything for this, either.
Thank you for your time.
As per the comments above, Magento's telling you that it's trying to call the method getEntityTablePrefix on an object whose classes don't have that method defined. Specifically in this method
#File: app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php
public function getBackendTable()
{
if ($this->_dataTable === null) {
if ($this->isStatic()) {
$this->_dataTable = $this->getEntityType()->getValueTablePrefix();
} else {
$backendTable = trim($this->_getData('backend_table'));
if (empty($backendTable)) {
$entityTable = array($this->getEntity()->getEntityTablePrefix(), $this->getBackendType());
$backendTable = $this->getResource()->getTable($entityTable);
}
$this->_dataTable = $backendTable;
}
}
return $this->_dataTable;
}
Given this happens from the following class
Mage_Catalog_Model_Resource_Product_Flat
It says to me that you have an extension and/or customization done that assumes you're not using the flat catalog data tables and wasn't coded to work with the flat table.
Dropping in a debugging call like this
if(!is_callable(array($this->getEntity()),'getEntityTablePrefix'))
{
mageDebugBacktrace();
//debug_print_backtrace();
exit;
}
right before the offending call (in a local code pool override, of course), will print out a call-stack that should point the offending code.
The seems that problem is in Mage_CatalogSearch_Model_Resource_Search_Collection::_getSearchEntityIdsSql that is not compatible with using the product flat index.
You can rewrite class Mage_CatalogSearch_Model_Resource_Search_Collection and do two little modifications.
1) Add new function _getSearchEntityIdsSqlUsingFlatIndex to rewrited class. This new function (I hope) does exactly the same thing as original _getSearchEntityIdsSql, but with using the product flat index.
2) Modify function _getSearchEntityIdsSql so that it calls new _getSearchEntityIdsSqlUsingFlatIndex if the catalog product flat index is enabled and built.
See source code:
class VENDOR_MODULE_Model_PATHTOREWRITECLASS extends Mage_CatalogSearch_Model_Resource_Search_Collection {
/**
* Retrieve SQL for search entities using product flat index.
*
* #param $query
* #return Varien_Db_Select
*/
protected function _getSearchEntityIdsSqlUsingFlatIndex($query)
{
/* #var $coreHelper Mage_Core_Model_Resource_Helper_Abstract */
$coreHelper = Mage::getResourceHelper('core');
$likeOptions = array('position' => 'any');
$flatTableName = $this->getTable('catalog/product_flat').'_'.$this->getStoreId();
/** #var Varien_Db_Select $select */
$select = $this->getConnection()
->select()
->from($flatTableName, array('entity_id'));
foreach ($this->_getAttributesCollection() as $attribute) {
/** #var Mage_Catalog_Model_Entity_Attribute $attribute */
if ($this->_isAttributeTextAndSearchable($attribute)) {
$attributeCode = $attribute->getAttributeCode();
$dbFieldName = in_array($attribute->getFrontendInput(), array('select', 'multiselect'))
? $attributeCode.'_value'
: $attributeCode;
if ($this->getConnection()->tableColumnExists($flatTableName, $dbFieldName)) {
$select->where($coreHelper->getCILike($dbFieldName, $this->_searchQuery, $likeOptions));
} else {
Mage::log(__METHOD__.": Attribute '$attributeCode' is missing in flat index.", Zend_Log::NOTICE);
}
}
}
return $select;
}
/**
* Retrieve SQL for search entities
*
* #param unknown_type $query
* #return string
*/
protected function _getSearchEntityIdsSql($query)
{
// HACK - make compatibility with flat index
/** #var Mage_Catalog_Helper_Product_Flat $flatHelper */
$flatHelper = Mage::helper('catalog/product_flat');
if ($this->getStoreId() > 0
&& $flatHelper->isEnabled($this->getStoreId())
&& $flatHelper->isBuilt($this->getStoreId())
) {
return $this->_getSearchEntityIdsSqlUsingFlatIndex($query);
}
// END HACK
return parent::_getSearchEntityIdsSql($query);
}
}

CodeIgniter Validation in Library does not accept callback

my problem is the following: I am writing a login library.
This library has a function _validation() and this uses the validation library to validate the data.
With using normal validation methods it works just fine, but using a callback function just does not work. It is not called.
I call it like this.
$this->CI->form_validation->set_rules('user', 'Username', 'required|callback__check_user');
The functions name is _check_user and it uses the username _check_user($user).
The function itself works fine and I can also call it in the class ($this->_check_user('username')) with a working result.
I am guessing, there might be a problem because I am not workin in a controller so I have a CI instance $this->CI instead of just the original instance $this->
Does anyone have a clue how to fix this?
Thanks in advance.
Hey, I figured out a way that works for me. By just extending the Form_validation library in MY_Form_validation.php you can create custom validation methods. I think it is a clean way and it works perfectly fine. I build the below validation method to check for existing usernames and passwords. $value is something like table_name.fieldname.
I have not message set so that it will use the _exist messages from the lang files.
/**
* Exist
*
* checks if the entry exists in the database
* returns a boolean
*
* #access private
* #param string
* #param field
* #return boolean
*/
function _exist($str, $value)
{
list($table, $column) = explode('.', $value, 2);
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = '$str'");
$row = $query->row();
return ($row->count > 0) ? TRUE : FALSE;
}
Thanks for your help though.
The form validation callback will only fire on a method inside the current controller.
Just do this in the controller you're using the callback:
function _check_user($user)
{
$this->load->model('login');
$result = $this->login->_check_user($user);
return $result;
}

Categories