<?php

namespace XQueue\Maileon\API\Transactions;

use XQueue\Maileon\API\JSON\AbstractJSONWrapper;

/**
 * A class for wrapping contact references.
 *
 * @author Viktor Balogh | Wanadis Kft. | balogh.viktor@maileon.hu
 */
class ContactReference extends AbstractJSONWrapper
{
    /**
     *
     * @var integer
     *  the Maileon ID of the contact to send the transaction to
     */
    public $id;
    /**
     *
     * @var string
     *  the external ID of the contact to send the transaction to
     */
    public $external_id;
    /**
     *
     * @var string
     *  the email address of the contact to send the transaction to
     */
    public $email;

    /**
     *
     * @var com_maileon_api_contacts_Permission
     *  the permission of this contact
     */
    public $permission;

    /**
     * @return \em string
     *    a human-readable representation of this ContactReference
     */
    function __toString() {
        return parent::__toString();
    }

    /**
     * Signals to the JSON serializer whether this object should be serialized
     *
     * @return boolean
     */
    function isEmpty() {
        $result = !isset($this->id) && !isset($this->external_id) && !isset($this->email);

        return $result;
    }

    function toArray() {
        $array = parent::toArray();

        if($this->permission != null) {
            $array['permission'] = $this->permission->code;
        }

        return $array;
    }
}


<?php
/**
 * Command
 *
 * This file is part of periodic
 *
 * periodic is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; version 3 of the License.
 *
 * periodic is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with periodic; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Core
 * @version $Revision: 999 $
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPL
 */

namespace Arbit\Periodic\Command\FileSystem;

use Arbit\Periodic\Command,
    Arbit\Periodic\Executor,
    Arbit\Periodic\Logger,
    Arbit\XML;

/**
 * Command
 *
 * Command to (recursively) copy files.
 */
class Copy extends Command
{
    /**
     * Run command
     *
     * Execute the actual bits.
     *
     * Should return one of the status constant values, defined as class
     * constants in Executor.
     *
     * @param XML\Node $configuration
     * @param Logger $logger
     * @return int
     */
    public function run( XML\Node $configuration, Logger $logger )
    {
        if ( !isset( $configuration->src ) )
        {
            $logger->log( 'No source provided.', Logger::ERROR );
            return Executor::ERROR;
        }
        $src = (string) $configuration->src;

        if ( !isset( $configuration->dst ) )
        {
            $logger->log( 'No destination provided.', Logger::ERROR );
            return Executor::ERROR;
        }
        $dst = (string) $configuration->dst;

        $depth = -1;
        if ( isset( $configuration->depth ) &&
             is_numeric( (string) $configuration->depth ) )
        {
            $depth = (int) (string) $configuration->depth;
        }

        $this->copyRecursive( $src, $dst, $depth, $logger );
        return Executor::SUCCESS;
    }

    /**
     * Copy files and directories recursively
     *
     * Copy files and directories recursively. I fone operation fails, a
     * warning will be issued and the operation will be continued.
     *
     * A negative depth means infinite recursion. A depth of 1 means that the
     * current files and directories are created, but no recursion is applied.
     *
     * @param string $src
     * @param string $dst
     * @param int $depth
     * @param Logger $logger
     * @return void
     */
    protected function copyRecursive( $src, $dst, $depth, Logger $logger )
    {
        if ( $depth == 0 )
        {
            return;
        }

        // Check if source file exists at all.
        if ( !is_file( $src ) && !is_dir( $src ) )
        {
            $logger->log( "$src is not a valid source.", Logger::WARNING );
            return;
        }

        // Skip non readable files in src directory
        if ( !is_readable( $src ) )
        {
            $logger->log( "$src is not readable, skipping.", Logger::WARNING );
            return;
        }

        // Destination file should not exist
        if ( is_file( $dst ) || is_dir( $dst ) )
        {
            $logger->log( "$dst already exists, and cannot be overwritten.", Logger::WARNING );
            return;
        }

        // Actually copy
        if ( is_dir( $src ) )
        {
            mkdir( $dst );
        }
        elseif ( is_file( $src ) )
        {
            copy( $src, $dst );
            return;
        }

        // Recurse into directory
        $dh = opendir( $src );
        while ( ( $file = readdir( $dh ) ) !== false )
        {
            if ( ( $file === '.' ) ||
                ( $file === '..' ) )
            {
                continue;
            }

            $this->copyRecursive(
                $src . '/' . $file,
                $dst . '/' . $file,
                $depth - 1,
                $logger
            );
        }
    }
}


<?php

namespace Cityware\MemoryShared\Storage;

use Zend\Stdlib\Glob;

class File implements StorageInterface {

    /**
     * Directory storage
     * @var string
     */
    protected $dir;

    /**
     *
     * @param string $dir
     */
    public function __construct($dir = null) {
        if (null === $dir) {
            $dir = DATA_PATH;
        }
        if (is_array($dir)) {
            if (!isset($dir['dir'])) {
                throw new Exception\RuntimeException(
                'File storage options must be a directory '
                . 'name or array with a "dir" key'
                );
            }
            $dir = $dir['dir'];
        }
        if (!file_exists($dir)) {
            throw new Exception\RuntimeException(
            'Directory "' . $dir . '" for the file storage do not exists'
            );
        }
        $this->dir = $dir;
    }

    /**
     * Test if has datas with $uid key
     * @param mixed $uid
     * @return boolean
     */
    public function has($uid) {
        return file_exists($this->dir . '/' . $uid);
    }

    /**
     * Read datas with $uid key
     * @param mixed $uid
     * @return mixed
     */
    public function read($uid) {
        if (!$this->has($uid)) {
            return false;
        }
        $contents = file_get_contents($this->dir . '/' . $uid);
        return unserialize($contents);
    }

    /**
     * Write datas on $uid key
     * @param mixed $uid
     * @param mixed $mixed
     */
    public function write($uid, $mixed) {
        $fp = @fopen($this->dir . '/' . $uid, 'w+');
        if (!$fp) {
            return false;
        }
        $r = fwrite($fp, serialize($mixed));
        fclose($fp);
        return $r;
    }

    /**
     * Clear datas with $uid key
     * @param mixed $uid
     * @return void
     */
    public function clear($uid = null) {
        if ($uid) {
            if (!$this->has($uid)) {
                return false;
            }
            return @unlink($this->dir . '/' . $uid);
        }
        array_map('unlink', Glob::glob($this->dir . '/*', 0));
        return true;
    }

    /**
     * Close storage
     * @param int
     */
    public function close() {
        return;
    }

    /**
     * Get max bloc allow
     * @return int
     */
    public function canAllowBlocsMemory($numBloc) {
        return true; // no limitation
    }

}


<?php
/*
 * This file is part of the CleverAge/PermissionBundle package.
 *
 * Copyright (c) 2015-2018 Clever-Age
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CleverAge\PermissionBundle\DependencyInjection;

use CleverAge\PermissionBundle\Voter\ClassVoter;
use Sidus\BaseBundle\DependencyInjection\SidusBaseExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Autoload services from Resources/config/services
 */
class CleverAgePermissionExtension extends SidusBaseExtension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        parent::load($configs, $container);

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $classVoterDefinition = $container->getDefinition(ClassVoter::class);
        foreach ($config['classes'] as $class => $configuration) {
            $classVoterDefinition->addMethodCall('addPermissions', [$class, $configuration['permissions']]);
        }
    }
}


<?php

namespace PhpOffice\PhpSpreadsheet\Writer\Ods;

use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;

class MetaInf extends WriterPart
{
    /**
     * Write META-INF/manifest.xml to XML format.
     *
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     *
     * @return string XML Output
     */
    public function writeManifest()
    {
        $objWriter = null;
        if ($this->getParentWriter()->getUseDiskCaching()) {
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
        } else {
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
        }

        // XML header
        $objWriter->startDocument('1.0', 'UTF-8');

        // Manifest
        $objWriter->startElement('manifest:manifest');
        $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0');
        $objWriter->writeAttribute('manifest:version', '1.2');

        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', '/');
        $objWriter->writeAttribute('manifest:version', '1.2');
        $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet');
        $objWriter->endElement();
        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', 'meta.xml');
        $objWriter->writeAttribute('manifest:media-type', 'text/xml');
        $objWriter->endElement();
        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', 'settings.xml');
        $objWriter->writeAttribute('manifest:media-type', 'text/xml');
        $objWriter->endElement();
        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', 'content.xml');
        $objWriter->writeAttribute('manifest:media-type', 'text/xml');
        $objWriter->endElement();
        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png');
        $objWriter->writeAttribute('manifest:media-type', 'image/png');
        $objWriter->endElement();
        $objWriter->startElement('manifest:file-entry');
        $objWriter->writeAttribute('manifest:full-path', 'styles.xml');
        $objWriter->writeAttribute('manifest:media-type', 'text/xml');
        $objWriter->endElement();
        $objWriter->endElement();

        return $objWriter->getData();
    }
}


<?php

namespace Vkovic\LaravelMeta\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Meta extends Model
{
    protected $guarded = ['id'];

    protected $table = 'meta';

