<?php

/**
 * MvcCore
 *
 * This source file is subject to the BSD 3 License
 * For the full copyright and license information, please view
 * the LICENSE.md file that are distributed with this source code.
 *
 * @copyright	Copyright (c) 2016 Tom Flídr (https://github.com/mvccore/mvccore)
 * @license		https://mvccore.github.io/docs/mvccore/4.0.0/LICENCE.md
 */

namespace MvcCore\Ext\Routers\MediaAndLocalization;

trait RedirectSections
{
	/**
	 * Redirect to target media site version and localization version with path
	 * and by global `$_GET` collection (cloned from request object). Return
	 * always `FALSE`.
	 * @param array $systemParams
	 * @return array `[string $urlBaseSection, string $urlPathWithQuerySection, array $systemParams, bool|NULL $urlPathWithQueryIsHome]`
	 */
	protected function redirectToVersionSections ($systemParams) {
		$request = & $this->request;
		$urlBaseSection = $request->GetBaseUrl();
		$urlPathWithQuerySection = $request->GetPath(TRUE);

		$targetMediaSiteVersion = NULL;
		$targetLocalization = NULL;

		$mediaVersionParamName = \MvcCore\Ext\Routers\IMedia::URL_PARAM_MEDIA_VERSION;
		$localizationParamName = \MvcCore\Ext\Routers\ILocalization::URL_PARAM_LOCALIZATION;
		$this->redirectStatusCode = \MvcCore\IResponse::MOVED_PERMANENTLY;

		if (isset($systemParams[$mediaVersionParamName]))
			$targetMediaSiteVersion = $systemParams[$mediaVersionParamName];
		if (isset($systemParams[$localizationParamName]))
			$targetLocalization = $systemParams[$localizationParamName];

		if ($targetMediaSiteVersion === NULL) {
			$this->redirectStatusCode = \MvcCore\IResponse::MOVED_PERMANENTLY;
			$targetMediaSiteVersion = $this->requestMediaSiteVersion !== NULL
				? $this->requestMediaSiteVersion
				: ($this->sessionMediaSiteVersion !== NULL
					? $this->sessionMediaSiteVersion
					: static::MEDIA_VERSION_FULL
				);
		}
		if ($targetLocalization === NULL) {
			$this->redirectStatusCode = \MvcCore\IResponse::SEE_OTHER;
			$targetLocalization = $this->requestLocalization !== NULL
				? $this->requestLocalization
				: ($this->sessionLocalization !== NULL
					? $this->sessionLocalization
					: $this->defaultLocalization
				);
		}

		// unset site key switch param and redirect to no switch param URL version
		$targetMediaUrlValue = $this->redirectMediaGetUrlValueAndUnsetGet($targetMediaSiteVersion);
		$targetLocalizationUrlValue = $this->redirectLocalizationGetUrlValueAndUnsetGet($targetLocalization);

		$urlPathWithQueryIsHome = NULL;
		if ($this->anyRoutesConfigured) {

			if ($targetMediaUrlValue === NULL) {
				unset($systemParams[$mediaVersionParamName]);
			} else {
				$systemParams[$mediaVersionParamName] = $targetMediaUrlValue;
			}

			if ($targetLocalizationUrlValue === NULL) {
				unset($systemParams[$localizationParamName]);
			} else {
				$systemParams[$localizationParamName] = $targetLocalizationUrlValue;
				if ($targetLocalizationUrlValue === $this->defaultLocalizationStr) {
					$urlPathWithQueryIsHome = $this->urlIsHomePath($urlPathWithQuerySection);
					if ($urlPathWithQueryIsHome)
						unset($systemParams[$localizationParamName]);
				}
			}

			$this->redirectAddAllRemainingInGlobalGet($urlPathWithQuerySection);
		} else {
			$this->removeDefaultCtrlActionFromGlobalGet();
			if ($this->requestGlobalGet)
				$urlPathWithQuerySection .= $request->GetScriptName();
			$this->redirectAddAllRemainingInGlobalGet($urlPathWithQuerySection);
		}

		return [
			$urlBaseSection,
			$urlPathWithQuerySection,
			$systemParams,
			$urlPathWithQueryIsHome
		];
	}
}


<?php
/**
 * Load Exchange Rates
 */
namespace Delatbabel\Keylists\Console\Commands;

use Delatbabel\Keylists\Models\Keytype;
use Delatbabel\Keylists\Models\Keyvalue;
use Illuminate\Console\Command;

/**
 * Class LoadExchangeRates
 *
 * This is an example of a script that can load data into the keytypes/keyvalues
 * tables from an external API. In this case the API used is openexchangerates.org
 * which provides a list of currencies and USD exchange rates.
 *
 * To use this script properly you will need to provide a proper app_id, which can
 * be obtained from the openexchangerates.org web site.  They provide a number of
 * packages where updated exchange rate data can be obtained at a reasonable cost.
 */
class LoadExchangeRates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'keylists:loadusdrates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Load USD Exchange Rates';

    /**
     * Filename to load from, as a one off if you don't have an API key
     *
     * @var string
     */
    protected $filename = __DIR__ . '/../../../database/data/exchange_rates.json';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // To get the data from the openexchangerates.org site, then uncomment
        // these lines and substitute in your own app_id.
        /*
        $request_url = 'https://openexchangerates.org/api/latest.json';
        $params = [
            'app_id' => 'YOUR_APP_ID_HERE',
        ];

        $client = new \GuzzleHttp\Client();
        $client->setDefaultOption('verify', false);

        $request_response = $client->get($request_url, ['query' => $params]);
        $response_data = json_decode($request_response->getBody()->getContents(), true);
        if (empty($response_data) or ! empty($response_data['error'])) {
            throw new \Exception('Empty response from api.');
        }
        */

        // To pull the data from the one off JSON file, then just use these
        // lines.
        $json_data     = file_get_contents($this->filename);
        $response_data = json_decode($json_data, true);

        /** @var Keytype $keytype */
        $keytype = Keytype::create([
            'name'          => 'usd_rates',
            'description'   => 'USD Exchange Rates',
            'created_by'    => 'loader',
            'updated_by'    => 'loader',
        ]);

        // Get this in advance
        $ratedata = $response_data['rates'];
        $count    = count($ratedata);
        $bar      = $this->output->createProgressBar($count);

        foreach ($ratedata as $code => $rate) {
            $keyval = Keyvalue::firstOrNew([
                'keytype_id'    => $keytype->id,
                'keyvalue'      => $code,
            ]);
            $keyval->keyname          = "USD to $code Exchange Rate";
            $keyval->extended_data    = [
                'exchange_rate' => $rate,
            ];
            $keyval->save();

            // progress advance
            $bar->advance();
        }

        // Finished
        $bar->finish();
        $this->output->writeln('Finished');
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators;

use Jin2\Language\Translation;

/**
 * Validateur : teste si une valeur est supérieure ou égale à une valeur donnée
 */
class Operator extends AbstractValidator
{

