<?php

/**
 * This file is part of Vegas package
 *
 * @author Adrian Malik <adrian.malik.89@gmail.com>
 * @copyright Amsterdam Standard Sp. Z o.o.
 * @homepage https://bitbucket.org/amsdard/vegas-phalcon
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vegas\Media;

use \Vegas\Media\Swf\Exception\InvalidSourceExtensionException;

class Swf
{
    /**
     * Constant extension for swf files
     */
    CONST SOURCE_EXTENSION = 'swf';

    /**
     * Source of the swf file
     *
     * @var string
     */
    private $source = '';

    /**
     * Width of the html element
     *
     * @var string
     */
    private $width = '100%';

    /**
     * Height of the html element
     *
     * @var string
     */
    private $height = '100%';

    /**
     * Embed tag decorator
     *
     * @var string
     */
    private $embedDecorator = '<embed width="%s" height="%s" src="%s"></embed>';

    /**
     * Object tag decorator
     *
     * @var string
     */
    private $objectDecorator = '<object width="%s" height="%s" data="%s"></object>';

    /**
     * Constructs the swf object
     *
     * @param array $params
     */
    public function construct(array $params = array()) {}

    /**
     * Sets source of the .swf file
     *
     * @param string $source
     * @throws Swf\Exception\InvalidSourceExtensionException
     * @return $this;
     */
    public function setSource($source = '')
    {
        if(!$this->isValid($source)) {
            throw new InvalidSourceExtensionException();
        }

        $this->source = $source;

        return $this;
    }

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

    /**
     * Sets width attribute
     *
     * @param $width
     * @return $this
     */
    public function setWidth($width)
    {
        $this->width = (string) $width;

        return $this;
    }

    /**
     * Sets height attribute
     *
     * @param $height
     * @return $this
     */
    public function setHeight($height)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * Returns embed decorator
     *
     * @return string
     */
    public function getEmbedDecorator()
    {
        return $this->embedDecorator;
    }

    /**
     * Returns object decorator
     *
     * @return string
     */
    public function getObjectDecorator()
    {
        return $this->objectDecorator;
    }

    /**
     * Checks if the source has allowed extension
     *
     * @param string $source
     * @return bool
     */
    private function isValid($source = '')
    {
        if(empty($source)) {
            return false;
        } else {
            $extension = substr($source, -3);

            if(strtolower($extension) !== 'swf') {
                return false;
            }
        }

        return true;
    }

    /**
     * Renders the embed tag html with attached source
     *
     * @return string
     * @throws Swf\Exception\InvalidSourceExtensionException
     */
    public function renderEmbed()
    {
        if(!$this->isValid($this->source)) {
            throw new InvalidSourceExtensionException();
        }

        return sprintf($this->embedDecorator, $this->width, $this->height, $this->source);
    }

    /**
     * Renders the object tag html with attached source
     *
     * @return string
     * @throws Swf\Exception\InvalidSourceExtensionException
     */
    public function renderObject()
    {
        if(!$this->isValid($this->source)) {
            throw new InvalidSourceExtensionException();
        }

        return sprintf($this->objectDecorator, $this->width, $this->height, $this->source);
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;

/**
 * User authentication controller
 */
class AuthController extends Controller
{
    /**
     * Displays a form to login
     *
     * @Template
     */
    public function loginAction(Request $request)
    {
        $session = $request->getSession();

        $form = $this->createFormBuilder()
            ->add('username', TextType::class, array('label' => 'Username'))
            ->add('password', PasswordType::class, array('label' => 'Password'))
            ->add('rememberMe', CheckboxType::class, array('label' => 'Remember Me', 'required' => false))
            ->getForm();

        $helper = $this->get('security.authentication_utils');
        if ($lastUsername = $helper->getLastUsername()) {
            $form->setData(array('username' => $lastUsername));
        }

        return array(
            'form' => $form->createView()
        );
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Orkestra\Bundle\ApplicationBundle\Entity\Group;

/**
 * Loads default group data
 */
class GroupData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param \Doctrine\Common\Persistence\ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        // Normal user
        $group = new Group();
        $group->setName('User');
        $group->setRole('ROLE_USER');
        $manager->persist($group);
        $this->addReference('user-group', $group);

        // Administrator
        $group = new Group();
        $group->setName('Administrator');
        $group->setRole('ROLE_ADMIN');
        $manager->persist($group);
        $this->addReference('admin-group', $group);

        $manager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 1;
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Entity\Contact;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Orkestra\Bundle\ApplicationBundle\Model\Contact\CountryInterface;
use Orkestra\Bundle\ApplicationBundle\Model\Contact\RegionInterface;
use Orkestra\Common\Entity\AbstractEntity;

/**
 * A country
 *
 * @ORM\Entity
 * @ORM\Table(name="orkestra_countries")
 */
class Country extends AbstractEntity implements CountryInterface
{
    /**
     * @var string $name
     *
     * @ORM\Column(name="name", type="string", length=60)
     */
    protected $name;

    /**
     * @var string $code The ISO 3166-1 2 letter code
     *
     * @ORM\Column(name="code", type="string", length=10)
     */
    protected $code;

    /**
     * @var string $longCode The ISO 3166-2 3 letter code
     *
     * @ORM\Column(name="long_code", type="string", length=10)
     */
    protected $longCode;

    /**
     * @var \Doctrine\Common\Collections\Collection Collection of region entities
     *
     * @ORM\OneToMany(targetEntity="Orkestra\Bundle\ApplicationBundle\Model\Contact\RegionInterface", mappedBy="country", cascade={"persist"})
     */
    protected $regions;

    /**
     * Constructor
     *
     * @param string $name     The name of the country
     * @param string $code     The 2-letter ISO abbreviation
     * @param string $longCode The 3-letter ISO abbreviation
     */
    public function __construct($name = '', $code = '', $longCode = '')
    {
        $this->regions = new ArrayCollection();

        if (!empty($name)) { $this->name = $name; }
        if (!empty($code)) { $this->code = $code; }
        if (!empty($longCode)) { $this->longCode = $longCode; }
    }

    /**
     * @return string The name of the country
     */
    public function __toString()
    {
        return sprintf('%s', $this->getName());
    }

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

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

    /**
     * Set code
     *
     * @param string $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

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

    /**
     * Set longCode
     *
     * @param string $longCode
     */
    public function setLongCode($longCode)
    {
        $this->longCode = $longCode;
    }

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

    /**
     * Add a region to this country
     *
     * @param \Orkestra\Bundle\ApplicationBundle\Model\Contact\RegionInterface $region
     */
    public function addRegion(RegionInterface $region)
    {
        $region->setCountry($this);
        $this->regions->add($region);
    }

    /**
     * Get regions
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getRegions()
    {
        return $this->regions;
    }
}


<?php
/**
 * @license MIT
 */
namespace Pivasic\Bundle\Common\File\MimeType;

use Pivasic\Bundle\Common\File\Exception\FileNotFoundException;
use Pivasic\Bundle\Common\File\Exception\AccessDeniedException;

/**
 * Class MimeTypeGuesser
 * @package Pivasic\Bundle\Common\File\MimeType
 */
class MimeType
{
    /**
     * Returns the singleton instance.
     *
     * @return MimeType
     */
    public static function getInstance(): MimeType
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Get mime type or NULL, if none could be guessed.
     *
     * @param string $path Path to the file
     * @return string
     * @throws \LogicException
     * @throws FileNotFoundException
     * @throws AccessDeniedException
     */
    public function guess(string $path): string
    {
        if (!is_file($path)) {
            throw new FileNotFoundException($path);
        }

        if (!is_readable($path)) {
            throw new AccessDeniedException($path);
        }

        if (0 == count($this->guesserList)) {
            $msg = 'Unable to guess the mime type as no guessers are available';
            if (!FileInfoMimeType::isSupported()) {
                $msg .= ' (Did you enable the php_fileinfo extension?)';
            }
            throw new \LogicException($msg);
        }

        /** @var FileInfoMimeType|BinaryMimeType $guesser */
        foreach ($this->guesserList as $guesser) {
            if ('' != $mimeType = $guesser->guess($path)) {
                return $mimeType;
            }
        }

        return '';
    }

    /**
     * Registers all natively provided mime type guessers.
     */
    private function __construct()
    {
        $this->guesserList = [];

        if (FileInfoMimeType::isSupported()) {
            $this->guesserList[] = new FileInfoMimeType();
        }
        if (BinaryMimeType::isSupported()) {
            $this->guesserList[] = new BinaryMimeType();
        }
    }

    /**
     * @var MimeType
     */
    private static $instance = null;

    private $guesserList;
}


<?php

/**
 * TechDivision\Import\Product\Media\Ee\Services\EeProductMediaProcessor
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * PHP version 5
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media
 * @link      http://www.techdivision.com
 */

namespace TechDivision\Import\Product\Media\Ee\Services;

use TechDivision\Import\Actions\ActionInterface;
use TechDivision\Import\Connection\ConnectionInterface;
use TechDivision\Import\Product\Media\Services\ProductMediaProcessor;
use TechDivision\Import\Product\Media\Repositories\ProductMediaGalleryRepositoryInterface;
use TechDivision\Import\Product\Media\Ee\Repositories\ProductMediaGalleryValueRepositoryInterface;
use TechDivision\Import\Product\Media\Ee\Repositories\ProductMediaGalleryValueToEntityRepositoryInterface;

/**
 * A processor implementation that provides media import functionality for the Magento 2 EE.
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media
 * @link      http://www.techdivision.com
 */
class EeProductMediaProcessor extends ProductMediaProcessor implements EeProductMediaProcessorInterface
{

    /**
     * Initialize the processor with the necessary assembler and repository instances.
     *
     * @param \TechDivision\Import\Connection\ConnectionInterface                                                    $connection                                 The connection to use
     * @param \TechDivision\Import\Product\Media\Repositories\ProductMediaGalleryRepositoryInterface                 $productMediaGalleryRepository              The product media gallery repository to use
     * @param \TechDivision\Import\Product\Media\Ee\Repositories\ProductMediaGalleryValueRepositoryInterface         $productMediaGalleryValueRepository         The product media gallery value repository to use
     * @param \TechDivision\Import\Product\Media\Ee\Repositories\ProductMediaGalleryValueToEntityRepositoryInterface $productMediaGalleryValueToEntityRepository The product media gallery value to entity repository to use
     * @param \TechDivision\Import\Actions\ActionInterface                                                           $productMediaGalleryAction                  The product media gallery action to use
     * @param \TechDivision\Import\Actions\ActionInterface                                                           $productMediaGalleryValueAction             The product media gallery value action to use
     * @param \TechDivision\Import\Actions\ActionInterface                                                           $productMediaGalleryValueToEntityAction     The product media gallery value to entity action to use
     * @param \TechDivision\Import\Actions\ActionInterface                                                           $productMediaGalleryValueVideoAction        The product media gallery value video action to use
     */
    public function __construct(
        ConnectionInterface $connection,
        ProductMediaGalleryRepositoryInterface $productMediaGalleryRepository,
        ProductMediaGalleryValueRepositoryInterface $productMediaGalleryValueRepository,
        ProductMediaGalleryValueToEntityRepositoryInterface $productMediaGalleryValueToEntityRepository,
        ActionInterface $productMediaGalleryAction,
        ActionInterface $productMediaGalleryValueAction,
        ActionInterface $productMediaGalleryValueToEntityAction,
        ActionInterface $productMediaGalleryValueVideoAction
    ) {
        $this->setConnection($connection);
        $this->setProductMediaGalleryRepository($productMediaGalleryRepository);
        $this->setProductMediaGalleryValueRepository($productMediaGalleryValueRepository);
        $this->setProductMediaGalleryValueToEntityRepository($productMediaGalleryValueToEntityRepository);
        $this->setProductMediaGalleryAction($productMediaGalleryAction);
        $this->setProductMediaGalleryValueAction($productMediaGalleryValueAction);
        $this->setProductMediaGalleryValueToEntityAction($productMediaGalleryValueToEntityAction);
        $this->setProductMediaGalleryValueVideoAction($productMediaGalleryValueVideoAction);
    }

    /**
     * Load's the product media gallery with the passed value/row ID.
     *
     * @param integer $valueId The value ID of the product media gallery value to entity to load
     * @param integer $rowId   The row ID of the product media gallery value to entity to load
     *
     * @return array The product media gallery
     */
    public function loadProductMediaGalleryValueToEntityByValueIdAndRowId($valueId, $rowId)
    {
        return $this->getProductMediaGalleryValueToEntityRepository()->findOneByValueIdAndRowId($valueId, $rowId);
    }

    /**
     * Load's the product media gallery value with the passed value/store/row ID.
     *
     * @param integer $valueId The value ID of the product media gallery value to load
     * @param string  $storeId The store ID of the product media gallery value to load
     * @param string  $rowId   The row ID of the parent product of the product media gallery value to load
     *
     * @return array The product media gallery value
     */
    public function loadProductMediaGalleryValueByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId)
    {
        return $this->getProductMediaGalleryValueRepository()->findOneByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId);
    }
}


<?php

/**
 * TechDivision\Import\Product\Media\Ee\Repositories\ProductMediaGalleryValueRepository
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * PHP version 5
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */

namespace TechDivision\Import\Product\Media\Ee\Repositories;

use TechDivision\Import\Product\Media\Ee\Utils\MemberNames;
use TechDivision\Import\Product\Media\Ee\Utils\SqlStatementKeys;

/**
 * Repository implementation to load product media gallery value data.
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */
class ProductMediaGalleryValueRepository extends \TechDivision\Import\Product\Media\Repositories\ProductMediaGalleryValueRepository implements ProductMediaGalleryValueRepositoryInterface
{

    /**
     * The prepared statement to load an existing product media gallery value entity.
     *
     * @var \PDOStatement
     */
    protected $productMediaGalleryStmt;

    /**
     * Initializes the repository's prepared statements.
     *
     * @return void
     */
    public function init()
    {

        // initialize the prepared statements
        $this->productMediaGalleryValueStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::PRODUCT_MEDIA_GALLERY_VALUE));
    }

    /**
     * Load's the product media gallery value with the passed value/store/row ID.
     *
     * @param integer $valueId The value ID of the product media gallery value to load
     * @param string  $storeId The store ID of the product media gallery value to load
     * @param string  $rowId   The row ID of the parent product of the product media gallery value to load
     *
     * @return array The product media gallery value
     */
    public function findOneByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId)
    {

        // initialize the params
        $params = array(
            MemberNames::VALUE_ID  => $valueId,
            MemberNames::STORE_ID  => $storeId,
            MemberNames::ROW_ID    => $rowId
        );

        // load and return the prodcut media gallery value with the passed value/store/parent ID
        $this->productMediaGalleryValueStmt->execute($params);
        return $this->productMediaGalleryValueStmt->fetch(\PDO::FETCH_ASSOC);
    }
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Controller\Auth;

