<?php
namespace Core\Toolbox\Strings;

/**
 * Normalize.php
 *
 * @author Michael "Tekkla" Zorn <tekkla@tekkla.de>
 * @copyright 2016
 * @license MIT
 */
class Normalize extends AbstractStrings
{

    /**
     * Normalizes a string
     *
     * @return string
     */
    function normalize(): string
    {
        $table = array(
            'Š' => 'S',
            'š' => 's',
            'Đ' => 'Dj',
            'đ' => 'dj',
            'Ž' => 'Z',
            'ž' => 'z',
            'Č' => 'C',
            'č' => 'c',
            'Ć' => 'C',
            'ć' => 'c',
            'À' => 'A',
            'Á' => 'A',
            'Â' => 'A',
            'Ã' => 'A',
            'Ä' => 'Ae',
            'Å' => 'A',
            'Æ' => 'A',
            'Ç' => 'C',
            'È' => 'E',
            'É' => 'E',
            'Ê' => 'E',
            'Ë' => 'E',
            'Ì' => 'I',
            'Í' => 'I',
            'Î' => 'I',
            'Ï' => 'I',
            'Ñ' => 'N',
            'Ò' => 'O',
            'Ó' => 'O',
            'Ô' => 'O',
            'Õ' => 'O',
            'Ö' => 'Oe',
            'Ø' => 'Oe',
            'Ù' => 'U',
            'Ú' => 'U',
            'Û' => 'U',
            'Ü' => 'Ue',
            'Ý' => 'Y',
            'Þ' => 'B',
            'ß' => 'Ss',
            'à' => 'a',
            'á' => 'a',
            'â' => 'a',
            'ã' => 'a',
            'ä' => 'ae',
            'å' => 'a',
            'æ' => 'a',
            'ç' => 'c',
            'è' => 'e',
            'é' => 'e',
            'ê' => 'e',
            'ë' => 'e',
            'ì' => 'i',
            'í' => 'i',
            'î' => 'i',
            'ï' => 'i',
            'ð' => 'o',
            'ñ' => 'n',
            'ò' => 'o',
            'ó' => 'o',
            'ô' => 'o',
            'õ' => 'o',
            'ö' => 'oe',
            'ø' => 'oe',
            'ù' => 'u',
            'ú' => 'u',
            'û' => 'u',
            'ü' => 'ue',
            'ý' => 'y',
            'ý' => 'y',
            'þ' => 'b',
            'ÿ' => 'y',
            'Ŕ' => 'R',
            'ŕ' => 'r'
        );

        $this->result = strtr($this->string, $table);

        return $this->result;
    }
}


<?php

/*
 * This file is part of the TecnoCreaciones package.
 *
 * (c) www.tecnocreaciones.com.ve
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tecnocreaciones\Vzla\GovernmentBundle\Menu\Template\Developer;

use Knp\Menu\ItemInterface;
use Symfony\Component\HttpFoundation\Request;
use Tecnocreaciones\Vzla\GovernmentBundle\Menu\MenuBuilder;

/**
 * Main menu builder.
 *
 * @author Anais Ortega <adcom23@tecnocreaciones.com.ve>
 */
class BackendMenuBuilder extends MenuBuilder
{
    protected $container;

    /**
     * Base de segundo nivel de sidebar
     * @var array
     */
    private $secondLevelOptions = array('childrenAttributes' => array('class' => 'big-menu'));

    const ROUTE_DEFAULT = '';

    /**
     * Builds backend sidebar menu.
     *
     * @param Request $request
     *
     * @return ItemInterface
     */
    public function createSidebarMenu(Request $request)
    {
        $menu = $this->factory->createItem('root', array(
            'childrenAttributes' => array(
                'class' => 'big-menu',
            )
        ));
        $section = 'sidebar';
        $menu->addChild('home',array(
            'route' => '',//Route
            'labelAttributes' => array('icon' => 'icon-home'),
        ))->setLabel($this->translate(sprintf('app.backend.menu.%s.home', $section)));

        $this->addExampleMenu($menu, $section);

        $menu->addChild('support', array(
            'route' => self::ROUTE_DEFAULT,
            'labelAttributes' => array('icon' => 'icon-info'),
        ))->setLabel($this->translate(sprintf('app.backend.menu.%s.support', 'sidebar')));
        return $menu;
    }

    /**
     * Construye el menu de ejemplo
     *
     * @param \Knp\Menu\ItemInterface $menu
     * @param type $section
     */
    function addExampleMenu(ItemInterface $menu, $section) {
        $child = $this->factory->createItem('example',
                    $this->getSubLevelOptions(array(
                    'uri' => null,
                    'labelAttributes' => array('icon' => 'icon-book',),
                    ))
                )
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.main', $section)));
        $child
                ->addChild('example.company', array(
                    'route' => '',
                    ))
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.company', $section)));
        $child
                ->addChild('example.technical_reports', array(
                    'route' => '',
                    ))
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.technical_reports', $section)));

            $subchild = $this->factory->createItem('subexample',
                        $this->getSubLevelOptions(array(
                        'uri' => null,
                        'labelAttributes' => array('icon' => 'icon-book',),
                        ))
                    )
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.main', $section)));
            $subchild
                    ->addChild('example.other.admin', array(
                        'route' => self::ROUTE_DEFAULT,
                        ))
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.admin', $section)));

            $subchild->addChild('example.other.groups', array(
                        'route' => self::ROUTE_DEFAULT,
                    ))
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.groups', $section)));

            $child->addChild($subchild);

        $menu->addChild($child);
    }

    protected function getSubLevelOptions(array $parameters = array()) {
        return array_merge($this->secondLevelOptions,$parameters);
    }

    protected function getSecondLevelOptions(array $parameters = array()) {
        return array_merge($this->secondLevelOptions,$parameters);
    }

    public function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null) {
        $this->container = $container;
    }
}


<?php

namespace Oxygen\Data\Migrations;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Tools\SchemaTool;
use Illuminate\Database\Migrations\MigrationRepositoryInterface;
use Mitch\LaravelDoctrine\Migrations\DoctrineMigrationRepository;
use Oxygen\Data\BaseServiceProvider;

class MigrationsServiceProvider extends BaseServiceProvider {

    /**
     * Indicates if loading of the provider is deferred.
     * @var bool
     */
    protected $defer = true;

    /**
     * Registers the migration repository.
     */
    public function register() {
        $this->loadEntitiesFrom(__DIR__);

        $this->app->singleton('migration.repository', function($app) {
            return new DoctrineMigrationRepository(
                function() use($app) {
                    return $app->make(EntityManagerInterface::class);
                },
                function() use($app) {
                    return $app->make(SchemaTool::class);
                },
                function() use($app) {
                    return $app->make(ClassMetadataFactory::class);
                }
            );
        });
        $this->app->bind(MigrationRepositoryInterface::class, 'migration.repository');
    }

    /**
     * Get the services provided by the provider.
     * @return array
     */
    public function provides() {
        return [
            EntityManagerInterface::class,
            EntityManager::class,
            MigrationRepositoryInterface::class,
            'migration.repository'
        ];
    }

}


<?php
/**
 * @author Serhii Nekhaienko <sergey.nekhaenko@gmail.com>
 * @license GPL
 * @copyright Serhii Nekhaienko &copy 2018
 * @version 4.0.2
 * @project endorphin-studio/browser-detector
 */

namespace EndorphinStudio\Detector\Detection;

use EndorphinStudio\Detector\Data\Model;

class ModelDetector extends AbstractDetection
{
    /**
     * @var string Key in config (os, device, etc.)
     */
    protected $configKey = 'model';

    /**
     * Setup result of object
     */
    protected function setupResultObject()
    {
        $name = $this->additionalInfo['name'];
        if (!\array_key_exists($name, $this->config)) {
            return;
        }
        $patternList = $this->config[$name];
        foreach ($patternList as $series => $data) {
            if(array_key_exists('pattern', $data)) {
                $this->detectModelByPattern($series,$data['pattern']);
            } elseif (array_key_exists('models', $data)) {
                $this->detectModelByModelList($series, $data['models']);
            }
        }
    }

