<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\Theme;

use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

/**
 * Class ThemeGenerator is the object assigned to generate the theme definition and slots folders for the given Theme
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Theme
 */
class ThemeGenerator extends ThemeBase
{
    /**
     * Generates the theme definition and slots
     */
    public function generate()
    {
        if (!$this->configurationHandler->isTheme() || $this->theme->getName() != $this->configurationHandler->handledTheme()) {
            return;
        }

        $templates = array_keys($this->templates["template"]);
        $homepage = json_decode(file_get_contents($this->configurationHandler->pagesDir() . '/' .$this->configurationHandler->homepage() . '/page.json'), true);
        $homepageTemplate = $homepage["template"];
        if (!in_array($homepageTemplate, $templates)) {
            $homepageTemplate = $templates[0];
        }

        $themeDefinition = array(
            "home_template" => $homepageTemplate,
            "templates" => $templates,
        );

        $this->synchronizeThemeSlots();
        FilesystemTools::writeFile($this->themeDir . '/theme.json', json_encode($themeDefinition));
    }

    private function writeSlots($template, array $slots, $repeat)
    {
        foreach ($slots as $slotName) {
            $fileName = sprintf('%s/%s/%s.json', $this->themeDir, $template, $slotName);
            $value = array(
                "blocks" => array(),
            );

            if (file_exists($fileName)) {
                $slot = json_decode(FilesystemTools::readFile($fileName), true);
                if ($slot["repeat"] == $repeat) {
                    continue;
                }

                $value["blocks"] = $slot["blocks"];
            }

            $value["repeat"] = $repeat;

            FilesystemTools::writeFile($fileName, json_encode($value));
        }
    }

    private function synchronizeThemeSlots()
    {
        $templateSlots = $this->findSlotsInTemplates();

        $files = $this->parseForRemovedTemplates($templateSlots["templates"]);
        $files = array_merge($files, $this->parseForRemovedSlots($templateSlots["base"]));
        $files = array_merge($files, $this->parseForRemovedSlots($templateSlots["templates"]));

        if (!empty($files)) {
            $fs = new Filesystem();
            $fs->remove($files);
        }

        $this->writeTemplatesFolder($templateSlots["base"]);
        $this->writeTemplatesFolder($templateSlots["templates"]);

        return $this;
    }

    private function parseForRemovedTemplates($templates)
    {
        $templates = array_keys($templates);
        $removedTemplates = array();
        $finder = new Finder();
        $existingTemplates = $finder->files()->directories()->depth(0)->in($this->themeDir);
        foreach($existingTemplates as $template) {
            $templateName = basename($template);
            if ($templateName == 'base') {
                continue;
            }

            if (!in_array($templateName, $templates)) {
                $removedTemplates[] = (string)$template;
            }
        }

        return $removedTemplates;
    }

    private function parseForRemovedSlots($templates)
    {
        $removedSlots = array();
        $finder = new Finder();
        $templateNames = array_keys($templates);
        foreach($templateNames as $template) {
            $templateDir = $this->themeDir . '/' . $template;
            if (!is_dir($templateDir)) {
                continue;
            }

            $allSlots = $this->mergeSlots($templates[$template]);
            $slots = $finder->files()->name('*.json')->in($templateDir);
            foreach($slots as $slot) {
                $slotName = basename($slot, '.json');
                if (!in_array($slotName, $allSlots)) {
                    $removedSlots[] = (string)$slot;
                }
            }
        }

        return $removedSlots;
    }