    protected static $realm = 'vkovic/laravel-meta';

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        // Set realm to always be in attributes by default
        $this->attributes['realm'] = static::$realm;
    }

    public static function boot()
    {
        parent::boot();

        // Add global scope to be used in every query
        static::addGlobalScope('realm', function (Builder $query) {
            $query->where(['realm' => static::$realm]);
        });

        // Saving callback
        static::saving(function (Meta $model) {
            $value = $model->attributes['value'];

            if (is_array($value)) {
                $type = 'array';
                $value = json_encode($value);
            } elseif (is_bool($value)) {
                $type = 'bool';
                $value = $value === true ? '1' : '0';
            } elseif ($value === null) {
                $type = 'null';
            } elseif (is_int($value)) {
                $type = 'int';
                $value = (string) $value;
            } elseif (is_float($value)) {
                $type = 'float';
                $value = (string) $value;
            } else {
                $type = 'string';
                $value = (string) $value;
            }

            $model->attributes['type'] = $type;
            $model->attributes['value'] = $value;
        });
    }

    public static function getRealm()
    {
        return static::$realm;
    }

    /**
     * Filter meta by realm and order by meta key
     *
     * @param Builder $query
     *
     * @return mixed
     */
    public function scopeRealm(Builder $query)
    {
        return $query->where(['realm' => static::$realm])->orderBy('key');
    }

    /**
     * Key setter
     *
     * @param $value
     *
     * @throws \Exception
     */
    public function setKeyAttribute($value)
    {
        // Key must be string
        if (!is_string($value)) {
            throw new \Exception('Invalid key type. Key must be string');
        }

        // Key must be below 129 chars
        if (strlen($value) > 128) {
            throw new \Exception('Invalid key length. Key must be below 128 chars');
        }

        $this->attributes['key'] = $value;
    }

    /**
     * Type setter
     *
     * @param $value
     *
     * @throws \Exception
     */
    public function setTypeAttribute($value)
    {
        throw new \Exception("Meta type can't be set explicitly");
    }

    /**
     * Value getter
     *
     * @param $value
     *
     * @return float|array|string
     */
    public function getValueAttribute($value)
    {
        $type = $this->attributes['type'];

        if ($type == 'string' || $type == 'null') {
            return $value;
        } elseif ($type == 'array') {
            return json_decode($value, true);
        } elseif ($type == 'int') {
            return (int) $value;
        } elseif ($type == 'float') {
            return (float) $value;
        } elseif ($type == 'bool') {
            return (bool) $value;
        }
    }
}


<?php

namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;

class Theme
{
    /**
     * Theme Name.
     *
     * @var string
     */
    private $themeName;

    /**
     * Colour Scheme Name.
     *
     * @var string
     */
    private $colourSchemeName;

    /**
     * Colour Map.
     *
     * @var array of string
     */
    private $colourMap;

    /**
     * Create a new Theme.
     *
     * @param mixed $themeName
     * @param mixed $colourSchemeName
     * @param mixed $colourMap
     */
    public function __construct($themeName, $colourSchemeName, $colourMap)
    {
        // Initialise values
        $this->themeName = $themeName;
        $this->colourSchemeName = $colourSchemeName;
        $this->colourMap = $colourMap;
    }

    /**
     * Get Theme Name.
     *
     * @return string
     */
    public function getThemeName()
    {
        return $this->themeName;
    }

    /**
     * Get colour Scheme Name.
     *
     * @return string
     */
    public function getColourSchemeName()
    {
        return $this->colourSchemeName;
    }

    /**
     * Get colour Map Value by Position.
     *
     * @param mixed $index
     *
     * @return string
     */
    public function getColourByIndex($index)
    {
        if (isset($this->colourMap[$index])) {
            return $this->colourMap[$index];
        }

        return null;
    }

    /**
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
     */
    public function __clone()
    {
        $vars = get_object_vars($this);
        foreach ($vars as $key => $value) {
            if ((is_object($value)) && ($key != '_parent')) {
                $this->$key = clone $value;
            } else {
                $this->$key = $value;
            }
        }
    }
}


<?php

namespace PhpOffice\PhpSpreadsheet\Calculation;

use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class TextData
{
    private static $invalidChars;

    private static function unicodeToOrd($character)
    {
        return unpack('V', iconv('UTF-8', 'UCS-4LE', $character))[1];
    }

    /**
     * CHARACTER.
     *
     * @param string $character Value
     *
     * @return string
     */
    public static function CHARACTER($character)
    {
        $character = Functions::flattenSingleValue($character);

        if ((!is_numeric($character)) || ($character < 0)) {
            return Functions::VALUE();
        }

        if (function_exists('iconv')) {
            return iconv('UCS-4LE', 'UTF-8', pack('V', $character));
        }

        return mb_convert_encoding('&#' . (int) $character . ';', 'UTF-8', 'HTML-ENTITIES');
    }

    /**
     * TRIMNONPRINTABLE.
     *
     * @param mixed $stringValue Value to check
     *
     * @return string
     */
    public static function TRIMNONPRINTABLE($stringValue = '')
    {
        $stringValue = Functions::flattenSingleValue($stringValue);

        if (is_bool($stringValue)) {
            return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        if (self::$invalidChars == null) {
            self::$invalidChars = range(chr(0), chr(31));
        }

        if (is_string($stringValue) || is_numeric($stringValue)) {
            return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F"));
        }

        return null;
    }

    /**
     * TRIMSPACES.
     *
     * @param mixed $stringValue Value to check
     *
     * @return string
     */
    public static function TRIMSPACES($stringValue = '')
    {
        $stringValue = Functions::flattenSingleValue($stringValue);
        if (is_bool($stringValue)) {
            return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        if (is_string($stringValue) || is_numeric($stringValue)) {
            return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' ');
        }

        return null;
    }

    /**
     * ASCIICODE.
     *
     * @param string $characters Value
     *
     * @return int
     */
    public static function ASCIICODE($characters)
    {
        if (($characters === null) || ($characters === '')) {
            return Functions::VALUE();
        }
        $characters = Functions::flattenSingleValue($characters);
        if (is_bool($characters)) {
            if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
                $characters = (int) $characters;
            } else {
                $characters = ($characters) ? Calculation::getTRUE() : Calculation::getFALSE();
            }
        }

        $character = $characters;
        if (mb_strlen($characters, 'UTF-8') > 1) {
            $character = mb_substr($characters, 0, 1, 'UTF-8');
        }

        return self::unicodeToOrd($character);
    }

    /**
     * CONCATENATE.
     *
     * @return string
     */
    public static function CONCATENATE(...$args)
    {
        $returnValue = '';

        // Loop through arguments
        $aArgs = Functions::flattenArray($args);
        foreach ($aArgs as $arg) {
            if (is_bool($arg)) {
                if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
                    $arg = (int) $arg;
                } else {
                    $arg = ($arg) ? Calculation::getTRUE() : Calculation::getFALSE();
                }
            }
            $returnValue .= $arg;
        }

        return $returnValue;
    }

    /**
     * DOLLAR.
     *
     * This function converts a number to text using currency format, with the decimals rounded to the specified place.
     * The format used is $#,##0.00_);($#,##0.00)..
     *
     * @param float $value The value to format
     * @param int $decimals The number of digits to display to the right of the decimal point.
     *                                    If decimals is negative, number is rounded to the left of the decimal point.
     *                                    If you omit decimals, it is assumed to be 2
     *
     * @return string
     */
    public static function DOLLAR($value = 0, $decimals = 2)
    {
        $value = Functions::flattenSingleValue($value);
        $decimals = $decimals === null ? 0 : Functions::flattenSingleValue($decimals);

        // Validate parameters
        if (!is_numeric($value) || !is_numeric($decimals)) {
            return Functions::NAN();
        }
        $decimals = floor($decimals);

        $mask = '$#,##0';
        if ($decimals > 0) {
            $mask .= '.' . str_repeat('0', $decimals);
        } else {
            $round = pow(10, abs($decimals));
            if ($value < 0) {
                $round = 0 - $round;
            }
            $value = MathTrig::MROUND($value, $round);
        }

        return NumberFormat::toFormattedString($value, $mask);
    }

    /**
     * SEARCHSENSITIVE.
     *
     * @param string $needle The string to look for
     * @param string $haystack The string in which to look
     * @param int $offset Offset within $haystack
     *
     * @return string
     */
    public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1)
    {
        $needle = Functions::flattenSingleValue($needle);
        $haystack = Functions::flattenSingleValue($haystack);
        $offset = Functions::flattenSingleValue($offset);

        if (!is_bool($needle)) {
            if (is_bool($haystack)) {
                $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE();
            }

            if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) {
                if (StringHelper::countCharacters($needle) == 0) {
                    return $offset;
                }

                $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8');
                if ($pos !== false) {
                    return ++$pos;
                }
            }
        }

        return Functions::VALUE();
    }

    /**
     * SEARCHINSENSITIVE.
     *
     * @param string $needle The string to look for
     * @param string $haystack The string in which to look
     * @param int $offset Offset within $haystack
     *
     * @return string
     */
    public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1)
    {
        $needle = Functions::flattenSingleValue($needle);
        $haystack = Functions::flattenSingleValue($haystack);
        $offset = Functions::flattenSingleValue($offset);

        if (!is_bool($needle)) {
            if (is_bool($haystack)) {
                $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE();
            }

            if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) {
                if (StringHelper::countCharacters($needle) == 0) {
                    return $offset;
                }

                $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8');
                if ($pos !== false) {
                    return ++$pos;
                }
            }
        }

        return Functions::VALUE();
    }

    /**
     * FIXEDFORMAT.
     *
     * @param mixed $value Value to check
     * @param int $decimals
     * @param bool $no_commas
     *
     * @return string
     */
    public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false)
    {
        $value = Functions::flattenSingleValue($value);
        $decimals = Functions::flattenSingleValue($decimals);
        $no_commas = Functions::flattenSingleValue($no_commas);

        // Validate parameters
        if (!is_numeric($value) || !is_numeric($decimals)) {
            return Functions::NAN();
        }
        $decimals = floor($decimals);

        $valueResult = round($value, $decimals);
        if ($decimals < 0) {
            $decimals = 0;
        }
        if (!$no_commas) {
            $valueResult = number_format($valueResult, $decimals);
        }

        return (string) $valueResult;
    }

    /**
     * LEFT.
     *
     * @param string $value Value
     * @param int $chars Number of characters
     *
     * @return string
     */
    public static function LEFT($value = '', $chars = 1)
    {
        $value = Functions::flattenSingleValue($value);
        $chars = Functions::flattenSingleValue($chars);

        if ($chars < 0) {
            return Functions::VALUE();
        }

        if (is_bool($value)) {
            $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return mb_substr($value, 0, $chars, 'UTF-8');
    }

    /**
     * MID.
     *
     * @param string $value Value
     * @param int $start Start character
     * @param int $chars Number of characters
     *
     * @return string
     */
    public static function MID($value = '', $start = 1, $chars = null)
    {
        $value = Functions::flattenSingleValue($value);
        $start = Functions::flattenSingleValue($start);
        $chars = Functions::flattenSingleValue($chars);

        if (($start < 1) || ($chars < 0)) {
            return Functions::VALUE();
        }

        if (is_bool($value)) {
            $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        if (empty($chars)) {
            return '';
        }

        return mb_substr($value, --$start, $chars, 'UTF-8');
    }

    /**
     * RIGHT.
     *
     * @param string $value Value
     * @param int $chars Number of characters
     *
     * @return string
     */
    public static function RIGHT($value = '', $chars = 1)
    {
        $value = Functions::flattenSingleValue($value);
        $chars = Functions::flattenSingleValue($chars);

        if ($chars < 0) {
            return Functions::VALUE();
        }

        if (is_bool($value)) {
            $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8');
    }

    /**
     * STRINGLENGTH.
     *
     * @param string $value Value
     *
     * @return int
     */
    public static function STRINGLENGTH($value = '')
    {
        $value = Functions::flattenSingleValue($value);

        if (is_bool($value)) {
            $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return mb_strlen($value, 'UTF-8');
    }

    /**
     * LOWERCASE.
     *
     * Converts a string value to upper case.
     *
     * @param string $mixedCaseString
     *
     * @return string
     */
    public static function LOWERCASE($mixedCaseString)
    {
        $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);

        if (is_bool($mixedCaseString)) {
            $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return StringHelper::strToLower($mixedCaseString);
    }

    /**
     * UPPERCASE.
     *
     * Converts a string value to upper case.
     *
     * @param string $mixedCaseString
     *
     * @return string
     */
    public static function UPPERCASE($mixedCaseString)
    {
        $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);

        if (is_bool($mixedCaseString)) {
            $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return StringHelper::strToUpper($mixedCaseString);
    }

    /**
     * PROPERCASE.
     *
     * Converts a string value to upper case.
     *
     * @param string $mixedCaseString
     *
     * @return string
     */
    public static function PROPERCASE($mixedCaseString)
    {
        $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);

        if (is_bool($mixedCaseString)) {
            $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
        }

        return StringHelper::strToTitle($mixedCaseString);
    }

    /**
     * REPLACE.
     *
     * @param string $oldText String to modify
     * @param int $start Start character
     * @param int $chars Number of characters
     * @param string $newText String to replace in defined position
     *
     * @return string
     */
    public static function REPLACE($oldText, $start, $chars, $newText)
    {
        $oldText = Functions::flattenSingleValue($oldText);
        $start = Functions::flattenSingleValue($start);
        $chars = Functions::flattenSingleValue($chars);
        $newText = Functions::flattenSingleValue($newText);

        $left = self::LEFT($oldText, $start - 1);
        $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1);

        return $left . $newText . $right;
    }

    /**
     * SUBSTITUTE.
     *
     * @param string $text Value
     * @param string $fromText From Value
     * @param string $toText To Value
     * @param int $instance Instance Number
     *
     * @return string
     */
    public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0)
    {
        $text = Functions::flattenSingleValue($text);
        $fromText = Functions::flattenSingleValue($fromText);
        $toText = Functions::flattenSingleValue($toText);
        $instance = floor(Functions::flattenSingleValue($instance));

        if ($instance == 0) {
            return str_replace($fromText, $toText, $text);
        }

        $pos = -1;
        while ($instance > 0) {
            $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8');
            if ($pos === false) {
                break;
            }
            --$instance;
        }

        if ($pos !== false) {
            return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText);
        }

        return $text;
    }

    /**
     * RETURNSTRING.
     *
     * @param mixed $testValue Value to check
     *
     * @return null|string
     */
    public static function RETURNSTRING($testValue = '')
    {
        $testValue = Functions::flattenSingleValue($testValue);

        if (is_string($testValue)) {
            return $testValue;
        }

        return null;
    }

    /**
     * TEXTFORMAT.
     *
     * @param mixed $value Value to check
     * @param string $format Format mask to use
     *
     * @return string
     */
    public static function TEXTFORMAT($value, $format)
    {
        $value = Functions::flattenSingleValue($value);
        $format = Functions::flattenSingleValue($format);

        if ((is_string($value)) && (!is_numeric($value)) && Date::isDateTimeFormatCode($format)) {
            $value = DateTime::DATEVALUE($value);
        }

        return (string) NumberFormat::toFormattedString($value, $format);
    }

    /**
     * VALUE.
     *
     * @param mixed $value Value to check
     *
     * @return bool
     */
    public static function VALUE($value = '')
    {
        $value = Functions::flattenSingleValue($value);

        if (!is_numeric($value)) {
            $numberValue = str_replace(
                StringHelper::getThousandsSeparator(),
                '',
                trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode())
            );
            if (is_numeric($numberValue)) {
                return (float) $numberValue;
            }

            $dateSetting = Functions::getReturnDateType();
            Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);

            if (strpos($value, ':') !== false) {
                $timeValue = DateTime::TIMEVALUE($value);
                if ($timeValue !== Functions::VALUE()) {
                    Functions::setReturnDateType($dateSetting);

                    return $timeValue;
                }
            }
            $dateValue = DateTime::DATEVALUE($value);
            if ($dateValue !== Functions::VALUE()) {
                Functions::setReturnDateType($dateSetting);

                return $dateValue;
            }
            Functions::setReturnDateType($dateSetting);

            return Functions::VALUE();
        }

        return (float) $value;
    }
}