  /**
   * Constructeur
   *
   * @param type $args Tableau d'arguments (operator -> opérateur de test, value -> valeur à comparer)
   */
  public function __construct($args) {
    parent::__construct($args, array('operator', 'value'));
  }

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'operator';
  }

  /**
   * Teste la validité
   *
   * @param  mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    parent::resetErrors();

    $vValue    = $this->getArgValue('value');
    $vOperator = $this->getArgValue('operator');
    $eMsg = '';

    if (!empty($value)) {
      if ($vOperator == '==' && !($value == $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_equal');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      } elseif ($vOperator == '!=' && !($value != $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_notequal');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      } elseif ($vOperator == '<' && !($value < $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_inferior');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      } elseif ($vOperator == '<=' && !($value <= $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_inferiororequal');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      } elseif ($vOperator == '>' && !($value > $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_superior');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      } elseif ($vOperator == '>=' && !($value >= $vValue)) {
        $error = true;
        $eMsg = Translation::get('validatorerror_operator_superiororequal');
        $eMsg = str_replace('%value%', $vValue, $eMsg);
      }

      if ($error) {
        parent::addError($eMsg);
        return false;
      }
    }

    return true;
  }

}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Loader;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\Interfaces\DependencyLoaderInterface;
use \Library\Helper\Directory as DirectoryHelper;

/**
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class TemplateEngineLoader
    implements DependencyLoaderInterface
{

    /**
     * Instance loader
     *
     * @param   array                       $config
     * @param   \CarteBlanche\App\Container $container
     * @return  \TemplateEngine\TemplateEngine
     */
    public function load(array $config = null, \CarteBlanche\App\Container $container)
    {
        $root_path      = $container->get('kernel')->getPath('root_path');
        $web_dir        = $container->get('kernel')->getPath('web_dir');
        $views_dir      = $container->get('kernel')->getPath('views_dir');
        $cbcore_dir     = $container->get('kernel')->getPath('carte_blanche_core');
        $base_cache_dir = $container->get('kernel')->getPath('web_tmp_dir');
        if (empty($base_cache_dir)) {
            $base_cache_dir = 'www'.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR;
        }
        $base_cache_path = DirectoryHelper::slashDirname($root_path).$base_cache_dir;

        $assets_tmp_path = $container->get('kernel')->getPath('asset_tmp_path');
        if (empty($assets_tmp_dir)) {
            $assets_tmp_path = DirectoryHelper::slashDirname($base_cache_path).'assets'.DIRECTORY_SEPARATOR;
            $container->get('kernel')->addPath('asset_tmp_dir', $assets_tmp_path, true, true);
        }

        $cache_path = $container->get('kernel')->getPath('web_cache_dir');
        if (empty($cache_path)) {
            $cache_path = DirectoryHelper::slashDirname($base_cache_path).'cache'.DIRECTORY_SEPARATOR;
            $container->get('kernel')->addPath('web_cache_dir', $cache_path, true, true);
        }
/*
echo '
'; var_export($root_path);
echo '
'; var_export(basename($web_dir));
echo '
'; var_export($web_dir);
echo '
'; var_export($cbcore_dir.$views_dir );
echo '
'; var_export($web_dir );
echo '
'; var_export($cache_path );
echo '
'; var_export($assets_tmp_path );
echo '
'; var_export($cbcore_dir);
echo '
'; var_export(DirectoryHelper::slashDirname($cbcore_dir).$views_dir );
//exit('yo');
//*/
        return \TemplateEngine\TemplateEngine::getInstance()
            ->guessFromAssetsLoader(\Assets\Loader::getInstance($root_path, basename($web_dir), $web_dir))
            ->setLayoutsDir( $cbcore_dir.$views_dir )
            ->setToTemplate('setWebRootPath', $web_dir )
            ->setToTemplate('setCachePath', $cache_path )
            ->setToTemplate('setAssetsCachePath', $assets_tmp_path )
            ->setToView('setIncludePath', $cbcore_dir)
            ->setToView('setIncludePath', DirectoryHelper::slashDirname($cbcore_dir).$views_dir )
            ;
    }

}

// Endfile


<?php

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

namespace Valkyrja\Events\Annotations;

use Valkyrja\Annotations\AnnotationsParser;
use Valkyrja\Annotations\NativeAnnotations;
use Valkyrja\Application;
use Valkyrja\Events\Listener as EventListener;
use Valkyrja\Support\Providers\Provides;

/**
 * Class ListenerAnnotations.
 *
 * @author Melech Mizrachi
 */
class NativeListenerAnnotations extends NativeAnnotations implements ListenerAnnotations
{
    use Provides;

    /**
     * Get the events.
     *
     * @param string[] $classes The classes
     *
     * @throws \ReflectionException
     *
     * @return \Valkyrja\Events\Listener[]
     */
    public function getListeners(string ...$classes): array
    {
        $annotations = [];

        // Iterate through all the classes
        foreach ($classes as $class) {
            $listeners = $this->methodsAnnotationsType('Listener', $class);

            // Get all the annotations for each class and iterate through them
            /** @var \Valkyrja\Events\Annotations\Listener $annotation */
            foreach ($listeners as $annotation) {
                $this->setListenerProperties($annotation);
                // Set the annotation in the annotations list
                $annotations[] = $this->getListenerFromAnnotation($annotation);
            }
        }

        return $annotations;
    }

    /**
     * Set the properties for a listener annotation.
     *
     * @param Listener $listener
     *
     * @throws \ReflectionException
     *
     * @return void
     */
    protected function setListenerProperties(Listener $listener): void
    {
        $classReflection = $this->getClassReflection($listener->getClass());

        if (
            $listener->getMethod()
            || $classReflection->hasMethod('__construct')
        ) {
            $methodReflection = $this->getMethodReflection(
                $listener->getClass(),
                $listener->getMethod() ?? '__construct'
            );
            $parameters       = $methodReflection->getParameters();

            // Set the dependencies
            $listener->setDependencies($this->getDependencies(...$parameters));
        }

        $listener->setMatches();
    }

    /**
     * Get a listener from a listener annotation.
     *
     * @param Listener $listener The listener annotation
     *
     * @return \Valkyrja\Events\Listener
     */
    protected function getListenerFromAnnotation(Listener $listener): EventListener
    {
        $eventListener = new EventListener();

        $eventListener
            ->setEvent($listener->getEvent())
            ->setId($listener->getId())
            ->setName($listener->getName())
            ->setClass($listener->getClass())
            ->setProperty($listener->getProperty())
            ->setMethod($listener->getMethod())
            ->setStatic($listener->isStatic())
            ->setFunction($listener->getFunction())
            ->setMatches($listener->getMatches())
            ->setDependencies($listener->getDependencies())
            ->setArguments($listener->getArguments());

        return $eventListener;
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            ListenerAnnotations::class,
        ];
    }

    /**
     * Bind the listener annotations.
     *
     * @param Application $app The application
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            ListenerAnnotations::class,
            new static(
                $app->container()->getSingleton(AnnotationsParser::class)
            )
        );
    }
}


<?php

namespace QCharts\ApiBundle\Controller;

use QCharts\CoreBundle\Exception\DatabaseException;
use QCharts\CoreBundle\Exception\InstanceNotFoundException;
use QCharts\CoreBundle\Exception\ParameterNotPassedException;
use QCharts\CoreBundle\Exception\SQLException;
use QCharts\CoreBundle\Exception\ValidationFailedException;
use QCharts\CoreBundle\Service\QueryService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use QCharts\CoreBundle\Exception\NoTableNamesException;
use QCharts\CoreBundle\Exception\NotFoundException;
use QCharts\CoreBundle\Exception\NotPlotableException;
use QCharts\CoreBundle\Exception\SnapshotException;
use QCharts\CoreBundle\Exception\TypeNotValidException;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use QCharts\CoreBundle\Entity\QueryRequest;

/**
 * Class DatabaseController
 * @package QCharts\ApiBundle\Controller
 */
class DatabaseController extends Controller
{
    /**
     * ApiDoc(
     * 		description="chartData Action, returns the data formatted for the chart",
     * 		parameters = {
     *          {
     *              "name" = "q",
     *              "dataType" = "integer",
     *              "required"  = true,
     *              "description" = "The requested Query Id"
     *          },
     *          {
     *              "name" = "snapshot",
     *              "dataType" = "string",
     *              "required" = false,
     *              "description" = "The selected snapshot to format, if not given uses the freshest snapshot"
     *          },
     *          {
     *              "name" = "type",
     *              "dataType" = "string",
     *              "required" = false,
     *              "description" = "Type of formatting to be applied to the results of the query, default = 'line'"
     *          }
     *      },
     *      statusCodes = {
     *          200 = "Returned successfully",
     *          402 = "Credentials not valid",
     *          404 = "Requested Query was not found with the given Id",
     *          405 = "Requested formatting is not supported",
     *          500 = "Exception found and returned with error",
     *          555 = "The snapshot given was not a valid format"
     *      }
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function chartDataAction(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $queryService = $this->get("qcharts.query");
        $resultsFormatter = $this->get("qcharts.query_results_formatter");
        $strategyFactory = $this->get("qcharts.core.fetching_factory");
        $snapshotService = $this->get("qcharts.core.snapshot_service");

        $roles = $this->getParameter('qcharts.user_roles');
        $allow_demo_users = $this->getParameter('qcharts.allow_demo_users');

        if ($authChecker->isGranted($roles["user"]) || $allow_demo_users)
        {
            $opts = [];
            try
            {
                $queryId = $request->query->get("q", 0);
                $formatType = $request->query->get("type", 'line');
                $snapshot = $request->query->get("snapshot", null);

                /** @var QueryRequest $queryRequest */
                $queryRequest = $queryService->getQueryRequestById($queryId);

                $strategy = $strategyFactory->createStrategy($queryRequest->getConfig()->getIsCached(), $snapshot);

                $results = $strategy->getResults($queryRequest);
                $queryDuration = $strategy->getDuration();

                $chartResults = $resultsFormatter->formatResults($results, $formatType);

                try
                {
                    $snapshotUsed = $snapshotService->formatSnapshotName($queryRequest, $snapshot);
                }
                catch (SnapshotException $e)
                {
                    $snapshotUsed = "Got results live";
                }

