PHP code example of lenny4 / doctrine-merge-persistent-collection-bundle

1. Go to this page and download the library: Download lenny4/doctrine-merge-persistent-collection-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lenny4 / doctrine-merge-persistent-collection-bundle example snippets




namespace App\Controller;

use Lenny4\DoctrineMergePersistentCollectionBundle\DoctrineMergePersistentCollection;
use Lenny4\DoctrineMergePersistentCollectionBundle\Entity\Father;
use Lenny4\DoctrineMergePersistentCollectionBundle\Entity\Son;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class PutFatherController extends AbstractController
{
    public function __invoke(Father $data, DoctrineMergePersistentCollection $doctrineMergePersistentCollection): Father
    {
        $doctrineMergePersistentCollection->merge(
            $data->getSons(),
            static function (Son $son1, Son $son2) {
                return $son1->getName() === $son2->getName();
            },
            static function (Son $son1, Son $son2) {
                $son1->setAge($son2->getAge());
            },
        );
        return $data;
    }
}

#[ApiResource(
    collectionOperations: [
        'get',
    ],
    itemOperations: [
        'get',
        'put' => [
            'controller' => PutFatherController::class,
        ],
    ],
    attributes: [
        'denormalization_context' => ['groups' => ['w-father']],
    ],
)]
#[ORM\Entity(repositoryClass: FatherRepository::class)]
class Father
{
    #[ORM\Column]
    #[ORM\GeneratedValue]
    #[ORM\Id]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Groups(['w-father'])]
    private ?string $name = null;

    /**
     * @var Collection<int, Son>|Son[]
     */
    #[ORM\OneToMany(mappedBy: 'father', targetEntity: Son::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
    #[Groups(['w-father'])]
    private Collection $sons;

    // getters setters
}

#[ApiResource()]
#[ORM\Entity(repositoryClass: SonRepository::class)]
class Son
{
    #[ORM\Column]
    #[ORM\GeneratedValue]
    #[ORM\Id]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Groups(['w-father'])]
    private ?string $name = null;

    #[ORM\Column]
    #[Groups(['w-father'])]
    private ?int $age = null;

    #[ORM\JoinColumn(nullable: false)]
    #[ORM\ManyToOne(inversedBy: 'sons')]
    private ?Father $father = null;

    // getters setters
}