<?php

namespace XQueue\Maileon\API\JSON;

use XQueue\Maileon\API\JSON\AbstractJSONWrapper;
use XQueue\Maileon\API\JSON\JSONSerializer;

/**
 * Helper class for serializing JSON data
 *
 * @author Balogh Viktor <balogh.viktor@maileon.hu> | Maileon - Wanadis Kft.
 */
class JSONSerializer {
    /**
     * Used to serialize Maileon classes to JSON
     *
     * @param AbstractJSONWrapper|array $object
     *  The object to serialize
     * @returns string
     *  The JSON representation of the object
     */
    static function json_encode($object) {
        return json_encode(self::toArray($object));
    }

    /**
     * Helper function used to prepare this object for JSON serialization
     *
     * @param array|com_maileon_api_json_AbstractJSONWrapper $object
     *  The object to prepare
     * @return array
     *  The array ready for json_encode
     */
    private static function toArray($object) {
        $type = gettype($object);

        if($type == 'array') {
            foreach($object as $element) {
                // call this method on each object in the array
                $result[]= self::toArray($element);
            }

            // return the processed array
            return $result;
        } else if ($type == 'object') {
            // if we can call toArray() on this object call it, otherwise return
            // the object as-is and trigger a notice
            if(is_subclass_of($object, 'AbstractJSONWrapper')) {
                return $object->toArray();
            } else {
                trigger_error("JSONSerializer: Trying to serialize " . get_class($object));
                return $object;
            }
        } else {
            // if this is not an object we have nothing to do
            return $object;
        }
    }
}


<?php
/*   _            _          _ ____   ___  _____
 *  | |          | |        | |___ \ / _ \| ____|
 *  | |      __ _| |__   ___| | __) | | | | |__
 *  | |     / _` | '_ \ / _ \ ||__ <|  -  |___ \
 *  | |____| (_| | |_) |  __/ |___) |     |___) |
 *  |______|\__,_|_.__/ \___|_|____/ \___/|____/
 *
 *  Copyright Label305 B.V. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Label305\AujaLaravel\Config;

use Doctrine\DBAL\Types\Type;
use Illuminate\Foundation\Application;

/**
 * A class for resolving configuration for a model.
 *
 * @author  Niek Haarman - <niek@label305.com>
 *
 * @package Label305\AujaLaravel
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
class ConfigResolver {

    private $displayFieldNames = ['name', 'title'];

    /**
     * @var ModelConfig
     */
    private $config;

    /**
     * @var Model
     */
    private $model;

    /**
     * Creates a new ConfigResolver for given Model.
     *
     * @param ModelConfig $config
     * @param Model $model The Model to generate a ModelConfig for.
     */
    public function __construct(ModelConfig $config, Model $model) {
        $this->model = $model;
        $this->config = $config;
    }

    /**
     * Resolves a Config instance.
     *
     * @return ModelConfig The resolved config.
     */
    public function resolve() {
        if (is_null($this->config->getDisplayField()) || $this->config->getDisplayField() == '') {
            $this->config->setDisplayField($this->resolveDisplayField());
            $this->config->setVisibleFields($this->resolveVisibleFields());
        }

        return $this->config;
    }

    /**
     * Tries to resolve the display field for the Model.
     * The possible column names are defined in $displayFieldNames.
     *
     * @return String the name of the column to use as display field.
     */
    private function resolveDisplayField() {
        $result = null;

        $columns = $this->model->getColumns();
        foreach ($columns as $column) {
            if ($column->getType() == Type::STRING && in_array($column->getName(), $this->displayFieldNames)) {
                $result = $column->getName();
            }
        }

        if ($result == null) {
            /* If we couldn't find a display field, just return the first one */
            $result = empty($columns) ? '' : $columns[0]->getName();
        }

        return $result;
    }

    /**
     * Resolves the fields to display in a Form.
     *
     * @return String[] The names of the fields to display.
     */
    private function resolveVisibleFields() {
        $result = [];

        $columns = $this->model->getColumns();
        foreach($columns as $column){
            $result[] = $column->getName();
        }

        return $result;
    }

}


<?php

namespace MiksIr\Yii2DbFaker\generator;

use MiksIr\Yii2DbFaker\Exception;

class FakerGenerator implements GeneratorInterface
{
    private $generator;
    private $iterate = 0;
    private $templateFullPath;

    /**
     * @var string locale of faker
     */
    public $language;

