Вызов функции-члена guessExtension () для строки с отношением один ко многим - PullRequest
1 голос
/ 05 марта 2020

Я пытаюсь загрузить несколько картинок в Symfony 4.4, но я получил эту ошибку:

Вызов функции-члена guessExtension () для строки

У меня есть связь ManyToOne между Событием и Картинкой. Каждое событие может быть связано со многими изображениями, но каждое изображение может быть связано только с одним событием.

Событие моей сущности:

/**
 * @ORM\Entity(repositoryClass="App\Repository\EventRepository")
 */
class Event
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Picture", mappedBy="event")
     */
    private $pictures;

    /**
     * getter and setter for $this->title
     */

    public function __construct()
    {
        $this->pictures = new ArrayCollection();
    }

    /**
     * @return Collection|Picture[]
     */
    public function getPictures()
    {
        return $this->pictures;
    }

    public function addPicture(Picture $picture)
    {
        if (!$this->pictures->contains($picture)) {
            $this->pictures[] = $picture;
            $picture->setEvent($this);
        }

        return $this;
    }

    public function removePicture(Picture $picture)
    {
        if ($this->pictures->contains($picture)) {
            $this->pictures->removeElement($picture);
            // set the owning side to null (unless already changed)
            if ($picture->getEvent() === $this) {
                $picture->setEvent(null);
            }
        }

        return $this;
    }
}

Изображение моей сущности:

/**
 * @ORM\Entity(repositoryClass="App\Repository\PictureRepository")
 */
class Picture
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="pictures")
     * @ORM\JoinColumn(nullable=false)
     */
    private $event;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * getter and setter for $this->name
     */

    public function getEvent()
    {
        return $this->event;
    }

    public function setEvent(?Event $event)
    {
        $this->event = $event;

        return $this;
    }
}

Форма EventType:

    $builder
        ->add('title', TextType::class)
        ->add('pictures', CollectionType::class, [
            'entry_type' => PictureType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'by_reference' => false,
            'label' => false
        ])
    ;

Форма PictureType

    $builder
        ->add('name', FileType::class, [
            'data_class' => null,
            'label' => ' '
        ])
    ;

Мой контроллер

/**
 * @Route("/new", name="admin-spectacle-new")
 */
public function new(Request $request)
{
    $event = new Event();
    $form = $this->createForm(EventType::class, $event);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $images = $form->get('pictures')->getData();
        foreach ($images as $image) {
                $fileName = md5(uniqid()).'.'.$image->getName()->guessExtension();
                $image->move($this->getParameter('image_spectacle'), $fileName);
                $image->setName($fileName);
        }
        //...
    }
    return $this->render(...);
}

Есть идеи, почему я получаю эту ошибку?

дамп для $ images

object(Doctrine\Common\Collections\ArrayCollection)[1082]
  private 'elements' => 
    array (size=2)
      0 => 
        object(App\Entity\Picture)[1183]
          private 'id' => null
          private 'name' => string 'C:\wamp64\tmp\php35B3.tmp' (length=25)
          private 'event' => 
            object(App\Entity\Event)[705]
              ...

дамп для $ image

object(App\Entity\Picture)[1581]
  private 'id' => null
  private 'name' => string 'C:\wamp64\tmp\phpD132.tmp' (length=25)
  private 'event' => 
    object(App\Entity\Event)[1103]
      private 'id' => null
      private 'title' => string 'azed' (length=4)
      private 'description' => null
      private 'age' => null
      private 'synopsis' => null
      private 'resume' => null
      private 'details' => null
      private 'pdf' => null
      private 'address' => null
      private 'schedule' => null
      private 'minia_picture' => string 'azed-5e620d41cbcc8.jpeg' (length=23)
      private 'header_picture' => string 'azed-5e620d41cc71e.jpeg' (length=23)
      private 'cover_picture' => string 'azed-5e620d41cce11.png' (length=22)
      private 'is_active' => int 1
      private 'categoryEvent' => null
      private 'pictures' => 
        object(Doctrine\Common\Collections\ArrayCollection)[1104]
          private 'elements' => 
            array (size=2)
              ...

Есть идеи?

1 Ответ

0 голосов
/ 06 марта 2020

guessExtension() предназначен для работы с File объектом, а не с простым путем к строке.

use Symfony\Component\HttpFoundation\File\File;

foreach ($images as $image) {
    $file=new File($image->getName());
    $fileName = md5(uniqid()).'.'.$file->guessExtension();
    $file->move($this->getParameter('image_spectacle'), $fileName);
    $image->setName($fileName);
}
...