use Orkestra\Bundle\ApplicationBundle\Controller\Controller;
use Orkestra\Bundle\ApplicationBundle\Http\JsonErrorResponse;
use Orkestra\Bundle\ApplicationBundle\Http\JsonSuccessResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route
 */
class PasswordResetController extends Controller
{
    /**
     * Displays a form to request a reset
     *
     * @Route("/reset-password", name="orkestra_password_reset_new")
     * @Template
     */
    public function newAction()
    {
        $form = $this->getResetForm();

        return array(
            'form' => $form->createView()
        );
    }

    /**
     * Resets a user's password and emails them the temporary password
     *
     * @Route("/reset-password/reset", name="orkestra_password_reset_create", defaults={"_format"="json"})
     * @Method("POST")
     */
    public function createAction(Request $request)
    {
        $form = $this->getResetForm();
        $form->bind($request);

        if ($form->isValid()) {
            $email = $form->get('email')->getData();
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('OrkestraApplicationBundle:User')->findOneBy(array('email' => $email));

            if ($user) {
                $passwordHelper = $this->get('orkestra.application.helper.password');
                $hashedEntity = $passwordHelper->sendPasswordResetEmail($user, 'Password Reset Request');

                $em->persist($user);
                $em->persist($hashedEntity);
                $em->flush();

                return new JsonSuccessResponse('Your password has been reset. Please check your email for further instructions.');
            }
        }

        sleep(2);

        return new JsonErrorResponse('Invalid or unknown email address');
    }