    private function detectModelByPattern(string $series, string $pattern)
    {
        $pattern = sprintf('/%s/', $pattern);
        $result = \preg_match($pattern, $this->detector->getUserAgent(), $model);
        if ($result) {
            $model = count($model) > 1 ? sprintf('%s%s', $series, end($model)) : $series;
            $this->resultObject->setModel($model);
            $this->resultObject->setSeries($series);
            return $result;
        }
    }

    private function detectModelByModelList(string $series, array $data)
    {
        foreach ($data as $model => $pattern) {
            $pattern = sprintf('/%s/', $pattern);
            $result = \preg_match($pattern, $this->detector->getUserAgent());
            if ($result) {
                $model = sprintf('%s%s', $series, $model);
                $this->resultObject->setModel($model);
                $this->resultObject->setSeries($series);
                return $result;
            }
        }
    }

    /**
     * Detect method
     * @param array $additional Additional Info
     */
    public function detect(array $additional = [])
    {
        $this->additionalInfo = $additional;
        if ($this->configKey !== 'none') {
            $this->config = $this->detector->getPatternList($this->detector->getDataProvider()->getConfig(), $this->configKey);
            $this->resultObject = new Model();
        }
        $this->setupResultObject();
        if ($this->resultObject->getModel()) {
            $this->detector->getResultObject()->getDevice()->setModel($this->resultObject);
            $this->detector->getResultObject()->getDevice()->setHasModel(true);
        }
    }
}


<?php
/**
 * Same as FilesystemPublisher but allows use of LivePubHelper stuff.
 *
 * @author Mark Guinn
 * @date 04.23.2013
 * @package livepub
 */
class LiveFilesystemPublisher extends FilesystemPublisher
{
    /**
     * @var string - you can change this if for some reason you need to. probably wise not to include
     *               any characters that might get encoded in url or html contexts though
     *               NOTE: setting this to empty will disable CSRF token handling
     */
    private static $security_token_placeholder = 'LIVESECURITYTOKENGOESHERE';

    /**
     * Generate the templated content for a PHP script that can serve up the
     * given piece of content with the given age and expiry.
     *
     * @param string $content
     * @param string $age
     * @param string $lastModified
     * @param string $contentType
     *
     * @return string
     */
    protected function generatePHPCacheFile($content, $age, $lastModified, $contentType)
    {
        $template = file_get_contents(dirname(__FILE__) . '/CachedPHPPage.tmpl');

        $csrfPlaceholder = Config::inst()->get('LiveFilesystemPublisher', 'security_token_placeholder');
        if (empty($csrfPlaceholder)) {
            $csrfPlaceholder = $csrfCode = 'DONT DO ANYTHING';
        } else {
            $csrfCode = '<' . '?php echo $security_token; ?' . '>';
        }

        return str_replace(
            array('**MAX_AGE**', '**LAST_MODIFIED**', '**CONTENT**', '**CONTENT_TYPE**', $csrfPlaceholder),
            array((int)$age, $lastModified, LivePubHelper::get_init_code_and_clear() . $content, $contentType, $csrfCode),
            $template
        );
    }

    /**
     * Wrapper for parent funciton. Switches on and off livepub publishing.
     *
     * @param  array $urls Relative URLs
     * @return array Result, keyed by URL. Keys:
     *               - "statuscode": The HTTP status code
     *               - "redirect": A redirect location (if applicable)
     *               - "path": The filesystem path where the cache has been written
     */
    public function publishPages($urls)
    {
        LivePubHelper::init_pub();
        $r = $this->realPublishPages($urls);
        LivePubHelper::stop_pub();
        return $r;
    }

    /**
     * @return Session
     */
    public function getFreshSession()
    {
        // set up CSRF token stuff
        $placeholder = Config::inst()->get('LiveFilesystemPublisher', 'security_token_placeholder');
        if ($placeholder) {
            $sessionKey = SecurityToken::inst()->getName();

            // This duplicates the SessionToken functionality exactly
            // But only requires the one class from Silverstripe
            LivePubHelper::require_session();
            LivePubHelper::add_init_code('
				function new_security_token() {
					require_once("'.BASE_PATH.'/framework/security/RandomGenerator.php");
					$generator = new RandomGenerator();
					return $_SESSION["'.$sessionKey.'"] = $generator->randomToken("sha1");
				}
				$security_token = isset($_SESSION["'.$sessionKey.'"]) ? $_SESSION["'.$sessionKey.'"] : new_security_token();
			', 'LiveSecurityToken');

            return new Session(array(
                $sessionKey => $placeholder
            ));
        } else {
            return new Session(null);
        }
    }

    /**
     * Uses {@link Director::test()} to perform in-memory HTTP requests
     * on the passed-in URLs.
     *
     * I didn't want to duplicate all this code from FilesystemPublisher but
     * I need to be able to touch the session to swap out the security token
     * stuff.
     *
     * @param  array $urls Relative URLs
     * @return array Result, keyed by URL. Keys:
     *               - "statuscode": The HTTP status code
     *               - "redirect": A redirect location (if applicable)
     *               - "path": The filesystem path where the cache has been written
     */
    public function realPublishPages($urls)
    {
        $result = array();

        // Do we need to map these?
        // Detect a numerically indexed arrays
        if (is_numeric(join('', array_keys($urls)))) {
            $urls = $this->urlsToPaths($urls);
        }

        // This can be quite memory hungry and time-consuming
        // @todo - Make a more memory efficient publisher
        increase_time_limit_to();
        increase_memory_limit_to();

        Config::inst()->nest();

        // Set the appropriate theme for this publication batch.
        // This may have been set explicitly via StaticPublisher::static_publisher_theme,
        // or we can use the last non-null theme.
        $customTheme = Config::inst()->get('FilesystemPublisher', 'static_publisher_theme');
        if ($customTheme) {
            Config::inst()->update('SSViewer', 'theme', $customTheme);
        }

        // Ensure that the theme that is set gets used.
        Config::inst()->update('SSViewer', 'theme_enabled', true);

        $currentBaseURL = Director::baseURL();
        $staticBaseUrl = Config::inst()->get('FilesystemPublisher', 'static_base_url');

        if ($staticBaseUrl) {
            Config::inst()->update('Director', 'alternate_base_url', $staticBaseUrl);
        }

        if ($this->fileExtension == 'php') {
            Config::inst()->update('SSViewer', 'rewrite_hash_links', 'php');
        }

        if (Config::inst()->get('FilesystemPublisher', 'echo_progress')) {
            echo $this->class.": Publishing to " . $staticBaseUrl . "\n";
        }

        $files = array();
        $i = 0;
        $totalURLs = sizeof($urls);

        foreach ($urls as $url => $path) {
            $origUrl = $url;
            $result[$origUrl] = array(
                'statuscode' => null,
                'redirect' => null,
                'path' => null
            );

            if ($staticBaseUrl) {
                Config::inst()->update('Director', 'alternate_base_url', $staticBaseUrl);
            }

            $i++;

            if ($url && !is_string($url)) {
                user_error("Bad url:" . var_export($url, true), E_USER_WARNING);
                continue;
            }

            if (Config::inst()->get('FilesystemPublisher', 'echo_progress')) {
                echo " * Publishing page $i/$totalURLs: $url\n";
                flush();
            }

            Requirements::clear();

            if ($url == "") {
                $url = "/";
            }
            if (Director::is_relative_url($url)) {
                $url = Director::absoluteURL($url);
            }
            $response = Director::test(str_replace('+', ' ', $url), null, $this->getFreshSession());

            if (!$response) {
                continue;
            }

            if ($response) {
                $result[$origUrl]['statuscode'] = $response->getStatusCode();
            }
            Requirements::clear();

            singleton('DataObject')->flushCache();

            // Check for ErrorPages generating output - we want to handle this in a special way below.
            $isErrorPage = false;
            $pageObject = null;
            if ($response && is_object($response) && ((int)$response->getStatusCode())>=400) {
                $obj = $this->owner->getUrlArrayObject()->getObject($url);
                if ($obj && $obj instanceof ErrorPage) {
                    $isErrorPage = true;
                }
            }

            // Skip any responses with a 404 status code unless it's the ErrorPage itself.
            if (!$isErrorPage && is_object($response) && $response->getStatusCode()=='404') {
                continue;
            }

            // Generate file content.
            // PHP file caching will generate a simple script from a template
            if ($this->fileExtension == 'php') {
                if (is_object($response)) {
                    if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
                        $content = $this->generatePHPCacheRedirection($response->getHeader('Location'));
                    } else {
                        $content = $this->generatePHPCacheFile($response->getBody(), HTTP::get_cache_age(), date('Y-m-d H:i:s'), $response->getHeader('Content-Type'));
                    }
                } else {
                    $content = $this->generatePHPCacheFile($response . '', HTTP::get_cache_age(), date('Y-m-d H:i:s'), $response->getHeader('Content-Type'));
                }

                // HTML file caching generally just creates a simple file
            } else {
                if (is_object($response)) {
                    if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
                        $absoluteURL = Director::absoluteURL($response->getHeader('Location'));
                        $result[$origUrl]['redirect'] = $response->getHeader('Location');
                        $content = "<meta http-equiv=\"refresh\" content=\"2; URL=$absoluteURL\">";
                    } else {
                        $content = $response->getBody();
                    }
                } else {
                    $content = $response . '';
                }
            }

            if (Config::inst()->get('FilesystemPublisher', 'include_caching_metadata')) {
                $content = str_replace(
                    '',
                    sprintf("\n\n", implode(" ", $this->getMetadata($url))),
                    $content
                );
            }

            if (!$isErrorPage) {
                $files[$origUrl] = array(
                    'Content' => $content,
                    'Folder' => dirname($path).'/',
                    'Filename' => basename($path),
                );
            } else {

                // Generate a static version of the error page with a standardised name, so they can be plugged
                // into catch-all webserver statements such as Apache's ErrorDocument.
                $code = (int)$response->getStatusCode();
                $files[$origUrl] = array(
                    'Content' => $content,
                    'Folder' => dirname($path).'/',
                    'Filename' => "error-$code.html",
                );
            }

            // Add externals
            /*
            $externals = $this->externalReferencesFor($content);
            if($externals) foreach($externals as $external) {
                // Skip absolute URLs
                if(preg_match('/^[a-zA-Z]+:\/\//', $external)) continue;
                // Drop querystring parameters
                $external = strtok($external, '?');

                if(file_exists("../" . $external)) {
                    // Break into folder and filename
                    if(preg_match('/^(.*\/)([^\/]+)$/', $external, $matches)) {
                        $files[$external] = array(
                            "Copy" => "../$external",
                            "Folder" => $matches[1],
                            "Filename" => $matches[2],
                        );

                    } else {
                        user_error("Can't parse external: $external", E_USER_WARNING);
                    }
                } else {
                    $missingFiles[$external] = true;
                }
            }*/
        }

