Brent Heigold
Brent Heigold

Reputation: 1273

(Symfony 4) Function expecting a repository class, when I have set it up to expect an entity class

I'm developing a basic social networking site, and when I try to call a function in my repository (likeExists), it exects an instance of App\Repository\User instead of expecting an instance of App\Entity\User, even though I am clearly setting the function to expect an entity, not a repository.

Here is the code leading up to my function call:

/**
 * @param $likeData
 */
public function addLike($likeData)
{
    $em = $this->getEntityManager();

    $userId = $likeData['userId'];
    /** @var User $user */
    $user = $this->userRepository->find($userId);

    $entityType = $likeData['entityType'];
    $likeType = $likeData['likeType'];

    $likeToAdd = new UserLike();
    $likeToAdd->setUser($user);
    $likeToAdd->setType($likeType);

    $likeAdded = true;

    switch ($likeType) {
        case UserLike::ENTITY_TYPE_POST:
            $postId = $likeData['entityId'];
            $post = $this->postRepository->find($postId);
            if ($this->likeExists($post, $likeType, $user))

Here is the function:

/**
 * @param $entity
 * @param $likeType
 * @param User $user
 */
public function likeExists($entity, $likeType, User $user)
{
    $em = $this->getEntityManager();

    if ($entity->getClassName == 'Post')
    {
        $like = $em->findBy(
            ['user' => $user],
            ['type' => $likeType],
            ['post' => $entity]
            );
    }

I am clearly setting it up to expect a User entity and not a UserRepository entity.

I get the following error:

Argument 3 passed to App\Repository\UserLikeRepository::likeExists() must be an instance of App\Repository\User, instance of App\Entity\User given

Upvotes: 0

Views: 59

Answers (2)

JessGabriel
JessGabriel

Reputation: 1072

You have to import the User real class path. In other side, the use of getClassName() as condition is not good. Because, think about that you have two class with the same name in the same project [that is very frequent]. So, this condition will always return true?

You can (and you should) use "instance of" instead.

if ($entity instance of Post::class) //Your logic

Upvotes: 1

Brent Heigold
Brent Heigold

Reputation: 1273

I had to actually have the statement

use App\Entity\User;

Up at the top.

Upvotes: 0

Related Questions