                $opts = [
                    "status"=>200,
                    "textStatus"=>"Data for chart returned",
                    "chartData"=>$chartResults,
                    "duration"=>"{$queryDuration} secs",
                    "snapshot" => $snapshotUsed
                ];

            }
            catch (NotPlotableException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (ValidationFailedException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (InstanceNotFoundException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (ParameterNotPassedException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (SQLException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (DatabaseException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (TypeNotValidException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (SnapshotException $e)
            {
                $opts = [
                    "status"=> 404,
                    "textStatus"=> "The snapshot is not yet cached, sorry for the inconvenience"
                ];
            }
            catch (NotFoundException $e)
            {
                $opts = [
                    "status" => $e->getCode(),
                    "textStatus" => $e->getMessage()
                ];
            }
            catch (IOException $e)
            {
                $opts = [
                    "status"=>$e->getCode(),
                    "textStatus"=>$e->getMessage()
                ];
            }
            finally
            {
                return new JsonResponse($opts);
            }
        }

        return new JsonResponse(ApiController::getNotValidCredentials());

    }

    /**
     *
     * ApiDoc(
     *      description = "Returns the information of the requested table from the database",
     *      parameters = {
     *          {
     *              "name" = "tableName",
     *              "dataType" = "string",
     *              "required" = true,
     *              "description" = "Name of the table in the database"
     *          },
     *          {
     *              "name" = "connection",
     *              "dataType" = "string",
     *              "required" = false,
     *              "description" = "The name of the connection used"
     *          }
     *      },
     *      statusCodes = {
     *          200 = "Information of the table returned",
     *          402 = "Credentials not valid",
     *          404 = "Table information not found",
     *          500 = "Uncaught Exception"
     *      }
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function tableInformationAction(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter('qcharts.user_roles');

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new JsonResponse(ApiController::getNotValidCredentials());
        }

        $options = [];
        try
        {
            $queryService = $this->get("qcharts.query");
            $columns = $queryService->getTableInformation($request->query);
            $options = [
                "status"=>200,
                "textStatus"=>"Information from the requested table returned",
                "data"=>$columns
            ];
        }
        catch (ParameterNotPassedException $e)
        {
            $options = [
                "data" => [],
                "status" => $e->getCode(),
                "textStatus"=> $e->getMessage()
            ];
        }
        catch (NoTableNamesException $e)
        {
            $options = [
                "data" => [],
                "status" => $e->getCode(),
                "textStatus"=> $e->getMessage()
            ];
        }
        catch (ValidationFailedException $e)
        {
            $options = [
                "data"=>[],
                "status"=>$e->getCode(),
                "textStatus"=> $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }
    }

    /**
     *
     * ApiDoc(
     * 		description = "Returns the schema tables",
     *      parameters = {
     *          {
     *              "name"="connection",
     *              "dataType"="string",
     *              "required"=false,
     *              "description"="The name of the connection to use"
     *          },
     *          {
     *              "name"="schema",
     *              "dataType"="string",
     *              "required"=true,
     *              "description"="The name of the schema to use"
     *          },
     *      },
     * 		statusCodes = {
     * 			200 = "Database tables returned",
     * 			402 = "Credentials not authorized"
     * 		}
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function tablesAction(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $queryService = $this->get("qcharts.query");

        $roles = $this->getParameter('qcharts.user_roles');

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new JsonResponse(ApiController::getNotValidCredentials());
        }

        $options = [];
        try
        {
            $connectionName = $request->query->get('connection', 'default');
            $schemaName = $request->query->get('schema');
            $tableNames = $queryService->getTableNames($schemaName, $connectionName);
            $options = [
                "status" => 200,
                "textStatus" => "Table names returned",
                "tables" => $tableNames
            ];
        }
        catch(NoTableNamesException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage(),
                "tables" => []
            ];
        }
        catch (ValidationFailedException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus"=>$e->getMessage(),
                "tables" => []
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }

    }

    /**
     *
     * ApiDoc(
     *      description = "Returns the name of the schemas found in the given connection",
     *      parameters = {
     *          {
     *              "name" = "connection",
     *              "dataType" = "string",
     *              "required" = true,
     *              "description" = "The connection to retrieve the desired schema information from"
     *          }
     *      },
     *      statusCodes = {
     *          200 = "Schema names returned",
     *          500 = "problem with the given connection name"
     *      }
     * )
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function schemasAction(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $queryService = $this->get("qcharts.query");

        $roles = $this->getParameter('qcharts.user_roles');

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new JsonResponse(ApiController::getNotValidCredentials());
        }

        $options = [];
        try
        {
            $connectionName = $request->query->get('connection', "default");
            $schemas = $queryService->getSchemas($connectionName);
            $options = [
                "schemas"=>$schemas,
                "status"=>200,
                "textStatus"=>"The schema information from the connection were returned"
            ];
        }
        catch (ValidationFailedException $e)
        {
            $options = [
                "status"=>$e->getCode(),
                "textStatus"=>$e->getMessage()
            ];
        }
        catch (DatabaseException $e)
        {
            $options = [
                "status"=>$e->getCode(),
                "textStatus"=>$e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }

    }

    /**
     *
     * ApiDoc(
     *      description = "Returns the names of the current supported connections",
     *      statusCodes = {
     *          200 = "Success, connections returned",
     *          500 = "Unexpected exception"
     *      }
     * )
     *
     * @return JsonResponse
     */
    public function connectionsAction()
    {
        $authChecker = $this->get('security.authorization_checker');
        $roles = $this->getParameter('qcharts.user_roles');

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new JsonResponse(ApiController::getNotValidCredentials());
        }

        $options = [];
        try
        {
            $queryService = $this->get("qcharts.query");
            $connections = $queryService->getConnections();
            $options = [
                "connections" => $connections,
                "status" => 200,
                "textStatus" => "Connection names returned"
            ];
        }
        catch (\Exception $e)
        {
            $options = [
                "status"=>$e->getCode(),
                "textStatus"=> $e->getMessage(),
                "connections"=>[]
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }

    }

    /**
     * ApiDoc(
     * 		description="Run Action, returns the results directly from database",
     * 		parameters={
     * 			{
     * 				"name"="query",
     * 				"dataType"="string",
     * 				"required"=true,
     * 				"description"="The query to run in the database"
     * 			},
     * 			{
     * 				"name"="limit",
     * 				"dataType"="integer",
     * 				"required"=false,
     * 				"description"="The limit to use"
     * 			},
     *          {
     *              "name"="connection",
     *              "dataType"="string",
     *              "required"=false,
     *              "description"="Connection to query from, default connection is used if not passed"
     *          }
     * 		},
     *      statusCodes = {
     *          200 = "Returned successfully",
     *          402 = "Credentials not valid",
     *          500 = "Exception found and returned with error"
     *      }
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function runAction(Request $request)
    {
        $authChecker = $this->get('security.authorization_checker');

        /** @var QueryService $queryService */
        $queryService = $this->get('qcharts.query');

        $chartValidator = $this->get("qcharts.chart_validator");

        $roles = $this->getParameter('qcharts.user_roles');

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new JsonResponse(ApiController::getNotValidCredentials());
        }

        $query = $request->request->get('query');
        try
        {
            $queryLimit = $request->request->get('limit', 0);
            $connection = $request->request->get('connection', 'default');

            $result = $queryService->getResultsFromQuery($query, $queryLimit, $connection);

            $isPieCompatible = false;
            try
            {
                $isPieCompatible = $chartValidator->resultsArePieCompatible($result["results"]);
                $isPieCompatible = $isPieCompatible && $chartValidator->resultsAreNumeric($result["results"], 'pie');
            }
            catch (ValidationFailedException $e)
            {
                $isPieCompatible = false;
            }
            finally
            {
                return new JsonResponse([
                    "status" => 200,
                    "originalQuery" => $query,
                    "textStatus" => "Results are returned",
                    "results" => $result["results"],
                    "lengthResults" => count($result["results"]),
                    "queryDuration" => $result["duration"],
                    "limit"=>$queryLimit,
                    "isPieChartCompatible" => $isPieCompatible,
                ]);
            }

        }
        catch (ParameterNotPassedException $e)
        {
            //return the error as an error
            return new JsonResponse([
                "status"=>500,
                "textStatus" => $e->getMessage(),
                "originalQuery" => $query,
            ]);
        }
        catch (DatabaseException $e)
        {
            return new JsonResponse([
                "status" => $e->getCode(),
                "textStatus"=>$e->getMessage()
            ]);
        }
        catch (ValidationFailedException $e)
        {
            return new JsonResponse([
                "status" => $e->getCode(),
                "textStatus"=>$e->getMessage(),
                "originalQuery"=>$query
            ]);
        }
        catch (\InvalidArgumentException $e)
        {
            return new JsonResponse([
                "status"=>500,
                "textStatus"=>$e->getMessage(),
                "originalQuery"=>$query
            ]);
        }
    }

}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CompressAbstract.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Compress_CompressInterface
 */

/**
 * Abstract compression adapter
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Filter_Compress_CompressAbstract implements Zend_Filter_Compress_CompressInterface
{
    /**
     * Class constructor
     *
     * @param array|Zend_Config $options (Optional) Options to set
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Returns one or all set options
     *
     * @param string $option (Optional) Option to return
     * @return mixed
     */
    public function getOptions($option = null)
    {
        if ($option === null) {
            return $this->_options;
        }

        if (!array_key_exists($option, $this->_options)) {
            return null;
        }

        return $this->_options[$option];
    }

    /**
     * Sets all or one option
     *
     * @param  array $options
     * @return Zend_Filter_Compress_Bz2
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $option) {
            $method = 'set' . $key;
            if (method_exists($this, $method)) {
                $this->$method($option);
            }
        }

        return $this;
    }
}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\TraitCollection;

/**
 * Container collection trait
 *
 * This trait define the base logic of
 * the container collections.
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait ContainerCollectionTrait
{
    /**
     * Contain
     *
     * This method is used to check if the
     * current collection contain a specified
     * value. It return true if the collection
     * contain the element.
     *
     * @param mixed $element The element needed
     *
     * @return boolean
     */
    public function contain($element)
    {
        return array_search($element, $this->content) !== false;
    }

    /**
     * Contain all
     *
     * This method is used to check if the
     * current collection contain a specific
     * list of values. It return true if the
     * collection contain all of the list
     * values.
     *
     * @param array $elements The list of needed elements
     *
     * @return boolean
     */
    public function containAll(array $elements)
    {
        foreach ($elements as $element) {
            if (!$this->contain($element)) {
                return false;
            }
        }

        return true;
    }
}


<?php
/**
 * Class KeylistsService
 *
 * @author del
 */

namespace Delatbabel\Keylists\Services;

use Delatbabel\Keylists\Models\Keyvalue;
use Illuminate\Support\Fluent;

/**
 * Class KeylistsService
 *
 * This class provides some utility functions for fetching keylist entries.
 *
 * ### Example
 *
 * <code>
 * $keyservice = new KeylistsService;
 * // @var Fluent $key
 * $key = $keyservice->getKeyValue('currencies', 'USD');
 * </code>
 */
class KeylistsService
{

    /**
     * Fetches a single keyvalue by key type and key value
     *
     * @param string $keyType
     * @param string $keyValue
     * @return Fluent
     */
    public function getKeyValue($keyType, $keyValue)
    {
        $list = Keyvalue::getKeyvaluesByKeyType($keyType);
        if (isset($list[$keyValue])) {
            return $list[$keyValue];
        }
        return null;
    }
}


<?php

namespace Oxygen\Data\Behaviour;

use Oxygen\Data\Exception\MassAssignmentException;

trait Fillable {

    /**
     * Fills the entity from and array.
     *
     * @param array $input
     * @return void
     * @throws MassAssignmentException if the input tries to assign an not-fillable field.
     */
    public function fromArray(array $input) {
        $fillable = $this->getFillableFields();

        foreach($input as $key => $value) {
            if(in_array($key, $fillable)) {
                $this->{'set' . ucfirst($key)}($value);
            } else {
                throw new MassAssignmentException($key);
            }
        }
    }

    /**
     * Returns the fields that should be fillable.
     *
     * @return array
     */

    protected function getFillableFields() {
        return [];
    }

}


<?php
/**
 * Поле типа «entities»
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Поле типа «entities»
 *
 * Транслируется в свойство, содержащее коллекцию сущностей указанного класса, связанных с текущим
 * объектом.
 *
 * Обязательные параметры:
 *
 * - «class» — полное имя класса объектов, привязанных к этому полю
 * - «reference» — имя поля привязанных объектов, ссылающегося на этот объект
 *
 * Необязательные параметры:
 *
 * - «cascade» — (массив) определяет, какие действия над этим объектом, должны быть повторены над
 *   объектами, привязанными к нему. Возможные ключевые слова: «persist» (добавление), «update»
 *   (обновление), «delete» (удаление)
 * - «orderBy» — (массив) определяет порядок сортировки привязанных объектов. Нечётные элементы
 *   массива должны задавать поля, чётные — направление сортировки.
 * - «filter» — (массив) фильтр привязанных объектов. Каждый элемент должен в свою очередь быть
 *   массивом, состоящим из трёх элементов: имя поля, оператор, значение. Оператор — это метод
 *   класса ezcQueryExpression.
 *
 * @package ORM
 * @since 3.00
 */
class ORM_Field_Entities extends ORM_Field_Abstract
{
    /**
     * Возвращает имя типа
     *
     * @return string
     *
     * @since 3.00
     */
    public function getTypeName()
    {
        return 'entities';
    }

    /**
     * Возвращает true если это виртуальный тип (т. е. для него не надо создавать поле в таблице)
     *
     * @return bool
     *
     * @since 3.00
     */
    public function isVirtual()
    {
        return true;
    }

    /**
     * Вычисляет и возвращает значение виртуального поля
     *
     * @param ORM_Entity $entity
     *
     * @throws LogicException
     *
     * @return mixed
     *
     * @since 3.00
     */
    public function evaluateVirtualValue(ORM_Entity $entity)
    {
        if ($entity->getPrimaryKey())
        {
            $table = $this->table->getDriver()->getManager()
                ->getTableByEntityClass($this->getParam('class'));
            if (is_null($table))
            {
                return array();
            }
            $referenceField = $this->getParam('reference');
            $columns = $table->getColumns();
            if (!array_key_exists($referenceField, $columns))
            {
                throw new LogicException(sprintf('Unknown reference column: %s', $referenceField));
            }
            if (!$columns[$referenceField]->canBeUsedInWhere())
            {
                throw new LogicException(
                    sprintf('Field "%s" can not be used as a reference field', $referenceField));
            }
            $q = $table->createSelectQuery();

            /* Формируем условие выборки */
            $where = array($q->expr->eq($referenceField,
                $q->bindValue($entity->getPrimaryKey(), ":$referenceField",
                    $columns[$referenceField]->getPdoType())));

            if ($this->hasParam('filter'))
            {
                foreach ($this->getParam('filter') as $filter)
                {
                    $where []= call_user_func(array($q->expr, $filter[1]), $filter[0], $filter[2]);
                }
            }
            $q->where($where);

            /* Задаём сортировку */
            if ($this->hasParam('orderBy'))
            {
                $pairs = array_chunk($this->getParam('orderBy'), 2);
                foreach ($pairs as $pair)
                {
                    $q->orderBy(reset($pair), next($pair));
                }
            }

            return $table->loadFromQuery($q);
        }
        else
        {
            return new ORM_Entity_Collection();
        }
    }

    /**
     * Действия, выполняемые после сохранения сущности
     *
     * @param ORM_Entity $entity
     */
    public function afterEntitySave(ORM_Entity $entity)
    {
        if (in_array('persist', $this->getParam('cascade', array())))
        {
            $table = $this->table->getDriver()->getManager()
                ->getTableByEntityClass($this->getParam('class'));
            if (is_null($table))
            {
                return;
            }
            foreach ($entity->{$this->getName()} as $childEntity)
            {
                /** @var ORM_Entity $childEntity */
                if ($childEntity->getEntityState() == ORM_Entity::IS_NEW)
                {
                    $childEntity->{$this->getParam('reference')} = $entity;
                    $table->persist($childEntity);
                }
            }
        }

        if (in_array('update', $this->getParam('cascade', array())))
        {
            $table = $this->table->getDriver()->getManager()
                ->getTableByEntityClass($this->getParam('class'));
            if (is_null($table))
            {
                return;
            }
            foreach ($entity->{$this->getName()} as $childEntity)
            {
                /** @var ORM_Entity $childEntity */
                if ($childEntity->getEntityState() == ORM_Entity::IS_DIRTY)
                {
                    $table->update($childEntity);
                }
            }
        }
    }

    /**
     * Действия, выполняемые после удаления сущности
     *
     * @param ORM_Entity $entity
     */
    public function afterEntityDelete(ORM_Entity $entity)
    {
        if (in_array('delete', $this->getParam('cascade', array())))
        {
            $table = $this->table->getDriver()->getManager()
                ->getTableByEntityClass($this->getParam('class'));
            if (is_null($table))
            {
                return;
            }
            foreach ($entity->{$this->getName()} as $childEntity)
            {
                $table->delete($childEntity);
            }
        }
    }

    /**
     * Возвращает список обязательных параметров
     *
     * @return string[]
     *
     * @since 3.00
     */
    protected function getRequiredParams()
    {
        return array('class', 'reference');
    }

    /**
     * Возвращает список возможных необязательных параметров
     *
     * @return string[]
     *
     * @since 3.00
     */
    protected function getOptionalParams()
    {
        return array('cascade', 'filter', 'orderBy');
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators;

use Jin2\Language\Translation;

/**
 * Validateur : teste si une valeur est numérique
 */
class IsNumeric extends AbstractValidator
{

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'isnumeric';
  }

  /**
   * Teste la validité
   *
   * @param mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    parent::resetErrors();
    if (!empty($value) && !is_numeric($value)) {
      parent::addError(Translation::get('validatorerror_isnumeric'));
      return false;
    }
    return true;
  }

}


<?php

namespace Oxygen\Data;

use Doctrine\ORM\EntityManager;
use Illuminate\Support\ServiceProvider as ServiceProvider;

abstract class BaseServiceProvider extends ServiceProvider {

    /**
     * Register a directory of Doctrine entities.
     *
     * @param  string  $directory
     * @return void
     */
    public function loadEntitiesFrom($directory) {
        $metadata = $this->app['config']['doctrine.managers.default.paths'];
        $metadata[] = $directory;
        $this->app['config']->set('doctrine.managers.default.paths', $metadata);
    }

    /**
     * Modify the entity manager
     *
     * @param callable $closure
     */
    public function extendEntityManager(callable $closure) {
        // use 'em' instead of full class name to get around bug: https://github.com/laravel/framework/issues/11226
        if($this->app->resolved('em')) {
            $closure($this->app[EntityManager::class]);
        } else {
            $this->app->resolving(EntityManager::class, $closure);
        }
    }

}


<?php

namespace Kcs\FunctionMock\Prophet;

use Kcs\FunctionMock\NamespaceProphecy;
use Kcs\FunctionMock\Registry\MockRegistry;
use Prophecy\Exception\Prediction\AggregateException;
use Prophecy\Exception\Prediction\PredictionException;

class Prophet
{
    /**
     * @var NamespaceProphecy[]
     */
    private $prophecies = [];

    public function prophesize($namespaceOrClass)
    {
        if (class_exists($namespaceOrClass) || interface_exists($namespaceOrClass)) {
            $reflectedClass = new \ReflectionClass($namespaceOrClass);
            $namespaceOrClass = $reflectedClass->getNamespaceName();
        }

        if (isset($this->prophecies[$namespaceOrClass])) {
            return $this->prophecies[$namespaceOrClass];
        }

        $prophecy = new NamespaceProphecy($namespaceOrClass);

        return $this->prophecies[$prophecy->getName()] = $prophecy;
    }

    /**
     * Check all prophecies for predictions
     *
     * @throws AggregateException
     */
    public function checkPredictions()
    {
        $exception = new AggregateException("Some predictions failed:\n");
        foreach ($this->prophecies as $prophecy) {
            try {
                $prophecy->checkPredictions();
            } catch (PredictionException $e) {
                $exception->append($e);
            }
        }

        $this->prophecies = [];
        MockRegistry::getInstance()->unregisterAll();

        if (count($exception->getExceptions())) {
            throw $exception;
        }

    }
}


<?php

namespace Admingenerator\UserBundle\Twig\TokenParser;

use Symfony\Component\DependencyInjection\ContainerInterface;

class ExtendsMyConfiguredLayoutTokenParser extends \Twig_TokenParser
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Parses a token and returns a node.
     *
     * @param \Twig_Token $token A \Twig_Token instance
     *
     * @return \Twig_NodeInterface A \Twig_NodeInterface instance
     */
    public function parse(\Twig_Token $token)
    {
        if (null !== $this->parser->getParent()) {
            throw new \Twig_Error_Syntax('Multiple extends tags are forbidden', $token->getLine());
        }

        $tpl = $this->container->getParameter($this->parser->getCurrentToken()->getValue());

        $this->parser->getExpressionParser()->parseExpression();

        $this->parser->setParent(new \Twig_Node_Expression_Constant($tpl,$token->getLine()));
        $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);

        return null;
    }

    /**
     * Gets the tag name associated with this token parser.
     *
     * @return string The tag name
     */
    public function getTag()
    {
        return 'extends_my_configured_layout';
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\ObjectStore\Storage;

use Symfony\Component\HttpFoundation\Session\SessionInterface;

final class SymfonySessionStorage implements StorageInterface
{
    private $session;
    private $key;

    public function __construct(SessionInterface $session, string $key)
    {
        $this->session = $session;
        $this->key = $key;
    }

    /**
     * {@inheritdoc}
     */
    public function get()
    {
        $this->startSession();

        return $this->session->get($this->key);
    }

    /**
     * {@inheritdoc}
     */
    public function set($data): void
    {
        $this->startSession();

        $this->session->set($this->key, $data);
    }

    /**
     * {@inheritdoc}
     */
    public function clear(): void
    {
        $this->startSession();

        $this->session->remove($this->key);
    }

    private function startSession(): void
    {
        if (!$this->session->isStarted()) {
            $this->session->start();
        }
    }
}


<?php namespace RestGalleries\Http\Plugins;

use RestGalleries\Http\Plugins\RequestPluginAdapter;

/**
 * Normalizes the cache plugin of the Http client, receives input data to configure the plugin, and adds several by default.
 */
abstract class Cache implements RequestPluginAdapter
{
    /**
     * Stores the cache system name.
     *
     * @var string
     */
    protected $system;

    /**
     * Stores the cache path as an array.
     *
     * @var array
     */
    protected $path;

    /**
     * Initializes processing of plugin data.
     *
     * @param  string $system
     * @param  array  $path
     * @return void
     */
    public function __construct($system = 'file', array $path = array())
    {
        $this->processPluginData($system, $path);
    }

    /**
     * Receives data to configure the plugin, then verifies and separates them into variables.
     *
     * @param  string $system
     * @param  array  $path
     * @throws \InvalidArgumentException
     * @return void
     */
    protected function processPluginData($system, $path)
    {
        if (! $this->isValidCacheSystem($system)) {
            throw new \InvalidArgumentException('Cache system is invalid.');
        }

        $this->system = $system;

        if (empty($path)) {
            $path = [
                'folder' => dirname(dirname(dirname(__FILE__))) . '/storage/cache',
            ];
        }

        $this->path = $path;
    }

    /**
     * Verifies if an string match some cache system.
     *
     * @param  string $system
     * @return boolean
     */
    protected function isValidCacheSystem($system)
    {
        $systems = ['array', 'file'];

        if (! in_array($system, $systems)) {
            return false;
        }

        return true;

    }

    /**
     * Calls another method that determine which plugin will be returned and return it.
     *
     * @return object
     */
    public function add()
    {
        return $this->getCacheExtension();
    }

    /**
     * Calls method that will return the cache system that specified in the property $system.
     *
     * @return object
     */
    protected function getCacheExtension()
    {
        $method = 'get';
        $method .= ucfirst($this->system);
        $method .= 'System';

        return call_user_func_array([$this, $method], [null]);

    }

    abstract protected function getArraySystem();
    abstract protected function getFileSystem();

}


<?php
namespace Li;

interface IUpload
{
    // 保存
    public function save();
    // 获得上传文件名
    public function getSaveName();
    // 获得上传路径
    public function getSavePath();
}

/**
 * 文件上传
 */
class Upload implements IUpload
{
    public $savePath='uploads';
    public $allowType='jpg,png,gif';
    public $maxSize=1024;

    protected $_mimeType=array(
        'ai'      => 'application/postscript',
        'aif'     => 'audio/x-aiff',
        'aifc'    => 'audio/x-aiff',
        'aiff'    => 'audio/x-aiff',
        'asc'     => 'text/plain',
        'asf'     => 'video/x-ms-asf',
        'asx'     => 'video/x-ms-asf',
        'au'      => 'audio/basic',
        'avi'     => 'video/x-msvideo',
        'bcpio'   => 'application/x-bcpio',
        'bin'     => 'application/octet-stream',
        'bmp'     => 'image/bmp',
        'bz2'     => 'application/x-bzip2',
        'cdf'     => 'application/x-netcdf',
        'chrt'    => 'application/x-kchart',
        'class'   => 'application/octet-stream',
        'cpio'    => 'application/x-cpio',
        'cpt'     => 'application/mac-compactpro',
        'csh'     => 'application/x-csh',
        'css'     => 'text/css',
        'dcr'     => 'application/x-director',
        'dir'     => 'application/x-director',
        'djv'     => 'image/vnd.djvu',
        'djvu'    => 'image/vnd.djvu',
        'dll'     => 'application/octet-stream',
        'dms'     => 'application/octet-stream',
        'doc'     => 'application/msword',
        'dvi'     => 'application/x-dvi',
        'dxr'     => 'application/x-director',
        'eps'     => 'application/postscript',
        'etx'     => 'text/x-setext',
        'exe'     => 'application/octet-stream',
        'ez'      => 'application/andrew-inset',
        'flv'     => 'video/x-flv',
        'gif'     => 'image/gif',
        'gtar'    => 'application/x-gtar',
        'gz'      => 'application/x-gzip',
        'hdf'     => 'application/x-hdf',
        'hqx'     => 'application/mac-binhex40',
        'htm'     => 'text/html',
        'html'    => 'text/html',
        'ice'     => 'x-conference/x-cooltalk',
        'ief'     => 'image/ief',
        'iges'    => 'model/iges',
        'igs'     => 'model/iges',
        'img'     => 'application/octet-stream',
        'iso'     => 'application/octet-stream',
        'jad'     => 'text/vnd.sun.j2me.app-descriptor',
        'jar'     => 'application/x-java-archive',
        'jnlp'    => 'application/x-java-jnlp-file',
        'jpe'     => 'image/jpeg',
        'jpeg'    => 'image/jpeg',
        'jpg'     => 'image/jpeg',
        'js'      => 'application/x-javascript',
        'kar'     => 'audio/midi',
        'kil'     => 'application/x-killustrator',
        'kpr'     => 'application/x-kpresenter',
        'kpt'     => 'application/x-kpresenter',
        'ksp'     => 'application/x-kspread',
        'kwd'     => 'application/x-kword',
        'kwt'     => 'application/x-kword',
        'latex'   => 'application/x-latex',
        'lha'     => 'application/octet-stream',
        'lzh'     => 'application/octet-stream',
        'm3u'     => 'audio/x-mpegurl',
        'man'     => 'application/x-troff-man',
        'me'      => 'application/x-troff-me',
        'mesh'    => 'model/mesh',
        'mid'     => 'audio/midi',
        'midi'    => 'audio/midi',
        'mif'     => 'application/vnd.mif',
        'mov'     => 'video/quicktime',
        'movie'   => 'video/x-sgi-movie',
        'mp2'     => 'audio/mpeg',
        'mp3'     => 'audio/mpeg',
        'mpe'     => 'video/mpeg',
        'mpeg'    => 'video/mpeg',
        'mpg'     => 'video/mpeg',
        'mpga'    => 'audio/mpeg',
        'ms'      => 'application/x-troff-ms',
        'msh'     => 'model/mesh',
        'mxu'     => 'video/vnd.mpegurl',
        'nc'      => 'application/x-netcdf',
        'odb'     => 'application/vnd.oasis.opendocument.database',
        'odc'     => 'application/vnd.oasis.opendocument.chart',
        'odf'     => 'application/vnd.oasis.opendocument.formula',
        'odg'     => 'application/vnd.oasis.opendocument.graphics',
        'odi'     => 'application/vnd.oasis.opendocument.image',
        'odm'     => 'application/vnd.oasis.opendocument.text-master',
        'odp'     => 'application/vnd.oasis.opendocument.presentation',
        'ods'     => 'application/vnd.oasis.opendocument.spreadsheet',
        'odt'     => 'application/vnd.oasis.opendocument.text',
        'ogg'     => 'application/ogg',
        'otg'     => 'application/vnd.oasis.opendocument.graphics-template',
        'oth'     => 'application/vnd.oasis.opendocument.text-web',
        'otp'     => 'application/vnd.oasis.opendocument.presentation-template',
        'ots'     => 'application/vnd.oasis.opendocument.spreadsheet-template',
        'ott'     => 'application/vnd.oasis.opendocument.text-template',
        'pbm'     => 'image/x-portable-bitmap',
        'pdb'     => 'chemical/x-pdb',
        'pdf'     => 'application/pdf',
        'pgm'     => 'image/x-portable-graymap',
        'pgn'     => 'application/x-chess-pgn',
        'png'     => 'image/png',
        'pnm'     => 'image/x-portable-anymap',
        'ppm'     => 'image/x-portable-pixmap',
        'ppt'     => 'application/vnd.ms-powerpoint',
        'ps'      => 'application/postscript',
        'qt'      => 'video/quicktime',
        'ra'      => 'audio/x-realaudio',
        'ram'     => 'audio/x-pn-realaudio',
        'ras'     => 'image/x-cmu-raster',
        'rgb'     => 'image/x-rgb',
        'rm'      => 'audio/x-pn-realaudio',
        'roff'    => 'application/x-troff',
        'rpm'     => 'application/x-rpm',
        'rtf'     => 'text/rtf',
        'rtx'     => 'text/richtext',
        'sgm'     => 'text/sgml',
        'sgml'    => 'text/sgml',
        'sh'      => 'application/x-sh',
        'shar'    => 'application/x-shar',
        'silo'    => 'model/mesh',
        'sis'     => 'application/vnd.symbian.install',
        'sit'     => 'application/x-stuffit',
        'skd'     => 'application/x-koan',
        'skm'     => 'application/x-koan',
        'skp'     => 'application/x-koan',
        'skt'     => 'application/x-koan',
        'smi'     => 'application/smil',
        'smil'    => 'application/smil',
        'snd'     => 'audio/basic',
        'so'      => 'application/octet-stream',
        'spl'     => 'application/x-futuresplash',
        'src'     => 'application/x-wais-source',
        'stc'     => 'application/vnd.sun.xml.calc.template',
        'std'     => 'application/vnd.sun.xml.draw.template',
        'sti'     => 'application/vnd.sun.xml.impress.template',
        'stw'     => 'application/vnd.sun.xml.writer.template',
        'sv4cpio' => 'application/x-sv4cpio',
        'sv4crc'  => 'application/x-sv4crc',
        'swf'     => 'application/x-shockwave-flash',
        'sxc'     => 'application/vnd.sun.xml.calc',
        'sxd'     => 'application/vnd.sun.xml.draw',
        'sxg'     => 'application/vnd.sun.xml.writer.global',
        'sxi'     => 'application/vnd.sun.xml.impress',
        'sxm'     => 'application/vnd.sun.xml.math',
        'sxw'     => 'application/vnd.sun.xml.writer',
        't'       => 'application/x-troff',
        'tar'     => 'application/x-tar',
        'tcl'     => 'application/x-tcl',
        'tex'     => 'application/x-tex',
        'texi'    => 'application/x-texinfo',
        'texinfo' => 'application/x-texinfo',
        'tgz'     => 'application/x-gzip',
        'tif'     => 'image/tiff',
        'tiff'    => 'image/tiff',
        'torrent' => 'application/x-bittorrent',
        'tr'      => 'application/x-troff',
        'tsv'     => 'text/tab-separated-values',
        'txt'     => 'text/plain',
        'ustar'   => 'application/x-ustar',
        'vcd'     => 'application/x-cdlink',
        'vrml'    => 'model/vrml',
        'wav'     => 'audio/x-wav',
        'wax'     => 'audio/x-ms-wax',
        'wbmp'    => 'image/vnd.wap.wbmp',
        'wbxml'   => 'application/vnd.wap.wbxml',
        'wm'      => 'video/x-ms-wm',
        'wma'     => 'audio/x-ms-wma',
        'wml'     => 'text/vnd.wap.wml',
        'wmlc'    => 'application/vnd.wap.wmlc',
        'wmls'    => 'text/vnd.wap.wmlscript',
        'wmlsc'   => 'application/vnd.wap.wmlscriptc',
        'wmv'     => 'video/x-ms-wmv',
        'wmx'     => 'video/x-ms-wmx',
        'wrl'     => 'model/vrml',
        'wvx'     => 'video/x-ms-wvx',
        'xbm'     => 'image/x-xbitmap',
        'xht'     => 'application/xhtml+xml',
        'xhtml'   => 'application/xhtml+xml',
        'xls'     => 'application/vnd.ms-excel',
        'xml'     => 'text/xml',
        'xpm'     => 'image/x-xpixmap',
        'xsl'     => 'text/xml',
        'xwd'     => 'image/x-xwindowdump',
        'xyz'     => 'chemical/x-xyz',
        'zip'     => 'application/zip'
    );

    protected $_error;

    protected function _checkType($file)
    {
        $mime = $this->_getMimeType($file['name']);

        // 检查文件类型
        $type = explode(',',$this->allowType);

        foreach($type as $value)
        {
            if(!empty($value) && $this->_mimeType[$value] == $mime)
            {
                return $value;
            }
        }

        return false;
    }

    protected function _checkSize($file)
    {
        if($file['size'] > $this->maxSize*1024)
        {
            return false;
        }

        return true;
    }

    /**
     * 上传文件
     * array(1) {
     *   ["file"]=>
     *   array(5) {
     *     ["name"]=>
     *     string(44) "a71ea8d3fd1f413458fdd278261f95cad0c85eea.jpg"
     *     ["type"]=>
     *     string(10) "image/jpeg"
     *     ["tmp_name"]=>
     *     string(24) "F:\xampp\tmp\phpBA0B.tmp"
     *     ["error"]=>
     *     int(0)
     *     ["size"]=>
     *     int(11345)
     *   }
     * }
     */
    public function save($file=null)
    {
        if(empty($file))
        {
            $this->_error='文件不存在';
            return false;
        }

        if ($file['error']) {
            $this->error($file['error']);
            return false;
        }
        $fileType = $this->_checkType($file);
        if(false === $fileType)
        {
            $this->_error='不允许该类型文件';
            return false;
        }

        if(false == $this->_checkSize($file))
        {
            $this->_error='文件太大';
            return false;
        }

        $saveName = $this->getSaveName($file);
        $savePath = $this->getSavePath($file);

        $saveFile = $savePath.DIRECTORY_SEPARATOR.$saveName.'.'.$fileType;

        if(false==move_uploaded_file($file['tmp_name'], APP_PATH.$saveFile))
        {
            $this->_error='上传失败';
            return false;
        }

        return '/'.str_replace('\\', '/', $saveFile);
    }

    public function saveRemoteImage($url)
    {

        //获取请求头并检测死链
        $heads = get_headers($url, 1);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            $this->error = '文件不存在';
            return;
        }

        if($heads['Content-Type'] == 'image/png')
        {
            $fileType = '.png';
        }
        else if($heads['Content-Type'] == 'image/jpeg')
        {
            $fileType = '.jpeg';
        }
        else if($heads['Content-Type'] == 'image/gif')
        {
            $fileType = '.gif';
        }
        else if($heads['Content-Type'] == 'image/x-jpg')
        {
            $fileType = '.jpg';
        }
        else
        {
            $this->_error='远程不是图片';
            return false;
        }

        $fileName = $this->getSaveName();
        $fileName = $this->getSavePath();

// debug($heads);
// die;

        //打开输出缓冲区并获取远程图片
        ob_start();
        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );

        if(strpos($imgUrl, 'wx_fmt=') !== false
            || strpos($imgUrl, 'wxfrom=') !== false
        )
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $imgUrl);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36');
            $img = curl_exec($ch);
            $m="";
            // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            $this->fileType = $fileType;
        }
        else
        {
            readfile($imgUrl, false, $context);
            $img = ob_get_contents();
            ob_end_clean();
            preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
        }

        $this->oriName = $m ? $m[1]:"";
        $this->fileSize = strlen($img);
        $this->fileType = empty($this->fileType) ? $this->getFileExt() : $this->fileType;
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }
        //移动文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    public function getSaveName($file=null)
    {
        if(empty($file))
        {
            return md5(NOW.mt_rand(111,999));
        }
        else
        {
            return md5($file['tmp_name']);
        }
    }

    public function getSavePath($recursive=false,$mode=0777)
    {
        $date = date('Ym', NOW);

        $savePath = 'public'.DIRECTORY_SEPARATOR.$this->savePath.DIRECTORY_SEPARATOR.$date;

        if(!is_dir(APP_PATH.$savePath))
        {
            mkdir(APP_PATH.$savePath,$mode,$recursive);
        }

        return $savePath;
    }

    protected function _getMimeType($filename, $debug = true ) {
        if ( function_exists( 'finfo_open' ) && function_exists( 'finfo_file' ) && function_exists( 'finfo_close' ) ) {

            $fileinfo = finfo_open( FILEINFO_MIME );
            $mime_type = finfo_file( $fileinfo, $filename );
            finfo_close( $fileinfo );

            if ( ! empty( $mime_type ) ) {
                if ( true === $debug )
                    return array( 'mime_type' => $mime_type, 'method' => 'fileinfo' );
                return $mime_type;
            }
        }
        if ( function_exists( 'mime_content_type' ) ) {
            $mime_type = mime_content_type( $filename );

            if ( ! empty( $mime_type ) ) {
                if ( true === $debug )
                    return array( 'mime_type' => $mime_type, 'method' => 'mime_content_type' );
                return $mime_type;
            }
        }
        $tmpVar = explode( '.', $filename );
        $ext = strtolower( array_pop( $tmpVar ) );

        if ( ! empty( $this->_mimeType[$ext] ) ) {
            if ( true === $debug )
            return $this->_mimeType[$ext];
        }

        if ( true === $debug )
            return array( 'mime_type' => 'application/octet-stream', 'method' => 'last_resort' );
        return 'application/octet-stream';
    }

    public function getError()
    {
        return $this->_error;
    }

}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\CollectionHelper\HelperTrait;

