<?php

namespace Asoc\Dadatata\Filter\PDFBox;

use Asoc\Dadatata\Exception\ProcessingFailedException;
use Asoc\Dadatata\Filter\FilterInterface;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ThingInterface;
use Asoc\Dadatata\Tool\PdfBox;
use Asoc\Dadatata\ToolInterface;
use Neutron\TemporaryFilesystem\TemporaryFilesystemInterface;

class ExtractText implements FilterInterface
{
    /**
     * @var \Asoc\Dadatata\ToolInterface|PdfBox
     */
    private $pdfBox;
    /**
     * @var \Neutron\TemporaryFilesystem\TemporaryFilesystemInterface
     */
    private $tmpFs;

    public function __construct(ToolInterface $pdfBox, TemporaryFilesystemInterface $tmpFs)
    {
        $this->pdfBox = $pdfBox;
        $this->tmpFs  = $tmpFs;
    }

    /**
     * @param ThingInterface   $thing
     * @param string           $sourcePath
     * @param OptionsInterface $options
     *
     * @throws \Asoc\Dadatata\Exception\ProcessingFailedException
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $tmpDir  = $this->tmpFs->createTemporaryDirectory();
        $tmpFile = $tmpDir.DIRECTORY_SEPARATOR.$thing->getKey();

        $pb      = $this->pdfBox->getProcessBuilder()
            ->extractText()
            ->source($sourcePath)
            ->output($tmpFile);
        $process = $pb->getProcess();

        $code = $process->run();
        if ($code !== 0) {
            throw ProcessingFailedException::create(
                'Failed to convert PDF to text',
                $code,
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        return [$tmpFile];
    }

    /**
     * @param ThingInterface $thing
     *
     * @return boolean
     */
    public function canHandle(ThingInterface $thing)
    {
        return $thing->getMime() === 'application/pdf';
    }

    /**
     * @param OptionsInterface $options
     */
    public function setOptions(OptionsInterface $options)
    {
    }
}


<?php

/**
 * This file is part of RawPHP - a PHP Framework.
 *
 * Copyright (c) 2014 RawPHP.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * PHP version 5.3
 *
 * @category  PHP
 * @package   RawPHP\RawRouter
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */

namespace RawPHP\RawRouter;

use RawPHP\RawDispatcher\Contract\IDispatcher;
use RawPHP\RawRouter\Contract\IController;
use RawPHP\RawRouter\Contract\IRouter;

/**
 * The Routing class.
 *
 * @category  PHP
 * @package   RawPHP\RawRouter
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */
class Router implements IRouter
{
    protected $defaultController = 'home';
    protected $defaultAction = 'index';
    /** @var  array */
    protected $namespaces = [ ];
    /** @var  array */
    protected $config;
    /** @var  IDispatcher */
    protected $dispatcher;

    /**
     * Create new router.
     *
     * @param array $config
     */
    public function __construct( array $config = [ ] )
    {
        $this->config = $config;

        $this->init( $config );
    }

    /**
     * Initialises the router.
     *
     * @param array $config configuration array
     */
    public function init( array $config = [ ] )
    {
        foreach ( $config as $key => $value )
        {
            switch ( $key )
            {
                case 'default_controller':
                    $this->defaultController = $value;
                    break;

                case 'default_action':
                    $this->defaultAction = $value;
                    break;

                case 'namespaces':
                    $this->namespaces = $value;
                    break;

                default:
                    // do nothing
                    break;
            }
        }
    }

    /**
     * Creates a controller and its associated action.
     *
     * @param string $route  the controller/action string
     *                       format [controllerName/actionName]
     * @param array  $params list of parameters
     *
     * @return Controller instance of a controller
     */
    public function createController( $route, $params )
    {
        $control = NULL;
        $route   = ltrim( $route, '/' );
        $route   = rtrim( $route, '/' );

        $vars = explode( '/', $route );

        if ( 1 === count( $vars ) && '' == $vars[ 0 ] )
        {
            $control = $this->_buildControllerName( $this->defaultController . 'Controller' );

            // build action
            $aName = $this->_buildActionName( $control, $this->defaultAction );
        }
        else if ( 1 === count( $vars ) )
        {
            // controller /

            $control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );

            array_shift( $vars );

            // build action
            $aName = $this->_buildActionName( $control, $this->defaultAction );
        }
        else if ( 2 === count( $vars ) )
        {
            // controller / action
            $control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );

            array_shift( $vars );

            // build action
            $aName = $this->_buildActionName( $control, $vars[ 0 ] );
        }
        else if ( 2 < count( $vars ) )
        {
            // controller / action / params
            $control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );

            array_shift( $vars );

            // build action
            $aName = $this->_buildActionName( $control, $vars[ 0 ] );

            array_shift( $vars );
        }
        else
        {
            $control = $this->_buildControllerName( $this->defaultController . 'Controller' );

            $aName = $this->defaultAction . 'Action';
        }

        $action = new Action( $aName, $params );

        /** @var IController $controller */
        $controller = new $control( $this->config );
        $controller->setAction( $action );
        $controller->setDispatcher( $this->dispatcher );
        $controller->addDefaultListeners();

        return $controller;
    }

    /**
     * Constructs the controller name.
     *
     * @param string $name the controller name
     *
     * @return string the name
     */
    private function _buildControllerName( $name )
    {
        $name = strtoupper( $name[ 0 ] ) . substr( $name, 1 );

        $controller = $name;

        $namespace = NULL;

        foreach ( $this->namespaces as $ns )
        {
            if ( class_exists( $ns . $controller ) )
            {
                $namespace  = $ns;
                $controller = $ns . $controller;

                break;
            }
        }

        if ( NULL === $namespace )
        {
            return strtoupper( $this->defaultController[ 0 ] )
            . substr( $this->defaultController, 1 ) . 'Controller';
        }
        else
        {
            return $controller;
        }
    }

    /**
     * Builds the action name.
     *
     * @param string $controllerName the controller name
     * @param string $actionName     the action name
     *
     * @return string the action name
     */
    private function _buildActionName( $controllerName, $actionName )
    {
        $actionName = $actionName . 'Action';

        if ( !method_exists( $controllerName, $actionName ) )
        {
            $actionName = $this->defaultAction . 'Action';
        }

        return $actionName;
    }

    /**
     * Set the event dispatcher.
     *
     * @param IDispatcher $dispatcher
     */
    public function setDispatcher( IDispatcher $dispatcher )
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * Get the event dispatcher.
     *
     * @return IDispatcher
     */
    public function getDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * Get the controller namespace.
     *
     * @return array
     */
    public function getNamespaces()
    {
        return $this->namespaces;
    }

    /**
     * Set the controller namespace.
     *
     * @param array $namespaces
     */
    public function setNamespaces( array $namespaces )
    {
        $this->namespaces = $namespaces;
    }

    /**
     * Get the default controller name.
     *
     * @return string
     */
    public function getDefaultController()
    {
        return $this->defaultController;
    }

    /**
     * Set the default controller name.
     *
     * @param string $defaultController
     */
    public function setDefaultController( $defaultController )
    {
        $this->defaultController = $defaultController;
    }

    /**
     * Get the default action name.
     *
     * @return string
     */
    public function getDefaultAction()
    {
        return $this->defaultAction;
    }

    /**
     * Set the default action name.
     *
     * @param string $defaultAction
     */
    public function setDefaultAction( $defaultAction )
    {
        $this->defaultAction = $defaultAction;
    }
}