    private function getResetForm()
    {
        return $this->createFormBuilder()
            ->add('email', EmailType::class)
            ->getForm();
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: inhere
 * Date: 2017/7/2
 * Time: 下午1:43
 */

namespace Toolkit\Pool;

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

/**
 * Class AbstractPool
 *  - 需要继承它，在自己的子类实现资源的创建和销毁. 以及一些自定义
 *
 * @package Toolkit\Pool
 */
abstract class AbstractPool implements PoolInterface
{
    use FulledPoolTrait;

    /**
     * @var string The pool name
     */
    protected $name = 'default';

    /**
     * metadata for connections
     * @var array[]
     * [
     *  'res id' => [
     *      'createAt' => int,
     *      'activeAt' => int, // Recent active time - 最近活跃时间
     *  ]
     * ]
     */
    protected $metas = [];

    /**
     * default 30 seconds
     * @var int
     */
    protected $expireTime = 30;

    /**
     * Initialize the pool size
     * @var int
     */
    protected $initSize = 0;

    /**
     * 扩大的增量(当资源不够时，一次增加资源的数量)
     * @var int
     */
    protected $stepSize = 1;

    /**
     * The maximum size of the pool resources
     * @var int
     */
    protected $maxSize = 200;

    /**
     * Maximum waiting time(ms) when get connection. - 获取资源等待超时时间
     * > 0  waiting time(ms)
     * 0    Do not wait
     * -1   Always waiting
     * @var int
     */
    protected $waitTimeout = 3000;

    /**
     * @var int The max free time(minutes) the free resource - 资源最大生命时长
     */
    protected $maxLifetime = 30;

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

    /**
     * 自定义的资源配置(创建资源对象时可能会用到 e.g mysql 连接配置)
     * @var array
     */
    protected $options = [];

    /**
     * StdObject constructor.
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        foreach ($config as $property => $value) {
            $setter = 'set' . ucfirst($property);

            if (\method_exists($this, $setter)) {
                $this->$setter($value);
            } elseif (\property_exists($this, $property)) {
                $this->$property = $value;
            }
        }

        $this->init();
    }

    /**
     * init
     */
    protected function init()
    {
        // fix mixSize
        if ($this->initSize > $this->maxSize) {
            $this->maxSize = $this->initSize;
        }
    }

    public function initPool()
    {
        // some works ...
        $this->prepare($this->initSize);

        if (!$this->logger) {
            $this->logger = new NullLogger();
        }
    }

    /**
     * call resource(will auto get and put resource)
     * @param \Closure $closure
     * @return mixed
     */
    public function call(\Closure $closure)
    {
        $resource = $this->get();
        $result = $closure($resource);
        $this->put($resource);

        return $result;
    }

    /**
     * 预(创建)准备资源
     * @param int $size
     * @return int
     */
    abstract protected function prepare(int $size): int;

    /**
     * @param mixed $obj
     * @return string
     */
    protected function genID($obj): string
    {
        if (\is_resource($obj)) {
            return (string)$obj;
        }

        if (\is_object($obj)) {
            return \spl_object_hash($obj);
        }

        return \md5(\json_encode($obj));
    }

    /**
     * 创建新的资源实例
     * @return mixed
     */
    abstract public function create();

    /**
     * 销毁资源实例
     * @param $obj
     * @return void
     */
    abstract public function destroy($obj);

    /**
     * 处理已过期的对象
     * @param $obj
     */
    protected function expire($obj)
    {
        // TODO ..
    }

    /**
     * 验证资源(eg. db connection)有效性
     * @param mixed $obj
     * @return bool
     */
    abstract protected function validate($obj): bool;

    /**
     * @return int
     */
    public function count(): int
    {
        return $this->getFreeCount() + $this->getBusyCount();
    }

    /**
     * release pool
     */
    public function __destruct()
    {
        $this->clear();
    }

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

    /**
     * @return int
     */
    public function getInitSize(): int
    {
        return $this->initSize;
    }

    /**
     * @param int $initSize
     */
    public function setInitSize(int $initSize)
    {
        $this->initSize = $initSize < 0 ? 0 : $initSize;
    }

    /**
     * @return int
     */
    public function getStepSize(): int
    {
        return $this->stepSize;
    }

    /**
     * @param int $stepSize
     */
    public function setStepSize(int $stepSize)
    {
        $this->stepSize = $stepSize < 1 ? 1 : $stepSize;
    }

    /**
     * @return int
     */
    public function getMaxSize(): int
    {
        return $this->maxSize;
    }

    /**
     * @param int $maxSize
     * @throws \InvalidArgumentException
     */
    public function setMaxSize(int $maxSize)
    {
        if ($maxSize < 1) {
            throw new \InvalidArgumentException('The resource pool max size cannot lt 1');
        }

        $this->maxSize = $maxSize;
    }

    /**
     * @return LoggerInterface
     */
    public function getLogger(): LoggerInterface
    {
        return $this->logger;
    }

    /**
     * @param LoggerInterface $logger
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @return int
     */
    public function getMaxLifetime(): int
    {
        return $this->maxLifetime;
    }

    /**
     * @param int $maxLifetime
     */
    public function setMaxLifetime(int $maxLifetime)
    {
        $this->maxLifetime = $maxLifetime;
    }

    /**
     * @param string $resId
     * @return array
     */
    public function getMeta(string $resId): array
    {
        return $this->metas[$resId] ?? [];
    }

    /**
     * @return array[]
     */
    public function getMetas(): array
    {
        return $this->metas;
    }

    /**
     * @param int $maxWait
     */
    public function setWaitTimeout(int $maxWait)
    {
        $this->waitTimeout = $maxWait;
    }

    /**
     * @return int
     */
    public function getWaitTimeout(): int
    {
        return $this->waitTimeout;
    }

    /**
     * @return array
     */
    public function getOptions(): array
    {
        return $this->options;
    }

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


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\Command\Worker;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Executes a worker
 */
class ExecuteCommand extends ContainerAwareCommand
{
    /**
     * Configures the current command
     */
    protected function configure()
    {
        $this->setName('orkestra:worker:execute')
            ->addArgument('name', InputArgument::REQUIRED, 'The internal name of the worker to execute.')
            ->setDescription('Executes the specified worker.');
    }

    /**
     * Executes the current command
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');

        /** @var $factory \Orkestra\Bundle\ApplicationBundle\Worker\WorkerFactoryInterface */
        $factory = $this->getContainer()->get('orkestra.worker_factory');
        $worker = $factory->getWorker($name);

        $worker->execute();

        $output->writeln(array(
            '',
            'The worker has completed successfully.',
            ''
        ));
    }
}


<?php

// ****************************** \\
// ***** ARTICLE CONTROLLER ***** \\
// ****************************** \\

namespace App\Controller;

use Pam\Controller\Controller;
use Pam\Model\ModelFactory;
use Pam\Helper\Session;

/** *********************************\
* All control actions to the articles
*/
class ArticleController extends Controller
{

  /** ****************\
  * Reads all articles
  * @return mixed => the rendering of the view article
  */
  public function IndexAction()
  {
    // Reads all articles, then stores them
    $allArticles = ModelFactory::get('Article')->list();

    // Returns the rendering of the view blog with all articles
    return $this->render('blog/blog.twig', ['allArticles' => $allArticles]);
  }

  /** *******************\
  * Creates a new article
  * @return mixed => the rendering of the view createArticle
  */
  public function CreateAction()
  {
    // Checks if the form has been completed
    if (!empty($_POST))
    {
      // Uploads the image & gets back the file name
      $data['image'] = $this->upload('img/blog');

      // Creates the $data array to store the new article
      $data['title']        = $_POST['title'];
      $data['link']         = $_POST['link'];
      $data['content']      = $_POST['content'];
      $data['created_date'] = $_POST['date'];
      $data['updated_date'] = $_POST['date'];

      // Creates the article
      ModelFactory::get('Article')->create($data);

      // Creates a valid message to confirm the creation of a new article
      htmlspecialchars(Session::createAlert('New article created successfully !', 'valid'));

      // Redirects to the admin
      $this->redirect('admin');
    }
    else {
      // Returns the rendering of the view createArticle with the empty fields
      return $this->render('admin/createArticle.twig');
    }
  }

  /** ***********************************************************\
  * Reads an article, his comments & attributes the user comments
  * @return mixed => the rendering of the view readArticle
  */
  public function ReadAction()
  {
    // Gets the article id, then stores it
    $id = $_GET['id'];

    // Reads the article & his comments, then stores them
    $article  = ModelFactory::get('Article')->read($id);
    $comments = ModelFactory::get('Comment')->list($id, 'article_id');

    if(!empty($comments))
    {
      // Loops on each comment
      for ($i = 0; $i < count($comments); $i++)
      {
        // Stores the comment user_id value
        $userId = $comments[$i]['user_id'];

        // Reads the user table with $userId instead of the user id value, then stores the user results
        $user = ModelFactory::get('User')->read($userId);

        // Stores the first_name value & the image value with new keys
        $comments[$i]['user']   = $user['first_name'];
        $comments[$i]['image']  = $user['image'];
      }
    }
    // Returns the rendering of the view readArticle with the article & his comments
    return $this->render('blog/readArticle.twig', [
      'article'   => $article,
      'comments'  => $comments
    ]);
  }

  /** ****************\
  * Updates an article
  * @return mixed => the rendering of the view updateArticle
  */
  public function UpdateAction()
  {
    // Gets the article id, then stores it
    $id = $_GET['id'];

    // Checks if the form has been completed
    if (!empty($_POST))
    {
      // Checks if a new file has been uploaded
      if (!empty($_FILES['file']['name']))
      {
        // Uploads the image, then gets back the file name
        $data['image'] = $this->upload('img/blog');
      }
      // Retrieves form data & stores them
      $data['title']        = $_POST['title'];
      $data['link']         = $_POST['link'];
      $data['content']      = $_POST['content'];
      $data['updated_date'] = $_POST['date'];

      // Updates the article
      ModelFactory::get('Article')->update($id, $data);

      // Creates an info message to confirm the update of the selected article
      htmlspecialchars(Session::createAlert('Successful modification of the selected article !', 'info'));

      // Redirects to the admin
      $this->redirect('admin');
    }
    // Reads the article, then store it
    $article = ModelFactory::get('Article')->read($id);

    // Returns the rendering of the view updateArticle with the current article
    return $this->render('admin/blog/updateArticle.twig', ['article' => $article]);
  }

  /** ****************\
  * Deletes an article
  */
  public function DeleteAction()
  {
    // Gets the article id, then stores it
    $id = $_GET['id'];

    // Deletes the article
    ModelFactory::get('Article')->delete($id);

    // Creates a delete message to confirm the removal of the selected article
    htmlspecialchars(Session::createAlert('Article permanently deleted !', 'delete'));

    // Redirects to the admin
    $this->redirect('admin');
  }
}


<?php

namespace Orchid\Defender;

use Illuminate\Support\Facades\Storage;

class Export
{
    /**
     * Current date.
     *
     * @var
     */
    public $date;

    /**
     * Export constructor.
     */
    public function __construct()
    {
        $this->date = date('Y-m-j');
        $this->storage = Storage::disk('local');
    }

    /**
     * Create log file.
     *
     * @param Defender $defender
     */
    public function export(Defender $defender)
    {
        $content = json_encode($defender->dangerFiles);
        $name = 'defender/defender-'.$this->date.'.json';

        if ($this->storage->exists($name)) {
            $this->storage->delete($name);
        }

        $this->storage->put($name, $content);
    }
}


<?php

namespace Orchid\Defender;

class Defender
{
    /**
     * Name the files to be excluded during the validation.
     *
     * @var array
     */
    public $exceptionsValid = [
        '.blade.php',
    ];

    /**
     * File extensions that will be scanned.
     *
     * @var array
     */
    public $extensions = [];

    /**
     * Typical signs of virus.
     *
     * @var array
     */
    public $signatures = [];

    /**
     * Scan directory.
     *
     * @var null|string
     */
    public $dir;

    /**
     * @var array
     */
    public $notValid = [];

    /**
     * @var array
     */
    public $dangerFiles = [];

    /**
     * Scanned files.
     *
     * @var array
     */
    private $files = [];

    /**
     * Defender constructor.
     *
     * @param string|null $dir
     */
    public function __construct($dir = null)
    {
        if (is_null($dir)) {
            $dir = public_path();
        }
        $this->dir = $dir;
        $this->extensions = config('defender.extensions');
        $this->signatures = config('defender.signatures');

        $this->files = $this->getDirContents($this->dir, $this->files);
    }

    /**
     * Get the contents of the selected directory and return an array of the listing.
     *
     * @param string $dir
     * @param array  $results
     *
     * @return array
     */
    private function getDirContents($dir, &$results = [])
    {
        $files = scandir($dir);

        foreach ($files as $value) {
            $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
            if (!is_dir($path)) {
                $results[] = $path;
                continue;
            }

            if ($value != '.' && $value != '..') {
                $this->getDirContents($path, $results);
                $results[] = $path;
            }
        }

        return $results;
    }

    /**
     * Scans for possible dangerous problems.
     *
     * @return Defender
     */
    public function scan()
    {
        $files = $this->extensionsFile($this->files);

        foreach ($files as $file) {
            $content = file_get_contents($file);

            if (str_contains($file, '.php') && !str_contains($file,
                    $this->exceptionsValid) && !$this->checkForValidPhp($content)
            ) {
                $this->notValid[] = $file;
            }

            if (str_contains($content, $this->signatures)) {
                $this->dangerFiles[] = $file;
                /*([
                    'path' => $file,
                    //'meta' => $meta,
                    'date' => date('d.m.Y',$meta['mtime']),
                    'size' => $meta['size'],
                ];
                */
            }
        }

        return $this;
    }

    /**
     * @param $files
     *
     * @return array
     */
    private function extensionsFile(array $files) : array
    {
        $extensionsFiles = [];

        foreach ($files as $file) {
            if (str_contains($file, $this->extensions)) {
                $extensionsFiles[] = $file;
            }
        }

        return $extensionsFiles;
    }

    /**
     * @param $content
     *
     * @return bool
     */
    private function checkForValidPhp($content) : bool
    {
        $len = strlen($content);
        $start = 0;
        $valid = false;
        while (($start = strpos($content, '<?', $start)) !== false) {
            $valid = true;
            $start++;
            $end = strpos($content, '?>', $start + 1);
            if ($end === false) {
                $end = $len;
            }
            while (++$start < $end) {
                $content = ord($content[$start]);
                if ($content < 9 || ($content >= 14 && $content <= 31) || $content == 11 || $content == 12) {
                    return false;
                }
            }
        }

        return $valid;
    }

    /**
     * @param array $signatures
     *
     * @return Defender
     */
    public function loadSignatures(array $signatures) : Defender
    {
        $this->signatures = $signatures;

        return $this;
    }

    /**
     * @param array $extensions
     *
     * @return Defender
     */
    public function loadExtensions(array $extensions) : Defender
    {
        $this->extensions = $extensions;

        return $this;
    }

    /**
     * @param array $exceptionsValid
     *
     * @return Defender
     */
    public function loadExceptionsValid(array $exceptionsValid) : Defender
    {
        $this->exceptionsValid = $exceptionsValid;

        return $this;
    }

    /**
     * @return array
     */
    public function infoDanger() : array
    {
        $files = [];
        foreach ($this->dangerFiles as $file) {
            $files[] = stat($file);
        }

        return $files;
    }

    /**
     * @return Defender
     */
    public function export() : Defender
    {
        $export = new Export();
        $export->export($this);

        return $this;
    }
}


<?php
namespace keenly\view;
/**
 * This file is part of keenly from.
 * @author brain_yang<qiaopi520@qq.com>
 * (c) brain_yang
 * github: https://github.com/keenlysoft/
 * @time 2017年7月25日
 * For the full copyright and license information, please view the LICENSE
 */
use keenly\config;
use keenly\exception\dbException;

class k{

    private static $tempEngine;
    private static $config;
    private static $dir;
    private static $param;
    private static $project;

    /**
    * k::render('index',[
    *   'name' => 'zhang'
    * ],true,3600)
    * @author brain_yang <qiaopi520@qq.com>
    * @name view
    * @date: 2017年7月25日 下午8:35:21
    * @author: brain_yang
    * @param: $dir is view file
    * @param: $param is array
    * @param: $cache  Cache enabled  defaults to off
    * @param: $ctime  cacheTime
    * @return:
    */
    public static function render($dir, array $param = null,$cache = NULL,$ctime = NULL){
        $trace = debug_backtrace(1);
        self::$param = $param;
        $project = isset($trace['3']['args']['0']['0'])?$trace['3']['args']['0']['0']:'admin';
        self::ReloadConfig($project);
        self::setTemplate();
        self::setCache($cache,$ctime);
        self::setParam();
        self::setView($dir);
    }

   private static function ReloadConfig($project){
       self::$project  = $project;
       self::$config = config::reload('config')->Get('view',$project);
       if(!self::$config){
           throw new dbException('Routing not configured');
       }
       self::$dir = self::MkBaseDir();
       self::$tempEngine = new \Smarty();
    }

    private static function setTemplate(){
        self::$tempEngine->template_dir = self::$dir.self::$config['template_dir'];

    }

    private static function setParam(){
        if(is_array(self::$param) && !empty(self::$param)){
            foreach (self::$param as $name => $variate){
                self::$tempEngine->assign($name,$variate);
            }

        }
        return true;
    }

    private static function setView($file){

        self::$tempEngine->display($file.self::$config['file_postfix']);
    }

    private static function setCache($cache,$ctime){
        $switch = is_bool($cache)?$cache:self::$config['cache'];
        self::$tempEngine->cache_dir =  self::$dir.self::$config['template_cache'];
        self::$tempEngine->compile_dir =  self::$dir.self::$config['compile_dir'];
        self::$tempEngine->caching = $switch;
        $time = empty($ctime)?self::$config['cache_time']:$ctime;
        self::$tempEngine->setCacheLifetime($time);
    }

    private static function MkBaseDir(){
        $vendorDir = dirname(dirname(__FILE__));
        $baseDir = dirname($vendorDir);
        return dirname(dirname($baseDir)).DIRECTORY_SEPARATOR.self::$project;
    }

}


<?php

/**
 * TechDivision\Import\Product\Media\Ee\Observers\EeMediaGalleryObserver
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * PHP version 5
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */

namespace TechDivision\Import\Product\Media\Ee\Observers;

use TechDivision\Import\Product\Media\Observers\MediaGalleryObserver;
use TechDivision\Import\Product\Media\Ee\Utils\MemberNames;

/**
 * Observer that provides extended mapping functionality to map a SKU to a row ID (EE Feature).
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */
class EeMediaGalleryObserver extends MediaGalleryObserver
{

    /**
     * Prepare the product media gallery value to entity that has to be persisted.
     *
     * @return array The prepared product media gallery value to entity attributes
     */
    protected function prepareProductMediaGalleryValueToEntityAttributes()
    {

        // initialize and return the entity
        return $this->initializeEntity(
            array(
                MemberNames::VALUE_ID  => $this->valueId,
                MemberNames::ROW_ID    => $this->parentId
            )
        );
    }

    /**
     * Map's the passed SKU of the parent product to it's PK.
     *
     * @param string $parentSku The SKU of the parent product
     *
     * @return integer The primary key used to create relations
     */
    protected function mapParentSku($parentSku)
    {
        return $this->mapSkuToRowId($parentSku);
    }

    /**
     * Return the row ID for the passed SKU.
     *
     * @param string $sku The SKU to return the row ID for
     *
     * @return integer The mapped row ID
     * @throws \Exception Is thrown if the SKU is not mapped yet
     */
    protected function mapSkuToRowId($sku)
    {
        return $this->getSubject()->mapSkuToRowId($sku);
    }
}


<?php
namespace Slion\Meta;
use Slion\Pack;

/**
 * Description of Base
 *
 * @author andares
 */
trait Serializable {
    /**
     * 序列化打包格式
     * @var string
     */
    protected static $_serialize_format = 'msgpack';

    /**
     * 数组化包版本号
     * @var int
     */
    protected static $_version  = 1;

    /**
     * 根据数字下标的array填充
     * @param array $arr
     * @param boolean $allow_default
     * @return array
     */
    public function fillByArray(array $arr, $allow_default = false) {
        $count  = 0;
        foreach ($this->getDefault() as $name => $default) {
            if ($allow_default && !isset($arr[$count])) {
                $this->$name = $default;
                continue;
            }
            $this->$name = $arr[$count];
            $count++;
        }
    }

    /**
     * 序列化相关
     * @return string
     */
    public function serialize() {
        $arr[] = static::$_version;
        foreach ($this->getDefault() as $name => $default) {
            $arr[] = isset($this->$name) ? $this->$name : $default;
        }
        return static::pack($arr);
    }

    /**
     *
     * @param type $data
     * @throws \UnexpectedValueException
     */
    public function unserialize($data) {
        $arr = static::unpack($data);
        if (!$arr) {
            throw new \UnexpectedValueException("unpack fail");
        }
        $last_version = array_shift($arr);

        // 触发升级勾子
        if ($last_version != static::$_version) {
            $arr = static::_renew($arr, $last_version);
        }
        if (!$arr) {
            throw new \UnexpectedValueException("unserialize fail");
        }

        $this->fillByArray($arr);
    }

    protected static function _renew(array $data, $last_version) {
        return $data;
    }

    protected static function pack(array $value) {
        return Pack::encode(static::$_serialize_format, $value);
    }

    protected static function unpack($data) {
        return Pack::decode(static::$_serialize_format, $data);
    }

    public function toBin() {
        return Pack::encode('msgpack', $this->toArray());
    }

}


<?php
namespace Slion\Meta;

/**
 * Description of Base
 *
 * @author andares
 */
abstract class Base implements \IteratorAggregate {
    /**
     * 结构及默认值配置
     * @var array
     */
    protected static $_default = [];

    /**
     * @var array
     */
    protected $_data = [];

    /**
     * 确认数据
     * @throws \UnexpectedValueException
     */
    public function confirm() {
        foreach ($this->getDefault() as $name => $default) {
            if ($this->$name === null && $default === null) {
                $default_method = "_default_$name";
                if (method_exists($this, $default_method)) {
                    $this->$name = $this->$default_method();
                } else {
                    throw new \InvalidArgumentException("meta:" . get_called_class() . " field [$name] could not be empty");
                }
            }

            $method = "_confirm_$name";
            if (method_exists($this, $method)) {
                $this->$name = $this->$method($this->$name);
            }

            if (is_object($this->$name)) {
                $object = $this->$name;
                ($object instanceof self) && $object->confirm();
            }
        }

        // 整体confirm勾子
        $this->_confirm();
        return $this;
    }

    /**
     * 待扩展的整体confirm方法
     */
    public function _confirm() {}

    /**
     * 填充数据
     * @param array|self $data
     * @param array $excludes
     * @return self
     */
    public function fill($data, $excludes = []) {
        if (!is_array($data) && !is_object($data)) {
            throw new \InvalidArgumentException("fill data error");
        }

        $fields = $this->getDefault();
        if ($excludes) {
            foreach ($excludes as $name) {
                unset($fields[$name]);
            }
        }
        foreach ($fields as $name => $default) {
            isset($data[$name]) && $this->$name = $data[$name];
        }
        return $this;
    }

    /**
     * 转换到数组
     * @param bool $not_null
     * @return array
     */
    public function toArray(bool $not_null = false): array {
        $arr = [];
        foreach ($this->getDefault() as $name => $default) {
            if (isset($this->$name)) {
                if (is_object($this->$name)) {
                    $object = $this->$name;
                    $value  = method_exists($object, 'toArray') ?
                        $object->toArray() : $object;
                } else {
                    $value  = $this->$name;
                }
            } else {
                $value  = $default;
            }
            if ($value === null && $not_null) {
                continue;
            }
            $arr[$name] = $value;
        }
        return $arr;
    }

    /**
     * 聚合迭代器
     * @return \ArrayIterator
     */
    public function getIterator() {
        return new \ArrayIterator($this->toArray());
    }

    public function getDefault($key = null) {
        return $key ?
            (array_key_exists($key, static::$_default) ? static::$_default[$key] : null) :
            static::$_default;
    }

    /**
     * 重载系列方法
     * @param type $name
     * @param type $value
     */
    public function __set($name, $value) {
        $this->_data[$name] = $value;
    }

    public function __get($name) {
        $default = $this->getDefault($name);
        return isset($this->_data[$name]) ? $this->_data[$name] : $default;
    }

    public function __isset($name) {
        return isset($this->_data[$name]);
    }

    public function __unset($name) {
        unset($this->_data[$name]);
    }

}


<?php
/**
 * @license MIT
 */
namespace  Pivasic\Bundle\Debug;

use Pivasic\Bundle\Template\Native;
use Pivasic\Core\Response;

/**
 * Handle exception or fatal error and output it.
 *
 * Class Wrap
 * @package Pivasic\Bundle\Debug
 */
class Wrap
{
    /**
     * @return bool
     */
    public static function isEnabled()
    {
        return self::$debugEnabled;
    }

    /**
     * @param string $path
     */
    public static function setPackageRoot(string $path)
    {
        self::$packageRoot = $path;
    }

    /**
     * Register error handle.
     */
    public static function register()
    {
        self::$debugEnabled = true;
        set_error_handler('Pivasic\Bundle\Debug\Wrap::render');
        register_shutdown_function(['Pivasic\Bundle\Debug\Wrap', 'handleFatal']);
    }

    /**
     * Handle fatal error.
     */
    public static function handleFatal()
    {
        $error = error_get_last();
        if(null !== $error) {
            self::render($error["type"], $error["message"], $error["file"], $error["line"]);
        }
    }

    /**
     * Handle exception.
     *
     * @param \Throwable $e
     */
    public static function handleException(\Throwable $e)
    {
        self::render($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), null, $e->getTrace(), get_class($e));
    }

    /**
     * Send response.
     *
     * @param string $code
     * @param string $message
     * @param string $file
     * @param string $line
     * @param null $context
     * @param array $backtrace
     * @param string $className
     */
    public static function render(string $code, string $message, string $file, string $line, $context = null, array $backtrace = [], string $className = '')
    {
        if (ob_get_length()) {
            ob_clean();
        }
        $data = [
            'message' => 'From ' . $className . ' ' . $message,
            'code' => $code,
            'file' => $file,
            'line' => $line,
            'trace' => $backtrace,
            'context' => $context
        ];

        if (!empty($data['trace'])) {
            foreach ($data['trace'] as $k => $item) {
                if (isset($item['type'])) {
                    switch ($item['type']) {
                        case '->':
                            $data['trace'][$k]['type'] = 'method';
                            break;
                        case '::':
                            $data['trace'][$k]['type'] = 'static method';
                            break;
                        default:
                            $data['trace'][$k]['type'] = 'function';
                    }
                }
            }
        }

        $template = new Native(self::$packageRoot, '', false);
        $content = $template->getContent('catch', $data);
        $response = new Response();
        $response->setStatusCode(418);
        $response->setContent($content);
        $response->send();
        print_r($data);
        exit;
    }

    private static $debugEnabled = false;
    private static $packageRoot = '';
}


<?php

/*
 * This file is part of the OrkestraApplicationBundle package.
 *
 * Copyright (c) Orkestra Community
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Orkestra\Bundle\ApplicationBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Orkestra\Bundle\ApplicationBundle\Entity\User;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Loads the database with an initial administrative user
 */
class InitialUserData extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param \Doctrine\Common\Persistence\ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $userGroup = $this->getReference('user-group');
        $adminGroup = $this->getReference('admin-group');

