<?php

namespace Kcs\FunctionMock;

use Kcs\FunctionMock\Call\CallCenter;
use Kcs\FunctionMock\Exception\InvalidNamespaceException;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Comparator\Factory;
use Prophecy\Exception\Prediction\AggregateException;
use Prophecy\Exception\Prediction\PredictionException;
use Prophecy\Prophecy\Revealer;
use Prophecy\Prophecy\RevealerInterface;
use SebastianBergmann\Comparator\ComparisonFailure;

class NamespaceProphecy
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var FunctionProphecy[]
     */
    private $prophecies;

    /**
     * @var Factory
     */
    private $comparatorFactory;

    /**
     * @var CallCenter
     */
    private $callCenter;

    /**
     * @var RevealerInterface
     */
    private $revealer;

    /**
     * Mock constructor.
     *
     * @param string $name Target namespace
     * @param CallCenter $callCenter
     * @param RevealerInterface $revealer
     */
    public function __construct($name, CallCenter $callCenter = null, RevealerInterface $revealer = null)
    {
        if (empty($name) || $name === '\\') {
            throw new InvalidNamespaceException('Cannot mock functions in global namespace');
        }

        $this->name = $name;
        $this->callCenter = $callCenter ?: new CallCenter();
        $this->revealer = $revealer ?: new Revealer();

        $this->comparatorFactory = Factory::getInstance();
        $this->prophecies = [];
    }

    public function findCalls($functionName, ArgumentsWildcard $argumentsWildcard)
    {
        return $this->callCenter->findCalls($functionName, $argumentsWildcard);
    }

    public function call($name, array $args)
    {
        return $this->callCenter->makeCall($this, $name, $args);
    }

    /**
     * Checks that registered method predictions do not fail.
     *
     * @throws \Prophecy\Exception\Prediction\AggregateException If any of registered predictions fail
     */
    public function checkPredictions()
    {
        $exception = new AggregateException(sprintf("%s:\n", $this->name));

        foreach ($this->prophecies as $prophecy) {
            try {
                $prophecy->checkPrediction();
            } catch (PredictionException $e) {
                $exception->append($e);
            }
        }

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

    public function getName()
    {
        return $this->name;
    }

    public function getProphecies()
    {
        return $this->prophecies;
    }

    public function addProphecy(FunctionProphecy $prophecy)
    {
        $this->prophecies[] = $prophecy;
    }

    public function __call($name, $arguments)
    {
        $arguments = new ArgumentsWildcard($this->revealer->reveal($arguments));

        foreach ($this->getProphecies() as $prophecy) {
            if ($prophecy->getName() !== $name) {
                continue;
            }

            $argumentsWildcard = $prophecy->getArgumentsWildcard();
            $comparator = $this->comparatorFactory->getComparatorFor(
                $argumentsWildcard, $arguments
            );

            try {
                $comparator->assertEquals($argumentsWildcard, $arguments);

                return $prophecy;
            } catch (ComparisonFailure $failure) {
            }
        }

        return new FunctionProphecy($this, $name, $arguments);
    }
}


<?php
namespace Core\Toolbox\Arrays;

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

    /**
     * Creates an multidimensional array out of an string notation and adds a value to the last element.
     *
     * @param array $arr
     *            Reference to the array to fill
     * @param string $path
     *            Path to create array from
     * @param mixed $value
     *            The value to assign to the last key
     * @param string $separator
     *            Optional seperator to be used while splittint the path into key values (Default: '.')
     */
    function assign(array &$arr, string $path, $value, string $separator = '.')
    {
        $keys = explode($separator, $path);

        foreach ($keys as $key) {
            $arr = &$arr[$key];
        }

        $arr = $value;
    }
}


<?php
namespace KapApigility;

use Zend\EventManager\StaticEventManager;
use Zend\ModuleManager\Feature\ControllerPluginProviderInterface;

class Module implements ControllerPluginProviderInterface
{
    public function onBootstrap($e)
    {
        $app = $e->getTarget();
        $this->sm = $app->getServiceManager();

        StaticEventManager::getInstance()->attach('ZF\Rest\RestController', 'getList.post', function($e) {
            $halCollection = $e->getParam('collection');
            $parameters = $e->getTarget()->queryParams();
            unset($parameters['page']);
            $halCollection->setCollectionRouteOptions(array(
                'query' => $parameters
            ));
        });
    }

    public function getConfig()
    {
        return include __DIR__ . '/../../config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__,
                ),
            ),
        );
    }

    /**
     * Expected to return \Zend\ServiceManager\Config object or array to
     * seed such an object.
     *
     * @return array|\Zend\ServiceManager\Config
     */
    public function getControllerPluginConfig()
    {
        return [
            'factories' => [
                'resource' => function(\Zend\Mvc\Controller\PluginManager $sm) {
                        $event = new ResourceEvent();
                        $event->setIdentity($sm->getServiceLocator()->get('api-identity'));
                        $sm->get('');
                    }
            ]
        ];
    }
}


<?php
namespace AcploUi\View\Helper;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class UrlFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function createService(ServiceLocatorInterface $sl)
    {
        $serviceLocator = $sl->getServiceLocator();
        $application = $serviceLocator->get('Application');

        return new Url($application->getRequest());
    }
}


<?php

namespace Reaction\Rbac;

use Reaction\Base\Component;
use Reaction\Exceptions\Error;
use Reaction\Exceptions\InvalidArgumentException;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Exceptions\InvalidValueException;
use Reaction\Promise\ExtendedPromiseInterface;
use function Reaction\Promise\reject;
use function Reaction\Promise\resolve;

/**
 * BaseManager is a base class implementing [[ManagerInterface]] for RBAC management.
 *
 * For more details and usage information on DbManager, see the [guide article on security authorization](guide:security-authorization).
 *
 * @property Role[] $defaultRoleInstances Default roles. The array is indexed by the role names. This property
 * is read-only.
 * @property string[] $defaultRoles Default roles. Note that the type of this property differs in getter and
 * setter. See [[getDefaultRoles()]] and [[setDefaultRoles()]] for details.
 *
 */
abstract class BaseManager extends Component implements ManagerInterface
{
    /**
     * @var array a list of role names that are assigned to every user automatically without calling [[assign()]].
     * Note that these roles are applied to users, regardless of their state of authentication.
     */
    protected $defaultRoles = [];

    /**
     * Returns the named auth item.
     * @param string $name the auth item name.
     * @return ExtendedPromiseInterface with Item the auth item corresponding to the specified name. Null is returned if no such item.
     */
    abstract protected function getItem($name);

    /**
     * Returns the items of the specified type.
     * @param int $type the auth item type (either [[Item::TYPE_ROLE]] or [[Item::TYPE_PERMISSION]]
     * @return ExtendedPromiseInterface with Item[] the auth items of the specified type.
     */
    abstract protected function getItems($type);

    /**
     * Adds an auth item to the RBAC system.
     * @param Item $item the item to add
     * @return ExtendedPromiseInterface with bool whether the auth item is successfully added to the system
     * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
     */
    abstract protected function addItem($item);

    /**
     * Adds a rule to the RBAC system.
     * @param Rule $rule the rule to add
     * @return ExtendedPromiseInterface with bool whether the rule is successfully added to the system
     * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
     */
    abstract protected function addRule($rule);

    /**
     * Removes an auth item from the RBAC system.
     * @param Item $item the item to remove
     * @return ExtendedPromiseInterface with bool whether the role or permission is successfully removed
     * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
     */
    abstract protected function removeItem($item);

    /**
     * Removes a rule from the RBAC system.
     * @param Rule $rule the rule to remove
     * @return ExtendedPromiseInterface with bool whether the rule is successfully removed
     * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
     */
    abstract protected function removeRule($rule);

    /**
     * Updates an auth item in the RBAC system.
     * @param string $name the name of the item being updated
     * @param Item $item the updated item
     * @return ExtendedPromiseInterface with bool whether the auth item is successfully updated
     * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
     */
    abstract protected function updateItem($name, $item);

    /**
     * Updates a rule to the RBAC system.
     * @param string $name the name of the rule being updated
     * @param Rule $rule the updated rule
     * @return bool whether the rule is successfully updated
     * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
     */
    abstract protected function updateRule($name, $rule);

    /**
     * {@inheritdoc}
     */
    public function createRole($name)
    {
        $role = new Role();
        $role->name = $name;
        return $role;
    }

    /**
     * {@inheritdoc}
     */
    public function createPermission($name)
    {
        $permission = new Permission();
        $permission->name = $name;
        return $permission;
    }

    /**
     * {@inheritdoc}
     */
    public function add($object)
    {
        if ($object instanceof Item) {
            if ($object->ruleName && $this->getRule($object->ruleName) === null) {
                $rule = \Reaction::create($object->ruleName);
                $rule->name = $object->ruleName;
                $this->addRule($rule);
            }

            return $this->addItem($object);
        } elseif ($object instanceof Rule) {
            return $this->addRule($object);
        }

        throw new InvalidArgumentException('Adding unsupported object type.');
    }

    /**
     * {@inheritdoc}
     */
    public function remove($object)
    {
        if ($object instanceof Item) {
            return $this->removeItem($object);
        } elseif ($object instanceof Rule) {
            return $this->removeRule($object);
        }

        throw new InvalidArgumentException('Removing unsupported object type.');
    }

    /**
     * {@inheritdoc}
     */
    public function update($name, $object)
    {
        if ($object instanceof Item) {
            if ($object->ruleName && $this->getRule($object->ruleName) === null) {
                $rule = \Reaction::create($object->ruleName);
                $rule->name = $object->ruleName;
                $this->addRule($rule);
            }

            return $this->updateItem($name, $object);
        } elseif ($object instanceof Rule) {
            return $this->updateRule($name, $object);
        }

        throw new InvalidArgumentException('Updating unsupported object type.');
    }