    private function writeTemplatesFolder(array $templates)
    {
        foreach ($templates as $template => $templateSlots) {
            if ( ! is_dir($this->themeDir . '/' . $template)) {
                mkdir($this->themeDir . '/' . $template);
            }
            foreach ($templateSlots as $repeat => $slots) {
                $this->writeSlots($template, $slots, $repeat);
            }
        }
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Item;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity()
 * @ORM\Table(
 *      uniqueConstraints={@ORM\UniqueConstraint(name="contentful_contenttype__space_id_rev_uniq",columns={"spaceId", "id", "revision"})},
 *      indexes={
 *          @ORM\Index(name="contentful_contenttype__name_idx", columns={"name"}),
 *          @ORM\Index(name="contentful_contenttype__spaceId_idx", columns={"spaceId"})
 *      }
 * )
 * @ORM\Entity(repositoryClass="Dothiv\Bundle\ContentfulBundle\Repository\DoctrineContentfulContentTypeRepository")
 */
class ContentfulContentType
{
    use Traits\ContentfulSys;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     * @Assert\NotNull()
     * @Assert\Type("string")
     * @var string
     */
    private $name;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     * @Assert\NotNull()
     * @Assert\Type("string")
     * @var string
     */
    private $displayField;

    public function __construct()
    {
        $this->entries = new ArrayCollection();
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

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

    /**
     * @param string $displayField
     */
    public function setDisplayField($displayField)
    {
        $this->displayField = $displayField;
    }

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

    /**
     * Updates the name according to the display field of the content type.
     *
     * @param ContentfulEntry $entry
     */
    public function updateEntryName(ContentfulEntry $entry)
    {
        $displayField = $this->getDisplayField();
        $values       = array_values((array)$entry->{$displayField});
        $entry->setName(isset($values[0]) ? $values[0] : 'Untitled');
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return sprintf('ContentfulContentType: %s@%s, v%d [%s]', $this->getId(), $this->getSpaceId(), $this->getRevision(), $this->getName());
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\file;

/**
 * Meta meta for file models (@todo determine if used?).
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Meta extends \canis\base\Object
{
    /**
     * @var SourceFile the source file referenced in this meta
     */
    protected $_sourceFile;
    /**
     * @var array attribute names
     */
    protected $_attributes;
    /**
     * @var InterfaceItem the interface for this meta
     */
    protected $_interface;

    /**
     * @var array static collection of metas
     */
    public static $_metas = [];

    /**
     * Get.
     *
     * @param InterfaceItem  $interface  the interface object
     * @param Source $sourceFile the source file
     *
     * @return Meta the prepared meta object
     */
    public static function get($interface, $sourceFile)
    {
        if (!isset(self::$_metas[$sourceFile->id])) {
            self::$_metas[$sourceFile->id] = new static($interface, $sourceFile);
        }

        return self::$_metas[$sourceFile->id];
    }

    /**
     * @inheritdoc
     */
    public function __construct($interface, $sourceFile)
    {
        $this->_sourceFile = $sourceFile;
        $this->_interface = $interface;
        $this->_attributes = $sourceFile->readLine(1);
    }

    /**
     * Get source file.
     *
     * @return Source the source file
     */
    public function getSourceFile()
    {
        return $this->_sourceFile;
    }

    /**
     * Check if a specific attribute exists.
     *
     * @param string $name attribute name
     *
     * @return bool true if attribute exists, false otherwise
     */
    public function hasAttribute($name)
    {
        return in_array($name, $this->_attributes);
    }

    /**
     * Get attribute keys.
     *
     * @return array array of attribute names
     */
    public function getAttributeKeys()
    {
        return $this->_attributes;
    }

    /**
     * Set interface.
     *
     * @param InterfaceItem $value interface item for meta
     */
    public function setInterface($value)
    {
        $this->_interface = $value;
    }

    /**
     * Get interface.
     *
     * @return InterfaceItem the interface item for meta
     */
    public function getInterface()
    {
        return $this->_interface;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Forecast;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 as PCpmrsPhase1;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 as PCpmrsPhase2;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Ov as POv;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Tv as PTv;
use Praxigento\BonusHybrid\Service\Calc\Forecast\Compress\GetPlainData as PGetPlainData;
use Praxigento\BonusHybrid\Service\Calc\Forecast\Z\Register as PCalcReg;

class Compress
    implements \Praxigento\Core\Api\App\Service\Process
{
    const CTX_IN_PERIOD = \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain::CTX_IN_PERIOD;

    /** @var array [period => [ [PV by custId], [plain tree] ] ] */
    private $cacheDwnlPlainData;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 */
    private $procCmprsPhase1;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 */
    private $procCmprsPhase2;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress\GetPlainData */
    private $procGetPlainData;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Ov */
    private $procOv;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Tv */
    private $procTv;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress\A\UpdateDwnl */
    private $procUpdateDwnl;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Z\Register */
    private $zCalcReg;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 $procCmprsPhase1,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 $procCmprsPhase2,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Tv $procTv,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Ov $procOv,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Z\Register $zCalcReg,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress\GetPlainData $procGetPlainData,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Compress\A\UpdateDwnl $procUpdateDwnl
    ) {
        $this->logger = $logger;
        $this->daoCalc = $daoCalc;
        $this->daoBonDwnl = $daoBonDwnl;
        /* TODO: these classes are not real Z-ordered classes. They should be moved to one level up - ...\Calc\Z */
        $this->procCmprsPhase1 = $procCmprsPhase1;
        $this->procCmprsPhase2 = $procCmprsPhase2;
        $this->procTv = $procTv;
        $this->procOv = $procOv;
        $this->zCalcReg = $zCalcReg;
        $this->procGetPlainData = $procGetPlainData;
        $this->procUpdateDwnl = $procUpdateDwnl;
    }

    /**
     * @param EBonDwnl $dwnl
     * @return EBonDwnl
     */
    private function calcOv($dwnl)
    {
        $in = new \Praxigento\Core\Data();
        $in->set(POv::IN_DWNL, $dwnl);
        $in->set(POv::IN_USE_SIGN_UP, false);
        $out = $this->procOv->exec($in);
        $result = $out->get(POv::OUT_DWNL);
        return $result;
    }

    /**
     * @param EBonDwnl $dwnl
     * @return EBonDwnl
     */
    private function calcTv($dwnl)
    {
        $in = new \Praxigento\Core\Data();
        $in->set(PTv::IN_DWNL, $dwnl);
        $out = $this->procTv->exec($in);
        $result = $out->get(PTv::OUT_DWNL);
        return $result;
    }

    private function compressPhase1($calcId, $period)
    {
        /* get the last forecast plain calculation and extract collected PV */
        $inPv = new \Praxigento\Core\Data();
        $inPv->set(PGetPlainData::IN_PERIOD, $period);
        $outPv = $this->procGetPlainData->exec($inPv);
        $pv = $outPv->get(PGetPlainData::OUT_PV);
        $downline = $outPv->get(PGetPlainData::OUT_DWNL);

        $ctx = new \Praxigento\Core\Data();
        $ctx->set(PCpmrsPhase1::IN_CALC_ID, $calcId);
        $ctx->set(PCpmrsPhase1::IN_PV, $pv);
        $ctx->set(PCpmrsPhase1::IN_DWNL_PLAIN, $downline);
        $ctx->set(PCpmrsPhase1::IN_KEY_CALC_ID, EBonDwnl::A_CALC_REF);
        $ctx->set(PCpmrsPhase1::IN_KEY_CUST_ID, EBonDwnl::A_CUST_REF);
        $ctx->set(PCpmrsPhase1::IN_KEY_PARENT_ID, EBonDwnl::A_PARENT_REF);
        $ctx->set(PCpmrsPhase1::IN_KEY_DEPTH, EBonDwnl::A_DEPTH);
        $ctx->set(PCpmrsPhase1::IN_KEY_PATH, EBonDwnl::A_PATH);
        $ctx->set(PCpmrsPhase1::IN_KEY_PV, EBonDwnl::A_PV);

        $outPhase1 = $this->procCmprsPhase1->exec($ctx);
        $result = $outPhase1->get(PCpmrsPhase1::OUT_COMPRESSED);
        return $result;
    }

    private function compressPhase2($calcId, $scheme, $dwnlPhase1, $period)
    {
        list($pv, $dwnlPlain) = $this->getDwnlPlain($period);
        $ctx = new \Praxigento\Core\Data();
        $ctx->set(PCpmrsPhase2::IN_CALC_ID_PHASE2, $calcId);
        $ctx->set(PCpmrsPhase2::IN_MAP_PV, $pv);
        $ctx->set(PCpmrsPhase2::IN_DWNL_PLAIN, $dwnlPlain);
        $ctx->set(PCpmrsPhase2::IN_DWNL_PHASE1, $dwnlPhase1);
        $ctx->set(PCpmrsPhase2::IN_SCHEME, $scheme);
        $out = $this->procCmprsPhase2->exec($ctx);
        $result = $out->get(PCpmrsPhase2::OUT_DWNL_PHASE2);
        return $result;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        $this->logger->info("'Forecast Compress' calculation is started.");

        /* clean up existing calculation data and register new one */
        $period = $ctx->get(self::CTX_IN_PERIOD);
        $calcId = $this->registerCalc($period);

        /* perform Phase1 compression */
        $dwnlPhase1 = $this->compressPhase1($calcId, $period);

        /* calculate TV & OV on compressed tree */
        $dwnlPhase1 = $this->calcTv($dwnlPhase1);
        $dwnlPhase1 = $this->calcOv($dwnlPhase1);

        /* calculate phase 2 compression for both schemes */
        $dwnlPhase2Def = $this->compressPhase2($calcId, Cfg::SCHEMA_DEFAULT, $dwnlPhase1, $period);
        $dwnlPhase2Eu = $this->compressPhase2($calcId, Cfg::SCHEMA_EU, $dwnlPhase1, $period);

        /* ... then populate Phase1 downline with ranks from Phase2 downlines */
        $dwnlPhase1 = $this->procUpdateDwnl->exec($dwnlPhase1, $dwnlPhase2Def, $dwnlPhase2Eu);

        /* save updated Phase1 compression */
        $this->saveDownline($dwnlPhase1);

        /* populate plain downline tree with ranks data */
        $this->saveRanksToPlainTree($period, $dwnlPhase1);

        /* finalize calculation */
        $this->daoCalc->markComplete($calcId);

        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("'Forecast Compress' calculation is completed.");
    }

    private function getDwnlPlain($period)
    {
        if (is_null($this->cacheDwnlPlainData)) {
            $this->cacheDwnlPlainData = [];
        }
        if (!isset($this->cacheDwnlPlainData[$period])) {
            /* get the last forecast plain calculation and extract collected PV */
            $in = new \Praxigento\Core\Data();
            $in->set(PGetPlainData::IN_PERIOD, $period);
            $out = $this->procGetPlainData->exec($in);
            $pv = $out->get(PGetPlainData::OUT_PV);
            $downline = $out->get(PGetPlainData::OUT_DWNL);
            $this->cacheDwnlPlainData[$period] = [$pv, $downline];
        }
        $result = $this->cacheDwnlPlainData[$period];
        return $result;
    }

    /**
     * Register new compression calculation.
     *
     * @param string $period
     * @return int calculation ID.
     */
    private function registerCalc($period)
    {
        $ctx = new \Praxigento\Core\Data();
        $ctx->set(PCalcReg::IN_CALC_TYPE_CODE, Cfg::CODE_TYPE_CALC_FORECAST_PHASE1);
        $ctx->set(PCalcReg::IN_PERIOD, $period);
        /** @var \Praxigento\Core\Data $res */
        $res = $this->zCalcReg->exec($ctx);
        $result = $res->get(PCalcReg::OUT_CALC_ID);
        return $result;
    }

    private function saveDownline($items)
    {
        foreach ($items as $item) {
            $entryId = $item->getId();
            $found = is_null($entryId) ? false : $this->daoBonDwnl->getById($entryId);
            if ($found) {
                $this->daoBonDwnl->updateById($entryId, $item);
            } else {
                $this->daoBonDwnl->create($item);
            }
        }
    }

    /**
     * @param string $period
     * @param EBonDwnl[] $dwnlPhase1
     */
    private function saveRanksToPlainTree($period, $dwnlPhase1)
    {
        list($unused, $plainTree) = $this->getDwnlPlain($period);
        /** @var EBonDwnl $one */
        foreach ($plainTree as $one) {
            $custId = $one->getCustomerRef();
            if (isset($dwnlPhase1[$custId])) {
                $zipItem = $dwnlPhase1[$custId];
                $rankId = $zipItem->getRankRef();
                $one->setRankRef($rankId);
                $one->setUnqMonths(0);
                $itemId = $one->getId();
                $this->daoBonDwnl->updateById($itemId, $one);
            }
        }
    }
}


<?php
namespace Lab123\Odin\Libs;

use App;

class Api
{

    /**
     * Url da API
     *
     * @return string
     */
    public static function url()
    {
        return env('API_URL', 'http://localhost/api');
    }

    /**
     * Return Id Decoded
     *
     * @return array
     */
    public static function decodeHashId($idHashed)
    {
        if (! config('odin.hashid.active')) {
            return $idHashed;
        }

        $hashids = App::make('Hashids');
        $hashId = $hashids->decode($idHashed);

        return (count($hashId) > 0) ? $hashId[0] : '';
    }

    /**
     * Return Id Encoded
     *
     * @return array
     */
    public static function encodeHashId($id)
    {
        if (! config('odin.hashid.active')) {
            return $id;
        }

        $hashids = App::make('Hashids');
        return $hashids->encode($id, date('d'));
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Validator;

use Ruwork\RunetIdBundle\Client\RunetIdClients;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class UniqueEmailValidator extends ConstraintValidator
{
    private $clients;

    public function __construct(RunetIdClients $clients)
    {
        $this->clients = $clients;
    }

    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof UniqueEmail) {
            throw new UnexpectedTypeException($constraint, UniqueEmail::class);
        }

        if (null !== $value &&
            !is_scalar($value) &&
            !(\is_object($value) && method_exists($value, '__toString'))
        ) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;

        if ('' === $value) {
            return;
        }

        if ($this->emailExists($constraint, $value)) {
            $this->context->buildViolation($constraint->message)
                ->setCode(UniqueEmail::NOT_UNIQUE_ERROR)
                ->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE))
                ->addViolation();
        }
    }

    private function emailExists(UniqueEmail $constraint, string $email): bool
    {
        $users = $this->clients
            ->get($constraint->client)
            ->userSearch()
            ->setEventId($constraint->eventId)
            ->setVisible($constraint->visible)
            ->setQuery($email)
            ->getResult()
            ->Users;

        return iterator_count($users) > 0;
    }
}


<?php
namespace Boekkooi\Bundle\AMQP\PublisherLocator;

use Boekkooi\Bundle\AMQP\Exception\MissingPublisherException;
use Boekkooi\Tactician\AMQP\Message;
use Boekkooi\Tactician\AMQP\Publisher\Locator\PublisherLocator;
use Boekkooi\Tactician\AMQP\Publisher\Publisher;

class HeaderPublisherLocator implements PublisherLocator
{
    /**
     * @var string
     */
    private $headerName;
    /**
     * @var string[][]
     */
    private $valueMap = [];
    /**
     * @var Publisher[]
     */
    private $publishers = [];

    public function __construct($headerName = 'x-symfony-command')
    {
        $this->headerName = $headerName;
    }

    public function registerPublisher(Publisher $publisher, array $headerValues = [])
    {
        $hash = spl_object_hash($publisher);

        $this->publishers[$hash] = $publisher;
        $this->valueMap[$hash] = $headerValues;
    }

    /**
     * Retrieves the publisher for a specified message
     *
     * @param Message $message
     *
     * @return Publisher
     *
     * @throws MissingPublisherException
     */
    public function getPublisherForMessage(Message $message)
    {
        $attributes = $message->getAttributes();
        if (!isset($attributes['headers']) || !isset($attributes['headers'][$this->headerName])) {
            throw MissingPublisherException::noHeaderInMessage($message, $this->headerName);
        }

        $value = $attributes['headers'][$this->headerName];
        foreach ($this->valueMap as $hash => $values) {
            if (!in_array($value, $values, true)) {
                continue;
            }

            return $this->publishers[$hash];
        }

        throw MissingPublisherException::noKnownPublisherFor($message);
    }
}


<?php
namespace Clusterpoint;

use Clusterpoint\Instance\Service;
use Clusterpoint\Helper\Key as ClusterpointKey;
use Clusterpoint\Helper\Raw as ClusterpointRaw;
use Clusterpoint\Exceptions\ClusterpointException;
use Clusterpoint\Standart\Connection as StandartConnection;
use Clusterpoint\Transport\Rest as DataLayer;

/**
 *
 * Client for communicating between developer and our service.
 * Holds helper function raw(), field(), escape().
 * Resolves dependencies and starts API workflow.
 *
 * @category   Clusterpoint 4.0 PHP Client API
 * @package    clusterpoint/php-client-api-v4
 * @copyright  Copyright (c) 2016 Clusterpoint (http://www.clusterpoint.com)
 * @author     Marks Gerasimovs <marks.gerasimovs@clusterpoint.com>
 * @license    http://opensource.org/licenses/MIT    MIT
 */
class Client
{
    /**
     * The stdClass with scope of connection access points.
     *
     * @var \stdClass
     */
    protected $constructConnections;
    protected $connection;

    /**
     * Validates connection for initializing service.
     *
     * @param  array|string  $connection
     * @return void
     */
    public function __construct($connection = "default")
    {
        $this->constructConnections = $connection;
        $this->connection = class_exists("Clusterpoint\Connection") ? new Connection($connection) : new StandartConnection($connection);
    }

	public function createDatabase($databaseName)
	{
		$this->connection->query = 'CREATE DATABASE ' . $databaseName;
		$this->connection->method = 'POST';
		$this->connection->action = '';

		$response = DataLayer::execute($this->connection, true);
		$this->connection->resetSelf();
		return $response;
	}

	public function dropDatabase($databaseName)
	{
		$this->connection->query = 'DROP DATABASE ' . $databaseName;
		$this->connection->method = 'POST';
		$this->connection->action = '';

		$response = DataLayer::execute($this->connection, true);
		$this->connection->resetSelf();
		return $response;
	}

	public function listDatabases()
	{
		$this->connection->query = 'LIST DATABASES';
		$this->connection->method = 'POST';
		$this->connection->multiple = true;
		$this->connection->action = '';

		$response = DataLayer::execute($this->connection, true);
		$this->connection->resetSelf();
		return $response;
	}

	public function listCollections($databaseName = '')
	{
		$data = 'LIST COLLECTIONS';
		if ($databaseName !== false) {
			$data .= ' FROM ' . $databaseName;
		}

		$this->connection->query = $data;
		$this->connection->method = 'POST';
		$this->connection->multiple = true;
		$this->connection->action = '';

		$response = DataLayer::execute($this->connection, true);
		$this->connection->resetSelf();
		return $response;
	}

    /**
     * Escapes string for special characters.
     *
     * @param  string  $string
     * @return string
     */
    public static function escape($string)
    {
        $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
        $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
        return str_replace($search, $replace, $string);
    }

    /**
     * Creates Key Object for valid json key usage while quering.
     *
     * @param  string  $string
     * @return \Clusterpoint\Helper\Key
     */
    public static function field($string)
    {
        return new ClusterpointKey($string);
    }

    /**
     * Creates Raw Object for valid JSSQL command usage while quering.
     *
     * @param  string  $string
     * @return \Clusterpoint\Helper\Raw
     */
    public static function raw($string)
    {
        return new ClusterpointRaw($string);
    }

    /**
     * Creates Service instance that extends Query Builder.
     *
     * @param  string  $db
     * @return \Clusterpoint\Instance\Service
     */
    public function database($db)
    {
        $connection = $this->connection;
        $connection->db = $db;

        $this->constructConnections = $connection;
        $connection = class_exists("Clusterpoint\Connection") ? new Connection($this->constructConnections) : new StandartConnection($this->constructConnections);
        return new Service($connection);
    }

    /**
     * Database method alias.
     *
     * @param  string  $db
     * @return \Clusterpoint\Instance\Service
     */
    public function db($db)
    {
        return $this->database($db);
    }

    /**
     * Wraps all method use in try - catch.
     *
     * @param  string  $method
     * @param  array  $arguments
     * @return $this
     */
    public function __call($method, $arguments)
    {
        return call_user_func_array(array($this, $method), $arguments);
    }

    /**
     * Handle dynamic static method calls into the method.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        $instance = new static;
        return call_user_func_array(array($instance, $method), $parameters);
    }
}


<?php
/**
 * @copyright   2010-2014, The Titon Project
 * @license     http://opensource.org/licenses/bsd-license.php
 * @link        http://titon.io
 */

namespace Titon\Db\Sqlite;

use Titon\Db\Driver\Dialect\AbstractPdoDialect;
use Titon\Db\Driver\Dialect\Statement;
use Titon\Db\Driver\Schema;
use Titon\Db\Exception\UnsupportedQueryStatementException;
use Titon\Db\Query;

/**
 * Inherit the default dialect rules and override for SQLite specific syntax.
 *
 * @package Titon\Db\Sqlite
 */
class SqliteDialect extends AbstractPdoDialect {

    const ABORT = 'abort';
    const BINARY = 'binary';
    const DEFERRABLE = 'deferrable';
    const FAIL = 'fail';
    const INIT_DEFERRED = 'initiallyDeferred';
    const INIT_IMMEDIATE = 'initiallyImmediate';
    const MATCH = 'match';
    const NOCASE = 'nocase';
    const NOT_DEFERRABLE = 'notDeferrable';
    const ON_CONFLICT = 'onConflict';
    const REPLACE = 'replace';
    const ROLLBACK = 'rollback';
    const RTRIM = 'rtrim';
    const UNIQUE = 'unique';

    /**
     * Configuration.
     *
     * @type array
     */
    protected $_config = [
        'quoteCharacter' => '"',
        'virtualJoins' => true
    ];

    /**
     * Modify clauses and keywords.
     */
    public function initialize() {
        parent::initialize();

        $this->addClauses([
            self::DEFERRABLE        => 'DEFERRABLE %s',
            self::EITHER            => 'OR %s',
            self::MATCH             => 'MATCH %s',
            self::NOT_DEFERRABLE    => 'NOT DEFERRABLE %s',
            self::UNIQUE_KEY        => 'UNIQUE (%2$s)'
        ]);

        $this->addKeywords([
            self::ABORT             => 'ABORT',
            self::BINARY            => 'BINARY',
            self::AUTO_INCREMENT    => 'AUTOINCREMENT',
            self::FAIL              => 'FAIL',
            self::IGNORE            => 'IGNORE',
            self::INIT_DEFERRED     => 'INITIALLY DEFERRED',
            self::INIT_IMMEDIATE    => 'INITIALLY IMMEDIATE',
            self::NOCASE            => 'NOCASE',
            self::PRIMARY_KEY       => 'PRIMARY KEY',
            self::REPLACE           => 'REPLACE',
            self::ROLLBACK          => 'ROLLBACK',
            self::RTRIM             => 'RTRIM',
            self::UNIQUE            => 'UNIQUE'
        ]);

        $this->addStatements([
            Query::INSERT        => new Statement('INSERT {or} INTO {table} {fields} VALUES {values}'),
            Query::SELECT        => new Statement('SELECT {distinct} {fields} FROM {table} {joins} {where} {groupBy} {having} {compounds} {orderBy} {limit}'),
            Query::UPDATE        => new Statement('UPDATE {or} {table} SET {fields} {where}'),
            Query::DELETE        => new Statement('DELETE FROM {table} {where}'),
            Query::CREATE_TABLE  => new Statement("CREATE {temporary} TABLE IF NOT EXISTS {table} (\n{columns}{keys}\n)"),
            Query::CREATE_INDEX  => new Statement('CREATE {type} INDEX IF NOT EXISTS {index} ON {table} ({fields})'),
            Query::DROP_TABLE    => new Statement('DROP TABLE IF EXISTS {table}'),
            Query::DROP_INDEX    => new Statement('DROP INDEX IF EXISTS {index}')
        ]);

        // SQLite doesn't support TRUNCATE
        unset($this->_statements[Query::TRUNCATE]);
    }

    /**
     * {@inheritdoc}
     *
     * @throws \Titon\Db\Exception\UnsupportedQueryStatementException
     */
    public function buildMultiInsert(Query $query) {
        throw new UnsupportedQueryStatementException('SQLite does not support multi-inserts');
    }

    /**
     * {@inheritdoc}
     */
    public function formatColumns(Schema $schema) {
        $columns = [];

        foreach ($schema->getColumns() as $column => $options) {
            $type = $options['type'];
            $dataType = $this->getDriver()->getType($type);
            $options = $options + $dataType->getDefaultOptions();

            // Sqlite doesn't like the shorthand version
            if ($type === 'int') {
                $type = 'integer';
            }

            if (!empty($options['length'])) {
                $type .= '(' . $options['length'] . ')';
            }

            $output = [$this->quote($column), strtoupper($type)];

            if (!empty($options['primary'])) {
                $output[] = $this->getKeyword(self::NOT_NULL);
                $output[] = $this->getKeyword(self::PRIMARY_KEY);
                $output[] = $this->getKeyword(self::AUTO_INCREMENT);

            } else {
                if (empty($options['null']) || !empty($options['primary'])) {
                    $output[] = $this->getKeyword(self::NOT_NULL);
                }

                if (!empty($options['collate']) && in_array($options['collate'], [self::BINARY, self::NOCASE, self::RTRIM])) {
                    $output[] = sprintf($this->getClause(self::COLLATE), $options['collate']);
                }

                if (array_key_exists('default', $options) && $options['default'] !== '') {
                    $output[] = sprintf($this->getClause(self::DEFAULT_TO), $this->getDriver()->escape($options['default']));
                }
            }

            $columns[] = implode(' ', $output);
        }

        return implode(",\n", $columns);
    }

    /**
     * {@inheritdoc}
     */
    public function formatTablePrimary(array $data) {
        return ''; // Return nothing as this will be handled as a column constraint
    }

}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */
namespace RedKiteCms\Content\Block;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Exclude;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Yaml\Yaml;

/**
 * Class ExtendableBlock is the object assigned to define an extendable block, which means a block you can extend its
 * properties.
 *
 * For example when you manage a block link, you can extend it adding an arbitrary "class" property to tags parameter
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Block
 */
abstract class ExtendableBlock extends BaseBlock
{
    /**
     * @Type("string")
     */
    protected $value = "";
    /**
     * @Type("array")
     */
    protected $tags = array();
    /**
     * @Type("string")
     */
    protected $source = null;

    /**
     * Constructor
     *
     * @param string $value
     * @param array $tags
     */
    public function __construct($value = null, array $tags = null)
    {
        parent::__construct();

        // @codeCoverageIgnoreStart
        if (null !== $this->source) {
            return;
        }
        // @codeCoverageIgnoreEnd

        if (null !== $value) {
            $this->value = $value;
        }
        if (null !== $tags) {
            $this->tags = $tags;
        }
        $this->updateSource();
    }

    /**
     * Updates the block source
     */
    public function updateSource()
    {
        $source = array(
            "value" => $this->value,
            "tags" => $this->tags,
            "type" => $this->type,
        );

        $this->source = Yaml::dump($source, 100, 2);
    }

    /**
     * Returns the block's source property
     *
     * @return string
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * Sets the block's source property
     *
     * @return string
     */
    public function setSource($value)
    {
        $this->source = $value;
    }

    /**
     * Returns the block's value property
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Sets the block's value property
     *
     * @param string $value
     */
    public function setValue($value)
    {
        $this->value = $value;
    }

    /**
     * Returns the block's tags property
     *
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Returns the block's tags property
     *
     * @param array $tags
     */
    public function setTags(array $tags)
    {
        $this->tags = $tags;
    }

    /**
     * @inheritdoc
     */
    protected function getTranslatorOptions()
    {
        return array(
            "fields" => array('value'),
        );
    }
}


<?php

class SDIS62_Controller_Action_OauthConsumer extends Zend_Controller_Action
{
    /**
     * Zend_Oauth_Consumer
     *
     * @var Zend_Oauth_Consumer|null
     */
	private $consumer;

    /**
     * Le chemin vers le fichier de configuration
     * Par défaut, le fichier de configuation doit se trouver dans application/configs/secret.ini
     *
     * @var string|null
     */
	protected $config_path;

    /**
     * Initialisation du controleur
     */
    public function init()
    {
        // Récupération du fichier de config
        $config = new Zend_Config_Ini(
            $this->config_path == null ? APPLICATION_PATH . DS . "configs" . DS . "secret.ini" : $config_path,
            APPLICATION_ENV
        );

        // Initialisation du consumer
		$this->setConsumer(new Zend_Oauth_Consumer(array(
            'callbackUrl' => $config->oauth->callback,
            'siteUrl' => $config->oauth->siteurl,
			'consumerKey' => $config->oauth->consumerkey,
			'consumerSecret' => $config->oauth->consumersecret
        )));
    }

    /**
     * Récupération du consumer oauth
     *
     * @return Zend_Oauth_Consumer|null
     */
    protected function getConsumer()
    {
        return $this->consumer;
    }

    /**
     * Définition du consumer oauth
     *
     * @param Zend_Oauth_Consumer $consumer
     */
    private function setConsumer(Zend_Oauth_Consumer $consumer)
    {
        $this->consumer = $consumer;
    }

    /**
     * Dispatch pour récupérer un request_token
     */
    public function indexAction()
    {
        // Récupération du request_token
        $_SESSION['request_token'] = serialize($this->getConsumer()->getRequestToken());

        // Redirection vers la page d'authentification
        $this->getConsumer()->redirect();
    }

    /**
     * Dispatch pour récupérer un access_token
     */
    public function callbackAction()
    {
        $request_token = unserialize($_SESSION['request_token']);
        $_SESSION['request_token'] = null;

        // On test si le request token correspond avec celui reçu à la première étape
        if($this->getParam("oauth_token") != $request_token->oauth_token)
        {
            throw new Exception("Les request_token ne correspondent pas ! (" . $this->getParam("oauth_token") .
                " != " . $request_token->oauth_token . ")", 500);
        }

        // Récupération de l'access_token
        $access_token = $this->getConsumer()->getAccessToken($_GET, $request_token);

        // Stockage de l'access_token
        $_SESSION['access_token'] = serialize($access_token);
    }
}


<?php

/*
 * This file is part of the Meta Reader package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MetaReader;

use Poppler\Processor\PdfFile;
use Temp\MetaReader\Value\MetaValue;
use Temp\MetaReader\Value\ValueBag;

/**
 * pdfinfo reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class PdfInfoReader implements ReaderInterface
{
    /**
     * @var PdfFile
     */
    private $pdfFile;

    /**
     * @param PdfFile $pdfFile
     */
    public function __construct(PdfFile $pdfFile)
    {
        $this->pdfFile = $pdfFile;
    }

    /**
     * {@inheritdoc}
     */
    public function available()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        try {
            $this->pdfFile->getInfo($filename);
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function read($filename)
    {
        $meta = new ValueBag();

        try {
            $infos = $this->pdfFile->getInfo($filename);

            foreach ($infos as $key => $value) {
                $meta->set(strtolower("pdfinfo.$key"), new MetaValue($value));
            }
        } catch (\Exception $e) {
        }

        return $meta;
    }
}


<?php

/*
 * This file is part of the Common API Interface package.
 *
 * (c) Pavel Logachev <alhames@mail.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alhames\Api\Authentication;

use Alhames\Api\Exception\AuthenticationException;
use Alhames\Api\HttpInterface;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class OpenId2AuthenticationClient.
 *
 * @see https://openid.net/specs/openid-authentication-2_0.html
 */
abstract class AbstractOpenId2Client extends AbstractAuthenticationClient
{
    const OPEN_ID_IDENTIFIER = 'http://specs.openid.net/auth/2.0/identifier_select';
    const OPEN_ID_NS = 'http://specs.openid.net/auth/2.0';
    protected static $openIdRequiredFields = ['ns', 'mode', 'op_endpoint', 'return_to', 'response_nonce', 'assoc_handle', 'signed', 'sig'];

    /**
     * {@inheritdoc}
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
        if (empty($config['redirect_uri'])) {
            throw new \InvalidArgumentException('Option "redirect_uri" is required.');
        }
        $this->redirectUri = $config['redirect_uri'];
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthenticationUri(?string $state = null, array $options = []): string
    {
        $redirectUri = $this->getRedirectUriWithState($state);
        $query = [
            'openid.ns' => self::OPEN_ID_NS,
            'openid.mode' => 'checkid_setup',
            'openid.identity' => $options['identity'] ?? self::OPEN_ID_IDENTIFIER,
            'openid.claimed_id' => $options['claimed_id'] ?? $options['identity'] ?? self::OPEN_ID_IDENTIFIER,
            'openid.return_to' => $redirectUri,
            'openid.realm' => parse_url($redirectUri, PHP_URL_SCHEME).'://'.parse_url($redirectUri, PHP_URL_HOST),
        ];

        return $this->getAuthEndpoint().'?'.http_build_query($query);
    }

    /**
     * {@inheritdoc}
     */
    public function authenticate(array $options = []): array
    {
        $query = [];
        foreach (self::$openIdRequiredFields as $field) {
            if (isset($options['openid_'.$field])) {
                $query['openid.'.$field] = $options['openid_'.$field];
            } elseif (isset($options['openid.'.$field])) {
                $query['openid.'.$field] = $options['openid.'.$field];
            } else {
                throw AuthenticationException::invalidArgument($field, $options);
            }
        }

        if (self::OPEN_ID_NS !== $query['openid.ns']) {
            throw AuthenticationException::invalidArgument('ns', $options);
        }

        if ('id_res' === $query['openid.mode']) {
            $query['openid.mode'] = 'check_authentication';
        } else {
            throw AuthenticationException::invalidArgument('mode', $options);
        }

        if ($this->getAuthEndpoint() !== $query['openid.op_endpoint']) {
            throw AuthenticationException::invalidArgument('op_endpoint', $options);
        }

        if ($this->getRedirectUriWithState($options['state'] ?? null) !== $query['openid.return_to']) {
            throw AuthenticationException::invalidArgument('return_to', $options);
        }

        if (isset($options['openid_claimed_id'], $options['openid_identity'])) {
            $query['openid.claimed_id'] = $options['openid_claimed_id'];
            $query['openid.identity'] = $options['openid_identity'];
        } elseif (isset($options['openid.claimed_id'], $options['openid.identity'])) {
            $query['openid.claimed_id'] = $options['openid.claimed_id'];
            $query['openid.identity'] = $options['openid.identity'];
        }

        try {
            $data = $this->httpClient->requestKeyValueForm(HttpInterface::METHOD_POST, $this->getAuthEndpoint(), $query);
        } catch (GuzzleException $e) {
            throw $this->handleApiException($e);
        }
        if (!isset($data['ns'], $data['is_valid']) || self::OPEN_ID_NS !== $data['ns'] || 'true' !== $data['is_valid']) {
            throw new AuthenticationException($data, 'OpendID authentication is failed.');
        }

        return array_merge($query, $data);
    }

    /**
     * @param string|null $state
     *
     * @return string
     */
    private function getRedirectUriWithState(?string $state = null): string
    {
        if (null === $state) {
            return $this->redirectUri;
        }

        $sep = false === strpos($this->redirectUri, '?') ? '?' : '&';

        return $this->redirectUri.$sep.'state='.$state;
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Validator;

/**
 * Main class for validators. Check correct values.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
abstract class ValidatorAbstract{

	/**
	 * Array with config options.
	 *
	 * @var mixed[] $options
	 */
	private $options=[];

	/**
	 * Implement method to validate value.
	 *
	 * @param mixed $value - value to parse
	 * @return string - error message
	 */
	abstract public function validate($value);

	/**
	 * Set extra options.
	 *
	 * @param string $name
	 * @param mixed $value
	 */
	final public function setOption($name,$value){
		$this->options[$name]=$value;
	}

	/**
	 * Get extra option.
	 *
	 * @param string $name - name of option
	 * @return mixed - option
	 * @throws ValueNotFoundException
	 */
	protected function getOption($name){
		if(!isset($this->options[$name])){
			throw new ValueNotFoundException($name);
		}

		return $this->options[$name];
	}
}


<?php
/**
 * Created by PhpStorm.
 * User: las
 * Date: 28/06/2016
 * Time: 22:22
 */
namespace Venus\lib\Request;

class Headers implements RequestInterface
{
    /**
     * get parameter
     * @param string $name
     * @param string $default
     * @return string
     */
    public function get(string $name, string $default = null)
    {
        if (isset(apache_request_headers()[$name]) && apache_request_headers()[$name] != '') {
            return apache_request_headers()[$name];
        } else if ($default !== null) {
            return $default;
        }
    }

    /**
     * set a new header
     * @param string $name
     * @param string $value
     * @return string|Headers
     */
    public function set(string $name, string $value = null) : Headers
    {
        if ($value !== null) {
            header($name . ': ' . $value);
        } else {
            header($name);
        }

        return $this;
    }
}


<?php

namespace Cpwc\Lta;

use Cpwc\Lta\Api\ApiInterface;
use Cpwc\Lta\Exception\InvalidArgumentException;
use Cpwc\Lta\Exception\BadMethodCallException;
use Cpwc\Lta\HttpClient\HttpClient;
use Cpwc\Lta\HttpClient\HttpClientInterface;

/**
 * Simple yet very cool PHP LTA client.
 *
 * @method Api\BusArrival busArrival()
 * @method Api\SBSTRopute sbstRoute()
 *
 * @author Poh Wei Cheng <calvinpohwc@gmail.com>
 */
class Client
{
    /**
     * Constant for authentication method. Indicates the new login method with
     * with username and token via HTTP Authentication.
     */
    const AUTH_HTTP_TOKEN = 'http_token';

    /**
     * @var array
     */
    private $options = array(
        'base_url'   => 'http://datamall2.mytransport.sg/ltaodataservice/',
        'user_agent' => 'php-lta-api (https://github.com/cpwc/php-lta-api)',
        'accept'     => 'application/json',
        'timeout'    => 10,
        'cache_dir'  => null
    );

    /**
     * The Buzz instance used to communicate with GitHub.
     *
     * @var HttpClient
     */
    private $httpClient;

    /**
     * Instantiate a new LTA client.
     *
     * @param null|HttpClientInterface $httpClient LTA http client
     */
    public function __construct(HttpClientInterface $httpClient = null)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * @param string $name
     *
     * @throws InvalidArgumentException
     *
     * @return ApiInterface
     */
    public function api($name)
    {
        switch ($name) {
            case 'bus_arrival':
            case 'busArrival':
                $this->getHttpClient()->client->setBaseUrl('http://datamall2.mytransport.sg/ltaodataservice/');
                $api = new Api\BusArrival($this);
                break;
            case 'sbst_route':
            case 'SBSTRoute':
                $this->getHttpClient()->client->setBaseUrl('http://datamall.mytransport.sg/ltaodataservice.svc/');
                $api = new Api\SBSTRoute($this);
                break;
            case 'smrt_route':
            case 'SMRTRoute':
                $this->getHttpClient()->client->setBaseUrl('http://datamall.mytransport.sg/ltaodataservice.svc/');
                $api = new Api\SMRTRoute($this);
                break;
            default:
                throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
        }

        return $api;
    }

    /**
     * Authenticate a user for all next requests.
     *
     * @param string      $accountKey   LTA DataMall AccountKey
     * @param string      $uniqueUserId UniqueUserID generated from DataMall Tool
     * @param null|string $authMethod   One of the AUTH_* class constants
     */
    public function authenticate($accountKey, $uniqueUserId, $authMethod = null)
    {
        if (null === $authMethod) {
            $authMethod = self::AUTH_HTTP_TOKEN;
        }

        $this->getHttpClient()->authenticate($accountKey, $uniqueUserId, $authMethod);
    }

    /**
     * @return HttpClient
     */
    public function getHttpClient()
    {
        if (null === $this->httpClient) {
            $this->httpClient = new HttpClient($this->options);
        }

        return $this->httpClient;
    }

    /**
     * @param HttpClientInterface $httpClient
     */
    public function setHttpClient(HttpClientInterface $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * Clears used headers.
     */
    public function clearHeaders()
    {
        $this->getHttpClient()->clearHeaders();
    }

    /**
     * @param array $headers
     */
    public function setHeaders(array $headers)
    {
        $this->getHttpClient()->setHeaders($headers);
    }

    /**
     * @param string $name
     *
     * @throws InvalidArgumentException
     *
     * @return mixed
     */
    public function getOption($name)
    {
        if (!array_key_exists($name, $this->options)) {
            throw new InvalidArgumentException(sprintf('Undefined option called: "%s"', $name));
        }

        return $this->options[$name];
    }

    /**
     * @param string $name
     * @param mixed  $value
     *
     * @throws InvalidArgumentException
     * @throws InvalidArgumentException
     */
    public function setOption($name, $value)
    {
        if (!array_key_exists($name, $this->options)) {
            throw new InvalidArgumentException(sprintf('Undefined option called: "%s"', $name));
        }

        $this->options[$name] = $value;
    }

    /**
     * @param string $name
     *
     * @throws InvalidArgumentException
     *
     * @return ApiInterface
     */
    public function __call($name, $args)
    {
        try {
            return $this->api($name);
        } catch (InvalidArgumentException $e) {
            throw new BadMethodCallException(sprintf('Undefined method called: "%s"', $name));
        }
    }
}


<?php

namespace nadir2\core\validator;

use nadir2\core\RunnableInterface;

/**
 * This is class for input data validation.
 * @author Leonid Selikhov
 */
class Validator implements RunnableInterface
{
    /** @var mixed[] Input data for validation. */
    protected $data = null;

    /** @var array Set of fields and their corresponding rules for validation. */
    protected $items = [];

    /** @var array Set of validation rules. */
    protected $rules = [];

    /** @var array Stack of data errors which occured during the validation. */
    protected $errors = [];

    /** @var boolean Flag is equal true when the data is validated. */
    protected $isRan = false;

    /**
     * The constructor initializes the validator and also sets the input data for
     * validation.
     * @param mixed[] $data Input data.
     */
    public function __construct($data)
    {
        if (is_array($data)) {
            $this->data = $data;
            $this->init();
        } else {
            $this->isRan = true;
            $this->addError('Invalid data set format.');
        }
    }

    /**
     * The method returns a tree element by a key, which is formed as a string
     * separated by points and reflecting the nesting hierarchy.
     * @param mixed[] $data Input tree.
     * @param string $key The field name. The name of the nested field is formed by
     * the path of the tree the tiers of which are separated by the point.
     * @return mixed
     * @throws \extensions\validator\Exception
     */
    public static function getArrayItemByPointSeparatedKey(array& $data, string $key)
    {
        if (strpos($key, '.') !== false) {
            preg_match('/([a-zA-Z0-9_\-]+)\.([a-zA-Z0-9_\-\.]+)/', $key, $keys);
            if (!isset($data[$keys[1]])) {
                throw new Exception('Undefined index: '.$keys[1]);
            }
            if (!is_array($data[$keys[1]])) {
                throw new Exception("The element indexed {$keys[1]} isn't an array.");
            }
            return self::getArrayItemByPointSeparatedKey(
                $data[$keys[1]],
                $keys[2]
            );
        } elseif (isset($data[$key])) {
            return $data[$key];
        } else {
            throw new Exception('Undefined index: '.$key);
        }
    }

    /**
     * The method checks if the input tree contains an element with the specified
     * index (the index contains a point-separator of tiers)
     * @param mixed[] $data Input tree.
     * @param string $key The field name. The name of the nested field is formed by
     * the path of the tree the tiers of which are separated by the point.
     * @return boolean
     */
    public static function isIndexSet(array& $data, string $key): bool
    {
        try {
            self::getArrayItemByPointSeparatedKey($data, $key);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * This method fills the validator with default set of rules (and options of rules)
     * such as rules for validating required fields, strings, numbers, arrays etc.
     * @return void
     */
    private function init(): void
    {
        $data = $this->data;

        $this
            // Required value rules
            ->addRule(
                'required',
                function (string $fieldName) use ($data): bool {
                    if (self::isIndexSet($data, $fieldName)) {
                        return true;
                    }
                    return false;
                },
                function ($fieldName): string {
                    return "Field '{$fieldName}' is required.";
                }
            )
            // String rules
            ->addRule(
                'string',
                function (string $fieldName, array $options = []) use ($data): bool {
                    if (self::isIndexSet($data, $fieldName)) {
                        $value = self::getArrayItemByPointSeparatedKey($data, $fieldName);
                        if (!is_string($value)) {
                            return false;
                        }
                        if (isset($options['notEmpty'])) {
                            $trimVal = trim($value);
                            if ($options['notEmpty'] && empty($trimVal)) {
                                return false;
                            }
                            if (!$options['notEmpty'] && !empty($trimVal)) {
                                return false;
                            }
                        }
                        if (isset($options['pattern'])) {
                            if (!preg_match($options['pattern'], $value)) {
                                return false;
                            }
                        }
                        if (isset($options['length'])) {
                            $length = mb_strlen($value);
                            if (isset($options['length']['min'])) {
                                if ($length < $options['length']['min']) {
                                    return false;
                                }
                            }
                            if (isset($options['length']['max'])) {
                                if ($length > $options['length']['max']) {
                                    return false;
                                }
                            }
                            if (isset($options['length']['equal'])) {
                                if ($length != $options['length']['equal']) {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                },
                function (string $fieldName, array $options = []): string {
                    if (!empty($options)) {
                        $keys = implode(', ', array_keys($options));
                        return "Invalid string field '{$fieldName}' value. "
                        . "Validation options: {$keys}";
                    }
                    return "Invalid string field '{$fieldName}' value.";
                }
            )
            // Number rules
            ->addRule(
                'number',
                function (string $fieldName, array $options = []) use ($data): bool {
                    if (self::isIndexSet($data, $fieldName)) {
                        $value = self::getArrayItemByPointSeparatedKey($data, $fieldName);
                        if (!is_numeric($value)) {
                            return false;
                        }
                        if (isset($options['float'])) {
                            if ($options['float'] && !is_float($value)) {
                                return false;
                            }
                            if (!$options['float'] && is_float($value)) {
                                return false;
                            }
                        }
                        if (isset($options['integer'])) {
                            if ($options['integer'] && !is_int($value)) {
                                return false;
                            }
                            if (!$options['integer'] && is_int($value)) {
                                return false;
                            }
                        }
                        if (isset($options['positive'])) {
                            if ($options['positive'] && $value <= 0) {
                                return false;
                            }
                            if (!$options['positive'] && $value >= 0) {
                                return false;
                            }
                        }
                        if (isset($options['value'])) {
                            if (isset($options['value']['equal'])) {
                                if ($value != $options['value']['equal']) {
                                    return false;
                                }
                            }
                            if (isset($options['value']['min'])) {
                                if ($value < $options['value']['min']) {
                                    return false;
                                }
                            }
                            if (isset($options['value']['max'])) {
                                if ($value > $options['value']['max']) {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                },
                function (string $fieldName, array $options = []) {
                    if (!empty($options)) {
                        $keys = implode(', ', array_keys($options));
                        return "Invalid number field '{$fieldName}' value. "
                        . "Validation options: {$keys}";
                    }
                    return "Invalid number field '{$fieldName}' value.";
                }
            )
            // Array rules
            ->addRule(
                'array',
                function (string $fieldName, array $options = []) use ($data): bool {
                    if (self::isIndexSet($data, $fieldName)) {
                        $value = self::getArrayItemByPointSeparatedKey($data, $fieldName);
                        if (!is_array($value)) {
                            return false;
                        }
                        if (isset($options['assoc'])) {
                            $isAssoc = function (array $array): bool {
                                // return false if array is empty
                                return (bool) count(array_filter(
                                    array_keys($array),
                                    'is_string'
                                ));
                            };
                            if ($options['assoc'] && !$isAssoc($value)) {
                                return false;
                            }
                            if (!$options['assoc'] && $isAssoc($value)) {
                                return false;
                            }
                            unset($isAssoc);
                        }
                        if (isset($options['length'])) {
                            $length = count($value);
                            if (isset($options['length']['min'])) {
                                if ($length < $options['length']['min']) {
                                    return false;
                                }
                            }
                            if (isset($options['length']['max'])) {
                                if ($length > $options['length']['max']) {
                                    return false;
                                }
                            }
                            if (isset($options['length']['equal'])) {
                                if ($length != $options['length']['equal']) {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                },
                function (string $fieldName, array $options = []): string {
                    if (!empty($options)) {
                        $keys = implode(', ', array_keys($options));
                        return "Invalid array field '{$fieldName}' value. "
                        . "Validation options: {$keys}";
                    }
                    return "Invalid array field '{$fieldName}' value.";
                }
            )
            // Boolean rules
            ->addRule(
                'boolean',
                function (string $fieldName, array $options = []) use ($data): bool {
                    if (self::isIndexSet($data, $fieldName)) {
                        $value = self::getArrayItemByPointSeparatedKey($data, $fieldName);
                        if (!is_bool($value)) {
                            return false;
                        }
                        if (isset($options['isTrue'])) {
                            if ($options['isTrue'] && !$value) {
                                return false;
                            }
                            if (!$options['isTrue'] && $value) {
                                return false;
                            }
                        }
                    }
                    return true;
                },
                function (string $fieldName, array $options = []): string {
                    if (!empty($options)) {
                        $keys = implode(', ', array_keys($options));
                        return "Invalid boolean field '{$fieldName}' value. "
                        . "Validation options: {$keys}";
                    }
                    return "Invalid boolean field '{$fieldName}' value.";
                }
            );
    }

    /**
     * The method adds a set of fields and their corresponding rules and parameters
     * for validating the input data
     * @param array $item This set is an array whose first element is a string
     * with a field name (or an array of field names), the second element is the
     * name of the validation rule (always a string), the third element is an
     * optional array of validation options.
     * @return self
     * @throws \extensions\validator\Exception
     */
    public function addItem(array $item): self
    {
        if (count($item) < 2) {
            throw new Exception('Invalid count of item elements.');
        }
        $this->items[] = $item;
        return $this;
    }

    /**
     * This is mass analog for addItem() method.
     * @param array $items The input array of sets.
     * @return self
     */
    public function setItems(array $items): self
    {
        foreach ($items as $item) {
            $this->addItem($item);
        }
        return $this;
    }

    /**
     * The method adds a validation rule to the stack of validator rulesets.
     * @param string $name The name of rule.
     * @param callable $func The callback function that defines the functional
     * of the data validation rule. The first parameter is the name of the validated
     * field, the second optional parameter is the set of validation options,
     * and the context (closure) is the input data.
     * @param string|callable|null $errorMsg The error message or callable function
     * which generates this message. This parameter is optional.
     * @return self
     */
    public function addRule(string $name, callable $func, $errorMsg = null): self
    {
        $this->rules[$name] = array($func, $errorMsg);
        return $this;
    }

    /**
     * The method adds the error message to the error stack which occurred during
     * validation.
     * @param string $sMsg
     * @return void
     */
    protected function addError(string $msg): void
    {
        $this->errors[] = $msg;
    }

    /**
     * The method adds default message to form a description of the validation
     * errors.
     * @param string $fieldName The field name.
     * @return void
     */
    protected function addDefaultError(string $fieldName): void
    {
        $this->addError("Invalid field '{$fieldName}' value.");
    }

    /**
     * The method applies the validation rule to the validable field.
     * @param string $fieldName The field name. The name of the nested field is
     * formed by the path of the tree the tiers of which are separated by the point.
     * @param string $ruleName The validation rule name.
     * @param array $options The validation options.
     * @return void
     * @throws \extensions\validator\Exception
     */
    private function applyRuleToField(
        string $fieldName,
        string $ruleName,
        array $options = []
    ): void {
        if (!isset($this->rules[$ruleName])) {
            throw new Exception('Undefined rule name.');
        }
        $func = $this->rules[$ruleName][0];
        if (!$func($fieldName, $options)) {
            if (isset($this->rules[$ruleName][1])) {
                if (is_callable($this->rules[$ruleName][1])) {
                    // If message entity is function
                    $funcMsg = $this->rules[$ruleName][1];
                    $this->addError($funcMsg($fieldName, $options));
                } else {
                    // If message entity is string
                    $this->addError((string) $this->rules[$ruleName][1]);
                }
            } else {
                // If message entity isn't set
                $this->addDefaultError($fieldName);
            }
        }
    }

    /**
     * The main executable method.
     * @return void
     */
    public function run(): void
    {
        if (!$this->isRan) {
            $this->isRan = true;
            foreach ($this->items as $item) {
                $options      = $item[2] ?? [];
                $ruleName = $item[1];
                foreach (is_array($item[0]) ? $item[0] : [$item[0]] as $fieldName) {
                    self::applyRuleToField($fieldName, $ruleName, $options);
                }
            }
        }
    }

    /**
     * It checks if processed input data is valid or not.
     * @return boolean
     * @throws \extensions\validator\Exception
     */
    public function isValid(): bool
    {
        if (!$this->isRan) {
            throw new Exception("The validation wasn't ran.");
        }
        return empty($this->errors);
    }

    /**
     * The method returns the contents of the stack of validation errors of
     * input data.
     * @return string[] The array of validation errors.
     * @throws \extensions\validator\Exception.
     */
    public function getErrors(): array
    {
        if (!$this->isRan) {
            throw new Exception("The validation wasn't ran.");
        }
        return $this->errors;
    }
}


<?php
/*
 * This file is part of the codeliner/php-equalsbuilder package.
 * (c) Alexander Miertsch <kontakt@codeliner.ws>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Codeliner\Comparison;

/**
 * Class EqualsBuilder
 *
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class EqualsBuilder
{
    protected $strict = false;

    protected $comparisonList = array();

    /**
     * @return EqualsBuilder
     */
    static public function create()
    {
        return new static();
    }

    /**
     * Enable or disable strict comparison
     *
     * @param bool $flag
     * @return EqualsBuilder
     */
    public function strict($flag = true)
    {
        $this->strict = $flag;
        return $this;
    }

    /**
     * Add a new value pair to comparison list
     *
     * @param mixed $a
     * @param mixed|true $b                     If you just provide $a it is compared with a boolean TRUE
     * @param null|callable $comparatorCallback If you pass in an optional callback, this callback is used to compare $a and $b.
     *                                          The callback should return TRUE if $a and $b are equals or FALSE if not.
     *                                          If $a and $b are arrays with a numeric index aka. lists, the callback is
     *                                          called for every item in list $a and the item of list $b with the same index.
     *
     * @return EqualsBuilder
     *
     * @example
     *
     * <code>
     * echo EqualsBuilder::create()
     *      ->append(1, 1)
     *      ->append('equals', 'equals')
     *      ->append($aArray, $bArray)
     *      ->append($vo->sameValueAs($otherVo))
     *      ->append($aVo, $bVo, function ($aVo, $bVo) { return $aVo->sameValueAs($bVo); })
     *      ->append($aList, $bList, function ($aItem, $bItem) { return $aItem->sameValueAs($bItem); })
     *      ->equals();
     * </code>
     */
    public function append($a, $b = true, $comparatorCallback = null)
    {
        $this->comparisonList[] = array($a, $b, $comparatorCallback);
        return $this;
    }

    /**
     * Compare all previous set value pairs
     *
     * @return boolean
     */
    public function equals()
    {
        foreach ($this->comparisonList as $valuePair) {
            $a = $valuePair[0];
            $b = $valuePair[1];
            $callback = $valuePair[2];

            if (! is_null($callback)) {

                if (! is_callable($callback)) {
                    throw new \InvalidArgumentException(
                        sprintf(
                            'Provided callback of type %s is not callable!',
                            is_object($callback)? get_class($callback) : gettype($callback)
                        )
                    );
                }

                if (is_array($a) && is_array($b) && $this->isList($a) && $this->isList($b)) {
                    $result = $this->compareListsWithCallback($a, $b, $callback);
                } else {
                    $result = call_user_func($callback, $a, $b);
                }

                if (! is_bool($result)) {
                    throw new \RuntimeException(
                        sprintf(
                            'Provided callback of type %s does not return a boolean value!',
                            is_object($callback)? get_class($callback) : gettype($callback)
                        )
                    );
                }

                return $result;
            }

            if (! (($this->strict)? $a === $b : $a == $b) ) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param array $value
     * @return bool
     */
    protected function isList(array $value)
    {
        return (array_values($value) === $value);
    }

    /**
     * @param array $aList
     * @param array $bList
     * @param callable $callback
     *
     * @throws \InvalidArgumentException
     * @return bool
     */
    protected function compareListsWithCallback(array $aList, array $bList, $callback)
    {
        if (count($aList) != count($bList)) {
            return false;
        }

        foreach ($aList as $index => $value) {
            if (! call_user_func($callback, $value, $bList[$index])) {
                return false;
            }
        }

        return true;
    }
}


<?php

namespace Senhung\CLI;

use Senhung\CLI\Command;
use Senhung\CLI\CommandEntry;

/**
 * Class Help
 * @package Senhung\CLI
 */
class Help extends Command
{
    /** @var string $signature */
    protected $signature = 'help {:function-name}';
    /** @var string $description */
    protected $description = 'List all functions';

    /**
     * Help command handler
     *
     * @return void
     */
    public function handle(): void
    {
        /* Help Guide Header */
        $help = " -----------------------------------------------------------------\n";
        $help .= " | Command Line Interface\n";
        $help .= " | See more in https://github.com/senhungwong/command-line-interface\n";
        $help .= " -------------------------------------------------------------------\n";

        /* Get All Commands */
        $commands = CommandEntry::getCommands();

        /* See Specific Function's Description */
        if ($command = $this->getArgument('function-name')) {
            $command = new $commands[$command];
            $help .= " - " . $command->getCommand() . ": ";
            $help .= $command->getDescription() . "\n";
        }

        /* List All Commands */
        else {
            foreach ($commands as $command) {
                $command = new $command;
                $help .= " - ";
                $help .= $command->getCommand() . ": ";
                $help .= $command->getDescription() . "\n";
            }
        }

        echo $help;
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Container\Exception;

use Exception;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionParameter;

/**
 * Exception that is thrown when an argument to a method that the container
 * needs to invoke, cannot be resolved.
 */
class UnresolvableArgumentException extends ContainerException
{
	/**
	 * Create a new exception from some reflection objects.
	 *
	 * @param  ReflectionParameter             $param
	 * @param  ReflectionFunctionAbstract|null $func
	 * @param  Exception|null                  $previous
	 * @param  string|null                     $afterMessage
	 *
	 * @return static
	 */
	public static function fromReflectionParam(
		ReflectionParameter $param,
		ReflectionFunctionAbstract $func = null,
		Exception $previous = null,
		$afterMessage = null
	) {
		$message = static::makeMessage($param, $func);

		if ($previous) {
			$message .= ' - '.$previous->getMessage();
		}

		if ($afterMessage) {
			$message .= ' - '.$afterMessage;
		}

		return new static($message, 0, $previous);
	}

	protected static function makeMessage(ReflectionParameter $param, ReflectionFunctionAbstract $func = null)
	{
		$pos = $param->getPosition() + 1;

		$name = $param->getName();

		$func = static::getFunctionName($func ?: $param->getDeclaringFunction());

		return "Unresolvable argument: Argument #{$pos} (\${$name}) of {$func}";
	}

	protected static function getFunctionName(ReflectionFunctionAbstract $func)
	{
		if ($func->isClosure()) {
			return 'closure in '.static::getClosureLocation($func);
		}

		if ($func instanceof ReflectionMethod) {
			return $func->getDeclaringClass()->getName() . '::' . $func->getName();
		}

		return $func->getName().' in '.$func->getFileName();
	}

	protected static function getClosureLocation(ReflectionFunctionAbstract $func)
	{
		if ($class = $func->getClosureScopeClass()) {
			$location = $class->getName();
		} else {
			$location = $func->getFileName();
		}

		$startLine = $func->getStartLine();
		$endLine = $func->getEndLine();

		if ($startLine == $endLine) {
			$location .= " on line $startLine";
		} else {
			$location .= " on lines {$startLine}-{$endLine}";
		}

		return $location;
	}
}


<?php

namespace Cpwc\Lta\HttpClient\Listener;

use Cpwc\Lta\HttpClient\Message\ResponseMediator;
use Guzzle\Common\Event;
use Cpwc\Lta\Exception\ErrorException;
use Cpwc\Lta\Exception\RuntimeException;
use Cpwc\Lta\Exception\ValidationFailedException;

/**
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class ErrorListener
{
    /**
     * @var array
     */
    private $options;

    /**
     * @param array $options
     */
    public function __construct(array $options)
    {
        $this->options = $options;
    }

    /**
     * {@inheritDoc}
     */
    public function onRequestError(Event $event)
    {
        /** @var $request \Guzzle\Http\Message\Request */
        $request = $event['request'];
        $response = $request->getResponse();

        if ($response->isClientError() || $response->isServerError()) {
            $content = ResponseMediator::getContent($response);
            if (is_array($content) && isset($content['message'])) {
                if (400 == $response->getStatusCode()) {
                    throw new ErrorException($content['message'], 400);
                } elseif (422 == $response->getStatusCode() && isset($content['errors'])) {
                    $errors = array();
                    foreach ($content['errors'] as $error) {
                        switch ($error['code']) {
                            case 'missing':
                                $errors[] = sprintf('The %s %s does not exist, for resource "%s"', $error['field'],
                                    $error['value'], $error['resource']);
                                break;

                            case 'missing_field':
                                $errors[] = sprintf('Field "%s" is missing, for resource "%s"', $error['field'],
                                    $error['resource']);
                                break;

                            case 'invalid':
                                if (isset($error['message'])) {
                                    $errors[] = sprintf('Field "%s" is invalid, for resource "%s": "%s"',
                                        $error['field'], $error['resource'], $error['message']);
                                } else {
                                    $errors[] = sprintf('Field "%s" is invalid, for resource "%s"', $error['field'],
                                        $error['resource']);
                                }
                                break;

                            case 'already_exists':
                                $errors[] = sprintf('Field "%s" already exists, for resource "%s"', $error['field'],
                                    $error['resource']);
                                break;

                            default:
                                $errors[] = $error['message'];
                                break;

                        }
                    }

                    throw new ValidationFailedException('Validation Failed: ' . implode(', ', $errors), 422);
                }
            }

            throw new RuntimeException(isset($content['message']) ? $content['message'] : $content,
                $response->getStatusCode());
        };
    }
}


<?php
namespace app\manage\controller;

class Module extends Base
{

    /**
     * !CodeTemplates.overridecomment.nonjd!
     *
     * @see \app\common\controller\Root::fetch()
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        // 模板文件
        $template || $template = MODULE_VIEW_PATH . \think\Loader::parseName(_CONTROLLER_) . '/' . _ACTION_ . '.html';

        return parent::fetch($template, $vars, $replace, $config);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\PageCollection;

use RedKiteCms\Configuration\ConfigurationHandler;
use Symfony\Component\Finder\Finder;

/**
 * Class PagesCollectionParser is the object assigned to handle the website pages information.
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Page
 */
class PagesCollectionParser extends PageCollectionBase
{
    /**
     * @type array
     */
    private $pages = array();
    /**
     * @type array
     */
    private $sitemap = array();
    /**
     * @type null|string
     */
    private $currentLanguage = null;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        parent::__construct($configurationHandler);

        $this->currentLanguage = $this->configurationHandler->language() . '_' . $this->configurationHandler->country();
    }

    /**
     * Return the website pages definitions
     * @return array
     */
    public function pages()
    {
        return array_values($this->pages);
    }

    /**
     * Returns the definition for the requested page
     * @param string $pageName
     *
     * @return null|array
     */
    public function page($pageName)
    {
        if (!array_key_exists($pageName, $this->pages)) {
            return null;
        }

        return $this->pages[$pageName];
    }

    /**
     * Returns the website seo sitemap
     *
     * @return array
     */
    public function sitemap()
    {
        return $this->sitemap;
    }

    /**
     * Return the permalinks for the given language. By default this method returns the permalinks for the handled
     * language
     *
     * @param null|string $language
     *
     * @return array
     */
    public function permalinksByLanguage($language = null)
    {
        $result = array();

        if (null === $language) {
            $language = $this->currentLanguage;
        }

        foreach ($this->pages as $page) {
            foreach ($page["seo"] as $pageAttribute) {
                if ($pageAttribute["language"] != $language) {
                    continue;
                }

                $result[] = $pageAttribute["permalink"];
            }
        }

        return $result;
    }

    /**
     * Parses the page to retrieve their definitions
     *
     * @return $this
     */
    public function parse()
    {
        $finder = new Finder();
        $pages = $finder->directories()->depth(0)->sortByName()->in($this->pagesDir);
        $languages = $this->configurationHandler->languages();
        $homepage = $this->configurationHandler->homepage();
        foreach ($pages as $page) {
            $pageDir = (string)$page;
            $pageName = basename($pageDir);
            $pageDefinitionFile = $pageDir . '/' . $this->pageFile;
            if (!file_exists($pageDefinitionFile)) {
                continue;
            }

            $seoDefinition = $this->fetchSeoDefinition($this->pagesDir . '/' . $pageName, $this->seoFile, $languages);
            $pageDefinition = json_decode(file_get_contents($pageDefinitionFile), true);
            $pageDefinition["seo"] = $seoDefinition;
            $pageDefinition["isHome"] = $homepage == $pageName;

            $this->pages[$pageName] = $pageDefinition;
        }

        return $this;
    }

    private function fetchSeoDefinition($dir, $seoFile, $languages)
    {
        $seo = array();
        foreach ($languages as $language) {
            $languageDir = $dir . '/' . $language;
            $languageName = basename($languageDir);
            $seoDefinitionFile = $languageDir . '/' . $seoFile;

            $value = json_decode(file_get_contents($seoDefinitionFile), true);
            $value["language"] = $languageName;
            $seo[] = $value;

            $this->sitemap[$value["permalink"]] = array(
                "sitemap_frequency" => $value["sitemap_frequency"],
                "sitemap_priority" => $value["sitemap_priority"],
            );
        }

        return $seo;
    }
}


<?php namespace ForeverPHP\Core;

use ForeverPHP\Core\Facades\Context;
use ForeverPHP\Core\Facades\Redirect;
use ForeverPHP\Http\Response;

/**
 * Controla todos los errores producidos, en modo Debug lanza mensajes
 * comprensibles para el desarrollador y en producción un error 500.
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 0.2.0
 */
class ExceptionManager {
    /**
     * Almacena la pila de errores.
     *
     * @var string
     */
    private static $errors = array();

    /**
     * Permite mostrar un excepción propia.
     *
     * @param  string $type
     * @param  string $message
     * @return void
     */
    private static function viewException($type, $message) {
        $template = 'exception';
        $title = 'Excepción';

        // 1 es Error
        if ($type === 1) {
            $title = 'Error';
        }

        if (Settings::getInstance()->inDebug()) {
            $contentBuffer = json_decode(ob_get_contents());

            // Limpio el buffer de salida previo
            if (ob_get_length()) {
                ob_clean();
            }

            Context::useGlobal(false);
            Context::set('exception', $title);
            Context::set('details', $message);

            $response = new Response();

            if (is_array($contentBuffer)) {
                $contentBuffer['ForeverPHPException'] = Context::all();

                $response->json($contentBuffer)->make();
            } else {
                // Si hay buffer de salida previo cambio el template
                if (ob_get_length() != 0) {
                    $template = 'exception-block';
                }

                // Le indico a la vista que haga render usando los templates del framework
                Settings::getInstance()->set('ForeverPHPTemplate', true);

                $response->render($template)->make();
            }
        } else {
            // Termino el buffer de salida y lo limpio
            ob_end_clean();

            // Redirijo a un error 500
            return Redirect::error(500);
        }
    }

    /**
     * Manipulador de excepciones.
     *
     * @param  Exception $exception
     * @return void
     */
    public static function exceptionHandler($exception) {
        $message = 'Tipo de excepción no valida.';

        /*
         * Primero se valida si viene el parametro $exception y que sea
         * de tipo Exception o herede de este.
         */
        if ($exception != null) {
            if ($exception instanceof \Exception) {
                // Crear un mensaje mas detallado
                $message = 'Message: ' . $exception->getMessage() . '
';
                $message .= 'Previus: ' . $exception->getPrevious() . '
';
                $message .= 'Code: ' . $exception->getCode() . '
';
                $message .= 'File: ' . $exception->getFile() . '
';
                $message .= 'Line: ' . $exception->getLine() . '
';
                $message .= 'Trace: ' . $exception->getTraceAsString() . '
';
            }
        }

        static::viewException(0, $message);
    }

    /**
     * Manipulador de errores, por ejemplo para controlar
     * errores fatales (E_ERROR).
     *
     * @param  int    $errno
     * @param  string $errstr
     * @param  string $errfile
     * @param  int    $errline
     * @return void
     */
    public static function errorHandler($errno, $errstr, $errfile, $errline) {
        /*
         * Si la configuración "debugHideNotices" existe, indica si se
         * muestran o no los errores de tipo E_NOTICE.
         */
        if (Settings::getInstance()->exists('debugHideNotices')) {
            if ($errno == E_NOTICE && Settings::getInstance()->get('debugHideNotices')) {
                return;
            }
        }

        switch ($errno){
            case E_ERROR: // 1
                $type = 'E_ERROR'; break;
            case E_WARNING: // 2
                $type = 'E_WARNING'; break;
            case E_PARSE: // 4
                $type = 'E_PARSE'; break;
            case E_NOTICE: // 8
                $type = 'E_NOTICE'; break;
            case E_CORE_ERROR: // 16
                $type = 'E_CORE_ERROR'; break;
            case E_CORE_WARNING: // 32
                $type = 'E_CORE_WARNING'; break;
            case E_COMPILE_ERROR: // 64
                $type = 'E_COMPILE_ERROR'; break;
            case E_CORE_WARNING: // 128
                $type = 'E_COMPILE_WARNING'; break;
            case E_USER_ERROR: // 256
                $type = 'E_USER_ERROR'; break;
            case E_USER_WARNING: // 512
                $type = 'E_USER_WARNING'; break;
            case E_USER_NOTICE: // 1024
                $type = 'E_USER_NOTICE'; break;
            case E_STRICT: // 2048
                $type = 'E_STRICT'; break;
            case E_RECOVERABLE_ERROR: // 4096
                $type = 'E_RECOVERABLE_ERROR'; break;
            case E_DEPRECATED: // 8192
                $type = 'E_DEPRECATED'; break;
            case E_USER_DEPRECATED: // 16384
                $type = 'E_USER_DEPRECATED'; break;
        }

        array_push(static::$errors, array(
            'type' => $type,
            'message' => $errstr,
            'file' => $errfile,
            'line' => $errline
        ));
    }

    /**
     * Muestra los errores.
     *
     * @return void
     */
    private static function showErrors() {
        if (count(static::$errors) > 0) {
            $errorsList = '';

            foreach (static::$errors as $error) {
                $errorsList .= 'Tipo: ' . $error['type'] . '
';
                $errorsList .= 'Mensaje: ' . $error['message'] . '
';
                $errorsList .= 'Archivo: ' . $error['file'] . '
';
                $errorsList .= 'Line: ' . $error['line'] . '

';
            }

            static::viewException(1, $errorsList);
        }
    }

    /**
     * Ultima función en ejecutarse, una vez terminada la ejecución del script.
     *
     * @return void
     */
    public static function shutdown() {
        if (count(static::$errors) == 0) {
            $error = error_get_last();

            if ($error != null) {
                ob_start();

                static::errorHandler($error['type'], $error['message'], $error['file'], $error['line']);
            }
        }

        // Muestra los errores
        static::showErrors();

        /*
         * Como ultima funcion en ejecutarse, es aca donde se termina el flujo
         * del buffer de salida y lo muestra.
         */
        ob_end_flush();
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelInterface\Model\BlockInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;

/**
 * Class AbstractDataGenerator
 */
abstract class AbstractDataGenerator
{
    protected $fixture;
    protected $container;
    protected $manager;
    protected $version;
    protected $status;

    /**
     * Constructor
     *
     * @param AbstractFixture    $fixture
     * @param ContainerInterface $container
     * @param ObjectManager      $manager
     * @param int                $version
     * @param string             $status
     */
    public function __construct(AbstractFixture $fixture, ContainerInterface $container, ObjectManager $manager, $version = '1', $status = 'status-published')
    {
        $this->fixture = $fixture;
        $this->container = $container;
        $this->manager = $manager;
        $this->version = $version;
        $this->status = $status;
    }

    /**
     * @param string $language
     *
     * @return Node
     */
    public function generateNode($language)
    {
        if ($language == "fr") {
            return $this->generateNodeFr();
        } else if ($language == "en") {
            return $this->generateNodeEn();
        } else {
            return $this->generateNodeDe();
        }
    }

    /**
     * @param BlockInterface $block
     *
     * @return BlockInterface
     */
    protected function generateBlock(BlockInterface $block)
    {
        $block->setSiteId('2');

        $this->manager->persist($block);
        $this->manager->flush();

        return $block;
    }

    /**
     * @return Node
     */
    abstract protected function generateNodeFr();

    /**
     * @return Node
     */
    abstract protected function generateNodeEn();

    /**
     * @return Node
     */
    abstract protected function generateNodeDe();

    /**
     * @return Node
     */
    protected function createBaseNode()
    {
        $node = new Node();
        $node->setMaxAge(1000);
        $node->setNodeType(NodeInterface::TYPE_DEFAULT);
        $node->setSiteId('2');
        $node->setPath('-');
        $node->setVersion($this->version);
        $node->setStatus($this->fixture->getReference($this->status));
        $node->setDeleted(false);
        $node->setTemplate('home');

        return $node;
    }

    /**
     * @param NodeInterface $node
     *
     * @return string
     */
    protected function getVersionName(NodeInterface $node)
    {
        $date = new \DateTime("now");

        return $node->getName().'_'. $node->getVersion(). '_'. $date->format("Y-m-d_H:i:s");
    }
}


<?php

declare(strict_types=1);

namespace Chubbyphp\Translation;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

final class Translator implements TranslatorInterface
{
    /**
     * @var LocaleTranslationProviderInterface[]
     */
    private $localeTranslationProviders = [];

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Translator constructor.
     *
     * @param array $localeTranslationProviders
     */
    public function __construct(array $localeTranslationProviders, LoggerInterface $logger = null)
    {
        foreach ($localeTranslationProviders as $localeTranslationProvider) {
            $this->addLocaleTranslationProvider($localeTranslationProvider);
        }
        $this->logger = $logger ?? new NullLogger();
    }

    /**
     * @param LocaleTranslationProviderInterface $localeTranslationProvider
     */
    private function addLocaleTranslationProvider(LocaleTranslationProviderInterface $localeTranslationProvider)
    {
        $this->localeTranslationProviders[$localeTranslationProvider->getLocale()] = $localeTranslationProvider;
    }

    /**
     * @param string $locale
     * @param string $key
     * @param array  $args
     *
     * @return string
     */
    public function translate(string $locale, string $key, array $args = []): string
    {
        if (isset($this->localeTranslationProviders[$locale])) {
            if (null !== $translation = $this->localeTranslationProviders[$locale]->translate($key, $args)) {
                $this->logger->info('translation: translate {locale} {key}', ['locale' => $locale, 'key' => $key]);

                return $translation;
            }

            $this->logger->notice('translation: missing {locale} {key}', ['locale' => $locale, 'key' => $key]);

            return $key;
        }

        $this->logger->warning('translation: missing {locale}', ['locale' => $locale]);

        return $key;
    }
}