        if (Config::inst()->get('FilesystemPublisher', 'static_base_url')) {
            Config::inst()->update('Director', 'alternate_base_url', $currentBaseURL);
        }

        if ($this->fileExtension == 'php') {
            Config::inst()->update('SSViewer', 'rewrite_hash_links', true);
        }

        $base = BASE_PATH . "/$this->destFolder";

        foreach ($files as $origUrl => $file) {
            Filesystem::makeFolder("$base/$file[Folder]");

            $path = "$base/$file[Folder]$file[Filename]";
            $result[$origUrl]['path'] = $path;

            if (isset($file['Content'])) {
                $fh = fopen($path, "w");
                fwrite($fh, $file['Content']);
                fclose($fh);
            } elseif (isset($file['Copy'])) {
                copy($file['Copy'], $path);
            }
        }

        Config::inst()->unnest();

        return $result;
    }
}


<?php

declare(strict_types=1);

namespace Psi\Bridge\ObjectAgent\Doctrine\PhpcrOdm;

use Doctrine\Common\Persistence\Mapping\MappingException;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ODM\PHPCR\DocumentManagerInterface;
use Psi\Component\ObjectAgent\AgentInterface;
use Psi\Component\ObjectAgent\Capabilities;
use Psi\Component\ObjectAgent\Exception\BadMethodCallException;
use Psi\Component\ObjectAgent\Exception\ObjectNotFoundException;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Query;

class PhpcrOdmAgent implements AgentInterface
{
    private $documentManager;

    public function __construct(
        DocumentManagerInterface $documentManager
    ) {
        $this->documentManager = $documentManager;
    }

    /**
     * {@inheritdoc}
     */
    public function find($identifier, string $class = null)
    {
        $object = $this->documentManager->find($class, $identifier);

        if (null === $object) {
            throw ObjectNotFoundException::forClassAndIdentifier($class, $identifier);
        }

        return $object;
    }

    /**
     * {@inheritdoc}
     */
    public function findMany(array $identifiers, string $class = null)
    {
        return $this->documentManager->findMany($class, $identifiers);
    }

