不允许序列化'Symfony \ Component \ HttpFoundation \ File \ UploadedFile'

时间:2014-05-07 08:16:57

标签: php symfony serialization file-upload

当我尝试上传与图像断言不匹配的错误文件时,会发生此错误。只接受图像。

用户实体:

<?php

namespace Test\BackBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 * @UniqueEntity(
 *     fields={"email"},
 *     message="This email already exists."
 *  )
 */
class User implements UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="lastName", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="firstName", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="job", type="string", length=255, nullable=true)
     */
    private $job;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(name="salt", type="string", length=255)
     */
    private $salt;

    /**
     * @var array
     *
     * @ORM\Column(name="roles", type="array")
     * @Assert\NotBlank()
     */
    private $roles;

    /**
     * @var boolean
     *
     * @ORM\Column(name="isActive", type="boolean")
     */
    private $isActive;

    /**
     * @var string
     *
     * @ORM\Column(name="avatar", type="string", length=255, nullable=true)
     */
    private $path;

    /**
     * @var string
     *
     * @Assert\Image()
     */
    public $file;

    public function __construct()
    {
        $this->isActive = true;
        $this->salt = md5(uniqid(null, true));
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string 
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string 
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set job
     *
     * @param string $job
     * @return User
     */
    public function setJob($job)
    {
        $this->job = $job;

        return $this;
    }

    /**
     * Get job
     *
     * @return string 
     */
    public function getJob()
    {
        return $this->job;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string 
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set salt
     *
     * @param string $salt
     * @return User
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;

        return $this;
    }

    /**
     * Get salt
     *
     * @return string 
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * Set role
     *
     * @param array $role
     * @throws \InvalidArgumentException
     * @return User
     */
    public function setRoles($role)
    {
        if(array_diff($role, array("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_CUSTOMER"))) {
            throw new \InvalidArgumentException("Bad role");
        }
        $this->roles = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return array 
     */
    public function getRoles()
    {
        return $this->roles;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return User
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean 
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
    }

    /**
     * Set username
     *
     * @param string $email
     *
     * @return string
     */
    public function setUsername($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->email;
    }

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        return 'uploads/img';
    }

    public function upload()
    {
        if (null === $this->file) {
            return;
        } else {
            $this->path = $this->firstName.'_'.$this->lastName.'_'.sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
        }

        $this->file->move($this->getUploadRootDir(), $this->path);

        $this->file = null;
    }

    public function getPath()
    {
        return $this->getWebPath();
    }
}

的用户类型:

$builder
    ->add('firstName', 'text', array(
                    'required' => true
                ))
     ->add('lastName', 'text', array(
                    'required' => true
                ))
     ->add('email', 'email', array(
                    'required' => true
                ))
     ->add('job', 'text', array(
                    'required' => false
                ))
     ->add('file', 'file', array(
                    'label' => false,
                    'required' => false,
                ))
            ;

控制器:

    public function updateMyAccountAction($id, Request $request)
    {
        $entityManager = $this->get('doctrine')->getManager();

        $user = $this->get('doctrine')
            ->getRepository('TestBackBundle:User')
            ->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm = $this->createForm(new UserType(), $user);

        $editForm->handleRequest($request);

        if ($editForm->isValid()) {

            $user->upload();

            $entityManager->persist($user);
            $entityManager->flush();
            $this->get('session')->getFlashBag()->add('success', 'Your profile has been updated');

            return $this->redirect($this->generateUrl('my_account', array('id' => $id)));
        } else {
            $this->get('session')->getFlashBag()->add('error', 'Erreur');

            return $this->redirect($this->generateUrl('my_account', array('id' => $id)));
        }
    }

当我尝试测试图像断言是否工作更新(例如pdf文件)时,会发生此错误。该文件未更新,因此很好。但我的控制器中的闪存包和重定向不起作用...如果我在控制器var_dump("test")中的else中写"test",则显示错误,Symfony检测到表单是无效。

发生错误时,这是​​堆栈跟踪的一部分:

  

在   /home/user/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php   在第155行

152.                $this->roles,
153.                $this->attributes
154.            )
155.        );
    }
    /**
  

at serialize(array(object(User),true,array(object(Role)),array()))   在   /home/kevin/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php   在第155行

读它,我觉得使用roles属性来序列化它有一个问题,因为它是一个数组(我们必须将这个属性声明为一个实现UserInterface的数组)

为什么会出现这种错误?

2 个答案:

答案 0 :(得分:8)

我找到了解决方案:我必须实现Serializable这样的界面:official doc

答案 1 :(得分:0)

DOZ单词的额外精度很少:

最好在图像(或文件,或@Vich \ Uploadable)实体中实现\Serializable ,而不是在用户实体上实现\Serializable,因为您可能会中断登录这种情况。

如果您像我一样使用VichUploader,请不要在用户实体上添加\Serializable并将其添加到@Vich\Uploadable(图像或文件)实体以及这两种方法上:

/** @see \Serializable::serialize() */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->image,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->image,
    ) = unserialize($serialized, array('allowed_classes' => false));
}