    /**
     * {@inheritdoc}
     */
    public function getRole($name)
    {
        return $this->getItem($name)->then(
            function($item) use ($name) {
                if ($item instanceof Item && $item->type == Item::TYPE_ROLE) {
                    return $item;
                }
                return reject(new Error("Role '$name' not found"));
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getPermission($name)
    {
        return $this->getItem($name)->then(
            function($item) use ($name) {
                if ($item instanceof Item && $item->type == Item::TYPE_PERMISSION) {
                    return $item;
                }
                return reject(new Error("Permission '$name' not found"));
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getRoles()
    {
        return $this->getItems(Item::TYPE_ROLE);
    }

    /**
     * Set default roles
     * @param string[]|\Closure $roles either array of roles or a callable returning it
     * @throws InvalidArgumentException when $roles is neither array nor Closure
     * @throws InvalidValueException when Closure return is not an array
     */
    public function setDefaultRoles($roles)
    {
        if (is_array($roles)) {
            $this->defaultRoles = $roles;
        } elseif ($roles instanceof \Closure) {
            $roles = call_user_func($roles);
            if (!is_array($roles)) {
                throw new InvalidValueException('Default roles closure must return an array');
            }
            $this->defaultRoles = $roles;
        } else {
            throw new InvalidArgumentException('Default roles must be either an array or a callable');
        }
    }

    /**
     * Get default roles
     * @return string[] default roles
     */
    public function getDefaultRoles()
    {
        return $this->defaultRoles;
    }

    /**
     * Returns defaultRoles as array of Role objects.
     * @return Role[] default roles. The array is indexed by the role names
     */
    public function getDefaultRoleInstances()
    {
        $result = [];
        foreach ($this->defaultRoles as $roleName) {
            $result[$roleName] = $this->createRole($roleName);
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getPermissions()
    {
        return $this->getItems(Item::TYPE_PERMISSION);
    }

    /**
     * Executes the rule associated with the specified auth item.
     *
     * If the item does not specify a rule, this method will return true. Otherwise, it will
     * return the value of [[Rule::execute()]].
     *
     * @param string|int $user the user ID. This should be either an integer or a string representing
     * the unique identifier of a user. See [[\yii\web\User::id]].
     * @param Item $item the auth item that needs to execute its rule
     * @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]] and will be passed to the rule
     * @return ExtendedPromiseInterface with bool the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned.
     */
    protected function executeRule($user, $item, $params)
    {
        if ($item->ruleName === null) {
            return resolve(true);
        }
        return $this->getRule($item->ruleName)->then(
            function($rule) use ($user, $item, $params) {
                if ($rule instanceof Rule) {
                    return $rule->execute($user, $item, $params);
                }
                return reject(false);
            }
        )->then(null, function() use ($item) {
            throw new InvalidConfigException("Rule not found: {$item->ruleName}");
        });
    }

    /**
     * Checks whether array of $assignments is empty and [[defaultRoles]] property is empty as well.
     *
     * @param Assignment[] $assignments array of user's assignments
     * @return bool whether array of $assignments is empty and [[defaultRoles]] property is empty as well
     */
    protected function hasNoAssignments(array $assignments)
    {
        return empty($assignments) && empty($this->defaultRoles);
    }
}


<?php
/**
 * package.xml generation class, package.xml version 1.0
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: v1.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 1.4.0a1
 */
/**
 * needed for PEAR_VALIDATE_* constants
 */
require_once 'PEAR/Validate.php';
require_once 'System.php';
require_once 'PEAR/PackageFile/v2.php';
/**
 * This class converts a PEAR_PackageFile_v1 object into any output format.
 *
 * Supported output formats include array, XML string, and a PEAR_PackageFile_v2
 * object, for converting package.xml 1.0 into package.xml 2.0 with no sweat.
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 1.4.0a1
 */
class PEAR_PackageFile_Generator_v1
{
    /**
     * @var PEAR_PackageFile_v1
     */
    var $_packagefile;
    function PEAR_PackageFile_Generator_v1(&$packagefile)
    {
        $this->_packagefile = &$packagefile;
    }

    function getPackagerVersion()
    {
        return '1.9.4';
    }

    /**
     * @param PEAR_Packager
     * @param bool if true, a .tgz is written, otherwise a .tar is written
     * @param string|null directory in which to save the .tgz
     * @return string|PEAR_Error location of package or error object
     */
    function toTgz(&$packager, $compress = true, $where = null)
    {
        require_once 'Archive/Tar.php';
        if ($where === null) {
            if (!($where = System::mktemp(array('-d')))) {
                return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: mktemp failed');
            }
        } elseif (!@System::mkDir(array('-p', $where))) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: "' . $where . '" could' .
                ' not be created');
        }
        if (file_exists($where . DIRECTORY_SEPARATOR . 'package.xml') &&
              !is_file($where . DIRECTORY_SEPARATOR . 'package.xml')) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: unable to save package.xml as' .
                ' "' . $where . DIRECTORY_SEPARATOR . 'package.xml"');
        }
        if (!$this->_packagefile->validate(PEAR_VALIDATE_PACKAGING)) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: invalid package file');
        }
        $pkginfo = $this->_packagefile->getArray();
        $ext = $compress ? '.tgz' : '.tar';
        $pkgver = $pkginfo['package'] . '-' . $pkginfo['version'];
        $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext;
        if (file_exists(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext) &&
              !is_file(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext)) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: cannot create tgz file "' .
                getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext . '"');
        }
        if ($pkgfile = $this->_packagefile->getPackageFile()) {
            $pkgdir = dirname(realpath($pkgfile));
            $pkgfile = basename($pkgfile);
        } else {
            return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: package file object must ' .
                'be created from a real file');
        }
        // {{{ Create the package file list
        $filelist = array();
        $i = 0;

        foreach ($this->_packagefile->getFilelist() as $fname => $atts) {
            $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
            if (!file_exists($file)) {
                return PEAR::raiseError("File does not exist: $fname");
            } else {
                $filelist[$i++] = $file;
                if (!isset($atts['md5sum'])) {
                    $this->_packagefile->setFileAttribute($fname, 'md5sum', md5_file($file));
                }
                $packager->log(2, "Adding file $fname");
            }
        }
        // }}}
        $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, 'package.xml', true);
        if ($packagexml) {
            $tar =& new Archive_Tar($dest_package, $compress);
            $tar->setErrorHandling(PEAR_ERROR_RETURN); // XXX Don't print errors
            // ----- Creates with the package.xml file
            $ok = $tar->createModify(array($packagexml), '', $where);
            if (PEAR::isError($ok)) {
                return $ok;
            } elseif (!$ok) {
                return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: tarball creation failed');
            }
            // ----- Add the content of the package
            if (!$tar->addModify($filelist, $pkgver, $pkgdir)) {
                return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: tarball creation failed');
            }
            return $dest_package;
        }
    }

    /**
     * @param string|null directory to place the package.xml in, or null for a temporary dir
     * @param int one of the PEAR_VALIDATE_* constants
     * @param string name of the generated file
     * @param bool if true, then no analysis will be performed on role="php" files
     * @return string|PEAR_Error path to the created file on success
     */
    function toPackageFile($where = null, $state = PEAR_VALIDATE_NORMAL, $name = 'package.xml',
                           $nofilechecking = false)
    {
        if (!$this->_packagefile->validate($state, $nofilechecking)) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toPackageFile: invalid package.xml',
                null, null, null, $this->_packagefile->getValidationWarnings());
        }
        if ($where === null) {
            if (!($where = System::mktemp(array('-d')))) {
                return PEAR::raiseError('PEAR_Packagefile_v1::toPackageFile: mktemp failed');
            }
        } elseif (!@System::mkDir(array('-p', $where))) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toPackageFile: "' . $where . '" could' .
                ' not be created');
        }
        $newpkgfile = $where . DIRECTORY_SEPARATOR . $name;
        $np = @fopen($newpkgfile, 'wb');
        if (!$np) {
            return PEAR::raiseError('PEAR_Packagefile_v1::toPackageFile: unable to save ' .
               "$name as $newpkgfile");
        }
        fwrite($np, $this->toXml($state, true));
        fclose($np);
        return $newpkgfile;
    }

    /**
     * fix both XML encoding to be UTF8, and replace standard XML entities < > " & '
     *
     * @param string $string
     * @return string
     * @access private
     */
    function _fixXmlEncoding($string)
    {
        if (version_compare(phpversion(), '5.0.0', 'lt')) {
            $string = utf8_encode($string);
        }
        return strtr($string, array(
                                          '&'  => '&',
                                          '>'  => '>',
                                          '<'  => '<',
                                          '"'  => '"',
                                          '\'' => ''' ));
    }

    /**
     * Return an XML document based on the package info (as returned
     * by the PEAR_Common::infoFrom* methods).
     *
     * @return string XML data
     */
    function toXml($state = PEAR_VALIDATE_NORMAL, $nofilevalidation = false)
    {
        $this->_packagefile->setDate(date('Y-m-d'));
        if (!$this->_packagefile->validate($state, $nofilevalidation)) {
            return false;
        }
        $pkginfo = $this->_packagefile->getArray();
        static $maint_map = array(
            "handle" => "user",
            "name" => "name",
            "email" => "email",
            "role" => "role",
            );
        $ret = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
        $ret .= "<!DOCTYPE package SYSTEM \"http://pear.php.net/dtd/package-1.0\">\n";
        $ret .= "<package version=\"1.0\" packagerversion=\"1.9.4\">\n" .
" <name>$pkginfo[package]</name>";
        if (isset($pkginfo['extends'])) {
            $ret .= "\n<extends>$pkginfo[extends]</extends>";
        }
        $ret .=
 "\n <summary>".$this->_fixXmlEncoding($pkginfo['summary'])."</summary>\n" .
" <description>".trim($this->_fixXmlEncoding($pkginfo['description']))."\n </description>\n" .
" <maintainers>\n";
        foreach ($pkginfo['maintainers'] as $maint) {
            $ret .= "  <maintainer>\n";
            foreach ($maint_map as $idx => $elm) {
                $ret .= "   <$elm>";
                $ret .= $this->_fixXmlEncoding($maint[$idx]);
                $ret .= "</$elm>\n";
            }
            $ret .= "  </maintainer>\n";
        }
        $ret .= "  </maintainers>\n";
        $ret .= $this->_makeReleaseXml($pkginfo, false, $state);
        if (isset($pkginfo['changelog']) && count($pkginfo['changelog']) > 0) {
            $ret .= " <changelog>\n";
            foreach ($pkginfo['changelog'] as $oldrelease) {
                $ret .= $this->_makeReleaseXml($oldrelease, true);
            }
            $ret .= " </changelog>\n";
        }
        $ret .= "</package>\n";
        return $ret;
    }

    // }}}
    // {{{ _makeReleaseXml()

    /**
     * Generate part of an XML description with release information.
     *
     * @param array  $pkginfo    array with release information
     * @param bool   $changelog  whether the result will be in a changelog element
     *
     * @return string XML data
     *
     * @access private
     */
    function _makeReleaseXml($pkginfo, $changelog = false, $state = PEAR_VALIDATE_NORMAL)
    {
        // XXX QUOTE ENTITIES IN PCDATA, OR EMBED IN CDATA BLOCKS!!
        $indent = $changelog ? "  " : "";
        $ret = "$indent <release>\n";
        if (!empty($pkginfo['version'])) {
            $ret .= "$indent  <version>$pkginfo[version]</version>\n";
        }
        if (!empty($pkginfo['release_date'])) {
            $ret .= "$indent  <date>$pkginfo[release_date]</date>\n";
        }
        if (!empty($pkginfo['release_license'])) {
            $ret .= "$indent  <license>$pkginfo[release_license]</license>\n";
        }
        if (!empty($pkginfo['release_state'])) {
            $ret .= "$indent  <state>$pkginfo[release_state]</state>\n";
        }
        if (!empty($pkginfo['release_notes'])) {
            $ret .= "$indent  <notes>".trim($this->_fixXmlEncoding($pkginfo['release_notes']))
            ."\n$indent  </notes>\n";
        }
        if (!empty($pkginfo['release_warnings'])) {
            $ret .= "$indent  <warnings>".$this->_fixXmlEncoding($pkginfo['release_warnings'])."</warnings>\n";
        }
        if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) {
            $ret .= "$indent  <deps>\n";
            foreach ($pkginfo['release_deps'] as $dep) {
                $ret .= "$indent   <dep type=\"$dep[type]\" rel=\"$dep[rel]\"";
                if (isset($dep['version'])) {
                    $ret .= " version=\"$dep[version]\"";
                }
                if (isset($dep['optional'])) {
                    $ret .= " optional=\"$dep[optional]\"";
                }
                if (isset($dep['name'])) {
                    $ret .= ">$dep[name]</dep>\n";
                } else {
                    $ret .= "/>\n";
                }
            }
            $ret .= "$indent  </deps>\n";
        }
        if (isset($pkginfo['configure_options'])) {
            $ret .= "$indent  <configureoptions>\n";
            foreach ($pkginfo['configure_options'] as $c) {
                $ret .= "$indent   <configureoption name=\"".
                    $this->_fixXmlEncoding($c['name']) . "\"";
                if (isset($c['default'])) {
                    $ret .= " default=\"" . $this->_fixXmlEncoding($c['default']) . "\"";
                }
                $ret .= " prompt=\"" . $this->_fixXmlEncoding($c['prompt']) . "\"";
                $ret .= "/>\n";
            }
            $ret .= "$indent  </configureoptions>\n";
        }
        if (isset($pkginfo['provides'])) {
            foreach ($pkginfo['provides'] as $key => $what) {
                $ret .= "$indent  <provides type=\"$what[type]\" ";
                $ret .= "name=\"$what[name]\" ";
                if (isset($what['extends'])) {
                    $ret .= "extends=\"$what[extends]\" ";
                }
                $ret .= "/>\n";
            }
        }
        if (isset($pkginfo['filelist'])) {
            $ret .= "$indent  <filelist>\n";
            if ($state ^ PEAR_VALIDATE_PACKAGING) {
                $ret .= $this->recursiveXmlFilelist($pkginfo['filelist']);
            } else {
                foreach ($pkginfo['filelist'] as $file => $fa) {
                    if (!isset($fa['role'])) {
                        $fa['role'] = '';
                    }
                    $ret .= "$indent   <file role=\"$fa[role]\"";
                    if (isset($fa['baseinstalldir'])) {
                        $ret .= ' baseinstalldir="' .
                            $this->_fixXmlEncoding($fa['baseinstalldir']) . '"';
                    }
                    if (isset($fa['md5sum'])) {
                        $ret .= " md5sum=\"$fa[md5sum]\"";
                    }
                    if (isset($fa['platform'])) {
                        $ret .= " platform=\"$fa[platform]\"";
                    }
                    if (!empty($fa['install-as'])) {
                        $ret .= ' install-as="' .
                            $this->_fixXmlEncoding($fa['install-as']) . '"';
                    }
                    $ret .= ' name="' . $this->_fixXmlEncoding($file) . '"';
                    if (empty($fa['replacements'])) {
                        $ret .= "/>\n";
                    } else {
                        $ret .= ">\n";
                        foreach ($fa['replacements'] as $r) {
                            $ret .= "$indent    <replace";
                            foreach ($r as $k => $v) {
                                $ret .= " $k=\"" . $this->_fixXmlEncoding($v) .'"';
                            }
                            $ret .= "/>\n";
                        }
                        $ret .= "$indent   </file>\n";
                    }
                }
            }
            $ret .= "$indent  </filelist>\n";
        }
        $ret .= "$indent </release>\n";
        return $ret;
    }

    /**
     * @param array
     * @access protected
     */
    function recursiveXmlFilelist($list)
    {
        $this->_dirs = array();
        foreach ($list as $file => $attributes) {
            $this->_addDir($this->_dirs, explode('/', dirname($file)), $file, $attributes);
        }
        return $this->_formatDir($this->_dirs);
    }

    /**
     * @param array
     * @param array
     * @param string|null
     * @param array|null
     * @access private
     */
    function _addDir(&$dirs, $dir, $file = null, $attributes = null)
    {
        if ($dir == array() || $dir == array('.')) {
            $dirs['files'][basename($file)] = $attributes;
            return;
        }
        $curdir = array_shift($dir);
        if (!isset($dirs['dirs'][$curdir])) {
            $dirs['dirs'][$curdir] = array();
        }
        $this->_addDir($dirs['dirs'][$curdir], $dir, $file, $attributes);
    }

    /**
     * @param array
     * @param string
     * @param string
     * @access private
     */
    function _formatDir($dirs, $indent = '', $curdir = '')
    {
        $ret = '';
        if (!count($dirs)) {
            return '';
        }
        if (isset($dirs['dirs'])) {
            uksort($dirs['dirs'], 'strnatcasecmp');
            foreach ($dirs['dirs'] as $dir => $contents) {
                $usedir = "$curdir/$dir";
                $ret .= "$indent   <dir name=\"$dir\">\n";
                $ret .= $this->_formatDir($contents, "$indent ", $usedir);
                $ret .= "$indent   </dir> <!-- $usedir -->\n";
            }
        }
        if (isset($dirs['files'])) {
            uksort($dirs['files'], 'strnatcasecmp');
            foreach ($dirs['files'] as $file => $attribs) {
                $ret .= $this->_formatFile($file, $attribs, $indent);
            }
        }
        return $ret;
    }

    /**
     * @param string
     * @param array
     * @param string
     * @access private
     */
    function _formatFile($file, $attributes, $indent)
    {
        $ret = "$indent   <file role=\"$attributes[role]\"";
        if (isset($attributes['baseinstalldir'])) {
            $ret .= ' baseinstalldir="' .
                $this->_fixXmlEncoding($attributes['baseinstalldir']) . '"';
        }
        if (isset($attributes['md5sum'])) {
            $ret .= " md5sum=\"$attributes[md5sum]\"";
        }
        if (isset($attributes['platform'])) {
            $ret .= " platform=\"$attributes[platform]\"";
        }
        if (!empty($attributes['install-as'])) {
            $ret .= ' install-as="' .
                $this->_fixXmlEncoding($attributes['install-as']) . '"';
        }
        $ret .= ' name="' . $this->_fixXmlEncoding($file) . '"';
        if (empty($attributes['replacements'])) {
            $ret .= "/>\n";
        } else {
            $ret .= ">\n";
            foreach ($attributes['replacements'] as $r) {
                $ret .= "$indent    <replace";
                foreach ($r as $k => $v) {
                    $ret .= " $k=\"" . $this->_fixXmlEncoding($v) .'"';
                }
                $ret .= "/>\n";
            }
            $ret .= "$indent   </file>\n";
        }
        return $ret;
    }

    // {{{ _unIndent()

    /**
     * Unindent given string (?)
     *
     * @param string $str The string that has to be unindented.
     * @return string
     * @access private
     */
    function _unIndent($str)
    {
        // remove leading newlines
        $str = preg_replace('/^[\r\n]+/', '', $str);
        // find whitespace at the beginning of the first line
        $indent_len = strspn($str, " \t");
        $indent = substr($str, 0, $indent_len);
        $data = '';
        // remove the same amount of whitespace from following lines
        foreach (explode("\n", $str) as $line) {
            if (substr($line, 0, $indent_len) == $indent) {
                $data .= substr($line, $indent_len) . "\n";
            }
        }
        return $data;
    }

    /**
     * @return array
     */
    function dependenciesToV2()
    {
        $arr = array();
        $this->_convertDependencies2_0($arr);
        return $arr['dependencies'];
    }

    /**
     * Convert a package.xml version 1.0 into version 2.0
     *
     * Note that this does a basic conversion, to allow more advanced
     * features like bundles and multiple releases
     * @param string the classname to instantiate and return.  This must be
     *               PEAR_PackageFile_v2 or a descendant
     * @param boolean if true, only valid, deterministic package.xml 1.0 as defined by the
     *                strictest parameters will be converted
     * @return PEAR_PackageFile_v2|PEAR_Error
     */
    function &toV2($class = 'PEAR_PackageFile_v2', $strict = false)
    {
        if ($strict) {
            if (!$this->_packagefile->validate()) {
                $a = PEAR::raiseError('invalid package.xml version 1.0 cannot be converted' .
                    ' to version 2.0', null, null, null,
                    $this->_packagefile->getValidationWarnings(true));
                return $a;
            }
        }

        $arr = array(
            'attribs' => array(
                             'version' => '2.0',
                             'xmlns' => 'http://pear.php.net/dtd/package-2.0',
                             'xmlns:tasks' => 'http://pear.php.net/dtd/tasks-1.0',
                             'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
                             'xsi:schemaLocation' => "http://pear.php.net/dtd/tasks-1.0\n" .
"http://pear.php.net/dtd/tasks-1.0.xsd\n" .
"http://pear.php.net/dtd/package-2.0\n" .
'http://pear.php.net/dtd/package-2.0.xsd',
                         ),
            'name' => $this->_packagefile->getPackage(),
            'channel' => 'pear.php.net',
        );
        $arr['summary'] = $this->_packagefile->getSummary();
        $arr['description'] = $this->_packagefile->getDescription();
        $maintainers = $this->_packagefile->getMaintainers();
        foreach ($maintainers as $maintainer) {
            if ($maintainer['role'] != 'lead') {
                continue;
            }
            $new = array(
                'name' => $maintainer['name'],
                'user' => $maintainer['handle'],
                'email' => $maintainer['email'],
                'active' => 'yes',
            );
            $arr['lead'][] = $new;
        }

        if (!isset($arr['lead'])) { // some people... you know?
            $arr['lead'] = array(
                'name' => 'unknown',
                'user' => 'unknown',
                'email' => 'noleadmaintainer@example.com',
                'active' => 'no',
            );
        }

        if (count($arr['lead']) == 1) {
            $arr['lead'] = $arr['lead'][0];
        }

        foreach ($maintainers as $maintainer) {
            if ($maintainer['role'] == 'lead') {
                continue;
            }
            $new = array(
                'name' => $maintainer['name'],
                'user' => $maintainer['handle'],
                'email' => $maintainer['email'],
                'active' => 'yes',
            );
            $arr[$maintainer['role']][] = $new;
        }

        if (isset($arr['developer']) && count($arr['developer']) == 1) {
            $arr['developer'] = $arr['developer'][0];
        }

        if (isset($arr['contributor']) && count($arr['contributor']) == 1) {
            $arr['contributor'] = $arr['contributor'][0];
        }

        if (isset($arr['helper']) && count($arr['helper']) == 1) {
            $arr['helper'] = $arr['helper'][0];
        }

        $arr['date'] = $this->_packagefile->getDate();
        $arr['version'] =
            array(
                'release' => $this->_packagefile->getVersion(),
                'api' => $this->_packagefile->getVersion(),
            );
        $arr['stability'] =
            array(
                'release' => $this->_packagefile->getState(),
                'api' => $this->_packagefile->getState(),
            );
        $licensemap =
            array(
                'php' => 'http://www.php.net/license',
                'php license' => 'http://www.php.net/license',
                'lgpl' => 'http://www.gnu.org/copyleft/lesser.html',
                'bsd' => 'http://www.opensource.org/licenses/bsd-license.php',
                'bsd style' => 'http://www.opensource.org/licenses/bsd-license.php',
                'bsd-style' => 'http://www.opensource.org/licenses/bsd-license.php',
                'mit' => 'http://www.opensource.org/licenses/mit-license.php',
                'gpl' => 'http://www.gnu.org/copyleft/gpl.html',
                'apache' => 'http://www.opensource.org/licenses/apache2.0.php'
            );

        if (isset($licensemap[strtolower($this->_packagefile->getLicense())])) {
            $arr['license'] = array(
                'attribs' => array('uri' =>
                    $licensemap[strtolower($this->_packagefile->getLicense())]),
                '_content' => $this->_packagefile->getLicense()
                );
        } else {
            // don't use bogus uri
            $arr['license'] = $this->_packagefile->getLicense();
        }

        $arr['notes'] = $this->_packagefile->getNotes();
        $temp = array();
        $arr['contents'] = $this->_convertFilelist2_0($temp);
        $this->_convertDependencies2_0($arr);
        $release = ($this->_packagefile->getConfigureOptions() || $this->_isExtension) ?
            'extsrcrelease' : 'phprelease';
        if ($release == 'extsrcrelease') {
            $arr['channel'] = 'pecl.php.net';
            $arr['providesextension'] = $arr['name']; // assumption
        }

        $arr[$release] = array();
        if ($this->_packagefile->getConfigureOptions()) {
            $arr[$release]['configureoption'] = $this->_packagefile->getConfigureOptions();
            foreach ($arr[$release]['configureoption'] as $i => $opt) {
                $arr[$release]['configureoption'][$i] = array('attribs' => $opt);
            }
            if (count($arr[$release]['configureoption']) == 1) {
                $arr[$release]['configureoption'] = $arr[$release]['configureoption'][0];
            }
        }

        $this->_convertRelease2_0($arr[$release], $temp);
        if ($release == 'extsrcrelease' && count($arr[$release]) > 1) {
            // multiple extsrcrelease tags added in PEAR 1.4.1
            $arr['dependencies']['required']['pearinstaller']['min'] = '1.4.1';
        }

        if ($cl = $this->_packagefile->getChangelog()) {
            foreach ($cl as $release) {
                $rel = array();
                $rel['version'] =
                    array(
                        'release' => $release['version'],
                        'api' => $release['version'],
                    );
                if (!isset($release['release_state'])) {
                    $release['release_state'] = 'stable';
                }

                $rel['stability'] =
                    array(
                        'release' => $release['release_state'],
                        'api' => $release['release_state'],
                    );
                if (isset($release['release_date'])) {
                    $rel['date'] = $release['release_date'];
                } else {
                    $rel['date'] = date('Y-m-d');
                }

                if (isset($release['release_license'])) {
                    if (isset($licensemap[strtolower($release['release_license'])])) {
                        $uri = $licensemap[strtolower($release['release_license'])];
                    } else {
                        $uri = 'http://www.example.com';
                    }
                    $rel['license'] = array(
                            'attribs' => array('uri' => $uri),
                            '_content' => $release['release_license']
                        );
                } else {
                    $rel['license'] = $arr['license'];
                }

                if (!isset($release['release_notes'])) {
                    $release['release_notes'] = 'no release notes';
                }

                $rel['notes'] = $release['release_notes'];
                $arr['changelog']['release'][] = $rel;
            }
        }

        $ret = new $class;
        $ret->setConfig($this->_packagefile->_config);
        if (isset($this->_packagefile->_logger) && is_object($this->_packagefile->_logger)) {
            $ret->setLogger($this->_packagefile->_logger);
        }

        $ret->fromArray($arr);
        return $ret;
    }

    /**
     * @param array
     * @param bool
     * @access private
     */
    function _convertDependencies2_0(&$release, $internal = false)
    {
        $peardep = array('pearinstaller' =>
            array('min' => '1.4.0b1')); // this is a lot safer
        $required = $optional = array();
        $release['dependencies'] = array('required' => array());
        if ($this->_packagefile->hasDeps()) {
            foreach ($this->_packagefile->getDeps() as $dep) {
                if (!isset($dep['optional']) || $dep['optional'] == 'no') {
                    $required[] = $dep;
                } else {
                    $optional[] = $dep;
                }
            }
            foreach (array('required', 'optional') as $arr) {
                $deps = array();
                foreach ($$arr as $dep) {
                    // organize deps by dependency type and name
                    if (!isset($deps[$dep['type']])) {
                        $deps[$dep['type']] = array();
                    }
                    if (isset($dep['name'])) {
                        $deps[$dep['type']][$dep['name']][] = $dep;
                    } else {
                        $deps[$dep['type']][] = $dep;
                    }
                }
                do {
                    if (isset($deps['php'])) {
                        $php = array();
                        if (count($deps['php']) > 1) {
                            $php = $this->_processPhpDeps($deps['php']);
                        } else {
                            if (!isset($deps['php'][0])) {
                                list($key, $blah) = each ($deps['php']); // stupid buggy versions
                                $deps['php'] = array($blah[0]);
                            }
                            $php = $this->_processDep($deps['php'][0]);
                            if (!$php) {
                                break; // poor mans throw
                            }
                        }
                        $release['dependencies'][$arr]['php'] = $php;
                    }
                } while (false);
                do {
                    if (isset($deps['pkg'])) {
                        $pkg = array();
                        $pkg = $this->_processMultipleDepsName($deps['pkg']);
                        if (!$pkg) {
                            break; // poor mans throw
                        }
                        $release['dependencies'][$arr]['package'] = $pkg;
                    }
                } while (false);
                do {
                    if (isset($deps['ext'])) {
                        $pkg = array();
                        $pkg = $this->_processMultipleDepsName($deps['ext']);
                        $release['dependencies'][$arr]['extension'] = $pkg;
                    }
                } while (false);
                // skip sapi - it's not supported so nobody will have used it
                // skip os - it's not supported in 1.0
            }
        }
        if (isset($release['dependencies']['required'])) {
            $release['dependencies']['required'] =
                array_merge($peardep, $release['dependencies']['required']);
        } else {
            $release['dependencies']['required'] = $peardep;
        }
        if (!isset($release['dependencies']['required']['php'])) {
            $release['dependencies']['required']['php'] =
                array('min' => '4.0.0');
        }
        $order = array();
        $bewm = $release['dependencies']['required'];
        $order['php'] = $bewm['php'];
        $order['pearinstaller'] = $bewm['pearinstaller'];
        isset($bewm['package']) ? $order['package'] = $bewm['package'] :0;
        isset($bewm['extension']) ? $order['extension'] = $bewm['extension'] :0;
        $release['dependencies']['required'] = $order;
    }

    /**
     * @param array
     * @access private
     */
    function _convertFilelist2_0(&$package)
    {
        $ret = array('dir' =>
                    array(
                        'attribs' => array('name' => '/'),
                        'file' => array()
                        )
                    );
        $package['platform'] =
        $package['install-as'] = array();
        $this->_isExtension = false;
        foreach ($this->_packagefile->getFilelist() as $name => $file) {
            $file['name'] = $name;
            if (isset($file['role']) && $file['role'] == 'src') {
                $this->_isExtension = true;
            }
            if (isset($file['replacements'])) {
                $repl = $file['replacements'];
                unset($file['replacements']);
            } else {
                unset($repl);
            }
            if (isset($file['install-as'])) {
                $package['install-as'][$name] = $file['install-as'];
                unset($file['install-as']);
            }
            if (isset($file['platform'])) {
                $package['platform'][$name] = $file['platform'];
                unset($file['platform']);
            }
            $file = array('attribs' => $file);
            if (isset($repl)) {
                foreach ($repl as $replace ) {
                    $file['tasks:replace'][] = array('attribs' => $replace);
                }
                if (count($repl) == 1) {
                    $file['tasks:replace'] = $file['tasks:replace'][0];
                }
            }
            $ret['dir']['file'][] = $file;
        }
        return $ret;
    }

    /**
     * Post-process special files with install-as/platform attributes and
     * make the release tag.
     *
     * This complex method follows this work-flow to create the release tags:
     *
     * <pre>
     * - if any install-as/platform exist, create a generic release and fill it with
     *   o <install as=..> tags for <file name=... install-as=...>
     *   o <install as=..> tags for <file name=... platform=!... install-as=..>
     *   o <ignore> tags for <file name=... platform=...>
     *   o <ignore> tags for <file name=... platform=... install-as=..>
     * - create a release for each platform encountered and fill with
     *   o <install as..> tags for <file name=... install-as=...>
     *   o <install as..> tags for <file name=... platform=this platform install-as=..>
     *   o <install as..> tags for <file name=... platform=!other platform install-as=..>
     *   o <ignore> tags for <file name=... platform=!this platform>
     *   o <ignore> tags for <file name=... platform=other platform>
     *   o <ignore> tags for <file name=... platform=other platform install-as=..>
     *   o <ignore> tags for <file name=... platform=!this platform install-as=..>
     * </pre>
     *
     * It does this by accessing the $package parameter, which contains an array with
     * indices:
     *
     *  - platform: mapping of file => OS the file should be installed on
     *  - install-as: mapping of file => installed name
     *  - osmap: mapping of OS => list of files that should be installed
     *    on that OS
     *  - notosmap: mapping of OS => list of files that should not be
     *    installed on that OS
     *
     * @param array
     * @param array
     * @access private
     */
    function _convertRelease2_0(&$release, $package)
    {
        //- if any install-as/platform exist, create a generic release and fill it with
        if (count($package['platform']) || count($package['install-as'])) {
            $generic = array();
            $genericIgnore = array();
            foreach ($package['install-as'] as $file => $as) {
                //o <install as=..> tags for <file name=... install-as=...>
                if (!isset($package['platform'][$file])) {
                    $generic[] = $file;
                    continue;
                }
                //o <install as=..> tags for <file name=... platform=!... install-as=..>
                if (isset($package['platform'][$file]) &&
                      $package['platform'][$file]{0} == '!') {
                    $generic[] = $file;
                    continue;
                }
                //o <ignore> tags for <file name=... platform=... install-as=..>
                if (isset($package['platform'][$file]) &&
                      $package['platform'][$file]{0} != '!') {
                    $genericIgnore[] = $file;
                    continue;
                }
            }
            foreach ($package['platform'] as $file => $platform) {
                if (isset($package['install-as'][$file])) {
                    continue;
                }
                if ($platform{0} != '!') {
                    //o <ignore> tags for <file name=... platform=...>
                    $genericIgnore[] = $file;
                }
            }
            if (count($package['platform'])) {
                $oses = $notplatform = $platform = array();
                foreach ($package['platform'] as $file => $os) {
                    // get a list of oses
                    if ($os{0} == '!') {
                        if (isset($oses[substr($os, 1)])) {
                            continue;
                        }
                        $oses[substr($os, 1)] = count($oses);
                    } else {
                        if (isset($oses[$os])) {
                            continue;
                        }
                        $oses[$os] = count($oses);
                    }
                }
                //- create a release for each platform encountered and fill with
                foreach ($oses as $os => $releaseNum) {
                    $release[$releaseNum]['installconditions']['os']['name'] = $os;
                    $release[$releaseNum]['filelist'] = array('install' => array(),
                        'ignore' => array());
                    foreach ($package['install-as'] as $file => $as) {
                        //o <install as=..> tags for <file name=... install-as=...>
                        if (!isset($package['platform'][$file])) {
                            $release[$releaseNum]['filelist']['install'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                        'as' => $as,
                                    ),
                                );
                            continue;
                        }
                        //o <install as..> tags for
                        //  <file name=... platform=this platform install-as=..>
                        if (isset($package['platform'][$file]) &&
                              $package['platform'][$file] == $os) {
                            $release[$releaseNum]['filelist']['install'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                        'as' => $as,
                                    ),
                                );
                            continue;
                        }
                        //o <install as..> tags for
                        //  <file name=... platform=!other platform install-as=..>
                        if (isset($package['platform'][$file]) &&
                              $package['platform'][$file] != "!$os" &&
                              $package['platform'][$file]{0} == '!') {
                            $release[$releaseNum]['filelist']['install'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                        'as' => $as,
                                    ),
                                );
                            continue;
                        }
                        //o <ignore> tags for
                        //  <file name=... platform=!this platform install-as=..>
                        if (isset($package['platform'][$file]) &&
                              $package['platform'][$file] == "!$os") {
                            $release[$releaseNum]['filelist']['ignore'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                    ),
                                );
                            continue;
                        }
                        //o <ignore> tags for
                        //  <file name=... platform=other platform install-as=..>
                        if (isset($package['platform'][$file]) &&
                              $package['platform'][$file]{0} != '!' &&
                              $package['platform'][$file] != $os) {
                            $release[$releaseNum]['filelist']['ignore'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                    ),
                                );
                            continue;
                        }
                    }
                    foreach ($package['platform'] as $file => $platform) {
                        if (isset($package['install-as'][$file])) {
                            continue;
                        }
                        //o <ignore> tags for <file name=... platform=!this platform>
                        if ($platform == "!$os") {
                            $release[$releaseNum]['filelist']['ignore'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                    ),
                                );
                            continue;
                        }
                        //o <ignore> tags for <file name=... platform=other platform>
                        if ($platform{0} != '!' && $platform != $os) {
                            $release[$releaseNum]['filelist']['ignore'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                    ),
                                );
                        }
                    }
                    if (!count($release[$releaseNum]['filelist']['install'])) {
                        unset($release[$releaseNum]['filelist']['install']);
                    }
                    if (!count($release[$releaseNum]['filelist']['ignore'])) {
                        unset($release[$releaseNum]['filelist']['ignore']);
                    }
                }
                if (count($generic) || count($genericIgnore)) {
                    $release[count($oses)] = array();
                    if (count($generic)) {
                        foreach ($generic as $file) {
                            if (isset($package['install-as'][$file])) {
                                $installas = $package['install-as'][$file];
                            } else {
                                $installas = $file;
                            }
                            $release[count($oses)]['filelist']['install'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                        'as' => $installas,
                                    )
                                );
                        }
                    }
                    if (count($genericIgnore)) {
                        foreach ($genericIgnore as $file) {
                            $release[count($oses)]['filelist']['ignore'][] =
                                array(
                                    'attribs' => array(
                                        'name' => $file,
                                    )
                                );
                        }
                    }
                }
                // cleanup
                foreach ($release as $i => $rel) {
                    if (isset($rel['filelist']['install']) &&
                          count($rel['filelist']['install']) == 1) {
                        $release[$i]['filelist']['install'] =
                            $release[$i]['filelist']['install'][0];
                    }
                    if (isset($rel['filelist']['ignore']) &&
                          count($rel['filelist']['ignore']) == 1) {
                        $release[$i]['filelist']['ignore'] =
                            $release[$i]['filelist']['ignore'][0];
                    }
                }
                if (count($release) == 1) {
                    $release = $release[0];
                }
            } else {
                // no platform atts, but some install-as atts
                foreach ($package['install-as'] as $file => $value) {
                    $release['filelist']['install'][] =
                        array(
                            'attribs' => array(
                                'name' => $file,
                                'as' => $value
                            )
                        );
                }
                if (count($release['filelist']['install']) == 1) {
                    $release['filelist']['install'] = $release['filelist']['install'][0];
                }
            }
        }
    }

    /**
     * @param array
     * @return array
     * @access private
     */
    function _processDep($dep)
    {
        if ($dep['type'] == 'php') {
            if ($dep['rel'] == 'has') {
                // come on - everyone has php!
                return false;
            }
        }
        $php = array();
        if ($dep['type'] != 'php') {
            $php['name'] = $dep['name'];
            if ($dep['type'] == 'pkg') {
                $php['channel'] = 'pear.php.net';
            }
        }
        switch ($dep['rel']) {
            case 'gt' :
                $php['min'] = $dep['version'];
                $php['exclude'] = $dep['version'];
            break;
            case 'ge' :
                if (!isset($dep['version'])) {
                    if ($dep['type'] == 'php') {
                        if (isset($dep['name'])) {
                            $dep['version'] = $dep['name'];
                        }
                    }
                }
                $php['min'] = $dep['version'];
            break;
            case 'lt' :
                $php['max'] = $dep['version'];
                $php['exclude'] = $dep['version'];
            break;
            case 'le' :
                $php['max'] = $dep['version'];
            break;
            case 'eq' :
                $php['min'] = $dep['version'];
                $php['max'] = $dep['version'];
            break;
            case 'ne' :
                $php['exclude'] = $dep['version'];
            break;
            case 'not' :
                $php['conflicts'] = 'yes';
            break;
        }
        return $php;
    }

    /**
     * @param array
     * @return array
     */
    function _processPhpDeps($deps)
    {
        $test = array();
        foreach ($deps as $dep) {
            $test[] = $this->_processDep($dep);
        }
        $min = array();
        $max = array();
        foreach ($test as $dep) {
            if (!$dep) {
                continue;
            }
            if (isset($dep['min'])) {
                $min[$dep['min']] = count($min);
            }
            if (isset($dep['max'])) {
                $max[$dep['max']] = count($max);
            }
        }
        if (count($min) > 0) {
            uksort($min, 'version_compare');
        }
        if (count($max) > 0) {
            uksort($max, 'version_compare');
        }
        if (count($min)) {
            // get the highest minimum
            $min = array_pop($a = array_flip($min));
        } else {
            $min = false;
        }
        if (count($max)) {
            // get the lowest maximum
            $max = array_shift($a = array_flip($max));
        } else {
            $max = false;
        }
        if ($min) {
            $php['min'] = $min;
        }
        if ($max) {
            $php['max'] = $max;
        }
        $exclude = array();
        foreach ($test as $dep) {
            if (!isset($dep['exclude'])) {
                continue;
            }
            $exclude[] = $dep['exclude'];
        }
        if (count($exclude)) {
            $php['exclude'] = $exclude;
        }
        return $php;
    }

    /**
     * process multiple dependencies that have a name, like package deps
     * @param array
     * @return array
     * @access private
     */
    function _processMultipleDepsName($deps)
    {
        $ret = $tests = array();
        foreach ($deps as $name => $dep) {
            foreach ($dep as $d) {
                $tests[$name][] = $this->_processDep($d);
            }
        }

        foreach ($tests as $name => $test) {
            $max = $min = $php = array();
            $php['name'] = $name;
            foreach ($test as $dep) {
                if (!$dep) {
                    continue;
                }
                if (isset($dep['channel'])) {
                    $php['channel'] = 'pear.php.net';
                }
                if (isset($dep['conflicts']) && $dep['conflicts'] == 'yes') {
                    $php['conflicts'] = 'yes';
                }
                if (isset($dep['min'])) {
                    $min[$dep['min']] = count($min);
                }
                if (isset($dep['max'])) {
                    $max[$dep['max']] = count($max);
                }
            }
            if (count($min) > 0) {
                uksort($min, 'version_compare');
            }
            if (count($max) > 0) {
                uksort($max, 'version_compare');
            }
            if (count($min)) {
                // get the highest minimum
                $min = array_pop($a = array_flip($min));
            } else {
                $min = false;
            }
            if (count($max)) {
                // get the lowest maximum
                $max = array_shift($a = array_flip($max));
            } else {
                $max = false;
            }
            if ($min) {
                $php['min'] = $min;
            }
            if ($max) {
                $php['max'] = $max;
            }
            $exclude = array();
            foreach ($test as $dep) {
                if (!isset($dep['exclude'])) {
                    continue;
                }
                $exclude[] = $dep['exclude'];
            }
            if (count($exclude)) {
                $php['exclude'] = $exclude;
            }
            $ret[] = $php;
        }
        return $ret;
    }
}
?>


<?php

namespace Gwsn\Prismic\Models;

use Gwsn\Prismic\Models\Dom\RichText;

/**
 * A parent class for all classes having fragments: Document, DocumentLink, GroupDoc
 * @package Gwsn\Prismic\Models
 */
class Fragment {

    /** @var array $fragments */
    private $fragments;

    /**
     * Fragment constructor.
     *
     * @param array $fragments
     */
    function __construct(array $fragments) {
        $this->fragments = $fragments;
    }

    /**
     * Parse fragments from a json document. For internal usage.
     *
     * @param array $rawData
     *
     * @return array
     */
    public static function parseFragments(array $rawData = [])
    {
        $fragments = [];
        foreach ($rawData as $type => $value) {
            // Skipp Custom values
            if(!is_array($value)) continue;

            $fragments[] = RichText::asHtml($value);
        }

        return $fragments;
    }

}


<?php
/**
 * Created by PhpStorm.
 * User: coffee
 * Date: 2017/8/17
 * Time: 上午12:59
 */

namespace SimpleShop\Brand\Repositories;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use SimpleShop\Repositories\Contracts\RepositoryInterface as Repository;
use SimpleShop\Repositories\Criteria\Criteria;

class Order extends Criteria
{
    /**
     * @var array
     */
    private $order;

    /**
     * Order constructor.
     *
     * @param array $order
     */
    public function __construct(array $order)
    {
        $this->order = $order;
    }

    /**
     * @param  Model|Builder $model
     * @param Repository     $repository
     *
     * @return mixed
     */
    public function apply($model, Repository $repository)
    {
        foreach ($this->order as $order => $by) {
            $model = $model->orderBy($order, $by);
        }

        return $model;
    }
}


<?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\View;

use Valkyrja\Application;
use Valkyrja\Support\Directory;
use Valkyrja\Support\Providers\Provides;
use Valkyrja\View\Exceptions\InvalidConfigPath;

/**
 * Class View.
 *
 * @author Melech Mizrachi
 */
class PhpView implements View
{
    use Provides;

    /**
     * The application.
     *
     * @var Application
     */
    protected $app;

    /**
     * The layout template.
     *
     * @var string
     */
    protected $layout;

    /**
     * The fully qualified layout path.
     *
     * @var string
     */
    protected $layoutPath;

    /**
     * The body content template.
     *
     * @var string
     */
    protected $template = 'index';

    /**
     * The fully qualified template path.
     *
     * @var string
     */
    protected $templatePath;

    /**
     * The template directory.
     *
     * @var string
     */
    protected $templateDir;

    /**
     * @var string
     */
    protected $fileExtension = '.phtml';

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

    /**
     * The block status.
     *
     * @var array
     */
    protected $blockStatus = [];

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

    /**
     * Whether to track layout changes.
     *
     * @var bool
     */
    protected $trackLayoutChanges = false;

    /**
     * Whether a layout change has occurred.
     *
     * @var bool
     */
    protected $hasLayoutChanged = false;

    /**
     * View constructor.
     *
     * @param Application $app       The application
     * @param string      $template  [optional] The template to set
     * @param array       $variables [optional] The variables to set
     *
     * @throws InvalidConfigPath
     */
    public function __construct(Application $app, string $template = null, array $variables = [])
    {
        $this->app = $app;
        $this->setVariables($variables);
        $this->setTemplateDir($this->app->config()['views']['dir']);
        $this->template($template ?? $this->template);
    }

    /**
     * Make a new View.
     *
     * @param string $template  [optional] The template to set
     * @param array  $variables [optional] The variables to set
     *
     * @throws InvalidConfigPath
     *
     * @return \Valkyrja\View\View
     */
    public function make(string $template = null, array $variables = []): View
    {
        return new static($this->app, $template, $variables);
    }

    /**
     * Get the variables.
     *
     * @return array
     */
    public function getVariables(): array
    {
        return $this->variables;
    }

    /**
     * Set the variables.
     *
     * @param array $variables [optional] The variables to set
     *
     * @return \Valkyrja\View\View
     */
    public function setVariables(array $variables = []): View
    {
        $this->variables = array_merge($this->variables, $variables);

        return $this;
    }

    /**
     * Get a variable.
     *
     * @param string $key The variable key to set
     *
     * @return mixed
     */
    public function variable(string $key)
    {
        return $this->variables[$key] ?? null;
    }

    /**
     * Set a single variable.
     *
     * @param string $key   The variable key to set
     * @param mixed  $value The value to set
     *
     * @return \Valkyrja\View\View
     */
    public function setVariable(string $key, $value): View
    {
        $this->variables[$key] = $value;

        return $this;
    }

    /**
     * Escape a value for output.
     *
     * @param string $value The value to escape
     *
     * @return string
     */
    public function escape(string $value): string
    {
        $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
        $value = htmlentities($value, ENT_QUOTES, 'UTF-8');

        return $value;
    }

    /**
     * Get the template directory.
     *
     * @param string $path [optional] The path to append
     *
     * @return string
     */
    public function getTemplateDir(string $path = null): string
    {
        return $this->templateDir . ($path
                ? Directory::DIRECTORY_SEPARATOR . $path
                : $path);
    }

    /**
     * Set the template directory.
     *
     * @param string $templateDir The path to set
     *
     * @return \Valkyrja\View\View
     */
    public function setTemplateDir(string $templateDir): View
    {
        $this->templateDir = $templateDir;

        return $this;
    }

    /**
     * Get the file extension.
     *
     * @return string
     */
    public function getFileExtension(): string
    {
        return $this->fileExtension;
    }

    /**
     * Set the file extension.
     *
     * @param string $extension The extension to set
     *
     * @return \Valkyrja\View\View
     */
    public function setFileExtension(string $extension): View
    {
        $this->fileExtension = $extension;

        return $this;
    }

    /**
     * Get the layout template path.
     *
     * @return string
     */
    public function getLayoutPath(): string
    {
        return $this->layoutPath;
    }

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

    /**
     * Set the layout for the view template.
     *
     * @param string $layout [optional] The layout to set
     *
     * @throws InvalidConfigPath
     *
     * @return \Valkyrja\View\View
     */
    public function layout(string $layout = null): View
    {
        // If no layout has been set
        if (null === $layout) {
            // Set to null
            return $this->withoutLayout();
        }

        // If we should be tracking layout changes
        if ($this->trackLayoutChanges) {
            // Set the flag
            $this->hasLayoutChanged = true;
        }

        $this->layout     = $layout;
        $this->layoutPath = $this->getFullPath($layout);

        return $this;
    }

    /**
     * Set no layout for this view.
     *
     * @return \Valkyrja\View\View
     */
    public function withoutLayout(): View
    {
        $this->layout     = null;
        $this->layoutPath = null;

        return $this;
    }

    /**
     * Set the template for the view.
     *
     * @param string $template The template
     *
     * @throws InvalidConfigPath
     *
     * @return \Valkyrja\View\View
     */
    public function template(string $template): View
    {
        $this->template     = $template;
        $this->templatePath = $this->getFullPath($template);

        return $this;
    }

    /**
     * Output a partial.
     *
     * @param string $partial   The partial
     * @param array  $variables [optional]
     *
     * @throws InvalidConfigPath
     *
     * @return string
     */
    public function partial(string $partial, array $variables = []): string
    {
        return $this->renderTemplate($this->getFullPath($partial), $variables);
    }

    /**
     * Output a block.
     *
     * @param string $name The block's name
     *
     * @return string
     */
    public function block(string $name): string
    {
        return $this->blocks[$name] ?? '';
    }

    /**
     * Determine if a block exists.
     *
     * @param string $name
     *
     * @return bool
     *  True if the block exists
     *  False if the block doesn't exist
     */
    public function hasBlock(string $name): bool
    {
        return isset($this->blocks[$name]);
    }

    /**
     * Determine if a block has been ended.
     *
     * @param string $name
     *
     * @return bool
     *  True if the block has been ended
     *  False if the block has not yet been ended
     */
    public function hasBlockBeenEnded(string $name): bool
    {
        return ! isset($this->blockStatus[$name]);
    }

    /**
     * Start a block.
     *
     * @param string $name The block's name
     *
     * @return void
     */
    public function startBlock(string $name): void
    {
        $this->blockStatus[$name] = $name;

        ob_start();
    }

    /**
     * End a block.
     *
     * @param string $name The block's name
     *
     * @return string
     */
    public function endBlock(string $name): string
    {
        unset($this->blockStatus[$name]);

        return $this->blocks[$name] = ob_get_clean();
    }

    /**
     * Render the templates and view.
     *
     * @param array $variables [optional] The variables to set
     *
     * @return string
     */
    public function render(array $variables = []): string
    {
        // Set the variables with the new variables and this view instance
        $this->variables = array_merge(
            $this->variables,
            $variables,
            ['view' => $this]
        );

        // Render the template
        $template = $this->renderTemplate($this->templatePath);

        // Check if a layout has been set
        if (null === $this->layout) {
            return $template;
        }

        // Begin tracking layout changes for recursive layout
        $this->trackLayoutChanges = true;

        return $this->renderTemplate($this->layoutPath);
    }

    /**
     * Get the view as a string.
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->render();
    }

    /**
     * Get the full path for a given template.
     *
     * @param string $template The template
     *
     * @throws InvalidConfigPath
     *
     * @return string
     */
    protected function getFullPath(string $template): string
    {
        // If the first character of the template is an @ symbol
        // Then this is a template from a path in the config
        if (strpos($template, '@') === 0) {
            $explodeOn = Directory::DIRECTORY_SEPARATOR;
            $parts     = explode($explodeOn, $template);
            $path      = config('views.paths.' . $parts[0]);

            // If there is no path
            if ($path === null) {
                // Then throw an exception
                throw new InvalidConfigPath(
                    'Invalid path '
                    . $parts[0]
                    . ' specified for template '
                    . $template
                );
            }

            // Remove any trailing slashes
            $parts[0] = $explodeOn . trim($path, $explodeOn);

            $path = implode($explodeOn, $parts);
        } else {
            $path = $this->getTemplateDir($template);
        }

        return $path . $this->getFileExtension();
    }

    /**
     * Render a template.
     *
     * @param string $templatePath The template path
     * @param array  $variables    [optional] The variables to set
     *
     * @return string
     */
    protected function renderTemplate(string $templatePath, array $variables = []): string
    {
        $variables = array_merge($this->variables, $variables);

        extract($variables, EXTR_OVERWRITE);

        ob_start();
        include $templatePath;

        return ob_get_clean();
    }

    /**
     * Render a layout path.
     *
     * @param string $layoutPath The layout path
     *
     * @return string
     */
    protected function renderLayout(string $layoutPath): string
    {
        // Render the layout
        $renderedLayout = $this->renderTemplate($layoutPath);

        // Check if the layout has changed
        if ($this->hasLayoutChanged) {
            // Reset the flag
            $this->hasLayoutChanged = false;
            // Render the new layout
            $renderedLayout = $this->renderLayout($this->layoutPath);
        }

        return $renderedLayout;
    }

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

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @throws InvalidConfigPath
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            View::class,
            new static($app)
        );
    }
}


<?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\Routing\Commands;

use Valkyrja\Console\CommandHandler;
use Valkyrja\Console\Enums\FormatForeground;
use Valkyrja\Console\Enums\FormatOption;
use Valkyrja\Console\Support\ProvidesCommand;
use Valkyrja\Routing\Route;

/**
 * Class RoutesListCommand.
 *
 * @author Melech Mizrachi
 */
class RoutesListCommand extends CommandHandler
{
    use ProvidesCommand;

    /**
     * The command.
     */
    public const COMMAND           = 'routes:list';
    public const PATH              = self::COMMAND;
    public const SHORT_DESCRIPTION = 'List all routes';
    public const DESCRIPTION       = '';

    protected const CYAN_FORMAT       = "\e[" . FormatForeground::CYAN . 'm';
    protected const LIGHT_CYAN_FORMAT = "\e[" . FormatForeground::LIGHT_CYAN . 'm';
    protected const INVERT_FORMAT     = "\e[" . FormatOption::INVERSE . 'm';
    protected const END_COLOR_FORMAT  = "\e[" . FormatForeground::DEFAULT . 'm';
    protected const END_FORMAT        = "\e[0m";

    /**
     * Run the command.
     *
     * @throws \InvalidArgumentException
     *
     * @return int
     */
    public function run(): int
    {
        $routerRoutes = router()->getRoutes();
        $routes       = [];
        $headerTexts  = [
            'Request Methods',
            'Path',
            'Name',
            'Dispatch',
        ];
        $lengths      = [
            \strlen($headerTexts[0]),
            \strlen($headerTexts[1]),
            \strlen($headerTexts[2]),
            \strlen($headerTexts[3]),
        ];

        foreach ($routerRoutes as $route) {
            $this->setRoute($route, $routes, $lengths);
        }

        $sepLine = $this->getSepLine($lengths);
        $odd     = false;

        output()->writeMessage($this->oddFormat(! $odd) . $sepLine, true);
        $this->headerMessage($headerTexts, $lengths);
        output()->writeMessage($sepLine, true);

        foreach ($routes as $key => $route) {
            $routeMessage = '| '
                . $route[0]
                . str_repeat(' ', $lengths[0] - \strlen($route[0]))
                . ' | '
                . $route[1]
                . str_repeat(' ', $lengths[1] - \strlen($route[1]))
                . ' | '
                . $route[2]
                . str_repeat(' ', $lengths[2] - \strlen($route[2]))
                . ' | '
                . $route[3]
                . str_repeat(' ', $lengths[3] - \strlen($route[3]))
                . ' |';

            $odd          = $key % 2 > 0;
            $routeMessage = $this->oddFormat($odd) . $routeMessage;

            output()->writeMessage($routeMessage . static::END_FORMAT, true);
        }

        output()->writeMessage(
            $this->oddFormat(! $odd) . $sepLine . static::END_FORMAT,
            true
        );

        return 0;
    }

    /**
     * Set a route as an array from a route object.
     *
     * @param Route $route   The route object
     * @param array $routes  The flat routes
     * @param array $lengths The longest string lengths
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    protected function setRoute(Route $route, array &$routes, array &$lengths): void
    {
        $requestMethod = implode(' | ', $route->getRequestMethods());
        $dispatch      = 'Closure';

        if (null !== $route->getFunction()) {
            $dispatch = $route->getFunction();
        } elseif (null !== $route->getClass()) {
            $dispatch = $route->getClass()
                . ($route->isStatic() ? '::' : '->')
                . ($route->getMethod()
                    ? $route->getMethod() . '()'
                    : $route->getProperty());
        }

        $lengths[0] = max($lengths[0], \strlen($requestMethod));
        $lengths[1] = max($lengths[1], \strlen($route->getPath()));
        $lengths[2] = max($lengths[2], \strlen($route->getName()));
        $lengths[3] = max($lengths[3], \strlen($dispatch));

        $routes[] = [
            $requestMethod,
            $route->getPath(),
            $route->getName() ?? '',
            $dispatch,
        ];
    }

    /**
     * Get the separation line.
     *
     * @param array $lengths The longest lengths
     *
     * @return string
     */
    protected function getSepLine(array $lengths): string
    {
        return '+-' . str_repeat('-', $lengths[0])
            . '-+-' . str_repeat('-', $lengths[1])
            . '-+-' . str_repeat('-', $lengths[2])
            . '-+-' . str_repeat('-', $lengths[3])
            . '-+';
    }

    /**
     * Output the header message.
     *
     * @param array $headerTexts The header texts
     * @param array $lengths     The longest lengths
     *
     * @return void
     */
    protected function headerMessage(array $headerTexts, array $lengths): void
    {
        $headerMessage = '| ' . $headerTexts[0]
            . str_repeat(' ', $lengths[0] - \strlen($headerTexts[0]))
            . ' | ' . $headerTexts[1]
            . str_repeat(' ', $lengths[1] - \strlen($headerTexts[1]))
            . ' | ' . $headerTexts[2]
            . str_repeat(' ', $lengths[2] - \strlen($headerTexts[2]))
            . ' | ' . $headerTexts[3]
            . str_repeat(' ', $lengths[3] - \strlen($headerTexts[3]))
            . ' |';

        output()->writeMessage($headerMessage, true);
    }

    protected function oddFormat(bool $odd): string
    {
        return $odd
            ? static::INVERT_FORMAT . static::CYAN_FORMAT
            : static::INVERT_FORMAT . static::LIGHT_CYAN_FORMAT;
    }
}


<?php

namespace AbuseIO\Notification;

use Composer\Autoload\ClassMapGenerator;
use Log;

/**
 * Class Factory
 * @package AbuseIO\Notification
 */
class Factory
{
    /**
     * Create a new Factory instance
     */
    public function __construct()
    {
        //
    }

    /**
     * Get a list of installed AbuseIO notifications and return as an array
     *
     * @return array
     */
    public static function getNotification()
    {
        $notificationClassList = ClassMapGenerator::createMap(base_path().'/vendor/abuseio');
        /** @noinspection PhpUnusedParameterInspection */
        $notificationClassListFiltered = array_where(
            array_keys($notificationClassList),
            function ($value, $key) {
                // Get all notifications, ignore all other packages.
                if (strpos($value, 'AbuseIO\Notification\\') !== false) {
                    return $value;
                }
                return false;
            }
        );

        $notifications = [];
        $notificationList = array_map('class_basename', $notificationClassListFiltered);
        foreach ($notificationList as $notification) {
            if (!in_array($notification, ['Factory', 'Notification'])) {
                $notifications[] = $notification;
            }
        }
        return $notifications;
    }

    /**
     * Create and return a Collector object and it's configuration
     *
     * @param string $requiredName
     * @return object
     */
    public static function create($requiredName)
    {
        /**
         * Loop through the notification list and try to find a match by name
         */
        $notifications = Factory::getNotification();
        foreach ($notifications as $notificationName) {

            if ($notificationName === ucfirst($requiredName)) {
                $notificationClass = 'AbuseIO\\Notification\\' . $notificationName;

                // Collector is enabled, then return its object
                if (config("notifications.{$notificationName}.notification.enabled") === true) {

                    return new $notificationClass();

                } else {
                    Log::info(
                        'AbuseIO\Notification\Factory: ' .
                        "The notification {$notificationName} has been disabled and will not be used."
                    );

                    return false;
                }
            }
        }

        // No valid notifications found
        Log::info(
            'AbuseIO\Notification\Factory: ' .
            "The notification {$requiredName} is not present on this system"
        );
        return false;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Model;

use Behat\Transliterator\Transliterator;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Trait UploadableTrait
 * @package Ekyna\Bundle\CoreBundle\Model
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
trait UploadableTrait
{
    use TimestampableTrait;

    /**
     * The key for the upload filesystem
     *
     * @var string
     */
    protected $key;

    /**
     * File uploaded
     *
     * @var File
     */
    protected $file;

    /**
     * Size
     *
     * @var int
     */
    protected $size;

    /**
     * Path
     *
     * @var string
     */
    protected $path;

    /**
     * Old path (for removal)
     *
     * @var string
     */
    protected $oldPath;

    /**
     * Name
     *
     * @var string
     */
    protected $rename;

    /**
     * Unlink (set the subject image field to null)
     *
     * @var bool
     */
    protected $unlink;

    /**
     * Sets the key.
     *
     * @param string $key
     * @return UploadableTrait
     */
    public function setKey($key)
    {
        $this->key = $key;

        if (0 < strlen($this->key) && !$this->hasRename()) {
            if ($this->hasPath()) {
                $this->rename = pathinfo($this->path, PATHINFO_BASENAME);
            } else {
                $this->rename = pathinfo($this->key, PATHINFO_BASENAME);
            }
            $this->setUpdatedAt(new \DateTime());
        }

        return $this;
    }

    /**
     * Returns whether the uploadable has an upload key.
     *
     * @return bool
     */
    public function hasKey()
    {
        return 0 < strlen($this->key);
    }

    /**
     * Returns the key.
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Set file
     *
     * @param File $file
     * @return UploadableTrait|$this
     */
    public function setFile(File $file = null)
    {
        $this->file = $file;

        if (null !== $file && !$this->hasRename()) {
            if ($this->hasPath()) {
                $this->rename = pathinfo($this->path, PATHINFO_BASENAME);
            } elseif ($file instanceof UploadedFile) {
                $this->rename = $file->getClientOriginalName();
            } elseif ($file instanceof File) {
                $this->rename = $file->getBasename();
            }
            $this->setUpdatedAt(new \DateTime());
        }

        return $this;
    }

    /**
     * Has file.
     *
     * @return boolean
     */
    public function hasFile()
    {
        return null !== $this->file;
    }

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

    /**
     * Sets the size.
     *
     * @param int $size
     * @return UploadableTrait|$this
     */
    public function setSize($size)
    {
        $this->size = intval($size);
        return $this;
    }

    /**
     * Returns the size.
     *
     * @return int
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * Set path.
     *
     * @param string $path
     * @return UploadableTrait|$this
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Has path.
     *
     * @return boolean
     */
    public function hasPath()
    {
        return null !== $this->path;
    }

    /**
     * Get path.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set old path.
     *
     * @param string $oldPath
     * @return UploadableTrait|$this
     */
    public function setOldPath($oldPath)
    {
        $this->oldPath = $oldPath;

        return $this;
    }

    /**
     * Has old path.
     *
     * @return boolean
     */
    public function hasOldPath()
    {
        return null !== $this->oldPath;
    }

    /**
     * Get old path.
     *
     * @return string
     */
    public function getOldPath()
    {
        return $this->oldPath;
    }

    /**
     * Returns whether the uploadable should be renamed or not.
     *
     * @return boolean
     */
    public function shouldBeRenamed()
    {
        return (bool) ($this->hasPath() && $this->guessFilename() != pathinfo($this->getPath(), PATHINFO_BASENAME));
    }

    /**
     * Guess file extension.
     *
     * @return string
     */
    public function guessExtension()
    {
        $extension = null;
        if ($this->hasFile()) {
            $extension = $this->file->guessExtension();
        } elseif ($this->hasKey()) {
            $extension = pathinfo($this->getKey(), PATHINFO_EXTENSION);
        } elseif ($this->hasPath()) {
            $extension = pathinfo($this->getPath(), PATHINFO_EXTENSION);
        }
        $extension = strtolower($extension);
        return $extension;
    }

    /**
     * Guess file name.
     *
     * @return string
     */
    public function guessFilename()
    {
        // Extension
        $extension = $this->guessExtension();

        // Filename
        $filename = null;
        if ($this->hasRename()) {
            $filename = Transliterator::urlize(pathinfo($this->rename, PATHINFO_FILENAME));
        } elseif ($this->hasFile()) {
            $filename = pathinfo($this->file->getFilename(), PATHINFO_FILENAME);
        } elseif ($this->hasKey()) {
            $filename = pathinfo($this->getKey(), PATHINFO_FILENAME);
        } elseif ($this->hasPath()) {
            $filename = pathinfo($this->path, PATHINFO_FILENAME);
        }

        if ($filename !== null && $extension !== null) {
            return $filename . '.' . $extension;
        }

        return null;
    }

    /**
     * GuessFilename alias.
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->guessFilename();
    }

    /**
     * Set rename.
     *
     * @param string $rename
     * @return UploadableTrait|$this
     */
    public function setRename($rename)
    {
        if ($rename !== $this->rename) {
            $this->updatedAt = new \DateTime();
        }
        $this->rename = strtolower($rename);

        return $this;
    }

    /**
     * Returns whether the uploadable has a rename or not.
     *
     * @return boolean
     */
    public function hasRename()
    {
        return 0 < strlen($this->rename);
    }

    /**
     * Get rename.
     *
     * @return string
     */
    public function getRename()
    {
        return $this->hasRename() ? $this->rename : $this->guessFilename();
    }

    /**
     * Sets the whether the uploadable should be unlinked from subject.
     *
     * @param boolean $unlink
     * @return UploadableTrait
     */
    public function setUnlink($unlink)
    {
        $this->unlink = (bool) $unlink;
        return $this;
    }

    /**
     * Returns whether the uploadable should be unlinked from subject.
     *
     * @return boolean
     */
    public function getUnlink()
    {
        return $this->unlink;
    }
}


<?php namespace Ordercloud\Entities\Users;

use JsonSerializable;

class UserProfile implements JsonSerializable
{
    const GENDER_MALE = 'M';
    const GENDER_FEMALE = 'F';

    /** @var string */
    private $firstName;
    /** @var string */
    private $surname;
    /** @var string */
    private $email;
    /** @var string */
    private $nickName;
    /** @var string */
    private $cellphoneNumber;
    /** @var string */
    private $sex;

    public function __construct($firstName, $surname, $email, $nickName, $cellphoneNumber, $sex)
    {
        $this->firstName = $firstName;
        $this->surname = $surname;
        $this->email = $email;
        $this->nickName = $nickName;
        $this->cellphoneNumber = $cellphoneNumber;
        $this->sex = $sex;
    }

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

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

    /**
     * @return string
     */
    public function getFullname()
    {
        return implode(' ', [$this->getFirstName(), $this->getSurname()]);
    }

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

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

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

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

    public function isMale()
    {
        return $this->getSex() == static::GENDER_MALE;
    }

    public function isFemale()
    {
        return $this->getSex() == static::GENDER_FEMALE;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'firstName' => $this->getFirstName(),
            'surname' => $this->getSurname(),
            'email' => $this->getEmail(),
            'nickName' => $this->getNickName(),
            'cellphoneNumber' => $this->getCellphoneNumber(),
            'sex' => $this->getSex(),
        ];
    }
}


<?php declare(strict_types=1); namespace BapCat\Tailor;

use BapCat\Hashing\Hash;
use BapCat\Hashing\Hasher;
use BapCat\Persist\File;

class DefaultHashGenerator implements HashGenerationStrategy {
  /** @var Hasher $hasher */
  private $hasher;

  public function __construct(Hasher $hasher) {
    $this->hasher = $hasher;
  }

  /**
   * {@inheritdoc}
   */
  public function generateHash(File $template, array $params): Hash {
    return $this->hasher->make($template->path . json_encode($params) . $template->modified);
  }
}