    /**
     * @var string directory with templates
     */
    public $directory = '@tests/unit/templates/fixtures/';

    /**
     * @var string (required) name of template (name of php file, see yiisoft/yii2-faker description)
     */
    public $template;

    public function generate($count=null)
    {
        if (!$this->templateFullPath) {
            $this->templateFullPath = $this->resolvePath($this->directory, $this->template);
        }

        if (is_null($this->generator)) {
            $this->generator = $this->templateFullPath ? \Faker\Factory::create($this->templateFullPath) : \Faker\Factory::create($this->templateFullPath);
        }

        $faker = $this->generator;

        while (is_null($count) || $count > 0) {
            $index = $this->iterate++;
            $count--;
            $data = require($this->templateFullPath);
            yield $data;
        }
    }

    /**
     * Resolve Yii aliases and check template file
     * @param $path_alias
     * @return string
     * @throws Exception
     */
    private function resolvePath($path_alias, $file_name)
    {
        $path = \Yii::getAlias($path_alias, false);
        $path = $path ? realpath($path) : $path;
        $file_name = !preg_match('/\.php$/i', $file_name) ? $file_name . '.php' : $file_name;

        if (!$path || !is_dir($path) || !file_exists($path . '/' . $file_name)) {
            throw new Exception("Faker template \"{$path}/{$file_name}\" not found");
        }

        return $path . '/' . $file_name;
    }

}


<?php

namespace PhpOffice\PhpSpreadsheet\Chart;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class DataSeriesValues
{
    const DATASERIES_TYPE_STRING = 'String';
    const DATASERIES_TYPE_NUMBER = 'Number';

    private static $dataTypeValues = [
        self::DATASERIES_TYPE_STRING,
        self::DATASERIES_TYPE_NUMBER,
    ];

    /**
     * Series Data Type.
     *
     * @var string
     */
    private $dataType;

    /**
     * Series Data Source.
     *
     * @var string
     */
    private $dataSource;

    /**
     * Format Code.
     *
     * @var string
     */
    private $formatCode;

    /**
     * Series Point Marker.
     *
     * @var string
     */
    private $pointMarker;

    /**
     * Point Count (The number of datapoints in the dataseries).
     *
     * @var int
     */
    private $pointCount = 0;

    /**
     * Data Values.
     *
     * @var array of mixed
     */
    private $dataValues = [];

    /**
     * Fill color.
     *
     * @var string
     */
    private $fillColor;

    /**
     * Line Width.
     *
     * @var int
     */
    private $lineWidth = 12700;

    /**
     * Create a new DataSeriesValues object.
     *
     * @param string $dataType
     * @param string $dataSource
     * @param null|mixed $formatCode
     * @param int $pointCount
     * @param mixed $dataValues
     * @param null|mixed $marker
     * @param null|string $fillColor
     */
    public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = [], $marker = null, $fillColor = null)
    {
        $this->setDataType($dataType);
        $this->dataSource = $dataSource;
        $this->formatCode = $formatCode;
        $this->pointCount = $pointCount;
        $this->dataValues = $dataValues;
        $this->pointMarker = $marker;
        $this->fillColor = $fillColor;
    }

    /**
     * Get Series Data Type.
     *
     * @return string
     */
    public function getDataType()
    {
        return $this->dataType;
    }

    /**
     * Set Series Data Type.
     *
     * @param string $dataType Datatype of this data series
     *                                Typical values are:
     *                                    DataSeriesValues::DATASERIES_TYPE_STRING
     *                                        Normally used for axis point values
     *                                    DataSeriesValues::DATASERIES_TYPE_NUMBER
     *                                        Normally used for chart data values
     *
     * @throws Exception
     *
     * @return DataSeriesValues
     */
    public function setDataType($dataType)
    {
        if (!in_array($dataType, self::$dataTypeValues)) {
            throw new Exception('Invalid datatype for chart data series values');
        }
        $this->dataType = $dataType;

        return $this;
    }

    /**
     * Get Series Data Source (formula).
     *
     * @return string
     */
    public function getDataSource()
    {
        return $this->dataSource;
    }

    /**
     * Set Series Data Source (formula).
     *
     * @param string $dataSource
     *
     * @return DataSeriesValues
     */
    public function setDataSource($dataSource)
    {
        $this->dataSource = $dataSource;

        return $this;
    }

    /**
     * Get Point Marker.
     *
     * @return string
     */
    public function getPointMarker()
    {
        return $this->pointMarker;
    }

    /**
     * Set Point Marker.
     *
     * @param string $marker
     *
     * @return DataSeriesValues
     */
    public function setPointMarker($marker)
    {
        $this->pointMarker = $marker;

        return $this;
    }

    /**
     * Get Series Format Code.
     *
     * @return string
     */
    public function getFormatCode()
    {
        return $this->formatCode;
    }

    /**
     * Set Series Format Code.
     *
     * @param string $formatCode
     *
     * @return DataSeriesValues
     */
    public function setFormatCode($formatCode)
    {
        $this->formatCode = $formatCode;

        return $this;
    }

    /**
     * Get Series Point Count.
     *
     * @return int
     */
    public function getPointCount()
    {
        return $this->pointCount;
    }

    /**
     * Get fill color.
     *
     * @return string HEX color
     */
    public function getFillColor()
    {
        return $this->fillColor;
    }

    /**
     * Set fill color for series.
     *
     * @param string $color HEX color
     *
     * @return   DataSeriesValues
     */
    public function setFillColor($color)
    {
        if (!preg_match('/^[a-f0-9]{6}$/i', $color)) {
            throw new Exception('Invalid hex color for chart series');
        }
        $this->fillColor = $color;

        return $this;
    }

    /**
     * Get line width for series.
     *
     * @return int
     */
    public function getLineWidth()
    {
        return $this->lineWidth;
    }

    /**
     * Set line width for the series.
     *
     * @param int $width
     *
     * @return DataSeriesValues
     */
    public function setLineWidth($width)
    {
        $minWidth = 12700;
        $this->lineWidth = max($minWidth, $width);

        return $this;
    }

    /**
     * Identify if the Data Series is a multi-level or a simple series.
     *
     * @return null|bool
     */
    public function isMultiLevelSeries()
    {
        if (count($this->dataValues) > 0) {
            return is_array($this->dataValues[0]);
        }

        return null;
    }

    /**
     * Return the level count of a multi-level Data Series.
     *
     * @return int
     */
    public function multiLevelCount()
    {
        $levelCount = 0;
        foreach ($this->dataValues as $dataValueSet) {
            $levelCount = max($levelCount, count($dataValueSet));
        }

        return $levelCount;
    }

    /**
     * Get Series Data Values.
     *
     * @return array of mixed
     */
    public function getDataValues()
    {
        return $this->dataValues;
    }

    /**
     * Get the first Series Data value.
     *
     * @return mixed
     */
    public function getDataValue()
    {
        $count = count($this->dataValues);
        if ($count == 0) {
            return null;
        } elseif ($count == 1) {
            return $this->dataValues[0];
        }

        return $this->dataValues;
    }

    /**
     * Set Series Data Values.
     *
     * @param array $dataValues
     *
     * @return DataSeriesValues
     */
    public function setDataValues($dataValues)
    {
        $this->dataValues = Functions::flattenArray($dataValues);
        $this->pointCount = count($dataValues);

        return $this;
    }

    public function refresh(Worksheet $worksheet, $flatten = true)
    {
        if ($this->dataSource !== null) {
            $calcEngine = Calculation::getInstance($worksheet->getParent());
            $newDataValues = Calculation::unwrapResult(
                $calcEngine->_calculateFormulaValue(
                    '=' . $this->dataSource,
                    null,
                    $worksheet->getCell('A1')
                )
            );
            if ($flatten) {
                $this->dataValues = Functions::flattenArray($newDataValues);
                foreach ($this->dataValues as &$dataValue) {
                    if ((!empty($dataValue)) && ($dataValue[0] == '#')) {
                        $dataValue = 0.0;
                    }
                }
                unset($dataValue);
            } else {
                $cellRange = explode('!', $this->dataSource);
                if (count($cellRange) > 1) {
                    list(, $cellRange) = $cellRange;
                }

                $dimensions = Coordinate::rangeDimension(str_replace('$', '', $cellRange));
                if (($dimensions[0] == 1) || ($dimensions[1] == 1)) {
                    $this->dataValues = Functions::flattenArray($newDataValues);
                } else {
                    $newArray = array_values(array_shift($newDataValues));
                    foreach ($newArray as $i => $newDataSet) {
                        $newArray[$i] = [$newDataSet];
                    }

                    foreach ($newDataValues as $newDataSet) {
                        $i = 0;
                        foreach ($newDataSet as $newDataVal) {
                            array_unshift($newArray[$i++], $newDataVal);
                        }
                    }
                    $this->dataValues = $newArray;
                }
            }
            $this->pointCount = count($this->dataValues);
        }
    }
}


<?php

namespace PhpOffice\PhpSpreadsheet\Calculation\Token;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;

class Stack
{
    /**
     * The parser stack for formulae.
     *
     * @var mixed[]
     */
    private $stack = [];

    /**
     * Count of entries in the parser stack.
     *
     * @var int
     */
    private $count = 0;

    /**
     * Return the number of entries on the stack.
     *
     * @return int
     */
    public function count()
    {
        return $this->count;
    }

    /**
     * Push a new entry onto the stack.
     *
     * @param mixed $type
     * @param mixed $value
     * @param mixed $reference
     */
    public function push($type, $value, $reference = null)
    {
        $this->stack[$this->count++] = [
            'type' => $type,
            'value' => $value,
            'reference' => $reference,
        ];
        if ($type == 'Function') {
            $localeFunction = Calculation::localeFunc($value);
            if ($localeFunction != $value) {
                $this->stack[($this->count - 1)]['localeValue'] = $localeFunction;
            }
        }
    }

