PHP code example of mlukman / doctrine-helper-bundle

1. Go to this page and download the library: Download mlukman/doctrine-helper-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/ */

    

mlukman / doctrine-helper-bundle example snippets


// config/bundles.php

return [
    // ...
    MLukman\DoctrineHelperBundle\DoctrineHelperBundle::class => ['all' => true],
];

$count = $em->getRepository(Comment::class)
    ->createQueryBuilder('c')
    ->select('COUNT(1)')
    ->where('email = :email')
    ->setParameter('email', $email)
    ->getQuery()
    ->getSingleScalarResult();

$count = $ds->count(Comment::class, ['email' => $email]);

  $ds->count(
      Comment::class, // entity class
      ['approved' => false] // (optional) filters
  );
  

  $ds->fulltextSearch(
      Comment::class, // entity class
      ['text'], // array of column names that have fulltext index
      $keyword, // the keyword to search
      ['approved' => true] // (optional) filters
  )->getQuery()->getResult();
  

  $ds->getPrevious(
      $current, // the current record used as pivot
      'submitDate', // the column to sort the records by
      ['parentPost'] // matcher fields (filter only records that match these fields with pivot record)    
  );
  
  // all these methods have same parameter signatures but different return values
  $ds->countPrevious($current, 'submitDate', ['parentPost']);
  $ds->getNext($current, 'submitDate', ['parentPost']);
  $ds->countNext($current, 'submitDate', ['parentPost']);
  

$specificRequest->populate($specificEntity);

use MLukman\DoctrineHelperBundle\DTO\RequestBody;

class CommentRequest extends RequestBody
{
    public ?string $name;
    public ?string $email;
    public ?string $comment;
}

use Doctrine\ORM\Mapping as ORM;
use MLukman\DoctrineHelperBundle\DTO\RequestBodyTargetInterface;

#[ORM\Entity]
class Comment implements RequestBodyTargetInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 30)]
    public ?string $name = null;

    #[ORM\Column(length: 30)]
    public ?string $email = null;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    private ?string $comment = null;

    public function setComment(string $comment): self
    {
        $this->comment = $comment;
        return $this;
    }
}

  #[Route('/comments/post', name: 'app_comments_post')]
  public function comments_post(?CommentRequest $commentRQI): Response
  

  $comment = new Comment();
  if ($commentRQI) {
      $commentRQI->populate($comment);
  }
  

#[Route('/comments/post', name: 'app_comments_post')]
public function comments_post(?CommentRequest $commentRQI, ObjectValidatorV2 $objectValidator): Response
{
    $comment = new Comment();
    if ($commentRQI) {
        $commentRQI->populate($comment);
	    $validateErrors = $objectValidator->validate($comment);
        if (empty($validateErrors)) {
            // Here we can safely save the $comment entity object to database
            // Then make sure to redirect to another page or this same page
        }
        // If we reach here it means $validateErrors has some results
        // We can pass this array to Twig template form to show the errors to the user
        // For now we just print_r
        print_r($validateErrors);
    }

}
   
[
    "quantity" => [
        "This value should not be blank.",
        "This value should be positive."
    ],
    "reference" => [
        "Value must be unique."
    ]
]

$objectValidator->addValidationError("quantity", "This value should not be blank.");
$objectValidator->addValidationError("quantity", "This value should be positive.");
$objectValidator->addValidationError("reference", "Value must be unique.");
$validateResult = $objectValidator->getErrors();

use Doctrine\ORM\Mapping as ORM;
use MLukman\DoctrineHelperBundle\Type\ImageWrapper;

#[ORM\Entity]
class Profile
{
    #[ORM\Column(type: "image", nullable: true)]
    public ?ImageWrapper $photo = null;
}

use MLukman\DoctrineHelperBundle\DTO\RequestBody;

class ProfileRequest extends RequestBody
{
    public ?ImageWrapper $photo = null;
}

$profile->photo = ImageWrapper::fromUploadedFile($uploadedFile);

// $image can be either a resource stream from fopen or simply the full path to the image file on the server
$profile->photo = new ImageWrapper($image);

   // passing $request is optional and only necessary for enabling client-side caching
   return $profile->photo->getDownloadResponse($request);
   

   // first, this method needs to be called inside controller
   $profile->photo->setDownloadLink($this->generateProfileImageLink($profile));
   

   $imageBinary = $profile->photo->get();
   

$profile->photo->resize(400, 300, ImageWrapper::RESIZE_FIT)->getBase64DataUrl();

use MLukman\DoctrineHelperBundle\Type\FileWrapper;

#[ORM\Entity]
class Profile
{
    #[ORM\Column(type: "file", nullable: true)]
    private ?FileWrapper $resume = null;
}

use MLukman\DoctrineHelperBundle\Type\FileWrapper;

#[ORM\Entity]
class Profile
{
    #[ORM\Column(type: "fsfile", nullable: true)]
    private ?FileWrapper $resume = null;
}
 
use MLukman\DoctrineHelperBundle\Type\EncryptedValue;

#[ORM\Entity]
class Profile
{
    #[ORM\Column(type: "encrypted", nullable: true)]
    private ?string $nationalId = null;
}

#[Route('/admin/users', name: 'app_admin_users')]
public function users(Paginator $paginator): Response

#[Route('/admin/users', name: 'app_admin_users')]
public function users(Paginator $paginator, DataStore $ds): Response
{
    $qb = $ds->queryBuilder(User::class, 'u')
        ->andWhere("u.status = 'Active'")
        ->addOrderBy('u.registered', 'DESC');
}

