PHP Classes

File: src/EasyPlaceholder.php

Recommend this page to a friend!
  Classes of Scott Arciszewski   EasyDB   src/EasyPlaceholder.php   Download  
File: src/EasyPlaceholder.php
Role: Class source
Content type: text/plain
Description: Class source
Class: EasyDB
Simple Database Abstraction Layer around PDO
Author: By
Last change:
Date: 1 year ago
Size: 1,749 bytes
 

Contents

Class file image Download
<?php

namespace ParagonIE\EasyDB;

use
ParagonIE\EasyDB\Exception\MustBeNonEmpty;
use
ParagonIE\EasyDB\Exception\EasyDBException;
use function
   
array_merge,
   
array_reduce,
   
is_array,
   
strpos,
   
substr,
   
str_repeat;

/**
 * Class EasyPlaceholder
 *
 * @package ParagonIE\EasyDB
 *
 * @example
 */
class EasyPlaceholder
{
    protected
string $mask;
   
/** @var array<array-key, scalar> $values */
   
protected array $values = [];

   
/**
     * Use custom mask for set value in INSERT or UPDATE
     *
     * @param string $mask
     * @param scalar|array|null ...$values
     *
     * @throws MustBeNonEmpty
     *
     * @psalm-taint-sink sql $mask
     */
   
public function __construct(string $mask, ...$values)
    {
       
$values = array_reduce($values, function ($values, $value) use (&$mask) {
            if (!
is_array($value)) {
               
$values []= $value;
                return
$values;
            }
           
$start_pos = strpos($mask, '?*');
            if (
$start_pos === false) {
                throw new
EasyDBException("Mask don't have \"?*\"");
            }
            if (
count($value) < 1) {
                throw new
MustBeNonEmpty();
            }
           
$mask = substr($mask, 0, $start_pos)
                .
"?"
               
. str_repeat(', ?', \count($value) - 1)
                .
substr($mask, $start_pos + 2);
            return
array_merge($values, $value);
        }, []);
       
$this->mask = $mask;
       
$this->values = $values;
    }

   
/**
     * @return string
     */
   
public function mask(): string
   
{
        return
$this->mask;
    }

   
/**
     * @return array
     */
   
public function values(): array
    {
        return
$this->values;
    }
}