    /**
     * {@inheritdoc}
     */
    public function getCapabilities(): Capabilities
    {
        return Capabilities::create([
            'can_set_parent' => true,
            'supported_comparators' => [
                Comparison::EQUALS,
                Comparison::NOT_EQUALS,
                Comparison::LESS_THAN,
                Comparison::LESS_THAN_EQUAL,
                Comparison::GREATER_THAN,
                Comparison::GREATER_THAN_EQUAL,
                Comparison::IN,
                Comparison::NOT_IN,
                Comparison::CONTAINS,
                Comparison::NOT_CONTAINS,
                Comparison::NULL,
                Comparison::NOT_NULL,
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function persist($object)
    {
        $this->documentManager->persist($object);
    }

    /**
     * {@inheritdoc}
     */
    public function remove($object)
    {
        $this->documentManager->remove($object);
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        $this->documentManager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getCanonicalClassFqn(string $classFqn): string
    {
        return ClassUtils::getRealClass($classFqn);
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifier($object)
    {
        $objectFqn = ClassUtils::getRealClass(get_class($object));
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
        $uuidFieldName = $metadata->getUuidFieldName();

        if (!$uuidFieldName) {
            throw new \RuntimeException(sprintf(
                'Document "%s" does not have a UUID-mapped property. All '.
                'PHPCR-ODM documents must have a mapped UUID proprety.',
                $objectFqn
            ));
        }

        $node = $this->documentManager->getNodeForDocument($object);

        return $node->getIdentifier();
    }

    /**
     * {@inheritdoc}
     */
    public function setParent($object, $parent)
    {
        $objectFqn = ClassUtils::getRealClass(get_class($object));
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
        $parentField = $metadata->parentMapping;

        if (!$parentField) {
            throw new \RuntimeException(sprintf(
                'Document "%s" does not have a ParentDocument mapping All '.
                'PHPCR-ODM documents must have a mapped parent proprety.',
                $objectFqn
            ));
        }

        $metadata->setFieldValue($object, $parentField, $parent);
    }

    /**
     * {@inheritdoc}
     */
    public function supports(string $class): bool
    {
        $metadataFactory = $this->documentManager->getMetadataFactory();

        $supports = false;
        try {
            $metadataFactory->getMetadataFor(ClassUtils::getRealClass($class));
            $supports = true;
        } catch (MappingException $exception) {
            // no metadata - class is not known to phpcr-odm
        }

        return $supports;
    }

    /**
     * {@inheritdoc}
     */
    public function query(Query $query): \Traversable
    {
        $sourceAlias = 'a';
        $queryBuilder = $this->documentManager->getRepository($query->getClassFqn())->createQueryBuilder($sourceAlias);

        if ($query->hasExpression()) {
            $visitor = new ExpressionVisitor(
                $queryBuilder,
                $sourceAlias
            );

            $visitor->dispatch($query->getExpression());
        }

        $orderBy = $queryBuilder->orderBy();
        foreach ($query->getOrderings() as $field => $order) {
            $order = strtolower($order);
            $orderBy->{$order}()->field($sourceAlias . '.' .  $field);
        }

        if (null !== $query->getFirstResult()) {
            $queryBuilder->setFirstResult($query->getFirstResult());
        }

        if (null !== $query->getMaxResults()) {
            $queryBuilder->setMaxResults($query->getMaxResults());
        }

        return $queryBuilder->getQuery()->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function queryCount(Query $query): int
    {
        throw BadMethodCallException::queryCountNotSupported(__CLASS__);
    }

    /**
     * Return the document mangaer instance (for use in events).
     */
    public function getDocumentManager(): DocumentManagerInterface
    {
        return $this->documentManager;
    }
}


<?php

namespace Reaction\I18n;

use Reaction;
use Reaction\Exceptions\InvalidConfigException;

/**
 * GettextPoFile represents a PO Gettext message file.
 */
class GettextPoFile extends GettextFile
{
    /**
     * Loads messages from a PO file.
     * @param string      $context message context
     * @param string|null $filePath file path
     * @return array message translations. Array keys are source messages and array values are translated messages:
     * source message => translated message.
     * @throws InvalidConfigException
     */
    public function load($context, $filePath = null)
    {
        if (isset($filePath)) {
            $this->filePath = $filePath;
        }
        if (!isset($this->_messages)) {
            $this->loadAll();
        }
        return isset($this->_messages[$context]) ? $this->_messages[$context] : [];
    }

    /**
     * Saves messages to a PO file.
     * @param array       $messages message translations. Array keys are source messages and array values are
     * translated messages: source message => translated message. Note if the message has a context,
     * the message ID must be prefixed with the context with chr(4) as the separator.
     * @param string|null $filePath file path
     * @throws InvalidConfigException
     */
    public function save($messages, $filePath = null)
    {
        if (!isset($filePath)) {
            $filePath = $this->filePath;
        }
        if (!isset($filePath)) {
            throw new InvalidConfigException("Not specified '\$filePath' parameter");
        }
        $language = str_replace('-', '_', basename(dirname($filePath)));
        $headers = [
            'msgid ""',
            'msgstr ""',
            '"Project-Id-Version: \n"',
            '"POT-Creation-Date: \n"',
            '"PO-Revision-Date: \n"',
            '"Last-Translator: \n"',
            '"Language-Team: \n"',
            '"Language: ' . $language . '\n"',
            '"MIME-Version: 1.0\n"',
            '"Content-Type: text/plain; charset=' . Reaction::$app->charset . '\n"',
            '"Content-Transfer-Encoding: 8bit\n"',
        ];
        $content = implode("\n", $headers) . "\n\n";
        foreach ($messages as $id => $message) {
            $separatorPosition = strpos($id, chr(4));
            if ($separatorPosition !== false) {
                $content .= 'msgctxt "' . substr($id, 0, $separatorPosition) . "\"\n";
                $id = substr($id, $separatorPosition + 1);
            }
            $content .= 'msgid "' . $this->encode($id) . "\"\n";
            $content .= 'msgstr "' . $this->encode($message) . "\"\n\n";
        }
        file_put_contents($filePath, $content);
    }

    /**
     * Get all categories list
     * @return string[]
     */
    public function getCategories()
    {
        if (!isset($this->_messages)) {
            $this->loadAll();
        }
        $categories = array_keys($this->_messages);
        sort($categories);
        return $categories;
    }

    /**
     * Get all messages from file
     * @return array
     * @throws InvalidConfigException
     */
    protected function loadAll()
    {
        if (!isset($this->filePath)) {
            throw new InvalidConfigException("Not specified '\$filePath' parameter");
        }
        $pattern = '/(msgctxt\s+"(.*?(?<!\\\\))")?\s+' // context
            . 'msgid\s+((?:".*(?<!\\\\)"\s*)+)\s+' // message ID, i.e. original string
            . 'msgstr\s+((?:".*(?<!\\\\)"\s*)+)/'; // translated string
        $content = file_get_contents($this->filePath);
        $matches = [];
        $matchCount = preg_match_all($pattern, $content, $matches);

        $this->_messages = [];

        for ($i = 0; $i < $matchCount; ++$i) {
            $id = $this->decode($matches[3][$i]);
            $message = $this->decode($matches[4][$i]);
            $context = $matches[2][$i];
            if (!isset($this->_messages[$context])) {
                $this->_messages[$context] = [];
            }
            $this->_messages[$context][$id] = $message;
        }

        return $this->_messages;
    }

    /**
     * Encodes special characters in a message.
     * @param string $string message to be encoded
     * @return string the encoded message
     */
    protected function encode($string)
    {
        return str_replace(
            ['"', "\n", "\t", "\r"],
            ['\\"', '\\n', '\\t', '\\r'],
            $string
        );
    }

    /**
     * Decodes special characters in a message.
     * @param string $string message to be decoded
     * @return string the decoded message
     */
    protected function decode($string)
    {
        $string = preg_replace(
            ['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'],
            ['', "\n", "\r", "\t", '"'],
            $string
        );

        return substr(rtrim($string), 1, -1);
    }
}


<?php namespace Ordercloud\Requests\Orders\Handlers;

use Ordercloud\Entities\Orders\OrderInvoice;
use Ordercloud\Requests\Handlers\AbstractGetRequestHandler;
use Ordercloud\Requests\Orders\GetOrderInvoiceRequest;
use Ordercloud\Support\Http\Response;

class GetOrderInvoiceRequestHandler extends AbstractGetRequestHandler
{
    /**
     * @param GetOrderInvoiceRequest $request
     */
    protected function configure($request)
    {
        $this->setUrl('/resource/orders/%d/invoice', $request->getOrderId());
    }

    /**
     * @param Response $response
     *
     * @return mixed
     */
    protected function transformResponse($response)
    {
        $filename = $this->getFileName($response);

        return new OrderInvoice($filename, $response->getRawResult());
    }

    /**
     * Retrieve the filename from headers.
     *
     * @param Response $response
     *
     * @return string
     */
    protected function getFileName(Response $response)
    {
        $headers = $response->getHeaders();
        $contentDisposition = isset($headers['Content-Disposition'][0]) ? $headers['Content-Disposition'][0] : null;

        if ($contentDisposition && preg_match('/filename="(.+)"/', $contentDisposition, $filename)) {
            return $filename[1];
        }

        return null;
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\HttpMessage;

use Valkyrja\HttpMessage\Exceptions\InvalidUploadedFile;

/**
 * Representation of an incoming, server-side HTTP request.
 *
 * Per the HTTP specification, this interface includes properties for
 * each of the following:
 *
 * - Protocol version
 * - HTTP method
 * - URI
 * - Headers
 * - Message body
 *
 * Additionally, it encapsulates all data as it has arrived to the
 * application from the CGI and/or PHP environment, including:
 *
 * - The values represented in $_SERVER.
 * - Any cookies provided (generally via $_COOKIE)
 * - Query string arguments (generally via $_GET, or as parsed via parse_str())
 * - Upload files, if any (as represented by $_FILES)
 * - Deserialized body parameters (generally from $_POST)
 *
 * $_SERVER values MUST be treated as immutable, as they represent application
 * state at the time of request; as such, no methods are provided to allow
 * modification of those values. The other values provide such methods, as they
 * can be restored from $_SERVER or the request body, and may need treatment
 * during the application (e.g., body parameters may be deserialized based on
 * content type).
 *
 * Additionally, this interface recognizes the utility of introspecting a
 * request to derive and match additional parameters (e.g., via URI path
 * matching, decrypting cookie values, deserializing non-form-encoded body
 * content, matching authorization headers to users, etc). These parameters
 * are stored in an "attributes" property.
 *
 * Requests are considered immutable; all methods that might change state MUST
 * be implemented such that they retain the internal state of the current
 * message and return an instance that contains the changed state.
 *
 * @author Melech Mizrachi
 */
class NativeServerRequest implements ServerRequest
{
    use RequestTrait;

    /**
     * The server params.
     *
     * @var array
     */
    protected $server = [];

    /**
     * The attributes.
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * The query params.
     *
     * @var array
     */
    protected $query = [];

    /**
     * The cookies.
     *
     * @var array
     */
    protected $cookies = [];

    /**
     * The parsed body.
     *
     * @var array[]
     */
    protected $parsedBody = [];

    /**
     * The files.
     *
     * @var array
     */
    protected $files = [];

    /**
     * NativeServerRequest constructor.
     *
     * @param Uri    $uri        [optional] The uri
     * @param string $method     [optional] The method
     * @param Stream $body       [optional] The body stream
     * @param array  $headers    [optional] The headers
     * @param array  $server     [optional] The server
     * @param array  $cookies    [optional] The cookies
     * @param array  $query      [optional] The query string
     * @param array  $parsedBody [optional] The parsed body
     * @param array  $files      [optional] The files
     * @param string $protocol   [optional] The protocol version
     *
     * @throws \InvalidArgumentException
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidMethod
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPath
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidPort
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidProtocolVersion
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidQuery
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidScheme
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidStream
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidUploadedFile
     */
    public function __construct(
        Uri $uri = null,
        string $method = null,
        Stream $body = null,
        array $headers = null,
        array $server = null,
        array $cookies = null,
        array $query = null,
        array $parsedBody = null,
        array $files = null,
        string $protocol = null
    ) {
        $this->initialize($uri, $method, $body, $headers);

        $this->headers    = $headers ?? [];
        $this->cookies    = $cookies ?? [];
        $this->query      = $query ?? [];
        $this->parsedBody = $parsedBody ?? [];
        $this->files      = $files ?? [];
        $this->protocol   = $protocol ?? '1.1';

        $this->validateUploadedFiles($this->files);
    }

    /**
     * Retrieve server parameters.
     *
     * Retrieves data related to the incoming request environment,
     * typically derived from PHP's $_SERVER superglobal. The data IS NOT
     * REQUIRED to originate from $_SERVER.
     *
     * @return array
     */
    public function getServerParams(): array
    {
        return $this->server;
    }

    /**
     * Retrieve cookies.
     *
     * Retrieves cookies sent by the client to the server.
     *
     * The data MUST be compatible with the structure of the $_COOKIE
     * superglobal.
     *
     * @return array
     */
    public function getCookieParams(): array
    {
        return $this->cookies;
    }

    /**
     * Return an instance with the specified cookies.
     *
     * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
     * be compatible with the structure of $_COOKIE. Typically, this data will
     * be injected at instantiation.
     *
     * This method MUST NOT update the related Cookie header of the request
     * instance, nor related values in the server params.
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * updated cookie values.
     *
     * @param array $cookies Array of key/value pairs representing cookies.
     *
     * @return static
     */
    public function withCookieParams(array $cookies)
    {
        $new = clone $this;

        $new->cookies = $cookies;

        return $new;
    }

    /**
     * Retrieve a specific cookie value.
     *
     * Retrieves a cookie value sent by the client to the server.
     *
     * @param string $name The cookie name to retrieve
     *
     * @return string|null
     */
    public function getCookieParam(string $name): ? string
    {
        return $this->cookies[$name] ?? null;
    }

    /**
     * Determine if a specific cookie exists.
     *
     * @param string $name The cookie name to check for
     *
     * @return bool
     */
    public function hasCookieParam(string $name): bool
    {
        return isset($this->cookies[$name]);
    }

    /**
     * Retrieve query string arguments.
     *
     * Retrieves the deserialized query string arguments, if any.
     *
     * Note: the query params might not be in sync with the URI or server
     * params. If you need to ensure you are only getting the original
     * values, you may need to parse the query string from
     * `getUri()->getQuery()` or from the `QUERY_STRING` server param.
     *
     * @return array
     */
    public function getQueryParams(): array
    {
        return $this->query;
    }

    /**
     * Return an instance with the specified query string arguments.
     *
     * These values SHOULD remain immutable over the course of the incoming
     * request. They MAY be injected during instantiation, such as from PHP's
     * $_GET superglobal, or MAY be derived from some other value such as the
     * URI. In cases where the arguments are parsed from the URI, the data
     * MUST be compatible with what PHP's parse_str() would return for
     * purposes of how duplicate query parameters are handled, and how nested
     * sets are handled.
     *
     * Setting query string arguments MUST NOT change the URI stored by the
     * request, nor the values in the server params.
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * updated query string arguments.
     *
     * @param array $query Array of query string arguments, typically from
     *                     $_GET.
     *
     * @return static
     */
    public function withQueryParams(array $query)
    {
        $new = clone $this;

        $new->query = $query;

        return $new;
    }

    /**
     * Retrieve normalized file upload data.
     *
     * This method returns upload metadata in a normalized tree, with each leaf
     * an instance of Psr\Http\Message\UploadedFileInterface.
     *
     * These values MAY be prepared from $_FILES or the message body during
     * instantiation, or MAY be injected via withUploadedFiles().
     *
     * @return array An array tree of UploadedFileInterface instances; an empty
     *               array MUST be returned if no data is present.
     */
    public function getUploadedFiles(): array
    {
        return $this->files;
    }

    /**
     * Create a new instance with the specified uploaded files.
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * updated body parameters.
     *
     * @param array $uploadedFiles An array tree of UploadedFileInterface
     *                             instances.
     *
     * @throws \InvalidArgumentException if an invalid structure is provided.
     *
     * @return static
     */
    public function withUploadedFiles(array $uploadedFiles)
    {
        $this->validateUploadedFiles($uploadedFiles);

        $new = clone $this;

        $new->files = $uploadedFiles;

        return $new;
    }

    /**
     * Retrieve any parameters provided in the request body.
     *
     * If the request Content-Type is either application/x-www-form-urlencoded
     * or multipart/form-data, and the request method is POST, this method MUST
     * return the contents of $_POST.
     *
     * Otherwise, this method may return any results of deserializing
     * the request body content; as parsing returns structured content, the
     * potential types MUST be arrays or objects only. A null value indicates
     * the absence of body content.
     *
     * @return array The deserialized body parameters, if any.
     *               These will typically be an array or object.
     */
    public function getParsedBody(): array
    {
        return $this->parsedBody;
    }

    /**
     * Return an instance with the specified body parameters.
     *
     * These MAY be injected during instantiation.
     *
     * If the request Content-Type is either application/x-www-form-urlencoded
     * or multipart/form-data, and the request method is POST, use this method
     * ONLY to inject the contents of $_POST.
     *
     * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
     * deserializing the request body content. Deserialization/parsing returns
     * structured data, and, as such, this method ONLY accepts arrays or
     * objects, or a null value if nothing was available to parse.
     *
     * As an example, if content negotiation determines that the request data
     * is a JSON payload, this method could be used to create a request
     * instance with the deserialized parameters.
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * updated body parameters.
     *
     * @param array $data The deserialized body data. This will
     *                    typically be in an array or object.
     *
     * @throws \InvalidArgumentException
     *      if an unsupported argument type is provided.
     *
     * @return static
     */
    public function withParsedBody(array $data)
    {
        $new = clone $this;

        $new->parsedBody = $data;

        return $new;
    }

    /**
     * Retrieve attributes derived from the request.
     *
     * The request "attributes" may be used to allow injection of any
     * parameters derived from the request: e.g., the results of path
     * match operations; the results of decrypting cookies; the results of
     * deserializing non-form-encoded message bodies; etc. Attributes
     * will be application and request specific, and CAN be mutable.
     *
     * @return array Attributes derived from the request.
     */
    public function getAttributes(): array
    {
        return $this->attributes;
    }

    /**
     * Retrieve a single derived request attribute.
     *
     * Retrieves a single derived request attribute as described in
     * getAttributes(). If the attribute has not been previously set, returns
     * the default value as provided.
     *
     * This method obviates the need for a hasAttribute() method, as it allows
     * specifying a default value to return if the attribute is not found.
     *
     * @see getAttributes()
     *
     * @param string $name    The attribute name.
     * @param mixed  $default Default value to return if the attribute does not
     *                        exist.
     *
     * @return mixed
     */
    public function getAttribute(string $name, $default = null)
    {
        return $this->attributes[$name] ?? $default;
    }

    /**
     * Return an instance with the specified derived request attribute.
     *
     * This method allows setting a single derived request attribute as
     * described in getAttributes().
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * updated attribute.
     *
     * @see getAttributes()
     *
     * @param string $name  The attribute name.
     * @param mixed  $value The value of the attribute.
     *
     * @return static
     */
    public function withAttribute(string $name, $value)
    {
        $new = clone $this;

        $new->attributes[$name] = $value;

        return $new;
    }

    /**
     * Return an instance that removes the specified derived request attribute.
     *
     * This method allows removing a single derived request attribute as
     * described in getAttributes().
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that removes
     * the attribute.
     *
     * @see getAttributes()
     *
     * @param string $name The attribute name.
     *
     * @return static
     */
    public function withoutAttribute(string $name)
    {
        $new = clone $this;

        unset($new->attributes[$name]);

        return $new;
    }

    /**
     * Is this an AJAX request?
     *
     * @return bool
     */
    public function isXmlHttpRequest(): bool
    {
        return 'XMLHttpRequest' === $this->hasHeader('X-Requested-With');
    }

    /**
     * Validate uploaded files.
     *
     * @param array $uploadedFiles The uploaded files
     *
     * @throws \Valkyrja\HttpMessage\Exceptions\InvalidUploadedFile
     *
     * @return void
     */
    protected function validateUploadedFiles(array $uploadedFiles): void
    {
        foreach ($uploadedFiles as $file) {
            if (\is_array($file)) {
                $this->validateUploadedFiles($file);

                continue;
            }

            if (! $file instanceof UploadedFile) {
                throw new InvalidUploadedFile(
                    'Invalid leaf in uploaded files structure'
                );
            }
        }
    }
}


<?php
namespace cymapgt\core\utility\notifier;

use cymapgt\Exception\NotifierEmailException;
use cymapgt\core\utility\notifier\abstractclass\NotifierInterface;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * class NotifierEmailPhpMailerService
 *
 * This interface implements the Notifier interface to provide a standard
 * method of configuring and using PHPMailer library from Wrox Labs
 *
 * PHP versions 7.0+
 *
 * @category    utility
 * @package     notifier
 * @author      <cogana@gmail.com>
 * @copyright   2017 CYMAPGT
 */

class NotifierEmailPhpMailerService implements NotifierInterface
{
    //the notifier type e.g. Email, SMS
    protected $notifierType  = null;

    //array of configurations required
    protected $configuration = array(
                                    'EMAIL_CLIENT'    => 'PHPMailer',
                                    'USERNAME'        => '',
                                    'PASSWORD'        => '',
                                    'HOST'            => '',
                                    'IS_SMTP'         => true,
                                    'SMTP_DEBUG'      => 2,
                                    'SMTP_AUTH'       => true,
                                    'PORT'            => 587,
                                    'SMTP_SECURE'     => 'tls',
                                    'LINE_ENDING'     => '\n',
                                    'CHARSET'         => 'utf-8',
                                    'EMAIL_FROM'      => '',
                                    'EMAIL_FROM_NAME' => '',
                                    'WORD_WRAP'       => 80,
                                    'IS_HTML'         => true
                               );

    //template settings e.g. if using php, smarty or twig
    protected $templatePath = '';
    protected $templateName = '';

    //init array, for additional data needed to do the job, after configuration
    protected $initArr = array();

    //messages array, where message payloads are stored before sending
    protected $messages = array();

    protected $mailHandler = null;

    /**
     * function __construct() - Constructor method
     */
    public function __construct(){
        //we embed an instance of PHPMailer to do the hard work
        $this->mailHandler = new PHPMailer(true); //exceptions enabled
    }

    /**
     * function setNotifierType() - Set the notifier type as per NotifierType data store
     * @param   string $type  - The notification type
     *
     * @return  void
     */
    public function setNotifierType($type){
        $this->notifierType = $type;
    }

    /**
     * function getNotifierType() - Get the notifier type as per NotifierType data store
     *
     * @return  string
     */
    public function getNotifierType(){
        return $this->notifierType;
    }

    /**
     * function setConfiguration() - Set all required configurations, passed in as an array
     * @param   array $configuration  - Array of various required configuration options
     *
     * @return  void
     */
    public function setConfiguration($configuration) {
        $emailRequiredConfigurations = $this->configuration;
        $configDiff = array_diff($emailRequiredConfigurations, $configuration);

        //validate that all required email settings are present
        if (
            is_array($configDiff
            && count($configDiff))
        ) {
            throw new NotifierEmailException('The configuration array does not contain all required Email configurations');
        }

        //set the configuration provided
        $this->configuration = $configuration;
    }

    /**
     * function getConfiguration() - Return the set configuration option array
     *
     * @return  array
     */
    public function getConfiguration() {
        return $this->configuration;
    }

    /**
     * function setTemplatePath() - Set the path to template files to use for the notifier service
     *
     * @param   string $path     - Path to the notification template file
     * @param   string $name     - Name of the notification template file
     *
     * @return  void
     */
    public function setTemplatePath($path, $name) {
        $this->templateName = $name;
        $this->templatePath = $path;
    }

    /**
     * function getTemplatePath() - Return the set template path
     *
     * @return  string
     */
    public function getTemplatePath(){
        return $this->templatePath;
    }

    /**
     * function getTemplateName() - Return the set template name
     *
     * @return  string
     */
    public function getTemplateName() {
        return $this->templateName;
    }

     /**
     * function initialize() - Initialize the object to workable state, should be called after
     *                         setting the configurations
     * @param   array $initArr     - Any additional initialization parameters
     *
     * @return  void
     */
    public function initialize($initArr) {
        $this->initArr = $initArr;
    }

    /**
     * function setMessage() - Input the actual message payload
     * @param   array $message - Array containing message payload e.g head,body,subject
     *
     * @return  void
     */
    public function setMessage($message) {
        $this->messages[] = $message;
    }

     /**
     * function getMessage() - Return all message payloads
     *
     * @return  array
     */
    public function getMessage() {
        return $this->messages;
    }

    /**
     * function getMessageById() - Return a message by its id
     *
     * @param mixed  $messageId
     *
     * @return array
     */
    public function getMessageById($messageId) {
        if (isset($this->messages[$messageId])) {
            return $this->messages[$messageId];
        } else {
            return false;
        }
    }

    /**
     * function resetMessageById() - Unset the message from $messages array
     *                               based on its ID
     * @param   mixed $messageId
     *
     * @return  boolean
     */
    public function resetMessageById($messageId) {
        if (isset($this->messages[$messageId])) {
            unset($this->messages[$messageId]);
            return true;
        } else {
            return false;
        }
    }

    /**
     * function resetMessagesAll() - Unset all messages in $messages array
     *
     * @return  boolean
     */
    public function resetMessagesAll() {
        foreach ($this->messages as $key => $message) {
            unset($this->messages[$key]);
        }
    }

    /**
     * function resetMessageById() - Send message where the payload has only
     *                               one message in its listing
     * @param   mixed $messageId
     *
     * @return  boolean
     */
    public function sendMessageOne($sendSettings) {
        $this->_bootstrapMailHandler();

        //get the key of the first message
        reset($this->messages);
        $key = key($this->messages);
        $this->_bootstrapMailMessage($key);

        //phpmailer exception used
        try {
            $this->mailHandler->send();
        } catch (phpmailerException $ex) {
            echo $ex->errorMessage();
        }

        //pop the message stack
        $msgStack = $this->messages;
        array_shift($msgStack);
        $this->messages = $msgStack;
    }

    /**
     * function sendMessageById() - Set message using its id
     *
     * @param   array $sendSettings - Additional send settings
     * @param   int   $messageId    - The message Id
     *
     * @return  boolean
     */
    public function sendMessageById($sendSettings, $messageId){
        $messageId = (int) $messageId;

        if (!(isset($this->messages[$messageId]))) {
            throw new NotifierEmailException('Trying to send Message by Id, for an Id that is not set');
        }

        $this->_bootstrapMailHandler();
        $this->_bootstrapMailMessage($messageId);

        //phpmailer exception used
        try {
            $this->mailHandler->send();
        } catch (phpmailerException $ex) {
            echo $ex->errorMessage();
        }
    }

    /**
     * function sendMessagesAll() - Send all messages in the messages
     *                              array
     *
     * @param   array $sendSettings - Additional send settings
     *
     * @return  boolean
     */
    public function sendMessagesAll($sendSettings){
        while (count($this->messages) > 0) {
            $this->sendMessageOne($sendSettings);
        }
    }

    /**
     * function _bootstrapMailHandler() - Prepare the mailHandler by setting the configurations
     *
     * @return void
     *
     * @access private
     */
    private function _bootstrapMailHandler(){
        //confirm that mailHandler is an instance of PHPMailer
        if(!isset($this->mailHandler)
          && !($this->mailHandler instanceof \PHPMailer)
        ){
            throw new NotifierEmailException("The mail handler is not an instance of PHPMailer");
        }

        //bootstrap some common settings
        if((bool)$this->configuration["IS_SMTP"] === true){
            $this->mailHandler->isSMTP();
        }

        if((bool) $this->configuration["IS_HTML"] === true){
            $this->mailHandler->isHTML(true);
        }

        $this->mailHandler->SMTPDebug  = (int)   $this->configuration["SMTP_DEBUG"];
        $this->mailHandler->SMTPAuth   = (bool)  $this->configuration["SMTP_AUTH"];
        $this->mailHandler->Port       = (int)   $this->configuration["PORT"];
        $this->mailHandler->SMTPSecure = (string)$this->configuration["SMTP_SECURE"];
        $this->mailHandler->Host       = (string)$this->configuration["HOST"];
        $this->mailHandler->Username   = (string)$this->configuration["USERNAME"];
        $this->mailHandler->Password   = (string)$this->configuration["PASSWORD"];
        $this->mailHandler->LE         = (string)$this->configuration["LINE_ENDING"];
        $this->mailHandler->CharSet    = (string)$this->configuration["CHARSET"];
        $this->mailHandler->From       = (string)$this->configuration["EMAIL_FROM"];
        $this->mailHandler->FromName   = (string)$this->configuration["EMAIL_FROM_NAME"];
        $this->mailHandler->WordWrap   = (int)   $this->configuration["WORD_WRAP"];
    }

    /**
     * function _bootstrapMailMessage() - Bootstrap a message for sending, clearing previous settings
     *
     * @param   $messageId  - The message Id
     *
     * @return void
     */
    private function _bootstrapMailMessage($messageId){
       //validate that the message exists
        if(!isset($this->messages[($messageId)])){
            throw new NotifierEmailException("Illegal attempt to bootstrap a message that doesnt exist");
        }

        //clear the mailHandler
        $this->mailHandler->clearAddresses();
        $this->mailHandler->clearAllRecipients();
        $this->mailHandler->clearAttachments();
        $this->mailHandler->clearBCCs();
        $this->mailHandler->clearCCs();
        $this->mailHandler->clearCustomHeaders();
        $this->mailHandler->clearReplyTos();
        $this->mailHandler->AltBody = "";
        $this->mailHandler->Timeout = 120;

        //begin bootstrapping the message

        //add receipients on main address
        foreach($this->messages[($messageId)]["TO"] as $emailUser){
            $this->mailHandler->AddAddress($emailUser["email"], $emailUser["name"]);
        }

        //add recepients on CC
        foreach($this->messages[($messageId)]["CC"] as $emailUser){
            $this->mailHandler->addCC($emailUser["mail"], $emailUser["name"]);
        }

        //add the subject
        $this->mailHandler->Subject = $this->messages[($messageId)]["SUBJECT"];

        //add the email altbody
        $this->mailHandler->AltBody = $this->messages[($messageId)]["ALT_BODY"];

        //set the message body (as HTML)
        $this->mailHandler->MsgHTML($this->messages[($messageId)]["MSG_HTML"]);

        //set the bootstrapped property to true
        $this->messages[($messageId)]["IS_BOOSTRAPPED"] = true;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Elastica;

use Elastica\Exception\ExceptionInterface;
use Elastica\Request;
use Elastica\Response;
use FOS\ElasticaBundle\Elastica\Client as BaseClient;

/**
 * Class Client
 * @package Ekyna\Bundle\CoreBundle\Elastica
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class Client extends BaseClient
{
    /**
     * {@inheritdoc}
     */
    public function request($path, $method = Request::GET, $data = [], array $query = [])
    {
        try {
            return parent::request($path, $method, $data, $query);
        } catch (ExceptionInterface $e) {
            if ($this->_logger) {
                $this->_logger->warning('Failed to send a request to ElasticSearch', [
                    'exception' => $e->getMessage(),
                    'path'      => $path,
                    'method'    => $method,
                    'data'      => $data,
                    'query'     => $query
                ]);
            }
            return new Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
        }
    }
}


<?php
/**
 * @author Serhii Nekhaienko <sergey.nekhaenko@gmail.com>
 * @license GPL
 * @copyright Serhii Nekhaienko &copy 2018
 * @version 4.0.0
 * @project endorphin-studio/browser-detector
 */

namespace EndorphinStudio\Detector\Detection;

use EndorphinStudio\Detector\Data\AbstractData;
use EndorphinStudio\Detector\Detector;
use EndorphinStudio\Detector\Tools;

/**
 * Class AbstractDetection
 * Abstract detector class
 * @package EndorphinStudio\Detector\Detection
 */
abstract class AbstractDetection implements DetectionInterface
{
    /**
     * @var array Additional Info
     */
    protected $additionalInfo = [];
    /**
     * @var string Key in config (os, device, etc.)
     */
    protected $configKey = 'none';

    /** @var array Data for detection (patterns, etc.) */
    protected $config;
    /** @var Detector Detector class */
    protected $detector;

    /** @var AbstractData Result object */
    protected $resultObject;

    /**
     * @param Detector $detector Init detection class with detector
     */
    public function init(Detector $detector)
    {
        $this->detector = $detector;
    }

    /**
     * Result object initialisation
     * @return null
     */
    protected function initResultObject()
    {
        if(!array_key_exists('default', $this->config)) {
            return null;
        }
        // init default value from data
        foreach ($this->config['default'] as $defaultKey => $defaultValue) {
            Tools::runSetter($this->resultObject, $defaultKey, $defaultValue);
        }
    }

    /**
     * Detect method
     * @param array $additional Additional info
     */
    public function detect(array $additional = [])
    {
        if ($this->configKey !== 'none') {
            $this->config = $this->detector->getPatternList($this->detector->getDataProvider()->getConfig(), $this->configKey);
            $resultObject = $this->detector->getResultObject();
            $this->resultObject = Tools::runGetter($resultObject, $this->configKey);
        }
        $this->initResultObject();
        $this->setupResultObject();
        $this->afterDetection();
    }

    /**
     * Setup Result Object
     * @return void
     */
    protected abstract function setupResultObject();

    /**
     * Detect by pattern
     * @param array $patternList list of patterns
     * @return array|null
     */
    protected function detectByPattern(array $patternList)
    {
        foreach ($patternList as $patternId => $patternData) {
            $pattern = $this->getPattern($patternId, $patternData);

            if (preg_match($pattern['pattern'], $this->detector->getUserAgent())) {
                return ['name' => $patternId, 'version' => Tools::getVersion($pattern['version'], $this->detector->getUserAgent()), 'originalInfo' => $patternData];
            }
        }
        return null;
    }

    /**
     * Get pattern form array
     * @param string $patternId ID in config
     * @param array $patternData array from yaml file
     * @return array
     */
    private function getPattern(string $patternId, array $patternData): array
    {
        if (array_key_exists('default', $patternData) && $patternData['default'] === true) {
            return ['pattern' => sprintf('/%s/', $patternId), 'version' => $patternId];
        }
        return ['pattern' => sprintf('/%s/', $patternData['pattern']), 'version' => array_key_exists('version', $patternData) ? $patternData['version'] : $patternId];
    }

    /**
     * Set attributes of result object
     * @param array $info Array
     */
    protected function setAttributes(array $info)
    {
        $result = $this->detector->getResultObject();
        if (array_key_exists('attributes', $info)) {
            foreach ($info['attributes'] as $attributeKey => $attributeValue) {
                Tools::runSetter($result, $attributeKey, $attributeValue);
            }
        }
    }

    /**
     * Detect by type
     * @param string $key
     * @return array
     */
    protected function detectByType($key = 'none'): array
    {
        $container = $key === 'none' ? $this->config : $this->config[$key];
        foreach ($container as $type => $patternList) {
            if ($type === 'default') {
                continue;
            }
            $browser = $this->detectByPattern($patternList);
            if (!empty($browser)) {
                return array_merge($browser, ['type' => $type]);
            }
        }
        return [];
    }

    /**
     * Detect by Key
     * @param string $keyName
     * @return array
     */
    protected function detectByKey($keyName = 'family'): array
    {
        foreach ($this->config as $key => $data) {
            if ($key === 'default') {
                continue;
            }
            $detectedData = $this->detectByType($key);
            if (!empty($detectedData)) {
                return array_merge($detectedData, [$keyName => $key]);
            }
        }
        return [];
    }

    protected function afterDetection() {
        /** Not required implementation */
    }
}


<?php

namespace Reaction\Cache;

use Reaction\Exceptions\Exception;
use Reaction\Helpers\ArrayHelper;
use function Reaction\Promise\reject;
use function Reaction\Promise\resolve;

/**
 * Class ArrayExpiringCache
 * @package Reaction\Cache
 */
class ArrayExpiringCache extends ExpiringCache
{
    /** @var array Data storage */
    protected $storage = [];
    /** @var array Tags associated with data keys */
    protected $tags = [];

    /**
     * {@inheritdoc}
     */
    public function get($key, $default = null)
    {
        $key = $this->processKey($key);
        if ($this->existInternal($key)) {
            $data = $this->unpackRecord($this->storage[$key]);
            return resolve($data);
        }
        return resolve($default);
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $value, $ttl = null, $tags = [])
    {
        $ttl = isset($ttl) ? $ttl : $this->lifetimeDefault;
        $expire = time() + $ttl;
        $key = $this->processKey($key);
        $record = $this->packRecord($value);
        $this->addKeyTags($key, $record, $tags);
        $this->storage[$key] = $record;
        $this->_timestamps[$key] = $expire;
        return resolve(true);
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        $key = $this->processKey($key);
        if ($this->existInternal($key)) {
            $tags = $this->storage[$key][$this->tagsKey];
            unset($this->storage[$key]);
            unset($this->_timestamps[$key]);
            foreach ($tags as $tag) {
                unset($this->tags[$tag][$key]);
            }
        }
        return resolve(true);
    }

    /**
     * {@inheritdoc}
     */
    public function deleteByTag($tag)
    {
        if (!isset($this->tags[$tag])) {
            return resolve(true);
        }
        $keys = $this->tags[$tag];
        unset($this->tags[$tag]);
        return !empty($keys) ? $this->deleteMultiple($keys) : resolve(true);
    }

    /**
     * {@inheritdoc}
     */
    public function exists($key)
    {
        $key = $this->processKey($key);
        if ($this->existInternal($key)) {
            return resolve(true);
        }
        return reject(new Exception(sprintf('Cache for key "%s" not exists', $key)));
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        $this->storage = [];
        $this->tags = [];
        $this->_timestamps = [];
        return resolve(true);
    }

    /**
     * Check that data exists in storage array
     * @param string $key
     * @return bool
     */
    protected function existInternal($key) {
        return ArrayHelper::keyExists($key, $this->storage);
    }

    /**
     * Save key tags
     * @param string   $key
     * @param array    $record
     * @param string[] $tags
     */
    protected function addKeyTags($key, &$record = [], $tags = [])
    {
        $record[$this->tagsKey] = $tags;
        foreach ($tags as $tag) {
            if (!isset($this->tags[$tag])) {
                $this->tags[$tag] = [];
            }
            $this->tags[$tag][$key] = $key;
        }
    }
}


<?php

namespace Gwsn\Prismic\Models;
use Gwsn\Transformer\Mapping\MappingInterface;

/**
 * Class Response
 * @package Gwsn\Prismic\Models
 */
class Response
{

    /** @var int $page */
    public $page;
    /** @var int $resultsPerPage */
    public $resultsPerPage;
    /** @var int $resultsSize */
    public $resultsSize;
    /** @var int $totalResultsSize */
    public $totalResultsSize;
    /** @var int $totalPages */
    public $totalPages;
    /** @var string $nextPage */
    public $nextPage;
    /** @var string $prevPage */
    public $prevPage;
    /** @var array $results */
    public $results;
    /** @var string $version */
    public $version;
    /** @var string $license */
    public $license;

    /**
     * Constructs a Response object.
     *
     * @param $response
     * @param MappingInterface $responseItemHandler
     */
    public function __construct(array $response = [], MappingInterface $responseItemHandler = null)
    {
        $responseItemHandler = ($responseItemHandler !== null ? $responseItemHandler : new ResponseItemData);

        if (!empty($response)) {
            $this->parseResponse($response, $responseItemHandler);
        }
    }

    /**
     * Returns the list of returned documents, which is an array of Document objects.
     *
     * @return array the list of returned documents
     */
    public function getResults()
    {
        return $this->results;
    }

    /**
     * Returns the page number for this query.
     *
     * @return int the page number for this query
     */
    public function getPage()
    {
        return $this->page;
    }

    /**
     * Returns the requested number of results per page on this query.
     *
     * @return int the requested number of results per page on this query
     */
    public function getResultsPerPage()
    {
        return $this->resultsPerPage;
    }

    /**
     * Returns the size of the current page.
     *
     * @return int the size of the current page
     */
    public function getResultsSize()
    {
        return $this->resultsSize;
    }

    /**
     * Returns the total number of documents, all pages together.
     *
     * @return int the total number of documents, all pages together
     */
    public function getTotalResultsSize()
    {
        return $this->totalResultsSize;
    }

    /**
     * Returns the number of pages for this query.
     *
     * @return int the number of pages for this query
     */
    public function getTotalPages()
    {
        return $this->totalPages;
    }

    /**
     * Returns the RESTful URL of the search request for the next page; null otherwise.
     *
     * @return string the RESTful URL of the search request for the next page; null otherwise
     */
    public function getNextPage()
    {
        return $this->nextPage;
    }

    /**
     * Returns the RESTful URL of the search request for the previous page; null otherwise.
     *
     * @return string the RESTful URL of the search request for the previous page; null otherwise
     */
    public function getPrevPage()
    {
        return $this->prevPage;
    }

    /**
     * @param array $response
     * @param MappingInterface $responseItemHandler
     *
     * @todo migrate to a transfomer object
     * @return Response
     */
    public function parseResponse(array $response, MappingInterface $responseItemHandler)
    {
        $responseItemHandler = ($responseItemHandler !== null ? $responseItemHandler : new ResponseItemData);

        $this->page = (!empty($response['page']) ? intval($response['page']) : 0);
        $this->resultsPerPage = (!empty($response['results_per_page']) ? intval($response['results_per_page']) : 0);
        $this->resultsSize = (!empty($response['results_size']) ? intval($response['results_size']) : 0);
        $this->totalResultsSize = (!empty($response['total_results_size']) ? intval($response['total_results_size']) : 0);
        $this->totalPages = (!empty($response['total_pages']) ? intval($response['total_pages']) : 0);
        $this->nextPage = $response['next_page'];
        $this->prevPage = $response['prev_page'];

        $this->version = $response['version'];
        $this->license = $response['license'];

        $responseItems = new ResponseItem($responseItemHandler);
        $responseItems->setItems($response['results']);

        $this->results = $responseItems->getItems();

        return $this;
    }

}


<?php

namespace helionogueir\shell;

/**
 * - Environment check
 * @author Helio Nogueira <helio.nogueir@gmail.com>
 * @version v1.0.0
 */
class Environment {

  const SERVER_CLI = "cli";

  /**
   * - Check script execute on shell
   * @return bool Case yes return true, or false case other
   */
  public function onShell(): bool {
    $check = true;
    if (PHP_SAPI != Environment::SERVER_CLI) {
      $check = false;
    }
    return $check;
  }

}