0

I wrote a function where I pass an id parameter trough ItemRepository, and then I check if that item already belongs to another user. I think I made a mistake because every time it returns Exception I defined.

My Service:

public function itemCheck(User $user, $id)
{
    /** @var Item $item */
    $item = $this->getItemRepository()->find($id);

    if(!$item) {
        throw new AppClientException('Item not found!');
    }
    if($user->getId()) {
        if($user->getId() == $item->getId()) {
            return true;
        } else {
            throw new AppClientException('This item belongs to another user!!');
        }
    }
}
Cave Johnson
  • 6,499
  • 5
  • 38
  • 57

1 Answers1

0

You don't need to pass User as parameters anymore here. Make it simple Just do like :

public function itemCheck($id)
{
    /** @var Item $item */
    $item = $this->getItemRepository()->find($id);

    //no record found in database, its okay
    if(!$item) {
        return true;
    }

    return false;
}
JessGabriel
  • 1,062
  • 9
  • 18
  • I want for it to check if belongs to other user and if does to throw an Exception. @JessGabriel – John Soprano Feb 08 '19 at 12:58
  • 1
    Inside this function is not the best place to throw exception. Throw exception only in a place when you can manage it. Here, this code check only if item already belong to an user. So, you can throw exception in the place you call it like : if (itemCheck($id)) {...} else {throw YourException;} – JessGabriel Feb 08 '19 at 13:01
  • I updated code and still throws Exception everytime @JessGabriel – John Soprano Feb 08 '19 at 13:14