PHP code example of kafoso / type-formatter

1. Go to this page and download the library: Download kafoso/type-formatter 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/ */

    

kafoso / type-formatter example snippets



use Kafoso\TypeFormatter\TypeFormatter;

$typeFormatter = TypeFormatter::create();

echo sprintf(
    "%s %s %s %s",
    $typeFormatter->cast(null),
    $typeFormatter->cast(true),
    $typeFormatter->cast("foo"),
    $typeFormatter->cast(new \stdClass)
);

/**
 * Will output:
 * null true "foo" \stdClass
 */



use Kafoso\TypeFormatter\TypeFormatter;

/**
 * @param string|int $value
 * @throws \InvalidArgumentException
 */
function foo($value){
    if (false == is_string($value) && false == is_int($value)) {
        throw new \InvalidArgumentException(sprintf(
            "Expects argument \$value to be a string or an integer. Found: %s",
            TypeFormatter::create()->typeCast($value)
        ));
    }
};

foo(["bar"]);

/**
 * Exception message will read:
 * Expects argument $value to be a string or an integer. Found: (array(1)) [(int) 0 => (string(3)) "bar"]
 */



use Kafoso\TypeFormatter\TypeFormatter;

$typeFormatter = TypeFormatter::create();


use Kafoso\TypeFormatter\TypeFormatter;

$typeFormatter = TypeFormatter::getDefault();
$typeFormatter = $typeFormatter->withArrayDepthMaximum(2);
TypeFormatter::setDefault($typeFormatter);



use Kafoso\TypeFormatter\TypeFormatter;

$typeFormatter = TypeFormatter::create();
$typeFormatter = $typeFormatter->withArrayDepthMaximum(3);
TypeFormatter::setVariation("variation1", $typeFormatter);
$typeFormatter = TypeFormatter::getVariation("variation1");



use Kafoso\TypeFormatter\Encoding;
use Kafoso\TypeFormatter\TypeFormatter;

$customTypeFormatter = TypeFormatter::create();
$customTypeFormatter = $customTypeFormatter->withArrayDepthMaximum(2);
$customTypeFormatter = $customTypeFormatter->withArraySampleSize(3);
$customTypeFormatter = $customTypeFormatter->withStringSampleSize(4);
$customTypeFormatter = $customTypeFormatter->withStringQuotingCharacter("`");



use Kafoso\TypeFormatter\Abstraction\Type\AbstractFormatter;
use Kafoso\TypeFormatter\Collection\Type\ArrayFormatterCollection;
use Kafoso\TypeFormatter\Encoding;
use Kafoso\TypeFormatter\Type\ArrayFormatterInterface;
use Kafoso\TypeFormatter\TypeFormatter;

$customTypeFormatter = TypeFormatter::create();
$customTypeFormatter = $customTypeFormatter->withCustomArrayFormatterCollection(new ArrayFormatterCollection([
    new class extends AbstractFormatter implements ArrayFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format(array $array): ?string
        {
            if (1 == count($array)) {
                return print_r($array, true);
            }
            if (2 == count($array)) {
                return "I am an array!";
            }
            if (3 === count($array)) {
                $array[0] = "SURPRISE!";
                // Override and use DefaultArrayFormatter for rendering output
                return $this->getTypeFormatter()->getDefaultArrayFormatter()->format($array);
            }
            return null; // Pass on to next formatter or lastly DefaultArrayFormatter
        }
    }
]));

echo $customTypeFormatter->cast(["foo"]) . PHP_EOL;

/**
 * Will output:
 * Array
 * (
 *     [0] => foo
 * )
 */

echo $customTypeFormatter->cast(["foo", "bar"]) . PHP_EOL;

/**
 * Will output:
 * I am an array!
 */

echo $customTypeFormatter->cast(["foo", "bar", "baz"]) . PHP_EOL;

/**
 * Will output:
 * [0 => "SURPRISE!", 1 => "bar", 2 => "baz"]
 */

echo $customTypeFormatter->cast(["foo", "bar", "baz", "bim"]) . PHP_EOL;

/**
 * Will output:
 * [0 => "foo", 1 => "bar", 2 => "baz", ... and 1 more element] (sample)
 */