use CSDT\CollectionsBundle\CollectionInterfaces\CollectionInterface;

/**
 * Helper marge trait
 *
 * This trait define the logic for the
 * helper merging support.
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait HelperMergeTrait
{
    /**
     * Merge collection
     *
     * Return a collection of the same type as
     * $collection1 with all the content of the
     * second collection. Note a data lost is
     * possible by example if you merge a
     * ValueCollection as $collection1 and a
     * MapCollection as $collection2.
     *
     * @param CollectionInterface $collection1 The first collection
     * @param CollectionInterface $collection2 The second collection
     *
     * @throws \ParseError if the caster manager is not able to parse the
     *                     array to the first collection
     * @return CollectionInterface
     */
    public function mergeCollections(
        CollectionInterface $collection1,
        CollectionInterface $collection2
    ) {
        return $this->mergeArray($collection1, $collection2->toArray());
    }

    /**
     * Merge array
     *
     * Return a collectino of the same type as
     * $collection with the content of the
     * array. Note a data lost is possible by
     * example if you merge a ValueCollection
     * as $collection and an associative array
     * as $array.
     *
     * @param CollectionInterface $collection The collection
     * @param array               $array      The array to merge
     *
     * @throws \ParseError if the caster manager is not able to parse the
     *                     array to the first collection
     * @return CollectionInterface
     */
    public function mergeArray(
        CollectionInterface $collection,
        array $array
    ) {
        $collectionContent = $collection->toArray();

        $content = array_merge($collectionContent, $array);

        return $this->arrayToCollection($content, get_class($collection));
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators\File;

use Jin2\Form\Validators\AbstractValidator;
use Jin2\Language\Translation;

/**
 * Validateur : teste si le fichier a une taille (en octets) maximum
 */
class MaxSize extends AbstractValidator
{

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'maxsize';
  }

  /**
   * Teste la validité
   *
   * @param mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    parent::resetErrors();

    if (isset($value['size'])) {
      if (parent::getArgValue('maxsize') <= 0) {
        return true;
      }

      if ($value['size'] > parent::getArgValue('maxsize')) {
        $eMsg = Translation::get('validatorerror_maxsize');

        $o = parent::getArgValue('maxsize');
        $ko = parent::getArgValue('maxsize') / 1024;
        $mo = parent::getArgValue('maxsize') / 1024 / 1024;

        $msize = $o .' octets';
        if ($mo > 1) {
          $msize = number_format($mo, 2).' Mo';
        } else if($ko > 1) {
          $msize = number_format($ko, 2).' Ko';
        }

        $eMsg = str_replace('%maxsize%', $msize, $eMsg);
        parent::addError($eMsg);

        return false;
      }
    }

    return true;
  }

}


<?php
/**
 * Item class file.
 * @copyright (c) 2015, Pavel Bariev
 * @license http://www.opensource.org/licenses/bsd-license.php
 */

namespace bariew\postModule\models;

use Yii;
use \yii\db\ActiveRecord;
use \bariew\yii2Tools\behaviors\FileBehavior;
use bariew\postModule\components\CategoryToItemBehavior;
use yii\db\ActiveQuery;

/**
 * Description.
 *
 * Usage:
 * @author Pavel Bariev <bariew@yandex.ru>
 * @property integer $id
 * @property integer $user_id
 * @property string $title
 * @property string $brief
 * @property string $content
 * @property integer $is_active
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $image
 *
 * @method FileBehavior getRemoveLink
 * @method FileBehavior getFileLink
 * @method FileBehavior getFilePositionLink
 * @method FileBehavior linkList
 * @method FileBehavior deleteFile
 * @method FileBehavior renameFile
 *
 */
class Item extends ActiveRecord
{
    const SCENARIO_ADMIN = 'admin';
    const SCENARIO_USER = 'user';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'brief', 'content'], 'required'],
            [['is_active'], 'boolean'],
            [['brief', 'content'], 'string'],
            [['title'], 'string', 'max' => 255],
            ['image', 'image', 'maxFiles' => 10],
            [['categoryIds'], 'safe', 'on' => [self::SCENARIO_ADMIN, self::SCENARIO_USER]],
            ['user_id', 'required', 'on' => self::SCENARIO_ADMIN],
            ['user_id', 'integer', 'on' => self::SCENARIO_ADMIN],
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            \yii\behaviors\TimestampBehavior::className(),
            'fileBehavior' => [
                'class' => FileBehavior::className(),
                'storage' => [$this, 'getStoragePath'],
                'fileField' => 'image',
                'imageSettings' => [
                    'thumb1' => ['method' => 'thumbnail', 'width' => 50, 'height' => 50],
                    'thumb2' => ['method' => 'thumbnail', 'width' => 100, 'height' => 100],
                    'thumb3' => ['method' => 'thumbnail', 'width' => 200, 'height' => 200],
                ]
            ],
            'categoryToItem' => [
                'class' => CategoryToItemBehavior::className()
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        switch ($this->scenario) {
            case self::SCENARIO_USER :
                $this->user_id = Yii::$app->user->id;
                break;
            case self::SCENARIO_DEFAULT:
                $this->is_active = 1;
                break;
        }
    }

    /**
     * Gets search query according to model scenario.
     * @param array $params search params key=>value
     * @return ActiveQuery
     */
    public function search($params = [])
    {
        return $this::find()->andFilterWhere(array_merge($this->attributes, $params));
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('modules/post', 'ID'),
            'user_id' => Yii::t('modules/post', 'User ID'),
            'title' => Yii::t('modules/post', 'Title'),
            'brief' => Yii::t('modules/post', 'Brief'),
            'content' => Yii::t('modules/post', 'Content'),
            'is_active' => Yii::t('modules/post', 'Is Active'),
            'created_at' => Yii::t('modules/post', 'Created At'),
            'updated_at' => Yii::t('modules/post', 'Updated At'),
            'image' => Yii::t('modules/post', 'Image'),
            'categoryIds' => Yii::t('modules/post', 'Category list'),
        ];
    }

    /**
     * @return ActiveQuery
     */
    public static function active()
    {
        return self::find()->andWhere(['is_active' => 1]);
    }

    /**
     * is_active field available values.
     * @return array
     */
    public static function activeList()
    {
        return [
            0 => Yii::t('modules/post', 'No'),
            1 => Yii::t('modules/post', 'Yes'),
        ];
    }

    /**
     * Relative path for saving model files.
     * @return string path.
     */
    public function getStoragePath()
    {
        $moduleName = \bariew\postModule\Module::moduleName($this);
        $user_id = $this->getAttribute('user_id') ? : Yii::$app->user->id;
        return "@app/web/files/{$user_id}/{$moduleName}/"
            . $this->formName() . '/' . $this->id;
    }
}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Config
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Xml.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Config
 */