#[Route('/admin/users', name: 'app_admin_users')]
public function users(Paginator $paginator, DataStore $ds): Response
{
    $qb = $ds->queryBuilder(User::class, 'u')
        ->andWhere("u.status = 'Active'")
        ->addOrderBy('u.registered', 'DESC');
    return $this->render('admin/users/index.html.twig', [
        'users' => $paginator->paginateResults($qb),
        'paginator' => $paginator,
    ]);
}

#[Route('/admin/comments', name: 'app_admin_comments')]
public function comments(SearchQuery $search): Response

#[Route('/admin/comments', name: 'app_admin_comments')]
public function comments(SearchQuery $search, DataStore $ds): Response
{
    $qb = $ds->queryBuilder(Comment::class, 'c')
        ->andWhere("c.deleted = 0")
        ->addOrderBy('c.posted', 'DESC');
}

#[Route('/admin/comments', name: 'app_admin_comments')]
public function comments(SearchQuery $search, DataStore $ds): Response
{
    $qb = $ds->queryBuilder(Comment::class, 'c')
        ->andWhere("c.deleted = 0")
        ->addOrderBy('c.posted', 'DESC');
    $search->applyFulltextSearch($qb, ['c.message']);
}

#[Route('/admin/comments', name: 'app_admin_comments')]
public function comments(SearchQuery $search, DataStore $ds): Response
{
    $qb = $ds->queryBuilder(Comment::class, 'c')
        ->andWhere("c.deleted = 0")
        ->addOrderBy('c.posted', 'DESC');
    $search->applyFulltextSearch($qb, ['c.message']);
    return $this->render('admin/comments/index.html.twig', [
        'comments' => $qb->getQuery()->getResult(),
        'searchquery' => $search,
    ]);
}

#[Route('/admin/assets', name: 'app_admin_assets')]
public function assets(PreDefinedQueries $status): Response

#[Route('/admin/assets', name: 'app_admin_assets')]
public function assets(PreDefinedQueries $status, DataStore $ds): Response
{
    $qb = $em->queryBuilder(Asset::class, 'a')
        ->addOrderBy('a.registered', 'DESC');
}

#[Route('/admin/assets', name: 'app_admin_assets')]
public function assets(PreDefinedQueries $status, DataStore $ds): Response
{
    $qb = $em->queryBuilder(Asset::class, 'a')
        ->addOrderBy('a.registered', 'DESC');
    $status
        ->addQuery('all', fn(QueryBuilder $qb) => $qb)
        ->addQuery('active', fn(QueryBuilder $qb) => $qb->andWhere("a.status = 'Active'"))
        ->addQuery('inactive', fn(QueryBuilder $qb) => $qb->andWhere("a.status IN ('Disposed', 'Consumed')"))
        ->apply($qb);
}

#[Route('/admin/assets', name: 'app_admin_assets')]
public function assets(PreDefinedQueries $status, DataStore $ds): Response
{
    $qb = $em->queryBuilder(Asset::class, 'a')
        ->addOrderBy('a.registered', 'DESC');
    $status
        ->addQuery('all', fn(QueryBuilder $qb) => $qb)
        ->addQuery('active', fn(QueryBuilder $qb) => $qb->andWhere("a.status = 'Active'"))
        ->addQuery('inactive', fn(QueryBuilder $qb) => $qb->andWhere("a.status IN ('Disposed', 'Consumed')"))
        ->apply($qb);
    return $this->render('admin/assets/index.html.twig', [
        'assets' => $qb->getQuery()->getResult(),
        'filter' => $status,
    ]);    
}

#[ORM\MappedSuperclass]
abstract class AuditedEntity implements AuditedEntityDatesInterface
{
    use AuditedEntityDatesTrait;
}

#[ORM\MappedSuperclass]
abstract class AuditedEntity implements AuditedEntityByInterface
{
    #[ORM\ManyToOne]
    #[ORM\JoinColumn(onDelete: 'SET NULL')]
    protected ?User $createdBy = null;

    #[ORM\ManyToOne]
    #[ORM\JoinColumn(onDelete: 'SET NULL')]
    protected ?User $updatedBy = null;

    public function getCreatedBy(): ?User
    {
        return $this->createdBy;
    }

    public function getUpdatedBy(): ?User
    {
        return $this->updatedBy;
    }

    public function setCreatedBy(?UserInterface $createdBy)
    {
        if ($createdBy instanceof Login) {
            $this->createdBy = $createdBy->getUser();
        }
    }

    public function setUpdatedBy(?UserInterface $updatedBy)
    {
        if ($updatedBy instanceof Login) {
            $this->updatedBy = $updatedBy->getUser();
        }
    }
}

#[ORM\Entity]
class Component
{
    use \MLukman\DoctrineHelperBundle\Trait\UuidEntityTrait;
}

#[ORM\Entity]
class Component
{
    use \MLukman\DoctrineHelperBundle\Trait\TimestampIdEntityTrait;
}

#[ORM\Entity]
class Component
{
    use \MLukman\DoctrineHelperBundle\Trait\Hex8IdEntityTrait;
}

#[ORM\Entity]
class Component
{
    use \MLukman\DoctrineHelperBundle\Trait\Hex16IdEntityTrait;
}

#[ORM\Entity]
class Component
{
    #[\MLukman\DoctrineHelperBundle\Attribute\Timezonify]
    protected \DateTime $createdDate;
}