How to access SESSION of loggedInUser outside CakePHP 2.x - session

I need to know if a user is logged in and need to access at his infos outside CakePHP but on the same domain.
I've tried the following code
session_start();
session_name('CAKEPHP');
if(isset($_COOKIE['CAKEPHP'])){
session_id($_COOKIE['CAKEPHP']);
echo "isset<br/>";
var_dump($_SESSION);
}
echo "user :".$_SESSION['userCakeUser']['email'];
I have the follwing output :
isset
array(1) {
["userCakeUser"]=> object(__PHP_Incomplete_Class)#1 (7)
{ ["__PHP_Incomplete_Class_Name"]=> string(12) "loggedInUser"
["email"]=> string(17) "a#a.net"<
["hash_pw"]=> string(65) "dsfsdfsdfsdfsdfsdfddsfsdfsdfsdf"
["user_id"]=> int(4) ["title"]=> string(10) "New Member"
["displayname"]=> string(5) "Toto"
["username"]=> string(5) "Toto"
}
}
Fatal error: Cannot use object of type __PHP_Incomplete_Class as array on line 15
Please can you tell me how do I access the email for example.

The error message is giving you enough information about what is wrong:
Fatal error: Cannot use object of type __PHP_Incomplete_Class as array on line 15
It's an object what you are dealing with. Try:
echo "user :".$_SESSION['userCakeUser']->email;

Thank you #Inigo Flores,
It is better, but I had the following error :
Notice: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "loggedInUser" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition on line 16`
So I have Included this class :
include("path_to_cake_php/models/class.user.php" )

Related

ApiResource attribute gives Compile Error: Constant expression contains invalid operations

I'm trying to expose only some endpoints with API Platform as explained here: https://api-platform.com/docs/v2.7/core/operations/.
If I just use the ApiResource attribute, I get the expected result (i.e. the default CRUD endpoints).
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Metadata\ApiResource;
use App\Repository\MyclassRepository;
#[ORM\Entity(repositoryClass: MyclassRepository::class)]
#[ApiResource]
class Myclass
{
}
But none of the options to show only some operations work.
This one:
#[ApiResource(operations=[
new Get(),
new GetCollection()
])]
... just outputs "No operations defined in spec!" on /api/docs. It also makes VSCode angry about "operation=":
Expression is not writable.intelephense(1024)
Undefined constant 'App\Entity\operations'.intelephense(1011)
Syntax error: unexpected token '='PHP(PHP2014)
This one:
#[ApiResource(
operations: [
new Get(),
new GetCollection()
]
)]
... produces the error "Compile Error: Constant expression contains invalid operations".
The project is running locally on Docker php:8.0-fpm with "api-platform/core": "^2.7".
The appropriate "use" statements are present.
I tried different combinations of methods and config (e.g. uriTemplate).
I also tried using api-platform ^2.6 with :
#[ApiResource(
collectionOperations: ['get'],
itemOperations: ['get'],
)]
... which produces the error "Unknown named parameter $collectionOperations".
What am I missing?
Thanks!!
API Platform requires PHP 8.1, not 8.0. After upgrading, this works:
#[ApiResource(
operations: [
new Get(),
new GetCollection()
]
)]

How to Catch a "Trying to get property of non-object Error" in Laravel

How can I find the culprit of the following error in Laravel?
Trying to get property of a non-object Error
This is most probably coming from calling a method\property on a null object. So to fail early, you should use Model::firstOrFail(); or Model::findOrFail(ID);.
Other than that a null check can do it before you use, but it gets ugly if you have many null checks in your code.
try {} catch (\Exception $e) {} is also a way to catch an exception and handle it manually, but doing this in many places is again a lot of work.
What I do is use a ternary operation on the model before accessing properties of that model like so
$model = Model::find($id); $model ? $name = $model->name : null;
with this you can always be rest assured that a fatal throwable error would not be thrown if the model is not found. This also means you have to check if the variable name is not null before working with it like so if(!is_null($name) { //do your stuff here}

How to fix null given error in laravel-dump-server?

I added "beyondcode/laravel-dump-server": "^1.2"
to my Laravel 5.7 application and sometimes I got error
[2018-10-18 03:44:02] local.ERROR: Argument 1 passed to Symfony\Component\VarDumper\Dumper\HtmlDumper::dump() must be an instance of Symfony\Component\VarDumper\Cloner\Data, null given, called in /mnt/_work_sdb8/wwwroot/lar/Votes/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php on line 47 {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Argument 1 passed to Symfony\\Component\\VarDumper\\Dumper\\HtmlDumper::dump() must be an instance of Symfony\\Component\\VarDumper\\Cloner\\Data, null given, called in /mnt/_work_sdb8/wwwroot/lar/Votes/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php on line 47 at /mnt/_work_sdb8/wwwroot/lar/Votes/vendor/symfony/var-dumper/Dumper/HtmlDumper.php:111)
[stacktrace]
I run server in my console as :
php artisan dump-server --format=html > public/dump.html
I added wrapper method to commom trait of my app:
<?php
namespace App\Http\Traits;
use File;
use Barryvdh\Debugbar\Facade as Debugbar;
use Carbon\Carbon;
use Config;
use Intervention\Image\Facades\Image as Image;
trait funcsTrait
{
public function d($data)
{
if (empty($data)) {
return;
}
dump($data);
}
and calling this method in my control :
$this->d('ProfilePageTest Test51:: $newUserSessionData::' . print_r($newUserSessionData, true));
And sometimes I got error described above.
In my wrapper I tried to exclude calling of dump with empty value, supposing that empty value could be reason of this error ?
But looks like the reason was different. If there is a way make work it properly?
Thanks!

Trying to get property of non-object laravel on command dispatch

I am using "Mapping Command Properties From Requests" getting this error
Trying to get property of non-object
My Code
use App\Command\CreateSomethingCommand;
public function store(Request $request)
{
$this->dispatchFrom(CreateSomethingCommand::class,$request,['user'=>Auth::User()->id]);
.....
}
Where as the command stated at laravel
https://laravel.com/docs/5.0/bus#dispatching-commands
Please Help!
The error is most likely triggered by this part of your code Auth::User()->id. If the user is not logged in then the result of Auth::user() will be null and since null is not an object you can't access the id property on it, thus throwing the exception:
Trying to get property of non-object
To fix that you can use Auth::id() which will return the ID of the logged in user or null otherwise, but you'll avoid the exception.

how can I return the validation errors for a REST call?

I am making a REST api for my application. It almost works, but I want it to return the validation errors when they occurs.
With CakePHP 2.x I see there was an invalidFields method, but it's not there anymore with Cake3. I see, instead, that there is an errors method in the Form class, but I don't know how can I use it.
This is what I have in my Users/json/add.ctp file:
<?php
$echo = [
'errors' => $this->Form->errors(),
'user' => $user
];
echo json_encode($echo);
As I said it doesn't work (I know that probably Form is used out of its scope here, but I don't even know if I am on the right path)...
This is the result:
{
"message": "Missing field name for FormHelper::errors",
"url": "\/fatturazione\/api\/users.json",
"code": 500
}
What is the correct way to display all the form errors when they occour?
This is what I would do, check for validation-errors in your controller and send them to the view serialized
public function add() {
$this->request->allowMethod('post');
$data = $this->Model->newEntity($this->request->data);
if($data->errors()) {
$this->set([
'errors' => $data->errors(),
'_serialize' => ['errors']]);
return;
}
//if no validation errors then save here
}

Resources