php8.1 - Deprecated Functionality: DateTime() - date

We use the following code that worked perfectly on php7.4, but we get a deprecated error on php8.1. But how can we succesfully rewrite this for php8.1?
Error:
Deprecated Functionality: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated
Current code:
$today = new \DateTime();$orderdate = new \DateTime($orders->getCreatedAt());
<?php if($orderdate->diff($today)->days > 14):?>
<?php endif;?>

You can no longer do this:
new \DateTime(null);
In your exact use case, I think that PHP has highlighted a bug in your code. If the order does not have a created at date, you'll populate the variable with the date/time when the script runs, which may not be what you want:
var_dump(new \DateTime('1985-12-31 15:00:00'));
var_dump(new \DateTime(''));
var_dump(new \DateTime(null));
object(DateTime)#1 (3) {
["date"]=>
string(26) "1985-12-31 15:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003960"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /in/67OFM on line 5
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003987"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
Demo
If you want to use DB information:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: null;
If you want to default to "now", make it explicit so nobody wonders whether it's intentional:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: new \DateTime();
Last but not least... Analyse if it makes sense from the business logic standpoint to have orders with no creation date. What does that mean?

Related

Unexpected data found during update on eloquent / Laravel

I am using ajax to update a model that contains timestamps, but it throw me an exception:
{message: "Unexpected data found.", exception: "InvalidArgumentException",…}
message: "Unexpected data found."
exception: "InvalidArgumentException"
file: "/home/asus/Devagnos/almada/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php"
line: 623
trace: [,…]
i have disabled the timestamps and i set the dateformat like this:
protected $dateFormat = 'Y-m-d H:i:s.u';
public $timestamps = false;
protected $dates = [
'created_at',
'updated_at'
];
alse I added these methods
/**
* #param $val
*/
public function setCreatedAtAttribute($val)
{
return Carbon::createFromFormat('Y-m-d H:i:s.u', $val);
}
/**
* #param $val
*/
public function setUpdatedAtAttribute($val)
{
return Carbon::createFromFormat('Y-m-d H:i:s.u', $val);
}
but I am always getting the same error, What am I doing wrong ?
I'm using laravel 6.8 and postgresql
If you're trying to use microseconds, then you should refer to this guide from the documentation:
https://carbon.nesbot.com/laravel/
I don't get what you tried with setCreatedAtAttribute and setUpdatedAtAttribute, setters are supposed to change the inner property, not to return a value.
Then check you gave to your DB columns enough precision (such as TIMESTAMP(6)) in your migration schemas.

Zend Expressive Route with optional parameter

I want use a route to get the complete collection and, if available, a filtered collection.
so my route:
$app->get("/companies", \App\Handler\CompanyPageHandler::class, 'companies');
My Handler for this route:
use App\Entity\Company;
use App\Entity\ExposeableCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class CompanyPageHandler extends AbstractHandler
{
public function handle(ServerRequestInterface $request): ResponseInterface
{
$categories = new ExposeableCollection();
foreach (['test', 'test1', 'test3'] as $name) {
$category = new Company();
$category->setName($name);
$categories->addToCollection($category);
}
return $this->publish($categories);
}
}
When getting this route /companies, i get the expected collection
[{"name":"test"},{"name":"test1"},{"name":"test3"}]
So now i change the route
$app->get("/companies[/:search]", \App\Handler\CompanyPageHandler::class, 'companies');
It's all fine when i'm browsing to /companies.
But if i try the optional parameter /companies/test1 then i got an error
Cannot GET http://localhost:8080/companies/test1
my composer require section:
"require": {
"php": "^7.1",
"zendframework/zend-component-installer": "^2.1.1",
"zendframework/zend-config-aggregator": "^1.0",
"zendframework/zend-diactoros": "^1.7.1 || ^2.0",
"zendframework/zend-expressive": "^3.0.1",
"zendframework/zend-expressive-helpers": "^5.0",
"zendframework/zend-stdlib": "^3.1",
"zendframework/zend-servicemanager": "^3.3",
"zendframework/zend-expressive-fastroute": "^3.0"
},
In Zend Framework 2 and Symfony4 this route definition works fine. So im confused.
Why my optional parameter doesn't work?
That's because you are using https://github.com/nikic/FastRoute router and correct syntax would be:
$app->get("/companies[/{search}]", \App\Handler\CompanyPageHandler::class, 'companies');
or be more strict and validate search param something like this:
$app->get("/companies[/{search:[\w\d]+}]", \App\Handler\CompanyPageHandler::class, 'companies');

I need to know how to disable the CSRF function in Impresspages cms