        $user = new User();
        $user->setFirstName('Administrative');
        $user->setLastName('User');
        $user->setUsername('admin');
        $user->setPassword('password');
        $user->addGroup($userGroup);
        $user->addGroup($adminGroup);

        $factory = $this->container->get('security.encoder_factory');
        $encoder = $factory->getEncoder($user);
        $user->setPassword($encoder->encodePassword($user->getPassword(), $user->getSalt()));

        $this->setReference('admin-user', $user);

        $manager->persist($user);

        $manager->flush();
    }

    /**
     * Sets the container
     *
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 2;
    }
}


<?php

/**
 * TechDivision\Import\Product\Media\Ee\Observers\EeMediaGalleryValueUpdateObserver
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * PHP version 5
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */

namespace TechDivision\Import\Product\Media\Ee\Observers;

use TechDivision\Import\Product\Media\Ee\Utils\MemberNames;

/**
 * Observer that provides extended mapping functionality to map a SKU to a row ID (EE Feature).
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-product-media-ee
 * @link      http://www.techdivision.com
 */
class EeMediaGalleryValueUpdateObserver extends EeMediaGalleryValueObserver
{

    /**
     * Initialize the product media gallery value with the passed attributes and returns an instance.
     *
     * @param array $attr The product media gallery value attributes
     *
     * @return array The initialized product media gallery value
     */
    protected function initializeProductMediaGalleryValue(array $attr)
    {

        // load the row/value/store ID
        $rowId = $attr[MemberNames::ROW_ID];
        $valueId = $attr[MemberNames::VALUE_ID];
        $storeId = $attr[MemberNames::STORE_ID];

        // query whether the product media gallery value already exists or not
        if ($entity = $this->loadProductMediaGalleryValueByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId)) {
            return $this->mergeEntity($entity, $attr);
        }