echo $customTypeFormatter->typeCast(["foo", "bar", "baz", "bim"]) . PHP_EOL;

/**
 * Will output:
 * (array(4)) [(int) 0 => (string(3)) "foo", (int) 1 => (string(3)) "bar", (int) 2 => (string(3)) "baz", ... and 1 more element] (sample)
 */



use Doctrine\Common\Persistence\Proxy;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Kafoso\TypeFormatter\Abstraction\Type\AbstractFormatter;
use Kafoso\TypeFormatter\Collection\Type\ObjectFormatterCollection;
use Kafoso\TypeFormatter\Encoding;
use Kafoso\TypeFormatter\Type\DefaultObjectFormatter;
use Kafoso\TypeFormatter\Type\ObjectFormatterInterface;
use Kafoso\TypeFormatter\TypeFormatter;
use PHPUnit\Framework\MockObject\Generator;
use PHPUnit\Framework\TestCase;

$generator = new Generator;
$entityManager = $generator->getMock(EntityManager::class, [], [], '', false);
$metadataFactory = $generator->getMock(ClassMetadataFactory::class, [], [], '', false);
$metadataFactory
    ->expects(TestCase::any())
    ->method('isTransient')
    ->withConsecutive(TestCase::equalTo('User'), TestCase::equalTo('stdClass'))
    ->willReturnOnConsecutiveCalls(TestCase::returnValue(false), TestCase::returnValue(true));
$entityManager
    ->expects(TestCase::any())
    ->method('getMetadataFactory')
    ->will(TestCase::returnValue($metadataFactory));

$customTypeFormatter = TypeFormatter::create();
$customTypeFormatter = $customTypeFormatter->withCustomObjectFormatterCollection(new ObjectFormatterCollection([
    new class ($entityManager) extends AbstractFormatter implements ObjectFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format($object): ?string
        {
            if (false == is_object($object)) {
                return null; // Pass on to next formatter or lastly DefaultObjectFormatter
            }
            if ($object instanceof \DateTimeInterface) {
                return sprintf(
                    "\\%s (%s)",
                    DefaultObjectFormatter::getClassName($object),
                    $object->format("c")
                );
            }
            return null; // Pass on to next formatter or lastly DefaultObjectFormatter
        }
    },
    new class extends AbstractFormatter implements ObjectFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format($object): ?string
        {
            if (false == is_object($object)) {
                return null; // Pass on to next formatter or lastly DefaultObjectFormatter
            }
            if ($object instanceof \Throwable) {
                return sprintf(
                    "\\%s {\$code = %s, \$file = %s, \$line = %s, \$message = %s}",
                    DefaultObjectFormatter::getClassName($object),
                    $this->getTypeFormatter()->cast($object->getCode()),
                    $this->getTypeFormatter()->cast($object->getFile(), false),
                    $this->getTypeFormatter()->cast($object->getLine()),
                    $this->getTypeFormatter()->cast($object->getMessage())
                );
            }
            return null; // Pass on to next formatter or lastly DefaultObjectFormatter
        }
    },
    new class ($entityManager) extends AbstractFormatter implements ObjectFormatterInterface
    {
        /**
         * @var EntityManager
         */
        private $entityManager;

        public function __construct(EntityManager $entityManager)
        {
            $this->entityManager = $entityManager;
        }

        /**
         * @inheritDoc
         */
        public function format($object): ?string
        {
            if (false == is_object($object)) {
                return null; // Pass on to next formatter or lastly DefaultObjectFormatter
            }
            $className = ($object instanceof Proxy) ? get_parent_class($object) : DefaultObjectFormatter::getClassName($object);
            $isEntity = (false == $this->entityManager->getMetadataFactory()->isTransient($className));
            $id = null;
            if ($isEntity && method_exists($object, 'getId')) {
                // You may of course implement logic, which can extract and present any @ORM\Id columns, even composite IDs.
                $id = $object->getId();
            }
            if (is_int($id)) {
                return sprintf(
                    "\\%s {\$id = %d}",
                    $className,
                    $id
                );
            }
            return null; // Pass on to next formatter or lastly DefaultObjectFormatter
        }
    },
]));