    /**
     * Pop the last entry from the stack.
     *
     * @return mixed
     */
    public function pop()
    {
        if ($this->count > 0) {
            return $this->stack[--$this->count];
        }

        return null;
    }

    /**
     * Return an entry from the stack without removing it.
     *
     * @param int $n number indicating how far back in the stack we want to look
     *
     * @return mixed
     */
    public function last($n = 1)
    {
        if ($this->count - $n < 0) {
            return null;
        }

        return $this->stack[$this->count - $n];
    }

    /**
     * Clear the stack.
     */
    public function clear()
    {
        $this->stack = [];
        $this->count = 0;
    }
}


<?php
namespace Psr6NullCache\Adapter;

use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheItemInterface;
use DateTime;
use Psr6NullCache\CacheItem;

final class MemoryCacheItemPool implements CacheItemPoolInterface
{

    /**
     *
     * @var array
     */
    private $data = [];

    private $deferred = [];

    /**
     * Returns a Cache Item representing the specified key.
     *
     * This method must always return a CacheItemInterface object, even in case of
     * a cache miss. It MUST NOT return null.
     *
     * @param string $key
     *            The key for which to return the corresponding Cache Item.
     *
     * @throws InvalidArgumentException If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *         MUST be thrown.
     *
     * @return CacheItemInterface
     */
    public function getItem($key)
    {
        if ($this->hasItem($key) !== true) {
            $this->data[$key] = new CacheItem($key, null, false);
        }

        return $this->data[$key];
    }

    /**
     * Returns a traversable set of cache items.
     *
     * @param array $keys
     *            An indexed array of keys of items to retrieve.
     *
     * @throws InvalidArgumentException If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
     *         MUST be thrown.
     *
     * @return array|\Traversable A traversable collection of Cache Items keyed by the cache keys of
     *         each item. A Cache item will be returned for each key, even if that
     *         key is not found. However, if no keys are specified then an empty
     *         traversable MUST be returned instead.
     */
    public function getItems(array $keys = [])
    {
        $result = [];

        foreach ($keys as $key) {
            $result[$key] = $this->getItem($key);
        }

        return $result;
    }

    /**
     * Confirms if the cache contains specified cache item.
     *
     * Note: This method MAY avoid retrieving the cached value for performance reasons.
     * This could result in a race condition with CacheItemInterface::get(). To avoid
     * such situation use CacheItemInterface::isHit() instead.
     *
     * @param string $key
     *            The key for which to check existence.
     *
     * @throws InvalidArgumentException If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *         MUST be thrown.
     *
     * @return bool True if item exists in the cache, false otherwise.
     */
    public function hasItem($key)
    {
        if (isset($this->data[$key])) {

            /* @var $item \Psr6NullCache\CacheItem */
            $item = $this->data[$key];

            if ($item->isHit() === true && ($item->getExpires() === null || $item->getExpires() > new DateTime())) {
                return true;
            }
        }

        return false;
    }

    /**
     * Deletes all items in the pool.
     *
     * @return bool True if the pool was successfully cleared. False if there was an error.
     */
    public function clear()
    {
        $this->data = [];

        return true;
    }

    /**
     * Removes the item from the pool.
     *
     * @param string $key
     *            The key for which to delete
     *
     * @throws InvalidArgumentException If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
     *         MUST be thrown.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     */
    public function deleteItem($key)
    {
        unset($this->data[$key]);

        return true;
    }

    /**
     * Removes multiple items from the pool.
     *
     * @param array $keys
     *            An array of keys that should be removed from the pool.
     *
     * @throws InvalidArgumentException If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
     *         MUST be thrown.
     *
     * @return bool True if the items were successfully removed. False if there was an error.
     */
    public function deleteItems(array $keys)
    {
        foreach ($keys as $key) {
            $this->deleteItem($key);
        }

        return true;
    }

    /**
     * Persists a cache item immediately.
     *
     * @param CacheItemInterface $item
     *            The cache item to save.
     *
     * @return bool True if the item was successfully persisted. False if there was an error.
     */
    public function save(CacheItemInterface $item)
    {
        $item->setIsHit(true);

        $this->data[$item->getKey()] = $item;

        return true;
    }

    /**
     * Sets a cache item to be persisted later.
     *
     * @param CacheItemInterface $item
     *            The cache item to save.
     *
     * @return bool False if the item could not be queued or if a commit was attempted and failed. True otherwise.
     */
    public function saveDeferred(CacheItemInterface $item)
    {
        $this->deferred[$item->getKey()] = $item;

        return true;
    }

    /**
     * Persists any deferred cache items.
     *
     * @return bool True if all not-yet-saved items were successfully saved or there were none. False otherwise.
     */
    public function commit()
    {
        foreach ($this->deferred as $item) {
            /* @var $item \Psr6NullCache\CacheItem */
            $this->save($item);
        }

        $this->deferred = [];

        return true;
    }
}


<?php

namespace Vkovic\LaravelMeta;

use Illuminate\Database\Eloquent\Model;
use Vkovic\LaravelMeta\Models\Meta;

class MetaHandler
{
    /**
     * @var Model
     */
    protected $metaModel;

    /**
     * MetaHandler constructor.
     *
     * @param Model|null $model Model that'll handle writing to meta table
     */
    public function __construct(Model $model = null)
    {
        $this->metaModel = $model ?? new Meta;
    }

    public function getModel()
    {
        return $this->metaModel;
    }

    /**
     * Set meta at given key
     * for package realm.
     * If meta exists, it'll be overwritten.
     *
     * @param string $key
     * @param mixed  $value
     */
    public function set($key, $value)
    {
        $meta = $this->metaModel::where('key', $key)->first();

        if ($meta === null) {
            $meta = new $this->metaModel;
            $meta->key = $key;
        }

        $meta->value = $value;

        $meta->save();
    }

    /**
     * Create meta at given key
     * for package realm.
     * If meta exists, exception will be thrown.
     *
     * @param string $key
     * @param mixed  $value
     *
     * @throws \Exception
     */
    public function create($key, $value)
    {
        $exists = $this->metaModel::where('key', $key)
            ->exists();

        if ($exists) {
            $message = "Can't create meta (key: $key). ";
            $message .= "Meta already exists";
            throw new \Exception($message);
        }

        $meta = new $this->metaModel;

        $meta->key = $key;
        $meta->value = $value;

        $meta->save();
    }

    /**
     * Update meta at given key
     * for package realm.
     * If meta doesn't exists, exception will be thrown.
     *
     * @param string $key
     * @param mixed  $value
     *
     * @throws \Exception
     */
    public function update($key, $value)
    {
        try {
            $meta = $this->metaModel::where('key', $key)
                ->firstOrFail();
        } catch (\Exception $e) {
            $message = "Can't update meta (key: $key). ";
            $message .= "Meta doesn't exist";

            throw new \Exception($message);
        }

        $meta->value = $value;

        $meta->save();
    }

    /**
     * Get meta at given key
     * for package realm
     *
     * @param string $key
     * @param mixed  $default
     *
     * @return array
     */
    public function get($key, $default = null)
    {
        $meta = $this->metaModel::where('key', $key)
            ->first();

        return $meta === null
            ? $default
            : $meta->value;
    }

    /**
     * Get multiple meta key value pairs using wildcard "*"
     *
     * @param      $query
     * @param null $default
     *
     * @return array
     */
    public function query($query, $default = null)
    {
        $query = str_replace('*', '%', $query);
        $meta = $this->metaModel::where('key', 'LIKE', $query)->get(['key', 'value', 'type']);

        if ($meta->isEmpty()) {
            return $default;
        }

        $data = [];
        foreach ($meta as $m) {
            $data[$m->key] = $m->value;
        }

        return $data;
    }

    /**
     * Check if meta key record exists by given key
     * for package realm
     *
     * @param string $key
     *
     * @return bool
     */
    public function exists($key)
    {
        return $this->metaModel::where('key', $key)
            ->exists();
    }

    /**
     * Count all meta
     * for package realm
     *
     * @param string $realm
     *
     * @return int
     */
    public function count()
    {
        return $this->metaModel::count();
    }

    /**
     * Get all meta
     * for package realm
     *
     * @return array
     */
    public function all()
    {
        $meta = $this->metaModel::get(['key', 'value', 'type']);

        $data = [];
        foreach ($meta as $m) {
            $data[$m->key] = $m->value;
        }

        return $data;
    }

    /**
     * Get all meta keys
     * for package realm
     *
     * @return array
     */
    public function keys()
    {
        return $this->metaModel::pluck('key')->toArray();
    }

    /**
     * Remove meta at given key or array of keys
     * for package realm
     *
     * @param string|array $key
     */
    public function remove($key)
    {
        $keys = (array) $key;

        $this->metaModel::whereIn('key', $keys)->delete();
    }

    /**
     * Purge meta
     * for package realm
     *
     * @return int Number of records deleted
     */
    public function purge()
    {
        return $this->metaModel::realm()->delete();
    }
}


<?php

namespace PhpOffice\PhpSpreadsheet\Reader\Xls;

class ErrorCode
{
    protected static $map = [
        0x00 => '#NULL!',
        0x07 => '#DIV/0!',
        0x0F => '#VALUE!',
        0x17 => '#REF!',
        0x1D => '#NAME?',
        0x24 => '#NUM!',
        0x2A => '#N/A',
    ];