        // simply return the attributes
        return $attr;
    }

    /**
     * Load's the product media gallery value with the passed value/store/row ID.
     *
     * @param integer $valueId The value ID of the product media gallery value to load
     * @param string  $storeId The store ID of the product media gallery value to load
     * @param string  $rowId   The row ID of the parent product of the product media gallery value to load
     *
     * @return array The product media gallery value
     */
    protected function loadProductMediaGalleryValueByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId)
    {
        return $this->getProductMediaProcessor()->loadProductMediaGalleryValueByValueIdAndStoreIdAndRowId($valueId, $storeId, $rowId);
    }
}


<?php
namespace Module\Module\Modules;

use DateTime;
use Skinny\Core\Configure;
use Skinny\Module\ModuleInterface;
use Skinny\Network\Wrapper;
use Skinny\Utility\Command;
use Skinny\Utility\Inflector;

class Module implements ModuleInterface
{
    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onChannelMessage(Wrapper $wrapper, $message)
    {
    }

    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onPrivateMessage(Wrapper $wrapper, $message)
    {
    }

    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onCommandMessage(Wrapper $wrapper, $message)
    {
        if ($message['command'] !== 'module') {
            return;
        }

        if (!isset($message['arguments'][1]) && $message['arguments'][0] !== 'loaded') {
            $wrapper->Message->reply(Command::syntax($message));

            return;
        }

        switch ($message['arguments'][0]) {
            case 'load':
                //Load the Module.
                $module = $wrapper->ModuleManager->load($message['arguments'][1]);

                switch ($module) {
                    //AlreadyLoaded
                    case 'AL':
                        $wrapper->Channel->sendMessage('The Module `' . $message['arguments'][1] .
                            '` is already loaded.');
                        break;

                    //Loaded
                    case 'L':
                        $wrapper->Channel->sendMessage('Module `' . $message['arguments'][1] .
                            '` loaded successfully.');
                        break;

                    //NotFound
                    case 'NF':
                        $wrapper->Channel->sendMessage('The Module `' . $message['arguments'][1] . '` was not found.');
                        break;
                }
                break;

            case 'unload':
                //Prevent for loading a file in the memory for nothing.
                if (Configure::read('debug') === false) {
                    $wrapper->Channel->sendMessage('You can\'t unload a Module when the debug is `false`.');
                    break;
                }

                //Unload the Module.
                $module = $wrapper->ModuleManager->unload($message['arguments'][1]);

                //AlreadyUnloaded
                if ($module === 'AU') {
                    $wrapper->Channel->sendMessage('The Module `' . $message['arguments'][1] .
                        '` is already unloaded or doesn\'t exist.');
                } else {
                    $wrapper->Channel->sendMessage('Module `' . $message['arguments'][1] . '` unloaded successfully.');
                }
                break;

            case 'reload':
                //Prevent for loading a file in the memory for nothing.
                if (Configure::read('debug') === false) {
                    $wrapper->Channel->sendMessage('You can\'t reload a Module when the debug is `false`.');
                    break;
                }

                //Check if we must reload all Modules.
                if ($message['arguments'][1] == "all") {
                    //Get the list of the loaded Modules.
                    $loadedModules = $wrapper->ModuleManager->getLoadedModules();

                    //For each Modules, we reload it.
                    foreach ($loadedModules as $module) {
                        $this->reloadModule($wrapper, $module);

                        //To avoid spam.
                        usleep(500000);
                    }

                    break;
                }

                //Else there is just one Module to reload.
                $this->reloadModule($wrapper, $message['arguments'][1]);
                break;

            case 'time':
                //Get the UNIX time.
                $time = $wrapper->ModuleManager->timeLoaded($message['arguments'][1]);

                //If $time is false, that mean the Module is not loaded and/or doesn't exist.
                if ($time === false) {
                    $wrapper->Channel->sendMessage('This Module is not loaded.');
                    break;
                }

                $seconds = floor(microtime(true) - $time);

                $start = new DateTime("@0");
                $end = new DateTime("@$seconds");

                $wrapper->Channel->sendMessage('The Module `' . Inflector::camelize($message['arguments'][1]) .
                    '` is loaded since ' . $start->diff($end)->format('%a days, %h hours, %i minutes and %s seconds.'));
                break;

            case 'loaded':
                //Get the loaded Modules and implode the array as a string.
                $modules = $wrapper->ModuleManager->getLoadedModules();
                $modules = implode("`, `", $modules);

                $wrapper->Channel->sendMessage('Modules loaded : `' . Inflector::camelize($modules) . '`.');
                break;

            default:
                $wrapper->Channel->sendMessage(Command::unknown($message));
        }
    }

    /**
     * Function to reload a Module and send the response.
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param string $module The module to reload.
     *
     * @return void
     */
    protected function reloadModule(Wrapper $wrapper, $module)
    {
        $moduleStatus = $wrapper->ModuleManager->reload($module);

        $module = Inflector::camelize($module);

        switch ($moduleStatus) {
            //AlreadyUnloaded
            case 'AU':
                $wrapper->Channel->sendMessage('The Module `' . $module . '` doesn\'t exist and cannot be reloaded.');
                break;

            //AlreadyLoaded
            case 'AL':
                $wrapper->Channel->sendMessage('The Module `' . $module . '` is already loaded.');
                break;

            //Loaded
            case 'L':
                $wrapper->Channel->sendMessage('Module `' . $module . '` reloaded successfully.');
                break;

            //NotFound
            case 'NF':
                $wrapper->Channel->sendMessage('Failed to reload the Module `' . $module . '`.');
                break;
        }
    }
}