/**
 * XML Adapter for Zend_Config
 *
 * @category  Zend
 * @package   Zend_Config
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Config_Xml extends Zend_Config
{
    /**
     * XML namespace for ZF-related tags and attributes
     */
    const XML_NAMESPACE = 'http://framework.zend.com/xml/zend-config-xml/1.0/';

    /**
     * Whether to skip extends or not
     *
     * @var boolean
     */
    protected $_skipExtends = false;

    /**
     * Loads the section $section from the config file (or string $xml for
     * access facilitated by nested object properties.
     *
     * Sections are defined in the XML as children of the root element.
     *
     * In order to extend another section, a section defines the "extends"
     * attribute having a value of the section name from which the extending
     * section inherits values.
     *
     * Note that the keys in $section will override any keys of the same
     * name in the sections that have been included via "extends".
     *
     * The $options parameter may be provided as either a boolean or an array.
     * If provided as a boolean, this sets the $allowModifications option of
     * Zend_Config. If provided as an array, there are two configuration
     * directives that may be set. For example:
     *
     * $options = array(
     *     'allowModifications' => false,
     *     'skipExtends'        => false
     *      );
     *
     * @param  string        $xml     XML file or string to process
     * @param  mixed         $section Section to process
     * @param  array|boolean $options
     * @throws Zend_Config_Exception When xml is not set or cannot be loaded
     * @throws Zend_Config_Exception When section $sectionName cannot be found in $xml
     */
    public function __construct($xml, $section = null, $options = false)
    {
        if (empty($xml)) {

            throw new Zend_Config_Exception('Filename is not set');
        }

        $allowModifications = false;
        if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            if (isset($options['allowModifications'])) {
                $allowModifications = (bool) $options['allowModifications'];
            }
            if (isset($options['skipExtends'])) {
                $this->_skipExtends = (bool) $options['skipExtends'];
            }
        }

        set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed
        if (strstr($xml, '<?xml')) {
            $config = simplexml_load_string($xml);
        } else {
            $config = simplexml_load_file($xml);
        }

        restore_error_handler();
        // Check if there was a error while loading file
        if ($this->_loadFileErrorStr !== null) {

            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        if ($section === null) {
            $dataArray = array();
            foreach ($config as $sectionName => $sectionData) {
                $dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
            }

            parent::__construct($dataArray, $allowModifications);
        } else if (is_array($section)) {
            $dataArray = array();
            foreach ($section as $sectionName) {
                if (!isset($config->$sectionName)) {

                    throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $xml");
                }

                $dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
            }

            parent::__construct($dataArray, $allowModifications);
        } else {
            if (!isset($config->$section)) {

                throw new Zend_Config_Exception("Section '$section' cannot be found in $xml");
            }

            $dataArray = $this->_processExtends($config, $section);
            if (!is_array($dataArray)) {
                // Section in the XML file contains just one top level string
                $dataArray = array($section => $dataArray);
            }

            parent::__construct($dataArray, $allowModifications);
        }

        $this->_loadedSection = $section;
    }

    /**
     * Helper function to process each element in the section and handle
     * the "extends" inheritance attribute.
     *
     * @param  SimpleXMLElement $element XML Element to process
     * @param  string           $section Section to process
     * @param  array            $config  Configuration which was parsed yet
     * @throws Zend_Config_Exception When $section cannot be found
     * @return array
     */
    protected function _processExtends(SimpleXMLElement $element, $section, array $config = array())
    {
        if (!isset($element->$section)) {

            throw new Zend_Config_Exception("Section '$section' cannot be found");
        }

        $thisSection  = $element->$section;
        $nsAttributes = $thisSection->attributes(self::XML_NAMESPACE);

        if (isset($thisSection['extends']) || isset($nsAttributes['extends'])) {
            $extendedSection = (string) (isset($nsAttributes['extends']) ? $nsAttributes['extends'] : $thisSection['extends']);
            $this->_assertValidExtend($section, $extendedSection);

            if (!$this->_skipExtends) {
                $config = $this->_processExtends($element, $extendedSection, $config);
            }
        }

        $config = $this->_arrayMergeRecursive($config, $this->_toArray($thisSection));

        return $config;
    }

    /**
     * Returns a string or an associative and possibly multidimensional array from
     * a SimpleXMLElement.
     *
     * @param  SimpleXMLElement $xmlObject Convert a SimpleXMLElement into an array
     * @return array|string
     */
    protected function _toArray(SimpleXMLElement $xmlObject)
    {
        $config       = array();
        $nsAttributes = $xmlObject->attributes(self::XML_NAMESPACE);

        // Search for parent node values
        if (count($xmlObject->attributes()) > 0) {
            foreach ($xmlObject->attributes() as $key => $value) {
                if ($key === 'extends') {
                    continue;
                }

                $value = (string) $value;

                if (array_key_exists($key, $config)) {
                    if (!is_array($config[$key])) {
                        $config[$key] = array($config[$key]);
                    }

                    $config[$key][] = $value;
                } else {
                    $config[$key] = $value;
                }
            }
        }

        // Search for local 'const' nodes and replace them
        if (count($xmlObject->children(self::XML_NAMESPACE)) > 0) {
            if (count($xmlObject->children()) > 0) {

                throw new Zend_Config_Exception("A node with a 'const' childnode may not have any other children");
            }

            $dom                 = dom_import_simplexml($xmlObject);
            $namespaceChildNodes = array();

            // We have to store them in an array, as replacing nodes will
            // confuse the DOMNodeList later
            foreach ($dom->childNodes as $node) {
                if ($node instanceof DOMElement && $node->namespaceURI === self::XML_NAMESPACE) {
                    $namespaceChildNodes[] = $node;
                }
            }

            foreach ($namespaceChildNodes as $node) {
                switch ($node->localName) {
                    case 'const':
                        if (!$node->hasAttributeNS(self::XML_NAMESPACE, 'name')) {

                            throw new Zend_Config_Exception("Misssing 'name' attribute in 'const' node");
                        }

                        $constantName = $node->getAttributeNS(self::XML_NAMESPACE, 'name');

                        if (!defined($constantName)) {

                            throw new Zend_Config_Exception("Constant with name '$constantName' was not defined");
                        }

                        $constantValue = constant($constantName);

                        $dom->replaceChild($dom->ownerDocument->createTextNode($constantValue), $node);
                        break;

                    default:

                        throw new Zend_Config_Exception("Unknown node with name '$node->localName' found");
                }
            }

            return (string) simplexml_import_dom($dom);
        }

        // Search for children
        if (count($xmlObject->children()) > 0) {
            foreach ($xmlObject->children() as $key => $value) {
                if (count($value->children()) > 0 || count($value->children(self::XML_NAMESPACE)) > 0) {
                    $value = $this->_toArray($value);
                } else if (count($value->attributes()) > 0) {
                    $attributes = $value->attributes();
                    if (isset($attributes['value'])) {
                        $value = (string) $attributes['value'];
                    } else {
                        $value = $this->_toArray($value);
                    }
                } else {
                    $value = (string) $value;
                }

                if (array_key_exists($key, $config)) {
                    if (!is_array($config[$key]) || !array_key_exists(0, $config[$key])) {
                        $config[$key] = array($config[$key]);
                    }

                    $config[$key][] = $value;
                } else {
                    $config[$key] = $value;
                }
            }
        } else if (!isset($xmlObject['extends']) && !isset($nsAttributes['extends']) && (count($config) === 0)) {
            // Object has no children nor attributes and doesn't use the extends
            // attribute: it's a string
            $config = (string) $xmlObject;
        }

        return $config;
    }
}