    /**
     * Map error code, e.g. '#N/A'.
     *
     * @param int $code
     *
     * @return bool|string
     */
    public static function lookup($code)
    {
        if (isset(self::$map[$code])) {
            return self::$map[$code];
        }

        return false;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: joro
 * Date: 15.5.2017 г.
 * Time: 17:21 ч.
 */

namespace Omniship\Traits;

use Carbon\Carbon;
use Omniship\Common\Address;
use Omniship\Common\ItemBag;
use Omniship\Common\PieceBag;
use Omniship\Consts;
use Omniship\Helper\Collection;
use Omniship\Helper\Data;
use Symfony\Component\HttpFoundation\ParameterBag;

trait ParametersData
{
    /**
     * @return boolean
     */
    public function getTestMode()
    {
        return $this->getParameter('test_mode');
    }
    /**
     * @param  boolean $value
     * @return $this
     */
    public function setTestMode($value)
    {
        return $this->setParameter('test_mode', $value);
    }
    /**
     * @return null|array
     */
    public function getConnectionOptions()
    {
        return $this->getParameter('connection_options');
    }
    /**
     * @param  array $value
     * @return $this
     */
    public function setConnectionOptions(array $value = null)
    {
        return $this->setParameter('connection_options', $value);
    }
    /**
     * Get the card token.
     *
     * @return string
     */
    public function getToken()
    {
        return $this->getParameter('token');
    }
    /**
     * Sets the card token.
     *
     * @param string $value
     * @return string
     */
    public function setToken($value)
    {
        return $this->setParameter('token', $value);
    }
    /**
     * Get the payment currency code.
     *
     * @return string
     */
    public function getCurrency()
    {
        return $this->getParameter('currency');
    }
    /**
     * Sets the payment currency code.
     *
     * @param string $value
     * @return $this
     */
    public function setCurrency($value)
    {
        if ($value !== null) {
            $value = strtoupper($value);
        }
        return $this->setParameter('currency', $value);
    }
    /**
     * Get the request description.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->getParameter('description');
    }
    /**
     * Sets the request description.
     *
     * @param string $value
     * @return string
     */
    public function setDescription($value)
    {
        return $this->setParameter('description', $value);
    }
    /**
     * @return string
     */
    public function getWeight()
    {
        return $this->getParameter('weight');
    }
    /**
     * @param  $value
     * @return $this
     */
    public function setWeight($value)
    {
        return $this->setParameter('weight', $value);
    }
    /**
     * @return string
     */
    public function getWeightUnit()
    {
        $weight_unit = $this->getParameter('weight_unit');
        if(!$weight_unit) {
            $this->setWeightUnit($this->findCountryData('WeightUnit'));
        }
        return $this->getParameter('weight_unit');
    }
    /**
     * @param  $weight_unit
     * @return $this
     */
    public function setWeightUnit($weight_unit)
    {
        return $this->setParameter('weight_unit', $weight_unit);
    }
    /**
     * @return string
     */
    public function getDimensionUnit()
    {
        $dimension_unit = $this->getParameter('dimension_unit');
        if(!$dimension_unit) {
            $this->setDimensionUnit($this->findCountryData('DimensionalUnit'));
        }
        return $this->getParameter('dimension_unit');
    }
    /**
     * @param  $dimension_unit
     * @return $this
     */
    public function setDimensionUnit($dimension_unit)
    {
        return $this->setParameter('dimension_unit', $dimension_unit);
    }
    /**
     * A list of items in this order
     *
     * @return ItemBag A bag containing items in this order
     */
    public function getItems()
    {
        return $this->getParameter('items') ? : new ItemBag([]);
    }
    /**
     * Set the items in this order
     *
     * @param ItemBag|array $items An array of items in this order
     * @return $this
     */
    public function setItems($items)
    {
        if ($items && !$items instanceof ItemBag) {
            $items = new ItemBag(is_array($items) ? $items : []);
        }
        return $this->setParameter('items', $items);
    }
    /**
     * A list of pieces in this order
     *
     * @return PieceBag A bag containing items in this order
     */
    public function getPieces()
    {
        return $this->getParameter('pieces') ? : new PieceBag([]);
    }
    /**
     * Set the pieces in this order
     *
     * @param PieceBag|array $pieces An array of items in this order
     * @return $this
     */
    public function setPieces($pieces)
    {
        if ($pieces && !$pieces instanceof PieceBag) {
            $pieces = new PieceBag(is_array($pieces) ? $pieces : []);
        }
        return $this->setParameter('pieces', $pieces);
    }
    /**
     * @return string
     */
    public function getPackageType()
    {
        return $this->getParameter('package_type');
    }
    /**
     * @param string $package_type
     * @return $this
     */
    public function setPackageType($package_type)
    {
        return $this->setParameter('package_type', $package_type);
    }
    /**
     * @return Carbon
     */
    public function getShipmentDate()
    {
        return $this->getParameter('shipment_date');
    }
    /**
     * @param  $shipment_date
     * @return $this
     */
    public function setShipmentDate(Carbon $shipment_date = null)
    {
        return $this->setParameter('shipment_date', $shipment_date);
    }
    /**
     * get number of packages
     * @return integer
     */
    public function getNumberOfPieces()
    {
        $number_of_pieces = $this->getPieces()->count();
        if($number_of_pieces < 1) {
            $number_of_pieces = 1;
        }
        return $number_of_pieces;
    }
    /**
     * @param float $value
     * @return $this
     */
    public function setCashOnDeliveryAmount($value) {
        return $this->setParameter('cash_on_delivery_amount', $value);
    }

    /**
     * @return float
     */
    public function getCashOnDeliveryAmount() {
        return $this->getParameter('cash_on_delivery_amount');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setCashOnDeliveryCurrency($value) {
        return $this->setParameter('cash_on_delivery_currency', $value);
    }

    /**
     * @return string
     */
    public function getCashOnDeliveryCurrency() {
        return $this->getParameter('cash_on_delivery_currency') ? : $this->getCurrency();
    }
    /**
     * Get the client note.
     *
     * @return string
     */
    public function getClientNote()
    {
        return $this->getParameter('client_note');
    }
    /**
     * Sets the client note.
     *
     * @param string $value
     * @return $this
     */
    public function setClientNote($value)
    {
        return $this->setParameter('client_note', $value);
    }
    /**
     * @return Address
     */
    public function getReceiverAddress()
    {
        return $this->getParameter('receiver_address');
    }
    /**
     * @param  Address|array $address
     * @return $this
     */
    public function setReceiverAddress($address)
    {
        if(!($address instanceof Address)) {
            $address = new Address($address);
        }
        if ($address->isEmpty()) {
            $this->invalidArguments('20001');
        }
        return $this->setParameter('receiver_address', $address);
    }
    /**
     * @return Address
     */
    public function getSenderAddress()
    {
        return $this->getParameter('sender_address');
    }
    /**
     * @param  Address|array $address
     * @return $this
     */
    public function setSenderAddress($address)
    {
        if(!($address instanceof Address)) {
            $address = new Address($address);
        }
        if ($address->isEmpty()) {
            $this->invalidArguments('20002');
        }
        return $this->setParameter('sender_address', $address);
    }

    /**
     * @return null|string
     */
    public function getSenderTimeZone() {
        return $this->getSenderAddress() ? $this->getSenderAddress()->getTimeZone() : null;
    }

    /**
     * @return null|string
     */
    public function getReceiverTimeZone() {
        return $this->getReceiverAddress() ? $this->getReceiverAddress()->getTimeZone() : null;
    }

    /**
     * @param float $value
     * @return $this
     */
    public function setInsuranceAmount($value) {
        return $this->setParameter('insurance_amount', $value);
    }

    /**
     * @return float
     */
    public function getInsuranceAmount() {
        return $this->getParameter('insurance_amount');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setInsuranceCurrency($value) {
        return $this->setParameter('insurance_currency', $value);
    }

    /**
     * @return string
     */
    public function getInsuranceCurrency() {
        return $this->getParameter('insurance_currency') ? : $this->getCurrency();
    }

    /**
     * @param float $value
     * @return $this
     */
    public function setDeclaredAmount($value) {
        return $this->setParameter('declared_amount', $value);
    }

    /**
     * @return float
     */
    public function getDeclaredAmount() {
        return $this->getParameter('declared_amount');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setDeclaredCurrency($value) {
        return $this->setParameter('declared_currency', $value);
    }

    /**
     * @return string
     */
    public function getDeclaredCurrency() {
        return $this->getParameter('declared_currency') ? : $this->getCurrency();
    }
    /**
     * Get the request TransactionId.
     *
     * @return string
     */
    public function getTransactionId()
    {
        return $this->getParameter('transaction_id');
    }
    /**
     * Sets the request TransactionId.
     *
     * @param string $value
     * @return $this
     */
    public function setTransactionId($value)
    {
        return $this->setParameter('transaction_id', $value);
    }
    /**
     * Get the request BolId.
     *
     * @return string|array|null
     */
    public function getBolId()
    {
        return $this->getParameter('bol_id');
    }
    /**
     * Sets the request BolId.
     *
     * @param string|array $value
     * @return $this
     */
    public function setBolId($value)
    {
        return $this->setParameter('bol_id', $value);
    }
    /**
     * Get the request date.
     *
     * @return null|Carbon
     */
    public function getStartDate()
    {
        return $this->getParameter('start_date');
    }
    /**
     * Sets the request date.
     *
     * @param Carbon $value
     * @return $this
     */
    public function setStartDate(Carbon $value = null)
    {
        return $this->setParameter('start_date', $value);
    }
    /**
     * Get the request date.
     *
     * @return null|Carbon
     */
    public function getEndDate()
    {
        return $this->getParameter('end_date');
    }
    /**
     * Sets the request date.
     *
     * @param Carbon $value
     * @return $this
     */
    public function setEndDate(Carbon $value = null)
    {
        return $this->setParameter('end_date', $value);
    }
    /**
     * Get the request CancelComment.
     *
     * @return string
     */
    public function getCancelComment()
    {
        return $this->getParameter('cancel_comment');
    }
    /**
     * Sets the request CancelComment.
     *
     * @param string $value
     * @return $this
     */
    public function setCancelComment($value)
    {
        return $this->setParameter('cancel_comment', $value);
    }
    /**
     * Get the request address type.
     *
     * @return Address
     */
    public function getAddress()
    {
        return $this->getParameter('address');
    }
    /**
     * Sets the request address.
     *
     * @param Address|array $value
     * @return $this
     */
    public function setAddress($value)
    {
        $value = !($value instanceof Address) ? new Address(is_array($value) ? $value : []) : $value;
        return $this->setParameter('address', $value);
    }
    /**
     * Get the request service id.
     *
     * @return string
     */
    public function getServiceId()
    {
        return $this->getParameter('service_id');
    }
    /**
     * Sets the request Service ID.
     *
     * @param string $value
     * @return $this
     */
    public function setServiceId($value)
    {
        return $this->setParameter('service_id', $value);
    }
    /**
     * @return string
     */
    public function getLanguageCode()
    {
        return $this->getParameter('language_code') ? : 'en';
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setLanguageCode($value)
    {
        return $this->setParameter('language_code', $value);
    }
    /**
     * @return string
     */
    public function getPayer()
    {
        return $this->getParameter('payer');
    }
    /**
     * @param  $payer
     * @return $this
     */
    public function setPayer($payer)
    {
        return $this->setParameter('payer', $payer);
    }
    /**
     * @return string
     */
    public function getLogo()
    {
        return $this->getParameter('logo');
    }
    /**
     * @param  $logo
     * @return $this
     */
    public function setLogo($logo)
    {
        return $this->setParameter('logo', $logo);
    }
    /**
     * @return string
     */
    public function getContent()
    {
        return $this->getParameter('content');
    }
    /**
     * @param string $content
     * @return $this
     */
    public function setContent($content)
    {
        return $this->setParameter('content', $content);
    }
    /**
     * @return bool
     */
    public function getIsDocuments()
    {
        return $this->getParameter('is_documents');
    }
    /**
     * @param bool $value
     * @return $this
     */
    public function setIsDocuments($value)
    {
        return $this->setParameter('is_documents', (bool)$value);
    }
    /**
     * Get options (open,test)
     * @return string
     */
    public function getOptionBeforePayment()
    {
        return $this->getParameter('option_before_payment');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setOptionBeforePayment($value)
    {
        return $this->setParameter('option_before_payment', $value);
    }
    /**
     * @return bool
     */
    public function getBackReceipt()
    {
        return (bool)$this->getParameter('back_receipt');
    }
    /**
     * @param bool $value
     * @return $this
     */
    public function setBackReceipt($value)
    {
        return $this->setParameter('back_receipt', (bool)$value);
    }
    /**
     * @return bool
     */
    public function getBackDocuments()
    {
        return (bool)$this->getParameter('back_documents');
    }
    /**
     * @param bool $value
     * @return $this
     */
    public function setBackDocuments($value)
    {
        return $this->setParameter('back_documents', (bool)$value);
    }
    /**
     * @return string
     */
    public function getReceiverEmail()
    {
        return $this->getParameter('receiver_email');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setReceiverEmail($value)
    {
        return $this->setParameter('receiver_email', $value);
    }
    /**
     * @return string
     */
    public function getSenderEmail()
    {
        return $this->getParameter('sender_email');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setSenderEmail($value)
    {
        return $this->setParameter('sender_email', $value);
    }
    /**
     * @return string
     */
    public function getReceiverPhone()
    {
        $address = $this->getReceiverAddress();
        return $address ? $address->getPhone() : null;
    }
    /**
     * @return string
     */
    public function getSenderPhone()
    {
        $address = $this->getSenderAddress();
        return $address ? $address->getPhone() : null;
    }
    /**
     * @return string
     */
    public function getPaymentMethod()
    {
        return $this->getParameter('payment_method');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setPaymentMethod($value)
    {
        return $this->setParameter('payment_method', $value);
    }
    /**
     * @return string
     */
    public function getInstructionReturns()
    {
        return $this->getParameter('instruction_returns');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setInstructionReturns($value)
    {
        return $this->setParameter('instruction_returns', $value);
    }
    /**
     * @return string
     */
    public function getCodAccount()
    {
        return $this->getParameter('cod_account');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setCodAccount($value)
    {
        return $this->setParameter('cod_account', $value);
    }
    /**
     * @return string
     */
    public function getPackageId()
    {
        return $this->getParameter('package_id');
    }
    /**
     * @param string $value
     * @return $this
     */
    public function setPackageId($value)
    {
        return $this->setParameter('package_id', $value);
    }
    /**
     * @return Carbon
     */
    public function getPriorityTime()
    {
        return $this->getParameter('priority_time');
    }
    /**
     * @param  $priority_time
     * @return $this
     */
    public function setPriorityTime(Carbon $priority_time = null)
    {
        return $this->setParameter('priority_time', $priority_time);
    }
    /**
     * @return Carbon
     */
    public function getPriorityTimeType()
    {
        return $this->getParameter('priority_time_type');
    }
    /**
     * @param  $priority_time_type
     * @return $this
     */
    public function setPriorityTimeType($priority_time_type)
    {
        return $this->setParameter('priority_time_type', $priority_time_type);
    }
    /**
     * @param array $value
     * @return $this
     */
    public function setAllowedServices(array $value)
    {
        return $this->setParameter('allowed_services', $value);
    }
    /**
     * @return array|null
     */
    public function getAllowedServices()
    {
        return $this->getParameter('allowed_services');
    }
    /**
     * @param bool $value
     * @return $this
     */
    public function setMoneyTransfer($value)
    {
        return $this->setParameter('money_transfer', $value);
    }
    /**
     * @return bool
     */
    public function getMoneyTransfer()
    {
        return (bool)$this->getParameter('money_transfer');
    }
    /**
     * @param $key
     * @param null $default
     * @return mixed|ParameterBag
     */
    public function getOtherParameters($key = null, $default = null)
    {
        if(is_null($this->getParameter('other_parameters'))) {
            $this->setParameter('other_parameters', new ParameterBag());
        }
        /** @var $other ParameterBag */
        $other = $this->getParameter('other_parameters');
        return $key ? $other->get($key, $default) : $other;
    }
    /**
     * @param  $key
     * @param  $value
     * @return $this
     */
    public function setOtherParameters($key, $value = null)
    {
        if(is_array($key) || $key instanceof ParameterBag) {
            foreach($key as $k => $v) {
                $this->getOtherParameters()->set($k, $v);
            }
        } else {
            $this->getOtherParameters()->set($key, $value);
        }
        return $this;
    }

    /**
     * @param string $type (WeightUnit|DimensionalUnit)
     * @return string|null
     */
    public function findCountryData($type) {
        if(is_null($address = $this->getSenderAddress())) {
            $address = $this->getAddress();
        }
        if(!$address || is_null($country = $address->getCountry())) {
            return null;
        }
        $country = Collection::make(Data::countries()->get(strtoupper($country->getIso2())));
        if(!$country->count()) {
            return null;
        }
        return $country->get($type);
    }

}


<?php
/**
 * Shipping Item Bag
 */
namespace Omniship\Common;

use Omniship\Helper\Collection;
use Omniship\Interfaces\ItemInterface;

/**
 * Shipping Item Bag
 *
 * This class defines a bag (multi element set or array) of single shipping items
 * in the Omniship system.
 *
 * @see Item
 */
class ItemBag extends Collection
{

    /**
     * Create a new collection.
     *
     * @param  mixed  $items
     */
    public function __construct($items = [])
    {
        $items = array_map(function($item) {
            return !($item instanceof ItemInterface) ? new Item($item) : $item;
        }, $items);
        parent::__construct($items);
    }

    /**
     * Set the item at a given offset.
     *
     * @param  mixed  $key
     * @param  mixed  $value
     * @return void
     */
    public function offsetSet($key, $value)
    {
        if(!($value instanceof ItemInterface)) {
            $value = new Item($value);
        }
        parent::offsetSet($key, $value);
    }

    /**
     * Get all of the items in the collection.
     *
     * @return Item[]
     */
    public function all()
    {
        return parent::all();
    }
}


<?php

namespace MiksIr\Yii2DbFaker;

use MiksIr\Yii2DbFaker\dbprovider\DbProviderInterface;
use MiksIr\Yii2DbFaker\generator\GeneratorInterface;
use yii\console\Controller;
use yii\di\Container;
use yii\helpers\Console;

/**
 * This command can fill your database with fake data.
 */
class FakerController extends Controller
{
    /**
     * @var int number of data rows
     */
    public $count = 1000;

    /**
     * @var int do not ask confirmation
     */
    public $force = 0;

    /**
     * @var string class name of data generator
     */
    public $generator = 'FakerGenerator';
    private $generator_fqn;
    /** @var GeneratorInterface */
    private $generator_obj;

    /**
     * @var string class of database store provider
     */
    public $dbprovider = 'Csv';
    private $dbprovider_fqn;
    /** @var  DbProviderInterface */
    private $dbprovider_obj;

    /**
     * @inheritdoc
     */
    public function options($actionID)
    {
        return array_merge(parent::options($actionID), [
            'count', 'force', 'generator', 'dbprovider'
        ]);
    }

    public function beforeAction($action)
    {
        $this->generator_fqn = $this->fixNamespace($this->generator, 'MiksIr\\Yii2DbFaker\\generator');
        $this->dbprovider_fqn = $this->fixNamespace($this->dbprovider, 'MiksIr\\Yii2DbFaker\\dbprovider');

        return parent::beforeAction($action);
    }

    public function actionHelp()
    {
        $this->stdout("Usage: faker/generate option=value option=value ...\n", Console::FG_YELLOW);
        if ($gen_help = $this->help_of_class($this->generator_fqn, 'generator')) {
            $this->stdout("Options for current generator \"{$this->generator}\":\n", Console::FG_GREEN);
            $this->stdout($gen_help);
        }
        if ($db_help = $this->help_of_class($this->dbprovider_fqn, 'dbprovider')) {
            $this->stdout("Options for current dbprovider \"{$this->dbprovider}\":\n", Console::FG_GREEN);
            $this->stdout($db_help);
        }
        $this->stdout("Also, you can use global options:\n",  Console::FG_GREEN);
        $this->stdout("\t--generator - class name of generator\n".
            "\t--dbprovider - class name of database storage\n".
            "\t--count=10000 - number of rows to generate\n");
    }

    /**
     * Generate fake data and
     */
    public function actionGenerate()
    {
        $input = $this->parseArguments(func_get_args());

        $container = new Container();
        $container->set(GeneratorInterface::class, array_merge(['class' => $this->generator_fqn], $input['generator']));
        $container->set(DbProviderInterface::class, array_merge(['class' => $this->dbprovider_fqn], $input['dbprovider']));

        $this->generator_obj = $container->get(GeneratorInterface::class);

        if (!$this->force && !$this->confirmGeneration()) {
            return;
        }

        $this->dbprovider_obj = $container->get(DbProviderInterface::class);

        Console::startProgress(0, $this->count);
        foreach ($this->dbprovider_obj->export($this->count) as $count) {
            Console::updateProgress($this->count - $count, $this->count);
        }
        Console::endProgress(true);
    }

    private function parseArguments($lines)
    {
        $args = [
            'generator' => [],
            'dbprovider' => [],
        ];
        foreach ($lines as $line) {
            list($key, $value) = explode('=', $line);
            if (strstr($key, '_')) {
                list ($prefix, $key) = explode('_', $key);
                $args[$prefix][$key] = $value;
            } else {
                $args[$key] = $value;
            }
        }
        return $args;
    }

    private function fixNamespace($class, $default_namespace)
    {
        $class = str_replace('/', '\\', $class);
        if (!strstr($class, '\\')) {
            $class = $default_namespace . '\\' . $class;
        }

        return $class;
    }

    private function help_of_class($class_name, $prefix)
    {
        $help = '';
        $class = new \ReflectionClass($class_name);
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            $name = $property->getName();
            $defaultValue = $property->getValue($this);
            $tags = $this->parseDocCommentTags($property);
            if (isset($tags['var']) || isset($tags['property'])) {
                $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
                if (is_array($doc)) {
                    $doc = reset($doc);
                }
                if (preg_match('/^(\S+)\s*(.*)/s', $doc, $matches)) {
                    $type = $matches[1];
                    $comment = $matches[2];
                } else {
                    $type = null;
                    $comment = $doc;
                }
            } else {
                $type = null;
                $comment = "???";
            }
            $name = $prefix . "_" . $name;
            $help .= "\t{$name} - {$comment}" . ($defaultValue ? " (defalt: {$defaultValue})" : "") . "\n";
        }
        return $help;
    }

    private function confirmGeneration()
    {
        $this->stdout("Example of fake data (1 row):\n", Console::FG_YELLOW);
        $fake_data = $this->generator_obj->generate()->current();
        foreach ($fake_data as $field=>$data) {
            $this->stdout("\t{$field}: {$data}\n");
        }
        return $this->confirm("Generate {$this->count} rows?", Console::FG_YELLOW);
    }
}


<?php

namespace Sirius\FormRenderer;

use Sirius\FormRenderer\Utils\TreeBuilder;
use Sirius\Html\Builder;
use Sirius\Input\InputFilter;

class Renderer extends Builder
{

    /**
     * @var DecoratorStack
     */
    private $decorators;

    /**
     * @param array $options
     */
    public function __construct($options = array())
    {
        parent::__construct($options);
        $this->decorators = new DecoratorStack();
        $this->registerTags();
        $this->registerDecorators();
    }

    /**
     * Registers a list of default tags to be used by the renderer
     */
    protected function registerTags()
    {
        // register the "normal" tags, ie tags that are not form controls (widgets, see below)
        $tags = array('error', 'hint', 'label', 'radioset', 'checkboxset');
        foreach ($tags as $tag) {
            $tagClass = str_replace(' ', '', ucwords(str_replace('-', ' ', $tag)));
            $this->registerTag($tag, __NAMESPACE__ . '\Tag\\' . $tagClass);
        }

        // register the "widget" tags, ie tags that are inputs
        $widgets = array(
            'text',
            'file',
            'textarea',
            'radio',
            'checkbox',
            'select',
            'multiselect',
            'checkboxset',
            'radioset',
            'email',
            'password',
            'radioset',
            'checkboxset',
            // buttons
            'button',
            'submit',
            'reset',
            // containers
            'group',
            'fieldset',
            'collection',
            'form'
        );
        foreach ($widgets as $widget) {
            $widgetClass = str_replace(' ', '', ucwords(str_replace('-', ' ', $widget)));
            $this->registerTag('widget-' . $widget, __NAMESPACE__ . '\Widget\\' . $widgetClass);
        }
    }

    /**
     * Adds a list of default decorators to the stack
     *
     */
    protected function registerDecorators()
    {
        $decorators = array('AutoId');
        foreach ($decorators as $decoratorClass) {
            $decoratorClass = '\\Sirius\FormRenderer\\Decorator\\' . $decoratorClass;
            $this->addDecorator(new $decoratorClass);
        }
    }

    /**
     * Add a tag decorator to the stack
     *
     * @param TagDecoratorInterface $decorator
     * @param int $priority
     *
     * @return self
     */
    public function addDecorator(TagDecoratorInterface $decorator, $priority = 0)
    {
        $this->decorators->add($decorator, $priority);
        return $this;
    }

    /**
     * Returns a Tag object
     *
     * @param string $tag
     * @param null|array $props
     * @param null|array $content
     * @return \Sirius\Html\Tag|string
     */
    public function make($tag, $props = null, $content = null)
    {
        $tag = parent::make($tag, $props, $content);
        $tag = $this->decorators->apply($tag, $this);

        return $tag;
    }

    /**
     * Renders a complete InputFilter object into a form
     * @param InputFilter $inputFilter
     * @return \Sirius\Html\Tag|string
     */
    public function render(InputFilter $inputFilter)
    {
        $inputFilter->prepare(); // ensure it is prepare
        $props = $inputFilter->getAttributes();
        $treeBuilder = new TreeBuilder($inputFilter);
        $props = array_merge($props, $treeBuilder->getTree());

        return $this->make('widget-form', $props);
    }

}


<?php

namespace XQueue\Maileon\API\TargetGroups;

use XQueue\Maileon\API\XML\AbstractXMLWrapper;

/**
 * The wrapper class for a Maileon target group.
 */
class TargetGroup extends AbstractXMLWrapper
{

    public $id;
    public $name;
    public $author;
    public $state;
    public $type;
    public $contactFilterName;
    public $contactFilterId;
    public $evaluated;
    public $created;
    public $updated;
    public $countActiveContacts;
    public $countContacts;

    /**
     * Creates a new target group wrapper object.
     *
     * @param number $id
     * @param string $name
     * @param string $author
     * @param string $state
     * @param string $type
     * @param string $contactFilterName
     * @param number $contactFilterId
     * @param string $evaluated
     * @param string $created
     * @param string $updated
     * @param number $countActiveContacts
     * @param number $countContacts
     */
    function __construct(
        $id = 0,
        $name = "",
        $author = "",
        $state = "",
        $type = "",
        $contactFilterName = "",
        $contactFilterId = 0,
        $evaluated = "1970-01-01 00:00:00",
        $created = "1970-01-01 00:00:00",
        $updated = "1970-01-01 00:00:00",
        $countActiveContacts = 0,
        $countContacts = 0)
    {
        $this->id = $id;
        $this->name = $name;
        $this->author = $author;
        $this->state = $state;
        $this->type = $type;
        $this->contactFilterName = $contactFilterName;
        $this->contactFilterId = $contactFilterId;
        $this->evaluated = $evaluated;
        $this->created = $created;
        $this->updated = $updated;
        $this->countActiveContacts = $countActiveContacts;
        $this->countContacts = $countContacts;
    }

    /**
     * Initializes this target group from an XML representation.
     *
     * @param SimpleXMLElement $xmlElement
     *  the XML representation to use
     */
    function fromXML($xmlElement)
    {

        $this->id = $xmlElement->id;
        $this->name = $xmlElement->name;
        $this->author = $xmlElement->author;
        $this->state = $xmlElement->state;
        $this->type = $xmlElement->type;
        $this->contactFilterName = $xmlElement->contact_filter_name;
        $this->contactFilterId = $xmlElement->contact_filter_id;
        $this->evaluated = $xmlElement->evaluated;
        $this->created = $xmlElement->created;
        $this->updated = $xmlElement->updated;
        $this->countActiveContacts = $xmlElement->count_active_contacts;
        $this->countContacts = $xmlElement->count_contacts;

    }

    /**
     * @return \em SimpleXMLElement
     *  containing the serialized representation of this target group
     */
    function toXML()
    {
        $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><targetgroup></targetgroup>");

        $xml->addChild("id", $this->id);
        $xml->addChild("name", $this->name);
        $xml->addChild("author", $this->author);
        $xml->addChild("state", $this->state);
        $xml->addChild("type", $this->type);
        $xml->addChild("contact_filter_name", $this->contactFilterName);
        $xml->addChild("contact_filter_id", $this->contactFilterId);
        $xml->addChild("evaluated", $this->evaluated);
        $xml->addChild("created", $this->created);
        $xml->addChild("updated", $this->updated);
        $xml->addChild("count_active_contacts", $this->countActiveContacts);
        $xml->addChild("count_contacts", $this->countContacts);

        return $xml;
    }

    /**
     * Serialization to a simple XML element as string
     *
     * @return \em string
     *  The string representation of the XML document.
     */
    function toXMLString()
    {
        $xml = $this->toXML();
        return $xml->asXML();
    }

    /**
     * @return \em string
     *  containing a human-readable representation of this target group
     */
    function toString()
    {
        return "ContactFilter [" .
        "id=" . $this->id .
        ", name=" . $this->name .
        ", author=" . $this->author .
        ", state=" . $this->state .
        ", type=" . $this->type .
        ", contactFilterName=" . $this->contactFilterName .
        ", contactFilterId=" . $this->contactFilterId .
        ", evaluated=" . $this->evaluated .
        ", created=" . $this->created .
        ", updated=" . $this->updated .
        ", countActiveContacts=" . $this->countActiveContacts .
        ", countContacts=" . $this->countContacts .
        "]";
    }
}