Source of file ProvidesTemplateData.php

Size: 1,731 Bytes - Last Modified: 2019-06-27T09:09:04+00:00

/home/vagrant/www/document-templates/src/TemplateDataSources/ProvidesTemplateData.php

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
<?php


namespace BWF\DocumentTemplates\TemplateDataSources;


trait ProvidesTemplateData
{
    /**
     * @var array|Array
     */
    protected $data = [];

    /**
     * @return array
     */
    protected function getData(){
        return $this->data;
    }

    /**
     * @return string|null
     */
    public function getNameSpace()
    {
        return $this->canonise($this->namespace ?? '');
    }

    /**
     * @param string|null $namespace
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;
    }

    /**
     * @param bool $useNamespace
     * @return array
     */
    public function getTemplateData($useNamespace = true)
    {
        $data = $this->getData();
        $name = $this->getNameSpace();

        if ($useNamespace) {
            $data = $name ? [$name => $data] : $data;
        }
        return $data;
    }

    /**
     * @param $name
     * @return string
     */
    protected function canonise($name)
    {
        return strtolower(strtr($name, ' ', '_'));
    }

    /**
     * @param $key
     * @return string
     */
    protected function createPlaceholder($key)
    {
        $placeholder = $key;
        if ($this->namespace) {
            $placeholder = $this->getNameSpace() . '.' . $key;
        }

        return $placeholder;
    }

    /**
     * @return \BWF\DocumentTemplates\TemplateDataSources\PlaceholderGroup
     */
    public function getPlaceholders()
    {
        $placeholders = [];
        foreach ($this->getData() as $key => $item) {
            $placeholders[] = $this->createPlaceholder($key);
        }

        return new PlaceholderGroup($this->getNameSpace(), $placeholders, TYPE_SINGLE_PLACEHOLDER);
    }
}