echo $customTypeFormatter->cast(new \stdClass) . PHP_EOL;

/**
 * Will output (standard TypeFormatter object-to-string output):
 * \stdClass
 */

echo $customTypeFormatter->cast(new \DateTimeImmutable("2019-01-01T00:00:00+00:00")) . PHP_EOL;

/**
 * Will output:
 * \DateTimeImmutable ("2019-01-01T00:00:00+00:00")
 */

class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $id = null;

    public function getId(): ?int
    {
        return $this->id;
    }
}
$doctrineEntity = new \User;

// Pretend we fetch it from a database
$reflectionObject = new \ReflectionObject($doctrineEntity);
$reflectionProperty = $reflectionObject->getProperty("id");
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($doctrineEntity, 1);

echo $customTypeFormatter->cast($doctrineEntity) . PHP_EOL;

/**
 * Will output:
 * \User {$id = 1}
 */

echo $customTypeFormatter->cast(new \RuntimeException("test", 1)) . PHP_EOL;

/**
 * Will output:
 * \RuntimeException {$code = 1, $file = "<file>", $line = <line>, $message = "test"}
 * , where:
 *    - <file> is the path this this file.
 *    - <line> is the line number at which the \RuntimeException is instantiated.
 */



use Kafoso\TypeFormatter\Abstraction\Type\AbstractFormatter;
use Kafoso\TypeFormatter\Collection\Type\ResourceFormatterCollection;
use Kafoso\TypeFormatter\Encoding;
use Kafoso\TypeFormatter\Type\ResourceFormatterInterface;
use Kafoso\TypeFormatter\TypeFormatter;

$customTypeFormatter = TypeFormatter::create();
$customTypeFormatter = $customTypeFormatter->withCustomResourceFormatterCollection(new ResourceFormatterCollection([
    new class extends AbstractFormatter implements ResourceFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format($resource): ?string
        {
            if (false == is_resource($resource)) {
                return null; // Pass on to next formatter or lastly DefaultResourceFormatter
            }
            if ("stream" === get_resource_type($resource)) {
                return "opendir/fopen/tmpfile/popen/fsockopen/pfsockopen {$resource}";
            }
            return null; // Pass on to next formatter or lastly DefaultResourceFormatter
        }
    },
    new class extends AbstractFormatter implements ResourceFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format($resource): ?string
        {
            if (false == is_resource($resource)) {
                return null; // Pass on to next formatter or lastly DefaultResourceFormatter
            }
            if ("xml" === get_resource_type($resource)) {
                return "XML {$resource}";
            }
            return null; // Pass on to next formatter or lastly DefaultResourceFormatter
        }
    },
]));

echo $customTypeFormatter->cast(fopen(__FILE__, "r+")) . PHP_EOL;

/**
 * Will output:
 * opendir/fopen/tmpfile/popen/fsockopen/pfsockopen Resource id #<id>
 */

echo $customTypeFormatter->cast(\xml_parser_create("UTF-8")) . PHP_EOL;

/**
 * Will output:
 * XML Resource id #<id>
 */



use Kafoso\TypeFormatter\Abstraction\Type\AbstractFormatter;
use Kafoso\TypeFormatter\Collection\Type\StringFormatterCollection;
use Kafoso\TypeFormatter\Encoding;
use Kafoso\TypeFormatter\Type\StringFormatterInterface;
use Kafoso\TypeFormatter\TypeFormatter;

$customTypeFormatter = TypeFormatter::create();
$customTypeFormatter = $customTypeFormatter->withCustomStringFormatterCollection(new StringFormatterCollection([
    new class extends AbstractFormatter implements StringFormatterInterface
    {
        /**
         * @inheritDoc
         */
        public function format(string $string): ?string
        {
            if ("What do we like?" === $string) {
                return $this->getTypeFormatter()->getDefaultStringFormatter()->format("CAKE!");
            }
            return null; // Pass on to next formatter or lastly DefaultStringFormatter
        }
    },
]));

echo $customTypeFormatter->cast("What do we like?") . PHP_EOL;

/**
 * Will output:
 * "CAKE!"
 */


cd tests
php ../bin/phpunit tests/Test/Unit