<?php

namespace Floppy\Common;

final class FileId implements HasFileInfo
{
    private $id;
    private $attributes;
    private $filename;
    private $info;

    public function __construct($id, array $attributes = array(), $filename = null, array $info = array())
    {
        $this->id = (string)$id;
        $this->attributes = new AttributesBag($attributes);
        $this->filename = $filename;
        $this->info = new AttributesBag($info);
    }

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

    /**
     * Attributes of this FileId, it have meaning to file identity
     *
     * @return AttributesBag
     */
    public function attributes()
    {
        return $this->attributes;
    }

    /**
     * Informations related to this FileId, it have no meaning to file identity
     *
     * @return AttributesBag
     */
    public function info()
    {
        return $this->info;
    }

    public function filename()
    {
        return $this->filename ?: $this->id;
    }

    public function isVariant()
    {
        return count($this->attributes->all()) > 0 || $this->filename() !== $this->id;
    }

    /**
     * Creates variant with given attributes of this file
     *
     * @param array $attrs Variant attributes - it might be image size, file name etc.
     *
     * @return FileId
     */
    public function variant(array $attrs)
    {
        return new self($this->id, $attrs, null, $this->info->all());
    }

    /**
     * Alias to {@see FileId#variant()) method
     *
     * @param array $attrs
     * @return FileId
     */
    public function with(array $attrs)
    {
        return $this->variant($attrs);
    }

    /**
     * Creates id to original file.
     *
     * @return FileId
     */
    public function original()
    {
        return new self($this->id, array(), null, $this->info->all());
    }

    /**
     * @param array $info
     * @return FileId
     */
    public function withInfo(array $info)
    {
        return new self($this->id, $this->attributes->all(), $this->filename, $info);
    }