I need to know how to disable the CSRF function in Impresspages cms. i saw a possible answer provided on a previous thread, but wasnt fully sorted. When my customer logs into my impress pages site at: cleanwaterpartnership.co.uk, he gets an "ERROR undefined" message. In the log files on the cms system it states:
Core.possibleCsrfAttack.
The notes say:
array(1) {
["post"]=>
array(6) {
["securityToken"]=> string(32) "b2766e9f8578bf04d456952a35882bb4"
["antispam"]=> array(2) { [0]=> string(0) "" [1]=> string(32) "ea3810b9e1da7fdaffe4003836be0541" }
["sa"]=> string(15) "Admin.loginAjax"
["global_error"]=> string(0) ""
["login"]=> string(16) "Alastair Stewart"
["password"]=> string(16) "XXXXXXXXX" }
}
Use PublicController type. https://www.impresspages.org/docs/controller
This type of controller doesn't do any checks.

Search field - laravel

My search in laravel doesn't work. I'm trying everything, but I've got error: Class 'Bike' not found.
Index.blade:
{{Form::open(array('url'=>'/'))}}
{{Form::text('keyword', null, array('placeholder'=>'Miasto'))}}
{{Form::submit('search')}}
{{Form::close()}}
route:
Route::post('/',function(){
$keyword = Input::get('keyword');
$bikes = Bike::where('city', 'LIKE', '%'.$keyword.'%')->get();
var_dump('search results');
foreach($bikes as $bike){
var_dump($bike->city);
}
You are not returning anything.
return var_dump($bike->city);

Sending template emails in Magento

I'm creating a Magento Module that can be used to send emails in certain occasions of my website. I'm following the tutorial from Branko Ajzele and everything seems to work fine until I try to send the email where I get a false response from the Send function.
Below is the code I'm using along with the result returned:
public function sendAction() {
/*
* Loads the html file named 'custom_email_template1.html' from
* app/locale/en_US/template/email/activecodeline_custom_email1.html
*/
$emailTemplate = Mage::getModel('core/email_template')
->loadDefault('custom_email_template1');
// var_dump(Mage::getModel('core/email_template'));
//Create an array of variables to assign to template
$emailTemplateVariables = array();
$emailTemplateVariables['myvar1'] = 'Branko';
$emailTemplateVariables['myvar2'] = 'Ajzele';
$emailTemplateVariables['myvar3'] = 'ActiveCodeline';
/**
* The best part <img src="http://inchoo.net/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">
* Opens the activecodeline_custom_email1.html, throws in the variable array
* and returns the 'parsed' content that you can use as body of email
*/
/*
* Or you can send the email directly,
* note getProcessedTemplate is called inside send()
*/
$emailTemplate->setSenderName('my name');
$emailTemplate->setSenderEmail('example#domain.com');
$emailTemplate->setTemplateSubject('STATUS CHANGED');
var_dump($emailTemplate->send('example#domain.com'));
echo "<br>";
var_dump($emailTemplate);
exit("test");
}
The var_dump given by var_dump($emailTemplate); returns the object with all the information correctly as shown below:
bool(false)
object(Gp_Notify_Model_Email_Template)#82 (19) { ["_templateFilter:protected"]=> NULL ["_preprocessFlag:protected"]=> bool(false) ["_mail:protected"]=> NULL ["_designConfig:protected"]=> NULL ["_emulatedDesignConfig:protected"]=> bool(false) ["_initialEnvironmentInfo:protected"]=> NULL ["_eventPrefix:protected"]=> string(13) "core_abstract" ["_eventObject:protected"]=> string(6) "object" ["_resourceName:protected"]=> string(19) "core/email_template" ["_resource:protected"]=> NULL ["_resourceCollectionName:protected"]=> string(30) "core/email_template_collection" ["_cacheTag:protected"]=> bool(false) ["_dataSaveAllowed:protected"]=> bool(true) ["_isObjectNew:protected"]=> NULL ["_data:protected"]=> array(6) { ["template_type"]=> int(2) ["template_subject"]=> string(14) "STATUS CHANGED" ["template_text"]=> string(208) "
ActiveCodeline custom email example by Branko Ajzele
Hi there {{var myvar1}} {{var myvar2}} from {{var myvar3}}. This is just some example template to test custom email module.
" ["template_id"]=> string(22) "custom_email_template1" ["sender_name"]=> string(7) "my name" ["sender_email"]=> string(15) "phil#gproxy.com" } ["_hasDataChanges:protected"]=> bool(true) ["_origData:protected"]=> NULL ["_idFieldName:protected"]=> NULL ["_isDeleted:protected"]=> bool(false) } test
The thing is that although everything seems to go well the send function returns false and of course I never get to receive the email.
Is there something I'm forgetting to do like any configuration in the backend or something?
---- UPDATE ----
After some investigation I realized that there are no emails reaching their destination at all in my Magento installation which I thought they were, so figured I should start from there.
I have already added all the emails in the backend.
I checked the Locale (language) and changed it to english/US (which I read could be an issue).
Any advise?
Are u trying it on the localhost or the live site. If you are trying in the localhost then you need to correct in the php.ini file for the email setting.