    public function __toString()
    {
        return $this->id;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: miky
 * Date: 26/10/16
 * Time: 10:14
 */

namespace Miky\Bundle\UserBundle\Manager;

use Doctrine\Common\Persistence\ObjectManager;
use Miky\Bundle\UserBundle\Entity\History;

class HistoryManager
{
    /**
     * @var ObjectManager
     */
    protected $objectManager;

    /**
     * @var string
     */
    protected $class;

    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    protected $repository;

    /**
     * Constructor.
     * @param ObjectManager $om
     * @param string $class
     */
    public function __construct(ObjectManager $om, $class)
    {
        $this->objectManager = $om;
        $this->repository = $om->getRepository($class);
        $metadata = $om->getClassMetadata($class);
        $this->class = $metadata->getName();
    }

    /**
     * {@inheritDoc}
     */
    public function deleteHistory(History $history)
    {
        $this->objectManager->remove($history);
        $this->objectManager->flush();
    }

    public function getClass()
    {
        return $this->class;
    }

    public function findHistoricalBy(array $criteria)
    {
        return $this->repository->findBy($criteria);
    }

    /**
     * @param array $criteria
     * @return History|null
     */
    public function findOneHistoricalBy(array $criteria)
    {
        return $this->repository->findOneBy($criteria);
    }

    public function updateHistory(History $history, $andFlush = true)
    {
        $this->objectManager->persist($history);
        if ($andFlush) {
            $this->objectManager->flush();
        }
    }

    /**
     * Returns an empty history instance
     *
     * @return History
     */
    public function createHistory()
    {
        $class = $this->getClass();
        $history = new $class;
        return $history;
    }

}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Markup;

/**
 * デバッグのために使用される Context です.
 * この Context は, handle メソッドを実行した時に自動で echo を行います.
 * 出力内容は, ノードツリーの構造を可視化した文字列となります.
 */
class DebugContext extends Context
{
    /**
     * 出力を整形するために使用される Indent です.
     * @var Indent
     */
    private $indent;

    /**
     * 出力結果です.
     * @var string
     */
    private $result;

    /**
     * true の場合, handle() を実行すると同時に echo を実行します.
     * @var bool
     */
    private $echoMode;

    /**
     * 新しい DebugContext を構築します.
     * @param bool $echoMode 自動で出力を行うかどうかの設定 (デフォルトで true)
     */
    public function __construct($echoMode = true)
    {
        $this->indent   = new Indent();
        $this->result   = "";
        $this->echoMode = (bool) $echoMode;
    }

    /**
     * ノードの開始を書式化します.
     *
     * @param string $name
     */
    private function startNode($name)
    {
        $result = $this->indent->indent() . $name . " {" . $this->indent->stepUp();
        if ($this->echoMode) {
            echo $result;
        }
        $this->result .= $result;
    }

    /**
     * インデントレベルを下げて "}" を出力します.
     */
    private function endNode()
    {
        $result = $this->indent->stepDown() . "}" . $this->indent->breakCode();
        if ($this->echoMode) {
            echo $result;
        }
        $this->result .= $result;
    }

    /**
     * 指定された文字列をインデントして追記します.
     * @param string $contents
     */
    private function append($contents)
    {
        $result = $this->indent->indent() . $contents . $this->indent->breakCode();
        if ($this->echoMode) {
            echo $result;
        }
        $this->result .= $result;
    }

    /**
     * 指定された Container の子ノードを再帰的に処理します.
     *
     * @param Container $container
     */
    private function handleContainer(Container $container)
    {
        foreach ($container->getChildNodes() as $node) {
            $this->handle($node);
        }
    }

    /**
     * デバッグ用の出力データを返します.
     * @return string
     */
    public function getResult()
    {
        return $this->result;
    }

    /**
     * Comment ノードのデバッグ文字列を出力します.
     * 出力内容は以下の通りです.
     *
     *
     * Comment {
     *     # 子ノードの出力内容
     * }
     *
     *
     * @param Comment $node
     */
    public function handleComment(Comment $node)
    {
        $this->startNode("Comment");
        $this->handleContainer($node);
        $this->endNode();
    }

    /**
     * ContainerElement ノードのデバッグ文字列を出力します.
     * 出力内容は以下の通りです.
     *
     *
     * ContainerElement(tagName) {
     *     # 子ノードの出力内容
     * }
     *
     *
     * @param ContainerElement $node
     */
    public function handleContainerElement(ContainerElement $node)
    {
        $name = $node->getName();
        $this->startNode("ContainerElement({$name})");
        $this->handleContainer($node);
        $this->endNode();
    }

    /**
     * EmptyElement ノードのデバッグ文字列を出力します.
     * 出力内容は以下の通りです.
     *
     *
     * EmptyElement(tagName)
     *
     *
     * @param EmptyElement $node
     */
    public function handleEmptyElement(EmptyElement $node)
    {
        $name = $node->getName();
        $this->append("EmptyElement({$name})");
    }

    /**
     * NodeList のデバッグ文字列を出力します.
     * 出力内容は以下の通りです.
     *
     *
     * NodeList {
     *     # 子ノードの出力内容
     * }
     *
     *
     * @param NodeList $node
     */
    public function handleNodeList(NodeList $node)
    {
        $this->startNode("NodeList");
        $this->handleContainer($node);
        $this->endNode();
    }

    /**
     * Text ノードのデバッグ文字列を出力します.
     * 出力内容は文字列 "Text" です.
     * @param Text $node
     */
    public function handleText(Text $node)
    {
        $this->append("Text");
    }

    /**
     * Code ノードのデバッグ文字列を出力します.
     * 出力内容は文字列 "Code" です.
     * @param Code $node
     */
    public function handleCode(Code $node)
    {
        $this->append("Code");
    }

    /**
     * None のデバッグ文字列を出力します.
     * 出力内容は文字列 "None" です.
     * @param None $none
     */
    public function handleNone(None $none)
    {
        $this->append("None");
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use Yii;
use yii\base\Component;
use yii\helpers\Json;

/**
 * JsonResponseFormatter formats the given data into a JSON or JSONP response content.
 *
 * It is used by [[Response]] to format response data.
 *
 * To configure properties like [[encodeOptions]] or [[prettyPrint]], you can configure the `response`
 * application component like the following:
 *
 * ```php
 * 'response' => [
 *     // ...
 *     'formatters' => [
 *         \yii\web\Response::FORMAT_JSON => [
 *              'class' => 'yii\web\JsonResponseFormatter',
 *              'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
 *              // ...
 *         ],
 *     ],
 * ],
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class JsonResponseFormatter extends Component implements ResponseFormatterInterface
{
    /**
     * @var boolean whether to use JSONP response format. When this is true, the [[Response::data|response data]]
     * must be an array consisting of `data` and `callback` members. The latter should be a JavaScript
     * function name while the former will be passed to this function as a parameter.
     */
    public $useJsonp = false;
    /**
     * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to
     * <http://www.php.net/manual/en/function.json-encode.php>.
     * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
     * This property has no effect, when [[useJsonp]] is `true`.
     * @since 2.0.7
     */
    public $encodeOptions = 320;
    /**
     * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose.
     * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]].
     * Defaults to `false`.
     * This property has no effect, when [[useJsonp]] is `true`.
     * @since 2.0.7
     */
    public $prettyPrint = false;

    /**
     * Formats the specified response.
     * @param Response $response the response to be formatted.
     */
    public function format($response)
    {
        if ($this->useJsonp) {
            $this->formatJsonp($response);
        } else {
            $this->formatJson($response);
        }
    }

    /**
     * Formats response data in JSON format.
     * @param Response $response
     */
    protected function formatJson($response)
    {
        $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
        if ($response->data !== null) {
            $options = $this->encodeOptions;
            if ($this->prettyPrint) {
                $options |= JSON_PRETTY_PRINT;
            }
            $response->content = Json::encode($response->data, $options);
        }
    }

    /**
     * Formats response data in JSONP format.
     * @param Response $response
     */
    protected function formatJsonp($response)
    {
        $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
        if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
            $response->content = sprintf('%s(%s);', $response->data['callback'], Json::htmlEncode($response->data['data']));
        } elseif ($response->data !== null) {
            $response->content = '';
            Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
        }
    }
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Markup;

/**
 * SGML や XML をマークアップするための必要最低限の書式化ルールを定義した抽象基底クラスです.
 *
 * {@link SgmlRenderer} および {@link XmlRenderer}
 * の共通部分の実装です.
 */
abstract class AbstractRenderer implements Renderer
{
    /**
     * 開始タグをマークアップします.
     * この書式化ルールは SGML, XML 共通です.
     * @param  Element $element 要素
     * @return string           開始タグ ("<tagName attr... >")
     */
    public final function formatStartTag(Element $element)
    {
        return $this->formatTagPrefix($element) . ">";
    }

    /**
     * 終了タグをマークアップします.
     * この書式化ルールは SGML, XML 共通です.
     * @param  Element $element 要素
     * @return string           終了タグ ("</tagName>")
     */
    public final function formatEndTag(Element $element)
    {
        return "</" . $element->getName() . ">";
    }

    /**
     * 空要素タグをマークアップします.
     * タグの末尾の書式化方法は各サブクラスに依存します.
     * @param  Element $element 要素
     * @return string           空要素タグ ("<tagName attr... >" または <tagName attr... />")
     */
    public final function formatEmptyTag(Element $element)
    {
        return $this->formatTagPrefix($element) . $this->formatEmptyTagSuffix();
    }

    /**
     * 開始タグまたは空要素タグの共通部分を書式化します.
     * @param  Element $element 書式化対象の要素
     * @return string           "<elementName ... "
     */
    protected final function formatTagPrefix(Element $element)
    {
        $tag  = "<";
        $tag .= $element->getName();
        foreach ($element->getAttributes() as $name => $value) {
            $tag .= " ";
            $tag .= ($value === null) ?
                $this->formatBooleanAttribute($name) : $this->formatAttribute($name, $value);
        }
        return $tag;
    }

    /**
     * 指定された属性を書式化します.
     *
     * @param  string $name  属性名
     * @param  string $value 属性値
     * @return string        属性
     */
    protected abstract function formatAttribute($name, $value);

    /**
     * 値の省略された属性を書式化します.
     *
     * @param  string $name 属性名
     * @return string       属性
     */
    protected abstract function formatBooleanAttribute($name);

    /**
     * 空要素タグの末尾を書式化します.
     * @return string 空要素の末尾. SGML は ">", XML は " />".
     */
    protected abstract function formatEmptyTagSuffix();
}


<?php

namespace MandarinMedien\MMMediaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MandarinMedien\MMMediaBundle\Entity\Media;
use MandarinMedien\MMMediaBundle\Form\MediaType;

/**
 * Media controller.
 */
class MediaController extends Controller
{
    /**
     * Lists all Media entities.
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MMMediaBundle:Media')->findAll();

        return $this->render('MMMediaBundle:Media:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Media entity.
     */
    public function createAction(Request $request)
    {
        $entity = new Media();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('media_show', array('id' => $entity->getId())));
        }

        return $this->render('MMMediaBundle:Media:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Media entity.
     *
     * @param Media $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Media $entity)
    {
        $form = $this->createForm(new MediaType(), $entity, array(
            'action' => $this->generateUrl('media_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Media entity.
     */
    public function newAction()
    {
        $entity = new Media();
        $form = $this->createCreateForm($entity);

        return $this->render('MMMediaBundle:Media:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Media entity.
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MMMediaBundle:Media')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Media entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('MMMediaBundle:Media:show.html.twig', array(
            'entity' => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Media entity.
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MMMediaBundle:Media')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Media entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('MMMediaBundle:Media:edit.html.twig', array(
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Creates a form to edit a Media entity.
     *
     * @param Media $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(Media $entity)
    {
        $form = $this->createForm(new MediaType(), $entity, array(
            'action' => $this->generateUrl('media_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Media entity.
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MMMediaBundle:Media')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Media entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('media_edit', array('id' => $id)));
        }

        return $this->render('MMMediaBundle:Media:edit.html.twig', array(
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Media entity.
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MMMediaBundle:Media')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Media entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('media'));
    }

    /**
     * Creates a form to delete a Media entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('media_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    public function uploadAction(Request $request)
    {
        var_dump($request);
    }
}


<?php
declare(strict_types=1);
/**
 * Caridea
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * @copyright 2015-2018 LibreWorks contributors
 * @license   Apache-2.0
 */
namespace Caridea\Http;

/**
 * Produces Pagination objects based on request parameters.
 *
 * @copyright 2015-2018 LibreWorks contributors
 * @license   Apache-2.0
 */
class PaginationFactory
{
    const DESC = "desc";
    const SORT = "sort";
    const ORDER = "order";
    const PAGE = "page";
    const START_PAGE = "startPage";
    const START_INDEX = "startIndex";
    const START = "start";
    const COUNT = "count";
    const MAX = "max";
    const LIMIT = "limit";
    const OFFSET = "offset";
    const RANGE = "Range";
    const REGEX_RANGE = '/^items=(\\d+)-(\\d+)$/';
    const REGEX_DOJO_SORT = '/^sort\\(.*\\)$/';

    private static $maxAlias = [self::MAX => null, self::LIMIT => null, self::COUNT => null];
    private static $offsetAlias = [self::START => null, self::OFFSET => null];
    private static $pageAlias = [self::PAGE => null, self::START_PAGE => null];

    /**
     * Checks the request query parameters and headers for pagination info.
     *
     * This class supports a good size sampling of different ways to provide
     * pagination info.
     *
     * #### Range
     * - `max` + `offset` (e.g. Grails): `&max=25&offset=0`
     * - `count` + `start` (e.g. `dojox.data.QueryReadStore`): `&count=25&start=0`
     * - `Range` header (e.g. `dojo.store.JsonRest`): `Range: items=0-24`
     * - `count` + `startIndex` (e.g. OpenSearch): `&count=25&startIndex=1`
     * - `count` + `startPage` (e.g. OpenSearch): `&count=25&startPage=1`
     * - `limit` + `page` (e.g. Spring Data REST): `&limit=25&page=1`
     * - `limit` + `start` (e.g. ExtJS): `&limit=25&start=0`
     *
     * Dojo, Grails, and ExtJS are all zero-based. OpenSearch and Spring Data
     * are one-based.
     *
     * #### Order
     * - OpenSearchServer: `&sort=foo&sort=-bar`
     * - OpenSearch extension: `&sort=foo:ascending&sort=bar:descending`
     * - Grails: `&sort=foo&order=asc`
     * - Spring Data REST: `&sort=foo,asc&sort=bar,desc`
     * - Dojo: `&sort(+foo,-bar)`
     * - Dojo w/field: `&[field]=+foo,-bar`
     * - ExtJS JSON: `&sort=[{"property":"foo","direction":"asc"},{"property":"bar","direction":"desc"}]`
     *
     * Because of the fact that many order syntaxes use multiple query string
     * parameters with the same name, it is absolutely *vital* that you do not
     * use a `ServerRequestInterface` that has been constructed with the `$_GET`
     * superglobal.
     *
     * The problem here is that PHP will overwrite entries in the `$_GET`
     * superglobal if they share the same name. With PHP, a request to
     * `file.php?foobar=foo&foobar=bar` will result in `$_GET` set to
     * `['foobar' => 'bar']`.
     *
     * Other platforms, like the Java Servlet specification, allow list-like
     * access to these parameters. Make sure the object you pass for `$request`
     * has a `queryParams` property that has been created to account for
     * multiple query parameters with the same name. The `QueryParams` class
     * will produce an array that accounts for this case.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request The server request. Please read important docs above.
     * @param string $sortParameter The name of the sort parameter
     * @param array<string,bool> $defaultSort The default sort if request lacks it
     * @return \Caridea\Http\Pagination The pagination details
     */
    public function create(\Psr\Http\Message\ServerRequestInterface $request, string $sortParameter = self::SORT, array $defaultSort = []): Pagination
    {
        $offset = 0;
        $max = PHP_INT_MAX;

        $params = $request->getQueryParams();
        $range = $request->getHeaderLine(self::RANGE);

        if ($range !== null && preg_match(self::REGEX_RANGE, $range, $rm)) {
            // dojo.store.JsonRest style
            $offset = (int)$rm[1];
            $max = (int)$rm[2] - $offset + 1;
        } else {
            $max = $this->parse(self::$maxAlias, $params, PHP_INT_MAX);
            // Grails, ExtJS, dojox.data.QueryReadStore, all zero-based
            $offVal = $this->parse(self::$offsetAlias, $params, 0);
            if ($offVal > 0) {
                $offset = $offVal;
            } elseif (isset($params[self::START_INDEX])) {
            // OpenSearch style, 1-based
                $startIdx = isset($params[self::START_INDEX]) ? (int)$params[self::START_INDEX] : 0;
                if ($startIdx > 0) {
                    $offset = $startIdx - 1;
                }
            } elseif (isset($params[self::START_PAGE]) || isset($params[self::PAGE])) {
            // OpenSearch or Spring Data style, 1-based
                $startPage = $this->parse(self::$pageAlias, $params, 0);
                if ($startPage > 0) {
                    $offset = ($max * ($startPage - 1));
                }
            }
        }

        return new Pagination($max, $offset, $this->getOrder($request, $sortParameter, $defaultSort));
    }

    /**
     * Parses the order array.
     *
     * Because of the fact that many order syntaxes use multiple query string
     * parameters with the same name, it is absolutely *vital* that you do not
     * use a `ServerRequestInterface` that has been constructed with the `$_GET`
     * superglobal.
     *
     * The problem here is that PHP will overwrite entries in the `$_GET`
     * superglobal if they share the same name. With PHP, a request to
     * `file.php?foobar=foo&foobar=bar` will result in `$_GET` set to
     * `['foobar' => 'bar']`.
     *
     * Other platforms, like the Java Servlet specification, allow list-like
     * access to these parameters. Make sure the object you pass for `$request`
     * has a `queryParams` property that has been created to account for
     * multiple query parameters with the same name. The `QueryParams` class
     * will produce an array that accounts for this case.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request The request
     * @param string $sortParameter The sort parameter
     * @param array<string,bool> $default The default sort order
     * @return array<string,bool> String keys to boolean values
     */
    protected function getOrder(\Psr\Http\Message\ServerRequestInterface $request, string $sortParameter, array $default = []): array
    {
        $order = [];
        $params = $request->getQueryParams();
        if (isset($params[$sortParameter])) {
            if (isset($params[self::ORDER])) {
            // stupid Grails ordering
                $order[$params[$sortParameter]] = strcasecmp(self::DESC, $params[self::ORDER]) !== 0;
            } else {
                $param = $params[$sortParameter];
                foreach ((is_array($param) ? $param : [$param]) as $s) {
                    $this->parseSort($s, $order);
                }
            }
        } else {
            foreach (preg_grep(self::REGEX_DOJO_SORT, array_keys($params)) as $s) {
                // sort(+foo,-bar)
                $this->parseSort(substr($s, 5, -1), $order);
            }
        }
        return empty($order) ? $default : $order;
    }

    /**
     * Attempts to parse a single sort value.
     *
     * @param string $sort The sort value
     * @param array<string,bool> $sorts String keys to boolean values
     */
    protected function parseSort(string $sort, array &$sorts)
    {
        if (strlen(trim($sort)) === 0) {
            return;
        }
        if (substr($sort, 0, 1) == "[") {
            // it might be the ridiculous JSON ExtJS sort format
            $json = json_decode($sort);
            if (is_array($json)) {
                foreach ($json as $s) {
                    if (is_object($s)) {
                        $sorts[$s->property] = strcasecmp(self::DESC, $s->direction) !== 0;
                    }
                }
                return;
            }
        }
        if (substr($sort, -4) == ",asc") {
        // foo,asc
            $sorts[substr($sort, 0, strlen($sort) - 4)] = true;
        } elseif (substr($sort, -5) == ",desc") {
        // foo,desc
            $sorts[substr($sort, 0, strlen($sort) - 5)] = false;
        } elseif (substr($sort, -10) == ":ascending") {
        // foo:ascending
            $sorts[substr($sort, 0, strlen($sort) - 10)] = true;
        } elseif (substr($sort, -11) == ":descending") {
        // foo:descending
            $sorts[substr($sort, 0, strlen($sort) - 11)] = false;
        } else {
            foreach (explode(',', $sort) as $s) {
                if (substr($s, 0, 1) === '-') {
                // -foo
                    $sorts[substr($s, 1)] = false;
                } elseif (substr($s, 0, 1) === '+') {
                // +foo
                    $sorts[substr($s, 1)] = true;
                } else {
                // foo
                    $sorts[$s] = true;
                }
            }
        }
    }

    /**
     * Gets the first numeric value from `$params`, otherwise `$defaultValue`.
     *
     * @param array $names
     * @param array $params
     * @param int $defaultValue
     * @return int
     */
    protected function parse(array &$names, array &$params, int $defaultValue) : int
    {
        $value = array_reduce(array_intersect_key($params, $names), function ($carry, $item) {
            return $carry !== null ? $carry : (is_numeric($item) ? (int)$item : null);
        });
        return $value === null ? $defaultValue : $value;
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\filters;

use Yii;
use yii\base\ActionFilter;
use yii\base\Action;

/**
 * HttpCache implements client-side caching by utilizing the `Last-Modified` and `Etag` HTTP headers.
 *
 * It is an action filter that can be added to a controller and handles the `beforeAction` event.
 *
 * To use HttpCache, declare it in the `behaviors()` method of your controller class.
 * In the following example the filter will be applied to the `list`-action and
 * the Last-Modified header will contain the date of the last update to the user table in the database.
 *
 * ```php
 * public function behaviors()
 * {
 *     return [
 *         [
 *             'class' => 'yii\filters\HttpCache',
 *             'only' => ['index'],
 *             'lastModified' => function ($action, $params) {
 *                 $q = new \yii\db\Query();
 *                 return $q->from('user')->max('updated_at');
 *             },
 * //            'etagSeed' => function ($action, $params) {
 * //                return // generate etag seed here
 * //            }
 *         ],
 *     ];
 * }
 * ```
 *
 * @author Da:Sourcerer <webmaster@dasourcerer.net>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HttpCache extends ActionFilter
{
    /**
     * @var callable a PHP callback that returns the UNIX timestamp of the last modification time.
     * The callback's signature should be:
     *
     * ```php
     * function ($action, $params)
     * ```
     *
     * where `$action` is the [[Action]] object that this filter is currently handling;
     * `$params` takes the value of [[params]]. The callback should return a UNIX timestamp.
     */
    public $lastModified;
    /**
     * @var callable a PHP callback that generates the Etag seed string.
     * The callback's signature should be:
     *
     * ```php
     * function ($action, $params)
     * ```
     *
     * where `$action` is the [[Action]] object that this filter is currently handling;
     * `$params` takes the value of [[params]]. The callback should return a string serving
     * as the seed for generating an Etag.
     */
    public $etagSeed;
    /**
     * @var mixed additional parameters that should be passed to the [[lastModified]] and [[etagSeed]] callbacks.
     */
    public $params;
    /**
     * @var string the value of the `Cache-Control` HTTP header. If null, the header will not be sent.
     */
    public $cacheControlHeader = 'public, max-age=3600';
    /**
     * @var string the name of the cache limiter to be set when [session_cache_limiter()](http://www.php.net/manual/en/function.session-cache-limiter.php)
     * is called. The default value is an empty string, meaning turning off automatic sending of cache headers entirely.
     * You may set this property to be `public`, `private`, `private_no_expire`, and `nocache`.
     * Please refer to [session_cache_limiter()](http://www.php.net/manual/en/function.session-cache-limiter.php)
     * for detailed explanation of these values.
     *
     * If this property is `null`, then `session_cache_limiter()` will not be called. As a result,
     * PHP will send headers according to the `session.cache_limiter` PHP ini setting.
     */
    public $sessionCacheLimiter = '';
    /**
     * @var boolean a value indicating whether this filter should be enabled.
     */
    public $enabled = true;

    /**
     * This method is invoked right before an action is to be executed (after all possible filters.)
     * You may override this method to do last-minute preparation for the action.
     * @param Action $action the action to be executed.
     * @return boolean whether the action should continue to be executed.
     */
    public function beforeAction($action)
    {
        if (!$this->enabled) {
            return true;
        }

        $verb = Yii::$app->getRequest()->getMethod();
        if ($verb !== 'GET' && $verb !== 'HEAD' || $this->lastModified === null && $this->etagSeed === null) {
            return true;
        }

        $lastModified = $etag = null;
        if ($this->lastModified !== null) {
            $lastModified = call_user_func($this->lastModified, $action, $this->params);
        }
        if ($this->etagSeed !== null) {
            $seed = call_user_func($this->etagSeed, $action, $this->params);
            $etag = $this->generateEtag($seed);
        }

        $this->sendCacheControlHeader();

        $response = Yii::$app->getResponse();
        if ($etag !== null) {
            $response->getHeaders()->set('Etag', $etag);
        }

        if ($this->validateCache($lastModified, $etag)) {
            $response->setStatusCode(304);
            return false;
        }

        if ($lastModified !== null) {
            $response->getHeaders()->set('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
        }

        return true;
    }

    /**
     * Validates if the HTTP cache contains valid content.
     * @param integer $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
     * If null, the Last-Modified header will not be validated.
     * @param string $etag the calculated ETag value. If null, the ETag header will not be validated.
     * @return boolean whether the HTTP cache is still valid.
     */
    protected function validateCache($lastModified, $etag)
    {
        if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
            // http://tools.ietf.org/html/rfc7232#section-3.3
            return $etag !== null && in_array($etag, Yii::$app->request->getEtags(), true);
        } elseif (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
            return $lastModified !== null && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified;
        } else {
            return $etag === null && $lastModified === null;
        }
    }

    /**
     * Sends the cache control header to the client
     * @see cacheControlHeader
     */
    protected function sendCacheControlHeader()
    {
        if ($this->sessionCacheLimiter !== null) {
            if ($this->sessionCacheLimiter === '' && !headers_sent() && Yii::$app->getSession()->getIsActive()) {
                header_remove('Expires');
                header_remove('Cache-Control');
                header_remove('Last-Modified');
                header_remove('Pragma');
            }
            session_cache_limiter($this->sessionCacheLimiter);
        }

        $headers = Yii::$app->getResponse()->getHeaders();
        $headers->set('Pragma');

        if ($this->cacheControlHeader !== null) {
            $headers->set('Cache-Control', $this->cacheControlHeader);
        }
    }

    /**
     * Generates an Etag from the given seed string.
     * @param string $seed Seed for the ETag
     * @return string the generated Etag
     */
    protected function generateEtag($seed)
    {
        return '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
    }
}


<?php

namespace DdvPhp\DdvRestfulApi\Lib;

use DdvPhp\DdvRestfulApi\Interfaces\RequestHeaders as RequestHeadersInterfaces;

class RequestHeaders implements RequestHeadersInterfaces
{
    // 请求头
    protected $headers = array();
    // 最后一次设置的头信息
    protected $lastSetHeaders = array();
    // app请求标识
    protected $headersPrefix = 'x-ddv-';
    // 授权头
    protected $authorization = '';
    // 主机头
    protected $host = '';
    // 主机头、不带端口
    protected $hostname = '';
    // 自定义头的keys
    protected $xHeadersKeys = [];
    // 系统头的keys
    protected $sysHeadersKeys = [];

    // 获取头信息前缀
    public function getHeadersPrefix()
    {
        return $this->headersPrefix;
    }

    public function __construct($headers = array())
    {
        $this->setHeaders($headers);
    }

    /**
     * 设置头信息前缀
     * @param null $headersPrefix
     * @return $this
     */
    public function setHeadersPrefix($headersPrefix = null)
    {
        $this->headersPrefix = is_null($headersPrefix) ? $this->headersPrefix : $headersPrefix;
        // 需要重新解析
        $this->parseHeaders();
        return $this;
    }

    // 获取头信息[授权的]
    public function getAuthorization()
    {
        return $this->authorization;
    }

    // 获取头信息[Host的]
    public function getHost()
    {
        return $this->host;
    }

    // 获取头信息[hostname，不带端口]
    public function getHostName()
    {
        return $this->hostname;
    }

    public function getHeader($key)
    {
        $keyt = $this->getHeaderKey($key, $this->headers);
        if (!empty($keyt)) {
            return $this->headers[$keyt];
        }
        return null;
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function getXHeadersKeys()
    {
        return $this->xHeadersKeys;
    }

    public function getSysHeadersKeys()
    {
        return $this->sysHeadersKeys;
    }

    // 获取头信息[自定义]
    public function getXHeaders()
    {
        $r = [];
        foreach ($this->xHeadersKeys as $key) {
            if (isset($this->headers[$key])) {
                $r[$key] = $this->headers[$key];
            }
        }
        return $r;

    }

    // 获取头信息[系统]
    public function getSysHeaders()
    {
        $r = [];
        foreach ($this->sysHeadersKeys as $key) {
            if (isset($this->headers[$key])) {
                $r[$key] = $this->headers[$key];
            }
        }
        return $r;
    }

    /**
     * 重置头
     * @param $headers
     * @return $this
     */
    public function setHeaders($headers)
    {
        if (!is_array($headers)) {
            $headers = array();
        }
        $this->lastSetHeaders = $headers;
        $this->headers = $this->parseHeaders();
        return $this;

    }

    protected function parseHeaders($headers = null)
    {
        if (empty($headers)) {
            $headers = $this->lastSetHeaders;
        }
        if (!is_array($headers)) {
            $headers = array();
        }

        // 前缀
        $headersPrefix = str_replace('-', '_', strtolower($this->getHeadersPrefix()));
        //所有headers参数传输的前缀
        $headersPrefixLen = strlen($headersPrefix);
        // http_长度
        $httpPrefixlen = strlen('http_');
        // 主机头
        $host = $this->parseHost($headers);
        // 授权头
        $authorization = $this->parseAuthorization($headers);
        // 授权头
        if (!empty($authorization)) {
            $this->authorization = $authorization;
        }
        // 主机头
        if (!empty($host)) {
            $this->host = $host;
            //试图去除端口
            try {
                $parseUrlTemp = parse_url($host);
                $hostname = isset($parseUrlTemp['host']) ? $parseUrlTemp['host'] : $host;
                unset($parseUrlTemp);
            } catch (Exception $e) {
                $hostname = $host;
            }
            $this->hostname = $hostname;
            unset($hostname);
        }

        $xHeadersKeys = [];
        $sysHeadersKeys = [];

        // 主机头保存
        $hostKey = $this->getHeaderKey('host', $headers, 'Host');
        if ($host) {
            $headers[$hostKey] = $host;
            $sysHeadersKeys[] = $hostKey;
        }

        // Content-Type
        $ContentTypeKey = $this->getHeaderKey('content-type', $headers, 'Content-Type');
        $ContentType = $this->parseContentType($headers);
        if (!empty($ContentType)) {
            $headers[$ContentTypeKey] = $ContentType;
            $sysHeadersKeys[] = $ContentTypeKey;
        }

        // Content-Md5
        $ContentMd5Key = $this->getHeaderKey('content-md5', $headers, 'Content-Md5');
        $ContentMd5 = $this->parseTryByKey('content-md5', $headers);
        if (!empty($ContentMd5)) {
            $headers[$ContentMd5Key] = $ContentMd5;
            $sysHeadersKeys[] = $ContentMd5Key;
        }

        // Content-Md5
        $ContentLengthKey = $this->getHeaderKey('content-length', $headers, 'Content-Length');
        $ContentLength = $this->parseTryByKey('content-length', $headers);
        if (!empty($ContentLength)) {
            $headers[$ContentLengthKey] = $ContentLength;
            $sysHeadersKeys[] = $ContentLengthKey;
        }

        foreach ($headers as $keyt => $value) {
            $keytLower = strtolower($keyt);
            if (substr($keytLower, 0, $headersPrefixLen) == $headersPrefix) {
                $headers[$keyt] = $value;
                $xHeadersKeys[] = $keyt;
            }
            unset($keytLower);
        }
        foreach ($_SERVER as $keyot => $value) {
            $keyt = substr($keyot, $httpPrefixlen);
            $keytLower = strtolower($keyt);
            if (substr($keytLower, 0, $headersPrefixLen) == $headersPrefix) {
                if (!$this->getHeaderKey($keyt, $headers)) {
                    $headers[$keyt] = $value;
                    $xHeadersKeys[] = $keyt;
                }
            }
            unset($keyt, $keytLower);
        }
        $this->xHeadersKeys = $xHeadersKeys;
        $this->sysHeadersKeys = $sysHeadersKeys;
        unset($headersPrefix, $headersPrefixLen, $httpPrefixlen, $host, $authorization, $xHeadersKeys, $sysHeadersKeys, $hostKey, $ContentTypeKey, $ContentType, $ContentMd5Key, $ContentMd5, $ContentLengthKey, $ContentLength);
        //返回
        return $headers;
    }

    protected function parseContentType($headers = array())
    {
        // 主机头
        $contentType = '';
        // 试图直接请求头读取
        if (isset($headers['content-type'])) {
            $contentType = $headers['content-type'];
        }
        // 试图通过  获取
        if (empty($contentType)) {
            $contentType = $this->parseTryByKey('content-type', $headers);
        }
        if (isset($contentType) && strpos($contentType, 'multipart/restful-form-data') !== false) {
            if (isset($_SERVER['REDIRECT_RESTFUL_MULTIPART_TYPE'])) {
                $contentType = $_SERVER['REDIRECT_RESTFUL_MULTIPART_TYPE'];
            }
        }
        if (isset($contentType) && strpos($contentType, 'multipart/restful-form-data') !== false) {
            if (isset($_SERVER['REDIRECT_HTTP_CONTENT_TYPE'])) {
                $contentType = $_SERVER['REDIRECT_HTTP_CONTENT_TYPE'];
            }
        }
        return $contentType;
    }

    protected function parseHost($headers = array())
    {
        // 主机头
        $host = '';
        // 试图直接请求头读取
        if (isset($headers['host'])) {
            $host = $headers['host'];
        }
        // 试图通过  获取
        if (empty($host)) {
            $host = $this->parseTryByKey('host', $headers);
        }
        return $host;
    }

    protected function parseAuthorization($headers = array())
    {
        // 授权头
        $authorization = '';
        $urlPrefix = $this->getHeadersPrefix();
        if (empty($authorization) && !empty($_GET[$urlPrefix . 'authorization'])) {
            $authorization = $_GET[$urlPrefix . 'authorization'];
            unset($_GET[$urlPrefix . 'authorization']);
        }
        if (empty($authorization) && !empty($_GET[$urlPrefix . 'auth'])) {
            $authorization = $_GET[$urlPrefix . 'auth'];
            unset($_GET[$urlPrefix . 'auth']);
        }
        // 试图直接请求头读取
        if (empty($authorization) && isset($headers['authorization'])) {
            $authorization = $headers['authorization'];
        }
        // 试图通过 HTTP_AUTHORIZATION 获取
        if (empty($authorization)) {
            $authorization = $this->parseTryByKey('authorization', $headers);
        }
        return $authorization;
    }

    public function getHeaderKey($key, $headers = null, $defaultValue = null)
    {
        if (!is_array($headers)) {
            $headers = $this->headers;
        }
        $keyLower = str_replace('-', '_', strtolower($key));
        // 试图通过 HTTP_AUTHORIZATION 获取
        foreach ($headers as $keyt => $value) {
            $keytLower = str_replace('-', '_', strtolower($keyt));
            if ($keytLower === $keyLower || $keytLower === ('http_' . $keyLower)) {
                return empty($keyt) ? $defaultValue : $keyt;
            }
        }
        return $defaultValue;
    }

    protected function parseTryByKey($key, $headers = array())
    {
        // 主机头
        $res = '';
        $keyLower = str_replace('-', '_', strtolower($key));
        $keyUpper = str_replace('-', '_', strtoupper($key));
        // 试图直接请求头读取
        if (empty($res) && isset($headers[$key])) {
            $res = $headers[$key];
        }
        // 试图通过 大写下滑杆 获取
        if (empty($res)) {
            foreach ($headers as $keyt => $value) {
                $keytLower = str_replace('-', '_', strtolower($keyt));
                if ($keytLower === $keyLower || $keytLower === ('http_' . $keyLower)) {
                    $res = $value;
                }
            }
        }
        // 试图 apache_request_headers 获取
        if (empty($res)) {
            if (function_exists('apache_request_headers')) {
                foreach (apache_request_headers() as $keyt => $value) {
                    $keytLower = str_replace('-', '_', strtolower($keyt));
                    if ($keytLower === $keyLower && !empty($value)) {
                        $res = $value;
                    }
                }
            }
        }
        // 试图 $_SERVER['HTTP_AUTHORIZATION'] 获取
        if (empty($res) && isset($_SERVER) && isset($_SERVER[('HTTP_' . $keyUpper)])) {
            $res = $_SERVER[('HTTP_' . $keyUpper)];
        }
        return $res;
    }

}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use Yii;
use yii\base\InvalidRouteException;

/**
 * Application is the base class for all web application classes.
 *
 * @property string $homeUrl The homepage URL.
 * @property Session $session The session component. This property is read-only.
 * @property User $user The user component. This property is read-only.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Application extends \yii\base\Application
{
    /**
     * @var string the default route of this application. Defaults to 'site'.
     */
    public $defaultRoute = 'site';
    /**
     * @var array the configuration specifying a controller action which should handle
     * all user requests. This is mainly used when the application is in maintenance mode
     * and needs to handle all incoming requests via a single action.
     * The configuration is an array whose first element specifies the route of the action.
     * The rest of the array elements (key-value pairs) specify the parameters to be bound
     * to the action. For example,
     *
     * ```php
     * [
     *     'offline/notice',
     *     'param1' => 'value1',
     *     'param2' => 'value2',
     * ]
     * ```
     *
     * Defaults to null, meaning catch-all is not used.
     */
    public $catchAll;
    /**
     * @var Controller the currently active controller instance
     */
    public $controller;

    /**
     * @inheritdoc
     */
    protected function bootstrap()
    {
        $request = $this->getRequest();
        Yii::setAlias('@webroot', dirname($request->getScriptFile()));
        Yii::setAlias('@web', $request->getBaseUrl());

        parent::bootstrap();
    }

    /**
     * Handles the specified request.
     * @param Request $request the request to be handled
     * @return Response the resulting response
     * @throws NotFoundHttpException if the requested route is invalid
     */
    public function handleRequest($request)
    {
        if (empty($this->catchAll)) {
            list ($route, $params) = $request->resolve();
        } else {
            $route = $this->catchAll[0];
            $params = $this->catchAll;
            unset($params[0]);
        }
        try {
            Yii::trace("Route requested: '$route'", __METHOD__);
            $this->requestedRoute = $route;
            $result = $this->runAction($route, $params);
            if ($result instanceof Response) {
                return $result;
            } else {
                $response = $this->getResponse();
                if ($result !== null) {
                    $response->data = $result;
                }

                return $response;
            }
        } catch (InvalidRouteException $e) {
            throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'), $e->getCode(), $e);
        }
    }

    private $_homeUrl;

    /**
     * @return string the homepage URL
     */
    public function getHomeUrl()
    {
        if ($this->_homeUrl === null) {
            if ($this->getUrlManager()->showScriptName) {
                return $this->getRequest()->getScriptUrl();
            } else {
                return $this->getRequest()->getBaseUrl() . '/';
            }
        } else {
            return $this->_homeUrl;
        }
    }

    /**
     * @param string $value the homepage URL
     */
    public function setHomeUrl($value)
    {
        $this->_homeUrl = $value;
    }

    /**
     * Returns the session component.
     * @return Session the session component.
     */
    public function getSession()
    {
        return $this->get('session');
    }

    /**
     * Returns the user component.
     * @return User the user component.
     */
    public function getUser()
    {
        return $this->get('user');
    }

    /**
     * @inheritdoc
     */
    public function coreComponents()
    {
        return array_merge(parent::coreComponents(), [
            'request' => ['class' => 'yii\web\Request'],
            'response' => ['class' => 'yii\web\Response'],
            'session' => ['class' => 'yii\web\Session'],
            'user' => ['class' => 'yii\web\User'],
            'errorHandler' => ['class' => 'yii\web\ErrorHandler'],
        ]);
    }
}


<?php

namespace AscensoDigital\PerfilBundle\Entity;

use AscensoDigital\PerfilBundle\Model\UserInterface;
use Cocur\Slugify\Slugify;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Archivo
 *
 * @ORM\Table(name="ad_perfil_archivo")
 * @ORM\Entity
 */
class Archivo
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\SequenceGenerator(sequenceName="archivo_id_seq", allocationSize=1, initialValue=1)
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titulo", type="string", length=255, nullable=true)
     */
    protected $titulo;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha_publicacion", type="datetime", nullable=true)
     */
    protected $fechaPublicacion;

    /**
     * @var string
     *
     * @ORM\Column(name="ruta", type="string", length=255, nullable=true)
     */
    protected $ruta;

    /**
     * @var boolean
     *
     * @ORM\Column(name="visible", type="boolean", nullable=false)
     */
    protected $visible = false;

    /**
     * @var string
     *
     * @ORM\Column(name="mime_type", type="string", length=200, nullable=true)
     */
    protected $mimeType;

    /**
     * @var UploadedFile $file
     * @Assert\NotBlank
     */
    protected $file;

    /**
     * @var UserInterface
     *
     * @ORM\ManyToOne(targetEntity="AscensoDigital\PerfilBundle\Model\UserInterface")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="creador_id", referencedColumnName="id")
     * })
     */
    protected $creador;

    public function __toString()
    {
        return $this->getTitulo();
    }

    public function getArraySerialize(){
        $ret = array();
        $ret['titulo'] = $this->getTitulo();
        $ret['id'] = $this->getId();

        return $ret;
    }

    public function getExtensionOriginal() {
        if(is_null($this->file)) {
            return '';
        }
        $nombreOriginal=$this->getFile()->getClientOriginalName();
        $arr=explode('.',$nombreOriginal);
        return '.'.$arr[count($arr)-1];
    }

    public function getNombre(){
        $get_nombre = explode("/", $this->getRuta());
        return array_pop($get_nombre);
    }

    public function getPath() {
        return $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $this->getRuta();
    }

    public function getUploadDir()
    {
        return 'uploads';
    }

    public function getUploadRootDir() {
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    /**
     * @param $directorio
     * @param $nombre
     * @param $file
     * @param bool|false $visible
     */
    public function saveFile($directorio, $nombre, $file, $visible = false)
    {
        $targetDir = $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $directorio;
        $fs = new Filesystem();
        $nombreArray=explode('.',$nombre);
        $extension=array_pop($nombreArray);
        $slugify = new Slugify();
        $nombre=$slugify->slugify(implode('.',$nombreArray)).'.'.$extension;
        $archivo = $targetDir . DIRECTORY_SEPARATOR . $nombre;

        try {
            $fs->dumpFile($archivo, $file);
        } catch (IOException $e) {
            echo "Se ha producido un error al crear el archivo ".$e->getPath();
        }
        $this->setRuta($directorio . DIRECTORY_SEPARATOR . $nombre);
        $this->visible = $visible;
    }

    /**
     * Upload archivo
     */
    public function upload($directorio, $nombre, $visible = false)
    {
        if(null === $this->file) {
            return false;
        }

        $targetDir = $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $directorio;
        $extension=$this->getExtensionOriginal();
        $nombreArray=explode('.',$nombre);
        $extNombre='.'.$nombreArray[count($nombreArray)-1];
        if($extNombre==$extension){
            array_pop($nombreArray);
        }
        $slugify = new Slugify();
        $nombre=$slugify->slugify(implode('.',$nombreArray)).$extension;
        $this->file->move($targetDir, $nombre);

        $this->setRuta($directorio . DIRECTORY_SEPARATOR . $nombre);
        $this->setMimeType($this->file->getClientMimeType());
        $this->visible = $visible;
        return $nombre;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titulo
     *
     * @param string $titulo
     * @return Archivo
     */
    public function setTitulo($titulo)
    {
        $this->titulo = $titulo;

        return $this;
    }

    /**
     * Get titulo
     *
     * @return string
     */
    public function getTitulo()
    {
        return $this->titulo;
    }

    /**
     * Set fechaPublicacion
     *
     * @param \DateTime $fechaPublicacion
     * @return Archivo
     */
    public function setFechaPublicacion($fechaPublicacion)
    {
        $this->fechaPublicacion = $fechaPublicacion;

        return $this;
    }

    /**
     * Get fechaPublicacion
     *
     * @return \DateTime
     */
    public function getFechaPublicacion()
    {
        return $this->fechaPublicacion;
    }

    /**
     * Set ruta
     *
     * @param string $ruta
     * @return Archivo
     */
    public function setRuta($ruta)
    {
        $this->ruta = $ruta;

        return $this;
    }

    /**
     * Get ruta
     *
     * @return string
     */
    public function getRuta()
    {
        return $this->ruta;
    }

    /**
     * Set visible
     *
     * @param boolean $visible
     * @return Archivo
     */
    public function setVisible($visible)
    {
        $this->visible = $visible;

        return $this;
    }

    /**
     * Get visible
     *
     * @return boolean
     */
    public function getVisible()
    {
        return $this->visible;
    }

    /**
     * Set mimeType
     *
     * @param string $mimeType
     * @return Archivo
     */
    public function setMimeType($mimeType)
    {
        $this->mimeType = $mimeType;

        return $this;
    }

    /**
     * Get mimeType
     *
     * @return string
     */
    public function getMimeType()
    {
        return $this->mimeType;
    }

    /**
     * Set creador
     *
     * @param UserInterface $creador
     * @return Archivo
     */
    public function setCreador(UserInterface $creador = null)
    {
        $this->creador = $creador;

        return $this;
    }

    /**
     * Get creador
     *
     * @return UserInterface
     */
    public function getCreador()
    {
        return $this->creador;
    }

    /**
     * Sets file
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        $this->setFechaPublicacion(new \DateTime());
    }

    /**
     * Get file
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }
}


<?php

namespace Floppy\Common;

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Floppy\Common\Stream\InputStream;
use Floppy\Common\Stream\LazyLoadedInputStream;

final class FileSource implements HasFileInfo
{
    private $stream;
    private $fileType;
    private $info;

    /**
     * @param \SplFileInfo $file
     *
     * @return FileSource
     */
    public static function fromFile(\SplFileInfo $file)
    {
        $extension = $file instanceof UploadedFile ? $file->getClientOriginalExtension() : self::getExtension($file);

        return new self(new LazyLoadedInputStream($file->getPathname()), new FileType(self::guessMimeType($file), strtolower($extension)));
    }

    private static function guessMimeType(\SplFileInfo $file)
    {
        if($file instanceof File) {
            return $file->getMimeType();
        }

        if(function_exists('finfo_open')) {
            $finfo = new \finfo(\FILEINFO_MIME_TYPE);

            return $finfo->file($file->getPathname());
        }

        return 'application/octet-stream';
    }

    private static function getExtension(\SplFileInfo $file)
    {
        if(\is_callable(array($file, 'getExtension'))) {
            return $file->getExtension();
        }

        //fallback for < php 5.3.6
        return \pathinfo($file->getBasename(), PATHINFO_EXTENSION);
    }

    public function __construct(InputStream $stream, FileType $fileType = null, array $info = array())
    {
        $this->stream = $stream;
        $this->fileType = $fileType ?: new FileType(null, null);
        $this->info = new AttributesBag($info);
    }

    /**
     * @return FileType
     */
    public function fileType()
    {
        return $this->fileType;
    }

    /**
     * @return string
     */
    public function content()
    {
        return $this->stream->read();
    }

    public function filepath()
    {
        return $this->stream->filepath();
    }

    public function discard()
    {
        $this->stream->close();
    }

    /**
     * @return AttributesBag
     */
    public function info()
    {
        return $this->info;
    }

    /**
     * @param array $info
     * @return FileSource
     */
    public function withInfo(array $info)
    {
        return new self($this->stream, $this->fileType, $info);
    }
}