<?php
// Copyright 2019 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

error_reporting((E_ALL | E_STRICT) & ~E_WARNING);
ini_set('display_errors', 1);

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/error.php';

Header('Access-Control-Allow-Origin: *');
Header('Content-Type: application/json');

$environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']);
if (!$environment->isValid())
    dieWithError('Unrecognized volunteer portal environment.');

echo json_encode([
    'contactName'   => 'Peter',
    'contactTarget' => 'mailto:' . $environment->getContact(),
    'title'         => $environment->getName(),

    'events' => [
        [
            'name'                  => 'AnimeCon 2021',
            'enablePortal'          => false,
            'enableRegistration'    => false,
            'timezone'              => 'Europe/Amsterdam',
            'website'               => 'https://www.animecon.nl/',
        ],
    ],
]);

<?php
// Copyright 2019 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

error_reporting((E_ALL | E_STRICT) & ~E_WARNING);
ini_set('display_errors', 1);

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/error.php';

Header('Access-Control-Allow-Origin: *');
Header('Content-Type: application/json');

$environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']);
if (!$environment->isValid())
    dieWithError('Unrecognized volunteer portal environment.');

echo json_encode([
    'contactName'   => 'Peter',
    'contactTarget' => 'mailto:' . $environment->getContact(),
    'title'         => $environment->getName(),

    'events' => [
        [
            'name'                  => 'AnimeCon 2021',
            'enablePortal'          => false,
            'enableRegistration'    => false,
            'slug'                  => '2021',
            'timezone'              => 'Europe/Amsterdam',
            'website'               => 'https://www.animecon.nl/',
        ],
    ],
]);

Include a slug for the upcoming event

Include a slug for the upcoming event


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/resource', function () {

    $authenticated = false;
    Session::set('authenticated' ,true);
    if (Session::has('authenticated')){
        if (Session::has('authenticated') == true ){
            $authenticated = true;
        }
    }

    if ($authenticated){
    return view('resource');
    }else {
        return view('login');
    }
});

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/resource', function () {

    $authenticated = false;
    \Debugbar::info("Xivato");
    \Debugbar::info(Session::all());
    //Session::set('authenticated' ,true);
    if (Session::has('authenticated')){
        if (Session::has('authenticated') == true ){
            $authenticated = true;
        }
    }

    if ($authenticated){
    return view('resource');
    }else {
        return view('login');
    }
});

Add Debugbar for comprovation errors for debug


<?php
/**
 * Validates login using basic authentication
 */

require_once __DIR__ . '/../bootstrap.php';

logout(); //Destroy any old sessions
Authenticate();

$result = new Entity(['success'=>'You have been logged in successfully!']);
echo $result->toJSON();

<?php
/**
 * Validates login using basic authentication
 */

require_once __DIR__ . '/../bootstrap.php';

logout(); //Destroy any old sessions
Authenticate();
$person = Person::user();
echo $person->toJSON();

Return person information when logging in


<?php if (!defined('APPLICATION')) exit();

// Cache
$Configuration['Cache']['Enabled'] = TRUE;
$Configuration['Cache']['Method'] = 'memcached';

// memcached
$Configuration['memcached']['Store'] = 'cache';

Set correct memcached store in Vanilla.

Set correct memcached store in Vanilla.


<?php

return array(

    // Always show the paginator, even if there are no pages?
    'always_show' => false,
    // Show the first/last page links?
    'show_first_last' => false,
    // Align simple paginator to the sides?
    'align_simple' => false,
    // Paginator's Bootstrap classes. See: http://twitter.github.io/bootstrap/components.html#pagination
    'classes' => 'pagination',

);

<?php

return array(

    // Always show the paginator, even if there are no pages?
    'always_show' => false,
    // Show the first/last page links?
    'show_first_last' => false,
    // Align simple paginator to the sides?
    'align_simple' => false,
    // Paginator's Bootstrap classes. See: http://getbootstrap.com/2.3.2/components.html#pagination
    'classes' => 'pagination',

);

Update link to example Bootstrap classes.


<?php
namespace LaravelRocket\Foundation\Tests\Listeners;

class DatabaseSetupListener extends \PHPUnit_Framework_BaseTestListener
{
    protected $suites = ['Application Test Suite'];

    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        if (in_array($suite->getName(), $this->suites)) {
            exec('php artisan migrate');
        }
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        if (in_array($suite->getName(), $this->suites)) {
            exec('php artisan migrate:rollback');
        }
    }
}

<?php
namespace LaravelRocket\Foundation\Tests\Listeners;

class DatabaseSetupListener extends \PHPUnit_Framework_BaseTestListener
{
    protected $suites = ['Application Test Suite'];

    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        if (in_array($suite->getName(), $this->suites)) {
            $this->initialize($suite);
        }
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        if (in_array($suite->getName(), $this->suites)) {
            $this->terminate($suite);
        }
    }

    protected function initialize(\PHPUnit_Framework_TestSuite $suite)
    {
        exec('php artisan migrate');
    }

    protected function terminate(\PHPUnit_Framework_TestSuite $suite)
    {
        exec('php artisan migrate:reset');
    }

}

Update Test Listner to be able to customize


<!DOCTYPE html>

  <title>Myna PHP Demo</title>

Myna PHP Demo

<?php
require_once '../src/autoload.php';

$experimentId = '8ebfeab2-c308-413f-93ff-45beb603949a';
$deploymentUuid = 'ae15f7c0-df1f-11e2-bfc7-7c6d628b25f7';
$client = \Myna\Myna::init($deploymentUuid);
$suggestion = $client->suggest($experimentId);

echo "
Suggestion is {$suggestion->name}
";
?>

<!DOCTYPE html>

  <title>Myna PHP Demo</title>

Myna PHP Demo

<?php
require_once '../src/autoload.php';

// Turn on logging
\Myna\Log::$enabled = true;

$experimentId = '8ebfeab2-c308-413f-93ff-45beb603949a';
$deploymentUuid = 'ae15f7c0-df1f-11e2-bfc7-7c6d628b25f7';
$client = \Myna\Myna::init($deploymentUuid);
$suggestion = $client->suggest($experimentId);

echo "
Suggestion is {$suggestion->name}
";
?>

Enable logging in the demo

Enable logging in the demo


<?php
class Kwc_Trl_Table_Root_Master extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['generators']['table'] = array(
            'class' => 'Kwf_Component_Generator_Page_Static',
            'component' => 'Kwc_Trl_Table_Table_Component',
            'name' => 'table',
        );
        return $ret;
    }
}

<?php
class Kwc_Trl_Table_Root_Master extends Kwc_Root_TrlRoot_Master_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['generators']['table'] = array(
            'class' => 'Kwf_Component_Generator_Page_Static',
            'component' => 'Kwc_Trl_Table_Table_Component',
            'name' => 'table',
        );
        unset($ret['generators']['flag']);
        unset($ret['generators']['box']);
        unset($ret['generators']['category']);
        return $ret;
    }
}

Fix setup for table trl test

Fix setup for table trl test


<?php
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));

if (APPLICATION_ENV === 'development') {
    ini_set('display_errors', true);
}

define('TEST_PATH', realpath(__DIR__));

chdir(realpath(TEST_PATH . '/../../'));

include 'init_autoloader.php';

if (isset($loader)) {
    $loader->add('MockObject', TEST_PATH);
    $loader->add('TestHelper', TEST_PATH);
}

//Regiser zf2 autoloader as fallback to autoload PHPUnit_* classes from include path
$zf2Autoloader = new Zend\Loader\StandardAutoloader();
$zf2Autoloader->setFallbackAutoloader(true);
$zf2Autoloader->register();

include 'vendor/Cl/Test/PHPUnitTestCase.php';

Cl\Test\PHPUnitTestCase::setApplication(
    Zend\Mvc\Application::init(include 'config/application.config.php')
    );

<?php
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));

if (APPLICATION_ENV === 'development') {
    ini_set('display_errors', true);
}

define('TEST_PATH', realpath(__DIR__));

chdir(realpath(TEST_PATH . '/../../'));

include 'init_autoloader.php';

if (isset($loader)) {
    $loader->add('MockObject', TEST_PATH);
    $loader->add('TestHelper', TEST_PATH);
}

//Regiser zf2 autoloader as fallback to autoload PHPUnit_* classes from include path
$zf2Autoloader = new Zend\Loader\StandardAutoloader();
$zf2Autoloader->setFallbackAutoloader(true);
$zf2Autoloader->register();

include 'module/Cl/Test/PHPUnitTestCase.php';

Cl\Test\PHPUnitTestCase::setApplication(
    Zend\Mvc\Application::init(include 'config/application.config.php')
    );

Fix broken include of Cl\PHPUnitTestCase


<?php
/**
 * Created by PhpStorm.
 * User: dtome
 * Date: 18/02/17
 * Time: 18:24
 */

namespace Slx\UserInterface\Controllers\User;

use Silex\Application;

class SignOutController
{
    /**
     * @var Application
     */
    private $application;

    /**
     * SignOutController constructor.
     *
     * @param Application $application
     */
    public function __construct(Application $application)
    {
        $this->application = $application;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function indexAction()
    {
        $this->application['signout.service']->execute();

        return $this->application->redirect($this->application['url_generator']->generate('signin'));
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: dtome
 * Date: 18/02/17
 * Time: 18:24
 */

namespace Slx\UserInterface\Controllers\User;

use Silex\Application;
use Slx\Infrastructure\Service\User\AuthenticateUserService;

class SignOutController
{
    /**
     * @var Application
     */
    private $application;

    /**
     * SignOutController constructor.
     *
     * @param Application $application
     */
    public function __construct(Application $application)
    {
        $this->application = $application;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function indexAction()
    {
        (new AuthenticateUserService($this->application['session']))->removeSession();

        return $this->application->redirect($this->application['url_generator']->generate('signin'));
    }
}

Use authentication service to signout

Use authentication service to signout


<?php

/*

Plugin Name: Castlegate IT WP Show ID
Plugin URI: http://github.com/castlegateit/cgit-wp-show-id
Description: Show post and page ID in WordPress admin panel.
Version: 1.1
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: MIT

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

require_once __DIR__ . '/classes/autoload.php';

$plugin = new \Cgit\ShowPostId\Plugin();

do_action('cgit_show_id_loaded');

<?php

/*

Plugin Name: Castlegate IT WP Show ID
Plugin URI: http://github.com/castlegateit/cgit-wp-show-id
Description: Show post and page ID in WordPress admin panel.
Version: 1.1
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: AGPL

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

require_once __DIR__ . '/classes/autoload.php';

$plugin = new \Cgit\ShowPostId\Plugin();

do_action('cgit_show_id_loaded');

Switch license from MIT to AGPL in plugin file


<?php

namespace mcfedr\TwitterPushBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DeviceController extends Controller {
    /**
     * @Route("/devices")
     * @Method({"POST"})
     */
    public function registerDeviceAction(Request $request) {
        $data = $this->handleJSONRequest($request);
        if($data instanceof Response) {
            return $data;
        }

        if(!isset($data['deviceID']) || !isset($data['platform'])) {
            return new Response('Missing parameters', 400);
        }

        try {
            if($this->getPushDevices()->registerDevice($data['deviceID'], $data['platform'])) {
                return new Response('Device registered', 200);
            }
        }
        catch(PlatformNotConfiguredException $e) {
            return new Response('Unknown platform', 400);
        }

        return new Response('Unknown error', 500);
    }

    /**
     * @return Devices
     */
    private function getPushDevices() {
        return $this->get('push_devices');
    }
}

<?php

namespace mcfedr\TwitterPushBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DeviceController extends Controller {
    /**
     * @Route("/devices")
     * @Method({"POST"})
     */
    public function registerDeviceAction(Request $request) {
        $data = $this->handleJSONRequest($request);
        if($data instanceof Response) {
            return $data;
        }

        if(!isset($data['deviceID']) || !isset($data['platform'])) {
            return new Response('Missing parameters', 400);
        }

        try {
            if(($arn = $this->getPushDevices()->registerDevice($data['deviceID'], $data['platform']))) {
                $this->get('logger')->info('Device registered', [
                    'arn' => $arn,
                    'device' => $data['deviceID'],
                    'platform' => $data['platform']
                ]);
                return new Response('Device registered', 200);
            }
        }
        catch(PlatformNotConfiguredException $e) {
            return new Response('Unknown platform', 400);
        }
        catch(\Exception $e) {
            $this->get('logger')->error('Exception registering device', [
                'e' => $e,
                'device' => $data['deviceID'],
                'platform' => $data['platform']
            ]);
        }

        return new Response('Unknown error', 500);
    }

    /**
     * @return Devices
     */
    private function getPushDevices() {
        return $this->get('push_devices');
    }
}

Add log when registering device

Add log when registering device


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Faq Repository
 *
 * @author Andrew Prohorovych <prohorovychua@gmail.com>
 */
class FaqRepository extends EntityRepository
{
    /**
     * @param int  $offset
     * @param null $limit
     *
     * @return Request
     */
    public function getAllEnabled($offset = 0, $limit = null)
    {
        $qb = $this->createQueryBuilder('f');

        $qb
            ->where($qb->expr()->eq('f.enabled', true))
            ->setFirstResult($offset);

        if (null !== $limit) {
            $qb->setMaxResults($limit);
        }

        return $qb->getQuery()->getArrayResult();
    }
}

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Faq Repository
 *
 * @author Andrew Prohorovych <prohorovychua@gmail.com>
 */
class FaqRepository extends EntityRepository
{
    /**
     * Get all enabled
     *
     * @param int  $offset Offset
     * @param null $limit  Limit
     *
     * @return Request
     */
    public function getAllEnabled($offset = 0, $limit = null)
    {
        $qb = $this->createQueryBuilder('f');

        $qb
            ->where($qb->expr()->eq('f.enabled', true))
            ->setFirstResult($offset);

        if (null !== $limit) {
            $qb->setMaxResults($limit);
        }

        return $qb->getQuery()->getResult();
    }
}

Fix query for FAQ entity

Fix query for FAQ entity


<?php

namespace Liip\RMT\Action;

use Liip\RMT\Changelog\ChangelogManager;
use Liip\RMT\Context;

/**
 * Update the changelog file
 */
class ChangelogUpdateAction extends BaseAction
{
    protected $options;

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

    public function execute()
    {
        if (isset($this->options['dump-commits']) && $this->options['dump-commits']===true) {
            $extraLines = Context::get('vcs')->getAllModificationsSince(
                Context::get('version-persister')->getCurrentVersionTag(),
                false
            );
            $this->options['extra-lines'] = $extraLines;
            unset($this->options['dump-commits']);
        }

        $manager = new ChangelogManager('CHANGELOG', 'semantic');
        $manager->update(
            Context::getParam('new-version'),
            Context::get('information-collector')->getValueFor('comment'),
            array_merge(
                array('type' => Context::get('information-collector')->getValueFor('type', null)),
                $this->options
            )
        );
        $this->confirmSuccess();
    }

    public function getInformationRequests()
    {
        return array('comment');
    }
}

<?php

namespace Liip\RMT\Action;

use Liip\RMT\Changelog\ChangelogManager;
use Liip\RMT\Context;

/**
 * Update the changelog file
 */
class ChangelogUpdateAction extends BaseAction
{
    protected $options;

    public function __construct($options)
    {
        $this->options = array_merge(array(
            'dump-commits' => false,
            'format' => 'simple',
            'file' => 'CHANGELOG'
        ), $options);
    }

    public function execute()
    {
        if ($this->options['dump-commits'] == true) {
            $extraLines = Context::get('vcs')->getAllModificationsSince(
                Context::get('version-persister')->getCurrentVersionTag(),
                false
            );
            $this->options['extra-lines'] = $extraLines;
            unset($this->options['dump-commits']);
        }

        $manager = new ChangelogManager($this->options['file'], $this->options['format']);
        $manager->update(
            Context::getParam('new-version'),
            Context::get('information-collector')->getValueFor('comment'),
            array_merge(
                array('type' => Context::get('information-collector')->getValueFor('type', null)),
                $this->options
            )
        );
        $this->confirmSuccess();
    }

    public function getInformationRequests()
    {
        return array('comment');
    }
}

Add possibility to configure the action CHANGELOG update


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTemplateListenerFactory implements FactoryInterface
{
    /**
     * Create and return an InjectTemplateListener instance.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return InjectTemplateListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $slConfig = $serviceLocator->get('Config');
        if (isset($slConfig['view_manager'])
            && (is_array($slConfig['view_manager']) || $slConfig['view_manager'] instanceof ArrayAccess)) {
            $config = $slConfig['view_manager'];
        } else {
            $config = array();
        }

        $listener = new InjectTemplateListener();

        if (isset($config['controller_map'])) {
            $listener->setControllerMap($config['controller_map']);
        }

        return $listener;
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTemplateListenerFactory implements FactoryInterface
{
    /**
     * Create and return an InjectTemplateListener instance.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return InjectTemplateListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $listener = new InjectTemplateListener();

        $config = $serviceLocator->get('Config');
        if (isset($config['view_manager'])
            && (is_array($config['view_manager']) || $config['view_manager'] instanceof ArrayAccess)
            && isset($config['view_manager']['controller_map'])
            && (is_array($config['view_manager']['controller_map']))
        ) {
            $listener->setControllerMap($config['view_manager']['controller_map']);
        }

        return $listener;
    }
}

Test for controller_map key in config once.

Also, ensure that controller_map is an array as the parameter to
setControllerMap() is type hinted.


<?php
namespace DemandwareXml\Parser;

use XMLReader;

interface NodeParserInterface
{
    public function __construct(XMLReader $reader);
    public function isMatch(): bool;
    public function parse(): array;
}

<?php
namespace DemandwareXml\Parser;

use XMLReader;

interface NodeParserInterface
{
    // Give the parser the current node.
    public function __construct(XMLReader $reader);

    // Determine if the give node is a match for parsing.
    public function isMatch(): bool;

    // Parse the given node into an array.
    public function parse(): array;
}

Add node parser interface docs.

Add node parser interface docs.


<?php namespace Laito;

/**
 * Http class
 *
 * @package default
 * @author Mangolabs
 */

class Http extends Core
{

    /**
     * @var array Fixed parameters array
     */
    private $params = [];

    /**
     * Sets fixed parameters to be sent in all calls
     *
     * @param array $params Parameters
     * @return object Http instance
     */
    public function setupParams ($params = []) {
        if (is_array($params)) {
            $this->params = array_merge($this->params, $params);
        }
        return $this;
    }

    /**
     * Makes an HTTP call
     *
     * @param string $url URL to request
     * @param string $method HTTP method
     * @param array $params Parameters
     * @return object Http instance
     */
    public function call ($url, $method = 'GET', $params = []) {

        // Set call parameters
        $params = array_merge($this->params, is_array($params)? $params : []);

        // Setup parameters
        $content = '';
        $queryString = http_build_query($params);
        if ($method === 'GET') {
            $url = $url . '?' . $queryString;
        } else {
            $content = $queryString;
        }

        // Make call
        $result = file_get_contents($url, false, stream_context_create([
            'http' => [
                'method'  => $method,
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $content
            ]
        ]));

        // Return result
        return $result;
    }

}

<?php namespace Laito;

/**
 * Http class
 *
 * @package default
 * @author Mangolabs
 */

class Http extends Core
{

    /**
     * @var array Fixed parameters array
     */
    private $params = [];

    /**
     * Sets fixed parameters to be sent in all calls
     *
     * @param array $params Parameters
     * @return object Http instance
     */
    public function setupParams ($params = []) {
        if (is_array($params)) {
            $this->params = array_merge($this->params, $params);
        }
        return $this;
    }

    /**
     * Makes an HTTP call
     *
     * @param string $url URL to request
     * @param string $method HTTP method
     * @param array $params Parameters
     * @return object Http instance
     */
    public function call ($url, $method = 'GET', $params = []) {

        // Set call parameters
        $params = array_merge($this->params, is_array($params)? $params : []);

        // Setup parameters
        $content = '';
        $queryString = http_build_query($params);
        if ($method === 'GET') {
            $url = $url . '?' . $queryString;
        } else {
            $content = $queryString;
        }

        // Make call
        $result = @file_get_contents($url, false, stream_context_create([
            'http' => [
                'method'  => $method,
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $content
            ]
        ]));

        // Return result
        return $result;
    }

}

Add failsafe to HTTP request

Add failsafe to HTTP request


<?php

namespace PhpSpec\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class DescribeCommand extends Command
{
    public function __construct()
    {
        parent::__construct('describe');

        $this->setDefinition(array(
            new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'),
        ));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getContainer();
        $container->configure();

        $classname = $input->getArgument('class');
        $pattern   = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/';

        if (!preg_match($pattern, $classname)) {
            throw new \InvalidArgumentException(sprintf(
                "String \"%s\" is not a valid class name.\nPlease see reference document: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md",
                $classname
            ));
        }

        $resource = $container->get('locator.resource_manager')->createResource($classname);

        $container->get('code_generator')->generate($resource, 'specification');
    }
}

<?php

namespace PhpSpec\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class DescribeCommand extends Command
{
    public function __construct()
    {
        parent::__construct('describe');

        $this->setDefinition(array(
            new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'),
        ));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getContainer();
        $container->configure();

        $classname = $input->getArgument('class');
        $pattern   = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/';

        if (!preg_match($pattern, $classname)) {
            throw new \InvalidArgumentException(
                sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL .
                'Please see reference document:' .
                'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md'
            );
        }

        $resource = $container->get('locator.resource_manager')->createResource($classname);

        $container->get('code_generator')->generate($resource, 'specification');
    }
}

Update class name validator implementation.


<?php

namespace Neuron\Net;

/**
 * Class QueryTrackingParameters
 * @package Neuron\Net
 */
class QueryTrackingParameters
{
	/**
	 * @return QueryTrackingParameters
	 */
	public function instance()
	{
		static $in;
		if (!isset($in)) {
			$in = new self();
		}
		return $in;
	}

	public $queryParameters = [
		'utm_abversion',
		'utm_referrer',
		'utm_source',
		'utm_medium',
		'utm_campaign',
		'utm_term',
		'utm_content',
		'_ga'
	];
}

<?php

namespace Neuron\Net;

/**
 * Class QueryTrackingParameters
 * @package Neuron\Net
 */
class QueryTrackingParameters
{
	/**
	 * @return QueryTrackingParameters
	 */
	public function instance()
	{
		static $in;
		if (!isset($in)) {
			$in = new self();
		}
		return $in;
	}

	public $queryParameters = [
		'utm_abversion',
		'utm_referrer',
		'utm_source',
		'utm_medium',
		'utm_campaign',
		'utm_term',
		'utm_content',
		'_ga',
		'pk_vid'
	];
}

Add piwik visitor tracking to tracking parameters.


<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->get('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->config('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

Fix generator path for service provider

Fix generator path for service provider


<?php
/**
 *
 *
 * @author      Knut Kohl <github@knutkohl.de>
 * @copyright   2012-2013 Knut Kohl
 * @license     GNU General Public License http://www.gnu.org/licenses/gpl.txt
 * @version     $Id$
 */
return array(

	// -----------------------------------------------------------------------
	// INTERNAL SETTINGS, DO NOT TOUCH
	// -----------------------------------------------------------------------
	/**
	 * View settings
	 */
	'View' => array(

		// Compile templates and reuse unless changed
		'ReuseCode'        => TRUE,

		// Replace static images by base64 encoded inline code
		// Only for images with max x/y of 16px
		'InlineImages'     => 16,

		// Don't compress HTML
		'Verbose'          => FALSE,

		// FALSE, 0, 10, 62, (95 is not working with UTF-8)
		'JavaScriptPacker' => 62,

		// XML View settings
		'XML' => array(
			'Node' => 'node',
			'Data' => 'data',
		),
	),

);

<?php
/**
 *
 *
 * @author      Knut Kohl <github@knutkohl.de>
 * @copyright   2012-2013 Knut Kohl
 * @license     GNU General Public License http://www.gnu.org/licenses/gpl.txt
 * @version     $Id$
 */
return array(

	// -----------------------------------------------------------------------
	// INTERNAL SETTINGS, DO NOT TOUCH
	// -----------------------------------------------------------------------
	/**
	 * View settings
	 */
	'View' => array(

		// Compile templates and reuse unless changed
		'ReuseCode'        => TRUE,

		// Replace static images by base64 encoded inline code
		// Only for images with max x/y of 8px
		'InlineImages'     => 8,

		// Don't compress HTML
		'Verbose'          => FALSE,

		// FALSE, 0, 10, 62, (95 is not working with UTF-8)
		'JavaScriptPacker' => 62,

		// XML View settings
		'XML' => array(
			'Node' => 'node',
			'Data' => 'data',
		),
	),

);

Change size of inline images

Change size of inline images


<?php

final class DiffusionMercurialLastModifiedQuery
  extends DiffusionLastModifiedQuery {

  protected function executeQuery() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $path = $drequest->getPath();

    // TODO: Share some of this with History query.
    list($hash) = $repository->execxLocalCommand(
      'log --template %s --limit 1 -b %s --rev %s:0 -- %s',
      '{node}',
      $drequest->getBranch(),
      $drequest->getCommit(),
      nonempty(ltrim($path, '/'), '.'));

    $commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
      'repositoryID = %d AND commitIdentifier = %s',
      $repository->getID(),
      $hash);

    if ($commit) {
      $commit_data = $commit->loadCommitData();
    } else {
      $commit_data = null;
    }

    return array($commit, $commit_data);
  }

}

<?php

final class DiffusionMercurialLastModifiedQuery
  extends DiffusionLastModifiedQuery {

  protected function executeQuery() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $path = $drequest->getPath();

    list($hash) = $repository->execxLocalCommand(
      'log --template %s --limit 1 --rev %s:0 -- %s',
      '{node}',
      $drequest->getCommit(),
      nonempty(ltrim($path, '/'), '.'));

    $commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
      'repositoryID = %d AND commitIdentifier = %s',
      $repository->getID(),
      $hash);

    if ($commit) {
      $commit_data = $commit->loadCommitData();
    } else {
      $commit_data = null;
    }

    return array($commit, $commit_data);
  }

}

Fix Mercurial "Last Modified" query

Fix Mercurial "Last Modified" query

Summary:
To determine when a file was last modified, we currently run `hg log ... -b branch ... file`. However, this is incorrect, because Mercurial does not interpret "-b x" as "all ancestors of the commit named x" like Git does, and we don't care about where the modification happened anyway (we always have a resolved commit as a starting point). I think this got copy-pasta'd from the History query.

Instead, drop the branch-specific qualifier and find the last modification, period.

Test Plan: Mercurial commit views of commits not on the repository's default branch are no longer broken.

Reviewers: DurhamGoode, vrana, chad

Reviewed By: chad

CC: aran

Differential Revision: https://secure.phabricator.com/D5146


<?php
declare(strict_types=1);

namespace PerFiUnitTest\Domain\Transaction\CommandHandler;

use PHPUnit\Framework\TestCase;

class ExecuteTransactionTest extends TestCase
{
    /**
     * @test
     */
    public function when_invoked_adds_transaction_to_repository()
    {
        self::markTestIncomplete();
    }

    /**
     * @test
     */
    public function when_invoked_records_transaction_on_source_account()
    {
        self::markTestIncomplete();
    }

    /**
     * @test
     */
    public function when_invoked_records_transaction_on_destination_account()
    {
        self::markTestIncomplete();
    }
}

<?php
declare(strict_types=1);

namespace PerFiUnitTest\Domain\Transaction\CommandHandler;

use Mockery as m;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use PerFi\Application\Transaction\InMemoryTransactionRepository;
use PerFi\Domain\Account\Account;
use PerFi\Domain\Command;
use PerFi\Domain\CommandHandler;
use PerFi\Domain\Transaction\CommandHandler\ExecuteTransaction as ExecuteTransactionHandler;
use PerFi\Domain\Transaction\Command\ExecuteTransaction as ExecuteTransactionCommand;
use PerFi\Domain\Transaction\TransactionRepository;

class ExecuteTransactionTest extends TestCase
{
    use MockeryPHPUnitIntegration;

    /**
     * @var TransactionRepository
     */
    private $repository;

    /**
     * @var Account
     */
    private $sourceAccount;

    /**
     * @var Account
     */
    private $destinationAccount;

    /**
     * @var Command
     */
    private $command;

    /**
     * @var CommandHandler
     */
    private $commandHandler;

    public function setup()
    {
        $this->repository = new InMemoryTransactionRepository();

        $this->sourceAccount = m::mock(Account::class);
        $this->sourceAccount->shouldReceive('recordTransaction')
            ->byDefault();

        $this->destinationAccount = m::mock(Account::class);
        $this->destinationAccount->shouldReceive('recordTransaction')
            ->byDefault();

        $this->command = new ExecuteTransactionCommand(
            $this->sourceAccount,
            $this->destinationAccount,
            '500',
            'RSD',
            'supermarket'
        );

        $this->commandHandler = new ExecuteTransactionHandler(
            $this->repository
        );
    }

    /**
     * @test
     */
    public function when_invoked_adds_transaction_to_repository()
    {
        $this->commandHandler->__invoke($this->command);

        $result = $this->repository->getAll();

        $expected = 1;

        self::assertSame($expected, count($result));
    }

    /**
     * @test
     */
    public function when_invoked_records_transaction_on_source_account()
    {
        $this->sourceAccount->shouldReceive('recordTransaction')
            ->once()
            ->with($this->command->payload());

        $this->commandHandler->__invoke($this->command);
    }

    /**
     * @test
     */
    public function when_invoked_records_transaction_on_destination_account()
    {
        $this->destinationAccount->shouldReceive('recordTransaction')
            ->once()
            ->with($this->command->payload());

        $this->commandHandler->__invoke($this->command);
    }
}

Test the transaction execution command handler


<?php
$exec = "/usr/local/bin/node run.js";
exec($exec, $output);
echo "<!doctype html>\n\n\n\n\n\n";
?>

<?php
$exec = "/usr/local/bin/node run.js";
exec($exec, $output);
echo "<!doctype html>\n\n\n"
	. "\n"
	. "\n"
	. "\n\n";
?>

Load fin/jsio on the fun app pages

Load fin/jsio on the fun app pages


<?php

/*
 * This file is part of the Stash package.
 *
 * (c) Robert Hafner <tedivm@tedivm.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Stash\Test\Driver;

/**
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 */
class FileSystemTest extends AbstractDriverTest
{
    protected $driverClass = 'Stash\Driver\FileSystem';

    protected function getOptions()
    {
        return array('memKeyLimit' => 2);
    }
}

<?php

/*
 * This file is part of the Stash package.
 *
 * (c) Robert Hafner <tedivm@tedivm.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Stash\Test\Driver;

use Stash\Driver\FileSystem;

/**
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 */
class FileSystemTest extends AbstractDriverTest
{
    protected $driverClass = 'Stash\Driver\FileSystem';

    protected function getOptions()
    {
        return array('memKeyLimit' => 2);
    }

    /**
     * @expectedException Stash\Exception\RuntimeException
     */
    public function testOptionKeyHashFunctionException()
    {
        $driver = new FileSystem(array('keyHashFunction' => 'foobar_'.mt_rand()));
    }

    public function testOptionKeyHashFunction()
    {
        $driver = new FileSystem(array('keyHashFunction' => 'md5'));
    }
}

Add test for keyHashFunction option in the FileSystem driver, test for success and for the exception.


<?php

/* @var $scenario Codeception\Scenario */

$I = new AcceptanceTester($scenario);

$I->amGoingTo('admin login page');
$I->amOnPage('/admin');
$I->canSee('Admin Login');
$I->canSee('Username');
$I->canSee('Password');

$I->amGoingTo('enter admin credentials');
$I->fillField('LoginForm[username]', 'admin');
$I->fillField('LoginForm[password]', 'ChangeMePlease');
$I->click('button[type=submit]');
$I->wait(3);

$I->wantTo('see API configuration parameters');
$I->see('Admin');
$I->see('Current config');

$cfg = json_decode(file_get_contents(Yii::$app->runtimePath . '/api.cfg'), true);
unset($cfg['type']);
foreach ($cfg as $k => $v){
    $I->see("[$k] => $v");
}

$I->see('WP Com Setup');
$I->see('WP Org Setup');

$I->click('Logout');
$I->wait(3);

$I->see('Links Index');

<?php

/* @var $scenario Codeception\Scenario */

$I = new AcceptanceTester($scenario);

$I->amGoingTo('admin login page');
$I->amOnPage('/admin');
$I->canSee('Admin Login');
$I->canSee('Username');
$I->canSee('Password');

$I->amGoingTo('enter admin credentials');
$I->fillField('LoginForm[username]', 'admin');
$I->fillField('LoginForm[password]', 'ChangeMePlease');
$I->click('button[type=submit]');
$I->wait(3);

$I->wantTo('see API configuration parameters');
$I->see('Admin');
$I->see('Current config');

switch($I->getConfig()->type){
    case 'com':
        $adminParams = ['clientId', 'clientSecret', 'redirectUrl', 'blogId', 'blogUrl', 'adminToken'];
        break;
    case 'org':
        $adminParams = ['consumerKey', 'consumerSecret', 'blogUrl'];
        break;
    default:
        throw new \Exception('config file not found.');
}

foreach ($adminParams as $k){
    $I->see("[$k]");
}

$I->see('WP Com Setup');
$I->see('WP Org Setup');

$I->click('Logout');
$I->wait(3);

$I->see('Shared Links:');

Update Admin page scenario test

Update Admin page scenario test

- check for different fields depending on COM or ORG
- Updated UI text check


<?php

$connectionOpts = ['host' => '127.0.0.1', 'user' => 'ndo', 'password' => 'ndo', 'dbname' => 'ndo'];
$poolOpts = ['persistent' => true, 'poolSize' => 1];

function get_pg_pid($pool)
{
    $query = new Enigma\Query('select pg_backend_pid() as pid');
    $resultset = \HH\Asio\join($pool->query($query));
    $results = $resultset->fetchArrays();
    return reset($results)['pid'];
}

$pool1 = Enigma\create_pool($connectionOpts, $poolOpts);
$pid1 = get_pg_pid($pool1);

$pool2 = Enigma\create_pool($connectionOpts, $poolOpts);
$pid2 = get_pg_pid($pool2);

$poolNonpersistent = Enigma\create_pool($connectionOpts);
$pidNonpersistent = get_pg_pid($poolNonpersistent);

echo ($pid1 === $pid2 && $pidNonpersistent !== $pid1) ? 'OK' : 'FAIL';

<?php

$connectionOpts = ['host' => '127.0.0.1', 'user' => 'ndo', 'password' => 'ndo', 'dbname' => 'ndo'];
$poolOpts = ['persistent' => true, 'pool_size' => 1];

function get_pg_pid($pool)
{
    $query = new Enigma\Query('select pg_backend_pid() as pid');
    $resultset = \HH\Asio\join($pool->query($query));
    $results = $resultset->fetchArrays();
    return reset($results)['pid'];
}

$pool1 = Enigma\create_pool($connectionOpts, $poolOpts);
$pid1 = get_pg_pid($pool1);

$pool2 = Enigma\create_pool($connectionOpts, $poolOpts);
$pid2 = get_pg_pid($pool2);

$poolNonpersistent = Enigma\create_pool($connectionOpts);
$pidNonpersistent = get_pg_pid($poolNonpersistent);

echo ($pid1 === $pid2 && $pidNonpersistent !== $pid1) ? 'OK' : 'FAIL';

Fix typo in persistent connect test

Fix typo in persistent connect test


<?php
/**
 * Class AutoLoader
 * @file    AutoLoader.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Fri Jun 01 10:19:04 2012
 * @copyright The BSD 3-Clause License
 */

namespace Veles;

/**
 * Class AutoLoader
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class AutoLoader
{
	/**
	 * Initialisation
	 */
	final public static function init()
	{
		spl_autoload_register(__NAMESPACE__ . '\AutoLoader::load');
	}

	/**
	 * AutoLoader
	 *
	 * @param string $name
	 */
	final public static function load($name)
	{
		$name = str_replace('\\', DIRECTORY_SEPARATOR, $name);

		// For using external libs with their own autoloaders
		// do not use strict require function
		include "$name.php";
	}
}

<?php
/**
 * Class AutoLoader
 * @file    AutoLoader.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Fri Jun 01 10:19:04 2012
 * @copyright The BSD 3-Clause License
 */

namespace Veles;

/**
 * Class AutoLoader
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class AutoLoader
{
	/**
	 * Initialisation
	 */
	final public static function init()
	{
		spl_autoload_register(__NAMESPACE__ . '\AutoLoader::load');
	}

	/**
	 * AutoLoader
	 *
	 * @param string $class_name
	 */
	final public static function load($class_name)
	{
		$class_name = ltrim($class_name, '\\');
		$namespace = $file_name = '';
		if ($last_ns_pos = strrpos($class_name, '\\')) {
			$namespace = substr($class_name, 0, $last_ns_pos);
			$class_name = substr($class_name, $last_ns_pos + 1);
			$file_name  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
		}
		$file_name = stream_resolve_include_path(
			$file_name . str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php'
		);

		if ($file_name) {
			include $file_name;
		}
	}
}

Implement Autoloader in PSR-0 standard

Implement Autoloader in PSR-0 standard


<?php
if (isset($meta) && is_object($meta)) {
    $_title = $meta->label;
    $_key = $meta->key;
    $tipo = $meta->type;
    $options = $meta->config['options'];
    ?>

    <div class="<?php echo $class; ?>">
        <?php
        $this->part("modal/title", ['title' => $_title]);

        if ($tipo === "select" && is_array($meta->config)) {
            $this->part("modal/entity-dropdown", ['attr' => $_key, 'options' => $options]);
        } else if ($tipo === "string" || $tipo === "int") { ?>
            <input type='text' name='<?php echo $_key; ?>' placeholder='<?php \MapasCulturais\i::esc_attr_e('Campo obrigatório')?>' required />
            <?php
        } else if ($tipo === "text") { ?>
            <textarea name='<?php echo $_key; ?>' maxlength='400'></textarea>

            <?php
        } else if ($tipo === "multiselect" && is_array($meta->config)) {
            foreach ($options as $option) { ?>
                <label for='<?php echo $_key; ?>'> <?php echo $option; ?>
                <input type='checkbox' name='<?php echo $_key; ?>' value='<?php echo $option; ?>'>

                <?php
            }
        }
        ?>

<?php
}

<?php
if (isset($meta) && is_object($meta)) {
    $_title = $meta->label;
    $_key = $meta->key;
    $tipo = $meta->type;
    $options = [];
    if (array_key_exists('options',$meta->config)) {
        $options = $meta->config['options'];
    }
    ?>

    <div class="<?php echo $class; ?>">
        <?php
        $this->part("modal/title", ['title' => $_title]);

        if ($tipo === "select" && is_array($meta->config)) {
            $this->part("modal/entity-dropdown", ['attr' => $_key, 'options' => $options]);
        } else if ($tipo === "string" || $tipo === "int") { ?>
            <input type='text' name='<?php echo $_key; ?>' placeholder='<?php \MapasCulturais\i::esc_attr_e('Campo obrigatório')?>' required />
            <?php
        } else if ($tipo === "text") { ?>
            <textarea name='<?php echo $_key; ?>' maxlength='400'></textarea>

            <?php
        } else if ($tipo === "multiselect" && is_array($meta->config)) {
            foreach ($options as $option) { ?>
                <label for='<?php echo $_key; ?>'> <?php echo $option; ?>
                <input type='checkbox' name='<?php echo $_key; ?>' value='<?php echo $option; ?>'>

                <?php
            }
        }
        ?>

<?php
}

Fix modal when there's no options available


<?php

namespace ChristsLightMinistries\WebBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends ContainerAware
{
    /**
     * @Route("/", "defaults" = {"page" = "index"})
     * @Route("/{page}.html")
     */
    public function indexAction($page)
    {
        return $this->container->get('templating')->render("ChristsLightMinistriesWebBundle:Default:$page.html.twig");
    }
}

<?php

namespace ChristsLightMinistries\WebBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends ContainerAware
{
    /**
     * @Route("/", defaults={"page" = "index"})
     * @Route("/{page}.html")
     */
    public function indexAction($page)
    {
        return $this->container->get('templating')->render("ChristsLightMinistriesWebBundle:Default:$page.html.twig");
    }
}

Fix syntax error in routing.

Fix syntax error in routing.


<?php

namespace Uro\TeltonikaFmParser\Codec;

use Uro\TeltonikaFmParser\Model\IoValue;
use Uro\TeltonikaFmParser\Model\IoElement;
use Uro\TeltonikaFmParser\Model\IoProperty;

class Codec8Extended extends BaseCodec
{
    public function decodeIoElement(): IoElement
    {
        return (new IoElement(
            $this->reader->readUInt16(),    // Event ID
            $this->reader->readUInt16()     // Number of elements
        ))->addProperties($this->decodeIoProperties());
    }

    private function decodeIoProperties(): array
    {
        $properties = [];
        for($bytes = 1; $bytes <= 8; $bytes *= 2) {
            $numberOfProperties = $this->reader->readUInt16();
            foreach(range(1,$numberOfProperties) as $i) {
                $properties[] = new IoProperty(
                    $this->reader->readUInt16(),
                    new IoValue($this->reader->readBytes($bytes))
                );
            }
        }

        return array_merge($properties, $this->decodeVariableLengthProperties());
    }

    private function decodeVariableLengthProperties()
    {
        $properties = [];

        $numberOfProperties = $this->reader->readUInt16();
        foreach(range(1, $numberOfProperties) as $i) {
            $properties[] = new IoProperty(
                $this->reader->readUInt16(),
                new IoValue($this->reader->readBytes($this->reader->readUInt16()))
            );
        }

        return $properties;
    }
}

<?php

namespace Uro\TeltonikaFmParser\Codec;

use Uro\TeltonikaFmParser\Model\IoValue;
use Uro\TeltonikaFmParser\Model\IoElement;
use Uro\TeltonikaFmParser\Model\IoProperty;

class Codec8Extended extends BaseCodec
{
    public function decodeIoElement(): IoElement
    {
        return (new IoElement(
            $this->reader->readUInt16(),    // Event ID
            $this->reader->readUInt16()     // Number of elements
        ))->addProperties($this->decodeIoProperties());
    }

    private function decodeIoProperties(): array
    {
        $properties = [];
        for($bytes = 1; $bytes <= 8; $bytes *= 2) {
            $numberOfProperties = $this->reader->readUInt16();
            for($i = 0; $i < $numberOfProperties; $i++) {
                $properties[] = new IoProperty(
                    $this->reader->readUInt16(),
                    new IoValue($this->reader->readBytes($bytes))
                );
            }
        }

        return array_merge($properties, $this->decodeVariableLengthProperties());
    }

    private function decodeVariableLengthProperties()
    {
        $properties = [];

        $numberOfProperties = $this->reader->readUInt16();
        for($i = 0; $i < $numberOfProperties; $i++) {
            $properties[] = new IoProperty(
                $this->reader->readUInt16(),
                new IoValue($this->reader->readBytes($this->reader->readUInt16()))
            );
        }

        return $properties;
    }
}

Fix IO Properties decode error

Fix IO Properties decode error


<?php
/**
 * Copyright 2015 Dirk Groenen
 *
 * (c) Dirk Groenen <dirk@bitlabs.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace DirkGroenen\Pinterest\Models;

class Pin extends Model {

    /**
     * The available object keys
     *
     * @var array
     */
    protected $fillable = ["id", "link", "creator", "board", "created_at", "note", "color", "counts", "media", "attribution", "image", "metadata"];

}

<?php
/**
 * Copyright 2015 Dirk Groenen
 *
 * (c) Dirk Groenen <dirk@bitlabs.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace DirkGroenen\Pinterest\Models;

class Pin extends Model {

    /**
     * The available object keys
     *
     * @var array
     */
    protected $fillable = ["id", "link", "url", "creator", "board", "created_at", "note", "color", "counts", "media", "attribution", "image", "metadata"];

}

Add URL access to pin

Add URL access to pin

Allows us to get the original URL to link to the pin


<?php

$version = (float) substr(phpversion(), 0, 3);
$rc_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$pos = strpos($rc_url, 'chigi/install');
$chigi_root_url = substr($rc_url, 0, $pos);
define('CHIGI_ROOT_URL', $chigi_root_url . 'chigi/');
// 当前config.php文件的路径
$rc_dir = dirname(__FILE__);
$rc_dir = str_replace('\\', '/', $rc_dir);
$pos = strpos($rc_dir, 'Chigi/install');
$chigi_root_path = substr($rc_dir, 0, $pos);
define('CHIGI_ROOT_PATH',$chigi_root_path . 'Chigi/');
if ($version >= 5.3) {
    //用户项目入口
    define('APP_NAME', 'Installation');
    define('APP_PATH', './');

    //define('APP_DEBUG', true); //您可以注释掉这行，关闭调试模式
    define('THINK_PATH', '../../Core/'); //定义正确的框架文件路径
    if(!file_exists(THINK_PATH . 'ThinkPHP.php')){
    	exit("未找到ThinkPHP内核位置，请在install/index.php中重新指定");
    }
    require_once THINK_PATH . 'ThinkPHP.php';
} else {
    exit("对不起，您的PHP版本略低，千木架构对PHP最低版本要求5.3");
}
?>

<?php

$version = (float) substr(phpversion(), 0, 3);
$rc_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$pos = strpos(strtolower($rc_url), 'chigi/install');
$chigi_root_url = substr(strtolower($rc_url), 0, $pos);
define('CHIGI_ROOT_URL', $chigi_root_url . 'chigi/');
// 当前config.php文件的路径
$rc_dir = dirname(__FILE__);
$rc_dir = str_replace('\\', '/', $rc_dir);
$pos = strpos($rc_dir, 'Chigi/install');
$chigi_root_path = substr($rc_dir, 0, $pos);
define('CHIGI_ROOT_PATH',$chigi_root_path . 'Chigi/');
if ($version >= 5.3) {
    //用户项目入口
    define('APP_NAME', 'Installation');
    define('APP_PATH', './');

    //define('APP_DEBUG', true); //您可以注释掉这行，关闭调试模式
    define('THINK_PATH', '../../Core/'); //定义正确的框架文件路径
    if(!file_exists(THINK_PATH . 'ThinkPHP.php')){
    	exit("未找到ThinkPHP内核位置，请在install/index.php中重新指定");
    }
    require_once THINK_PATH . 'ThinkPHP.php';
} else {
    exit("对不起，您的PHP版本略低，千木架构对PHP最低版本要求5.3");
}
?>

Fix URL detection error for upper case in the installer

Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>


<?php

/**
 * Represents an Exception that happened while communicating with Factual.
 * Includes information about the request that triggered the problem.
 * This is a refactoring of the Factual Driver by Aaron: https://github.com/Factual/factual-java-driver
 * @author Tyler
 * @package Factual
 * @license Apache 2.0
 */
class FactualApiException extends Exception {
	protected $info; //debug array
	protected $helpUrl = "https://github.com/Factual/factual-php-driver#help-debugging--testing";

	public function __construct($info) {
		$this->info = $info;
		$this->message = $info['message']." Details:\n".print_r($info,true)."\n use FactualApiException::debug()" .
				" to obtain this information programatically. See ". $this->helpUrl.
				" for information on submitting bugs and questions.\n\n";
	}

	public function debug(){
		return $this->info;
	}
}
?>

<?php

/**
 * Represents an Exception that happened while communicating with Factual.
 * Includes information about the request that triggered the problem.
 * This is a refactoring of the Factual Driver by Aaron: https://github.com/Factual/factual-java-driver
 * @author Tyler
 * @package Factual
 * @license Apache 2.0
 */
class FactualApiException extends Exception {
	protected $info; //debug array
	protected $helpUrl = "https://github.com/Factual/factual-php-driver/wiki/Debugging-and-Support";

	public function __construct($info) {
		$this->info = $info;
		$this->message = $info['message'];
		$this->message .= " Use Factual::debug() to echo detailed debug info to stdout, " .
				"or use FactualApiException::debug() to obtain debug information " .
				"programatically. See ". $this->helpUrl. " for information on " .
				"debug mode, submitting issues, and figuring out, generally, WTF is going on";
	}

	public function debug(){
		return $this->info;
	}
}
?>

Debug info is no longer returned automatically with every exception. Use Factual::debug() instead.


<?php

/**
 * Hoa Framework
 *
 *
 * @license
 *
 * GNU General Public License
 *
 * This file is part of Hoa Open Accessibility.
 * Copyright (c) 2007, 2008 Ivan ENDERLIN. All rights reserved.
 *
 * HOA Open Accessibility is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * HOA Open Accessibility is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HOA Open Accessibility; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 * @category    Framework
 * @package     Hoa_Test
 * @subpackage  Hoa_Test_Urg
 *
 */

/**
 * Hoa_Framework
 */
require_once 'Framework.php';

/**
 * Hoa_Test_Urg_Exception
 */
import('Test.Urg.Exception');

/**
 * Class Hoa_Test_Urg.
 *
 * .
 *
 * @author      Ivan ENDERLIN <ivan.enderlin@hoa-project.net>
 * @copyright   Copyright (c) 2007, 2008 Ivan ENDERLIN.
 * @license     http://gnu.org/licenses/gpl.txt GNU GPL
 * @since       PHP 5
 * @version     0.1
 * @package     Hoa_Test
 * @subpackage  Hoa_Test_Urg
 */

class Hoa_Test_Urg {

    /**
     * Combine a discrete uniform distribution (based on a Mersenne Twister for
     * pseudo-random algorithm).
     *
     * @access  public
     * @param   int     $lower    Lower bound.
     * @param   int     $upper    Upper bound.
     * @return  int
     */
    public static function Ud ( $lower = null, $upper = null ) {

        if(null === $lower)
            $lower = ~PHP_INT_MAX;

        if(null === $upper)
            $upper =  PHP_INT_MAX;

        return mt_rand($lower, $upper);
    }

    /**
     * Combine a continuous uniform distribution (based on a linear
     * congruential generator).
     *
     * @access  public
     * @param   float   $lower    Lower bound.
     * @param   float   $upper    Upper bound.
     * @return  float
     */
    public static function Uc ( $lower = null, $upper = null ) {

        return $lower + lcg_value() * ($upper - $lower);
    }
}

Add Ud() and Uc() static method, respectively for discrete and continous uniform distribution combinator.


<?php

namespace Oro\Bundle\PlatformBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class OroPlatformExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        $configLoader = new CumulativeConfigLoader(
            'oro_app_config',
            new YamlCumulativeFileLoader('Resources/config/oro/app.yml')
        );
        $resources    = $configLoader->load();
        $extensions   = $container->getExtensions();
        foreach ($resources as $resource) {
            foreach ($resource->data as $name => $config) {
                var_dump($name);
                if (!empty($extensions[$name])) {
                    $container->prependExtensionConfig($name, $config);
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

        $loader->load('services.yml');
    }
}

<?php

namespace Oro\Bundle\PlatformBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class OroPlatformExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        $configLoader = new CumulativeConfigLoader(
            'oro_app_config',
            new YamlCumulativeFileLoader('Resources/config/oro/app.yml')
        );
        $resources    = $configLoader->load();
        $extensions   = $container->getExtensions();
        foreach ($resources as $resource) {
            foreach ($resource->data as $name => $config) {
                if (!empty($extensions[$name])) {
                    $container->prependExtensionConfig($name, $config);
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

        $loader->load('services.yml');
    }
}

BAP-6772: Remove organization calendar type from community edition


<?php

namespace Scriptotek\Sru\Providers;

use Illuminate\Support\ServiceProvider;
use Scriptotek\Sru\Client as SruClient;

class SruServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes(array(
            __DIR__.'/../../config/config.php' => config_path('sru.php')
        ));
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $app = $this->app;
        $this->mergeConfigFrom(
            __DIR__.'/../../config/config.php',
            'sru'
        );
        $app['sru-client'] = $app->share(function ($app) {
            return new SruClient($app['config']->get('sru.endpoint'), $app['config']->get('sru'));
        });
        $app->alias('sru-client', SruClient::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('sru-client');
    }
}

<?php

namespace Scriptotek\Sru\Providers;

use Illuminate\Support\ServiceProvider;
use Scriptotek\Sru\Client as SruClient;

class SruServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes(array(
            __DIR__.'/../../config/config.php' => config_path('sru.php')
        ));
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../../config/config.php',
            'sru'
        );
        $this->app->singleton(SruClient::class, function ($app) {
            return new SruClient($app['config']->get('sru.endpoint'), $app['config']->get('sru'));
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [SruClient::class];
    }
}

Update service provider to work with Laravel 5.4


<?php
namespace phpgt\dom;

class HTMLCollectionTest extends \PHPUnit_Framework_TestCase {

public function testType() {
	$document = new HTMLDocument(TestHelper::HTML);
	$this->assertInstanceOf("\phpgt\dom\HTMLCollection", $document->children);
}

/**
 * The type of the Nodes that are stored within an HTMLCollection should only
 * be derivatives of Element.
 */
public function testElementType() {

}

}#

<?php
namespace phpgt\dom;

class HTMLCollectionTest extends \PHPUnit_Framework_TestCase {

public function testType() {
	$document = new HTMLDocument(TestHelper::HTML);
	$this->assertInstanceOf("\phpgt\dom\HTMLCollection", $document->children);
}

public function testNonElementsRemoved() {
	$document = new HTMLDocument(TestHelper::HTML_MORE);
	$bodyChildNodes = $document->body->childNodes;
	$bodyChildren = $document->body->children;

	$this->assertInstanceOf("\DOMNodeList", $bodyChildNodes);
	$this->assertInstanceOf("\phpgt\dom\HTMLCollection", $bodyChildren);

	$this->assertInstanceOf("\phpgt\dom\Text", $bodyChildNodes->item(0));
	$this->assertInstanceOf("\phpgt\dom\Element", $bodyChildren->item(0));
}

}#

Test non-Element nodes are not present

Test non-Element nodes are not present


<?php

namespace Morrislaptop\VarDumperWithContext;

use Symfony\Component\VarDumper\Dumper\CliDumper as BaseDumper;

class CliDumper extends BaseDumper implements DumpContextInterface {

	use ContextDumper;

	public function getContext($file, $line) {
		return "{$file}:{$line}";
	}

}

<?php

namespace Morrislaptop\VarDumperWithContext;

use Symfony\Component\VarDumper\Dumper\CliDumper as BaseDumper;

class CliDumper extends BaseDumper implements DumpContextInterface {

	use ContextDumper;

	public function getContext($file, $line) {
		return "\n{$file}:{$line}";
	}

}

Add new line for CLI to help Code terminal make file path clickable


<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

$error = NULL;
try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

openid: Fix notice about unititialized variable.


<?php

class DeliveryProfileLiveDash extends DeliveryProfileLive
{
	function __construct()
	{
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kRedirectManifestRenderer';
	}

	public function checkIsLive($url)
	{
		$content = $this->urlExists($url, array('application/dash+xml'));
		if(!$content)
		{
			return false;
		}

		return $this->doesMinimumUpdatePeriodExist($content);
	}

	protected function getHttpUrl($entryServerNode)
	{
		$baseUrl = $this->getBaseUrl($entryServerNode->serverNode);
		return rtrim($baseUrl, "/") . "/" . $this->getStreamName() . "/manifest.mpd" . $this->getQueryAttributes();
	}

	/**
	 * @param string $content
	 * @return bool
	 */
	protected function doesMinimumUpdatePeriodExist($content)
	{
		$xml = new SimpleXMLElement($content);
		$minimumUpdatePeriod = $xml->attributes()->minimumUpdatePeriod;
		return $minimumUpdatePeriod ? true : false;
	}
}

<?php

class DeliveryProfileLiveDash extends DeliveryProfileLive
{
	function __construct()
	{
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kRedirectManifestRenderer';
	}

	public function checkIsLive($url)
	{
		$content = $this->urlExists($url, array('application/dash+xml'));
		if(!$content)
		{
			return false;
		}

		return $this->doesMinimumUpdatePeriodExist($content);
	}

	protected function getHttpUrl($entryServerNode)
	{
		$baseUrl = $this->getBaseUrl($entryServerNode->serverNode);
		return rtrim($baseUrl, "/") . "/" . $this->getStreamName() . "/manifest.mpd" . $this->getQueryAttributes();
	}

	/**
	 * @param string $content
	 * @return bool
	 */
	protected function doesMinimumUpdatePeriodExist($content)
	{
		try
		{
			$xml = new SimpleXMLElement($content);
		}
		catch (Exception $e)
		{
			KalturaLog::debug('Failed to parse MPD content as XML: ' . $e->getMessage());
			return false;
		}

		$minimumUpdatePeriod = $xml->attributes()->minimumUpdatePeriod;
		return $minimumUpdatePeriod ? true : false;
	}
}

PLAT-22874: Add error handling upon failure to parse MPD content as XMl


<?php

use React\EventLoop\Factory;
use Clue\React\Buzz\Browser;

class FunctionalBrowserTest extends TestCase
{
    private $loop;
    private $browser;

    public function setUp()
    {
        $this->loop = Factory::create();
        $this->browser = new Browser($this->loop);
    }

    public function testSimpleRequest()
    {
        $this->expectPromiseResolve($this->browser->get('http://www.google.com'));

        $this->loop->run();
    }

    public function testNotFollowingRedirectsResolvesWithRedirectResult()
    {
        $browser = $this->browser->withOptions(array('followRedirects' => false));

        $this->expectPromiseResolve($browser->get('http://www.google.com'));

        $this->loop->run();
    }

    public function testRejectingRedirectsRejects()
    {
        $browser = $this->browser->withOptions(array('maxRedirects' => 0));

        $this->expectPromiseReject($browser->get('http://www.google.com'));

        $this->loop->run();
    }

    public function testInvalidPort()
    {
        $this->expectPromiseReject($this->browser->get('http://www.google.com:443'));

        $this->loop->run();
    }

    public function testInvalidPath()
    {
        $this->expectPromiseReject($this->browser->get('http://www.google.com/does-not-exist'));

        $this->loop->run();
    }
}

<?php

use React\EventLoop\Factory;
use Clue\React\Buzz\Browser;

class FunctionalBrowserTest extends TestCase
{
    private $loop;
    private $browser;

    /** base url to the httpbin service  **/
    private $base = 'http://httpbin.org/';

    public function setUp()
    {
        $this->loop = Factory::create();
        $this->browser = new Browser($this->loop);
    }

    public function testSimpleRequest()
    {
        $this->expectPromiseResolve($this->browser->get($this->base . 'get'));

        $this->loop->run();
    }

    public function testRedirectRequest()
    {
        $this->expectPromiseResolve($this->browser->get($this->base . 'redirect-to?url=' . urlencode($this->base . 'get')));

        $this->loop->run();
    }

    public function testNotFollowingRedirectsResolvesWithRedirectResult()
    {
        $browser = $this->browser->withOptions(array('followRedirects' => false));

        $this->expectPromiseResolve($browser->get($this->base . 'redirect/3'));

        $this->loop->run();
    }

    public function testRejectingRedirectsRejects()
    {
        $browser = $this->browser->withOptions(array('maxRedirects' => 0));

        $this->expectPromiseReject($browser->get($this->base . 'redirect/3'));

        $this->loop->run();
    }

    public function testInvalidPort()
    {
        $this->expectPromiseReject($this->browser->get('http://www.google.com:443'));

        $this->loop->run();
    }

    public function testInvalidPath()
    {
        $this->expectPromiseReject($this->browser->get($this->base . 'status/404'));

        $this->loop->run();
    }
}

Use httpbin to perform functional tests

Use httpbin to perform functional tests


<?php

require_once('tests/php/base.php');
require_once('framework/php/classes/plants/EchoPlant.php');

class CASHPlantTests extends UnitTestCase {

	function testEchoPlant(){
		$eplant = new EchoPlant('blarg',1);
		$this->assertIsa($eplant, 'EchoPlant');
		$output = $eplant->processRequest();
		$this->assertTrue($output);
	}
}
?>

<?php

require_once('tests/php/base.php');
require_once('framework/php/classes/plants/ElementPlant.php');
require_once('framework/php/classes/plants/EchoPlant.php');

class CASHPlantTests extends UnitTestCase {

	function testEchoPlant(){
		$eplant = new EchoPlant('blarg',1);
		$this->assertIsa($eplant, 'EchoPlant');
		$output = $eplant->processRequest();
		$this->assertTrue($output);
	}

	function testElementPlant(){
		$e = new ElementPlant(42, 69);
		$this->assertIsa($e, 'ElementPlant');
	}
}
?>

Add a basic test for ElementPlant

Add a basic test for ElementPlant


<?php

namespace SlimAdditions;

class RouteGenerator
{
    private $controller_cache = array();
    private $app;

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

    private function permissions($controller_name, $method)
    {
        if (!isset($this->permissions_cache[$controller_name])) {
            $class_name = "\\App\\Permissions\\" . $controller_name;
            $this->permissions_cache[$controller_name] = new $class_name($this->app);
        }

        return array($this->permissions_cache[$controller_name], "check");
    }

    private function action($controller_name, $method)
    {
        if (!isset($this->controller_cache[$controller_name])) {
            $class_name = '\\App\\Controllers\\' . $controller_name;
            $this->controller_cache[$controller_name] = new $class_name($this->app);
        }

        return array($this->controller_cache[$controller_name], $method);
    }

    private function get($url, $controller, $action)
    {
        return $this->app->get($url, $this->permissions($controller, $action), $this->action($controller, $action));
    }

    private function patch($url, $controller, $action)
    {
        return $this->app->patch($url, $this->permissions($controller, $action), $this->action($controller, $action));
    }

    private function post($url, $controller, $action)
    {
        return $this->app->post($url, $this->permissions($controller, $action), $this->action($controller, $action));
    }

    private function put($url, $controller, $action)
    {
        return $this->app->put($url, $this->permissions($controller, $action), $this->action($controller, $action));
    }

    private function delete($url, $controller, $action)
    {
        return $this->app->delete($url, $this->permissions($controller, $action), $this->action($controller, $action));
    }

    private function options($url, $controller, $action)
    {
        return $this->app->options($url, $this->action($controller, $action));
    }

    private function defaultConditions($conditions)
    {
        \Slim\Route::setDefaultConditions($conditions);
    }

    public function loadRoutes()
    {
        include 'config/routes.php';
    }
}

<?php

namespace SlimAdditions;

class RouteGenerator
{
    private $app;

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

    private function permissions($controller_name, $method)
    {
        return '\\App\\Permissions\\' . $controller_name . ':check';
    }

    private function request($controller_name, $method)
    {
        return '\\App\\Controllers\\' . $controller_name . ":" . $method;
    }

    private function route($http_method, $url, $controller, $action)
    {
        return $this->app->$http_method($url, $this->request($controller, $action))->add($this->permissions($controller, $action));
    }

    public function loadRoutes($path = "config/routes.php")
    {
        include $path;
    }
}

Add route generator for Slim v3

Add route generator for Slim v3


<?php
declare(strict_types = 1);

namespace App\Service\Speaker;

use League\Flysystem\FilesystemInterface;
use Psr\Http\Message\UploadedFileInterface;
use Ramsey\Uuid\Uuid;

final class FlysystemMoveSpeakerHeadshot implements MoveSpeakerHeadshotInterface
{
    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    public function __construct(FilesystemInterface $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * {@inheritDoc}
     * @throws \League\Flysystem\FileExistsException
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function __invoke(UploadedFileInterface $uploadedFile): string
    {
        switch($uploadedFile->getClientMediaType()) {
            case 'image/png':
                $extension = 'png';
                break;
            case 'image/gif':
                $extension = 'gif';
                break;
            default:
                $extension = 'jpg';
        }
        $filename = (string)Uuid::uuid4() . '.' . $extension;
        $this->filesystem->write(
            $filename,
            $uploadedFile->getStream()->getContents(),
            [
                'ACL' => 'public-read',
            ]
        );
        return $filename;
    }
}

<?php
declare(strict_types = 1);

namespace App\Service\Speaker;

use League\Flysystem\FilesystemInterface;
use Psr\Http\Message\UploadedFileInterface;
use Ramsey\Uuid\Uuid;

final class FlysystemMoveSpeakerHeadshot implements MoveSpeakerHeadshotInterface
{
    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    public function __construct(FilesystemInterface $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * {@inheritDoc}
     * @throws \League\Flysystem\FileExistsException
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function __invoke(UploadedFileInterface $uploadedFile): string
    {
        switch ($uploadedFile->getClientMediaType()) {
            case 'image/png':
                $extension = 'png';
                break;
            case 'image/gif':
                $extension = 'gif';
                break;
            default:
                $extension = 'jpg';
        }
        $filename = (string)Uuid::uuid4() . '.' . $extension;
        $this->filesystem->write(
            $filename,
            $uploadedFile->getStream()->getContents(),
            [
                'ACL' => 'public-read',
            ]
        );
        return $filename;
    }
}

Fix CS issue in build

Fix CS issue in build


<?php

header('Content-Type: application/json');

$input   = file_get_contents('php://input');
$params  = (object) json_decode($input, true);

$to      = '<valid-email>';
$subect  = '<the-subject>';

if (isset($params->email) && filter_var($params->email, FILTER_VALIDATE_EMAIL)):
  $from    = $params->email;
  $headers = "From: $from\r\nReply-To: $from\r\nX-Mailer: PHP/" . phpversion();
  $status  = mail($to, $subect, $input, $headers);

  echo json_encode(array('status' => $status));
else:
  header('Bad Request', true, 400);
  echo json_encode(array('error' => 'A valid email is required'));
endif;

<?php

header('Content-Type: application/json');

$input   = file_get_contents('php://input');
$params  = (object) json_decode($input, true);

$to      = '<valid-email>';
$subect  = '<the-subject>';

if (isset($params->email) && filter_var($params->email, FILTER_VALIDATE_EMAIL)):
  $from    = $params->email;
  $headers = "From: $from\r\nReply-To: $from\r\nX-Mailer: PHP/" . phpversion();
  $status  = mail($to, $subect, $input, $headers);

  return die(json_encode(array('status' => $status)));
else:
  header('Bad Request', true, 400);
  return die(json_encode(array('error' => 'A valid email is required')));
endif;

Return die instead of echoing

Return die instead of echoing


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Runtime\Internal;

use Symfony\Component\ErrorHandler\BufferingLogger;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\ErrorHandler\ErrorHandler;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
class SymfonyErrorHandler
{
    public static function register(bool $debug): void
    {
        BasicErrorHandler::register($debug);

        if (class_exists(ErrorHandler::class)) {
            DebugClassLoader::enable();
            restore_error_handler();
            ErrorHandler::register(new ErrorHandler(new BufferingLogger(), true));
        }
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Runtime\Internal;

use Symfony\Component\ErrorHandler\BufferingLogger;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\ErrorHandler\ErrorHandler;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
class SymfonyErrorHandler
{
    public static function register(bool $debug): void
    {
        BasicErrorHandler::register($debug);

        if (class_exists(ErrorHandler::class)) {
            DebugClassLoader::enable();
            restore_error_handler();
            ErrorHandler::register(new ErrorHandler(new BufferingLogger(), $debug));
        }
    }
}

[Runtime] Fix passing $debug parameter to `ErrorHandler`


<?php
class commands_ClearAll extends commands_AbstractChangeCommand
{
	/**
	 * @return String
	 */
	function getUsage()
	{
		return "";
	}

	/**
	 * @return String
	 */
	function getDescription()
	{
		return "clear all";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	function _execute($params, $options)
	{
		$this->message("== Clear all ==");

		$parent = $this->getParent();
		$parent->executeCommand("clearLog");
		$parent->executeCommand("clearCache");
		$parent->executeCommand("clearWebappCache");
		$parent->executeCommand("clearSimplecache");
		$parent->executeCommand("clearDatacache");
		$parent->executeCommand("clearDocumentscache");
		$this->quitOk("All was cleared");
	}
}

<?php
class commands_ClearAll extends commands_AbstractChangeCommand
{
	/**
	 * @return String
	 */
	function getUsage()
	{
		return "";
	}

	/**
	 * @return String
	 */
	function getDescription()
	{
		return "clear all";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	function _execute($params, $options)
	{
		$this->message("== Clear all ==");

		$parent = $this->getParent();
		$parent->executeCommand("updateAutoload");
		$parent->executeCommand("clearLog");
		$parent->executeCommand("clearCache");
		$parent->executeCommand("clearWebappCache");
		$parent->executeCommand("clearSimplecache");
		$parent->executeCommand("clearDatacache");
		$parent->executeCommand("clearDocumentscache");
		$this->quitOk("All was cleared");
	}
}

[UPDATE] Add update-autoload on clear-all command


<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms
{
    private $manager;

    /**
     * TraitsOfOrganisms constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @param 'fennec_ids' => [13,7,12,5]
     * @returns array $result
     * <code>
     * array(type_cvterm_id => array(
     * 'trait_type' => 'habitat',
     * 'trait_entry_ids' => array(1, 20, 36, 7),
     * 'fennec_ids' => array(13, 20, 5)
     * );
     * </code>
     */
    public function execute($fennec_ids)
    {
        return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
    }
}

<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms
{
    private $manager;

    /**
     * TraitsOfOrganisms constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @param 'fennec_ids' => [13,7,12,5]
     * @returns array $result
     * <code>
     * array(type_cvterm_id => array(
     * 'trait_type' => 'habitat',
     * 'trait_entry_ids' => array(1, 20, 36, 7),
     * 'fennec_ids' => array(13, 20, 5)
     * );
     * </code>
     */
    public function execute($fennec_ids)
    {
        if(isset($_REQUEST['fennec_ids'])){
            $fennec_ids = $_REQUEST['fennec_ids'];
        }
        return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
    }
}

Add statement to check if fennec_ids are set in the request


<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Nodes\DataNode;
use Minty\Compiler\Parser;
use Minty\Compiler\Stream;
use Minty\Compiler\Tag;
use Minty\Compiler\Tags\Helpers\MethodNodeHelper;
use Minty\Compiler\Token;

class ParentTag extends Tag
{
    /**
     * @var MethodNodeHelper
     */
    private $helper;

    public function __construct(MethodNodeHelper $helper)
    {
        $this->helper = $helper;
    }

    public function getTag()
    {
        return 'parent';
    }

    public function parse(Parser $parser, Stream $stream)
    {
        $node = $this->helper->createRenderBlockNode(
            $parser->getCurrentBlock(),
            $this->helper->createContext(
                $stream->next()->test(Token::IDENTIFIER, 'using'),
                $stream,
                $parser
            )
        );
        $node->getChild('expression')->addArgument(new DataNode(true));

        return $node;
    }
}

<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Nodes\DataNode;
use Minty\Compiler\Nodes\FunctionNode;
use Minty\Compiler\Parser;
use Minty\Compiler\Stream;
use Minty\Compiler\Tag;
use Minty\Compiler\Tags\Helpers\MethodNodeHelper;
use Minty\Compiler\Token;

class ParentTag extends Tag
{
    /**
     * @var MethodNodeHelper
     */
    private $helper;

    public function __construct(MethodNodeHelper $helper)
    {
        $this->helper = $helper;
    }

    public function getTag()
    {
        return 'parent';
    }

    public function parse(Parser $parser, Stream $stream)
    {
        $node = $this->helper->createRenderBlockNode(
            $parser->getCurrentBlock(),
            $this->helper->createContext(
                $stream->next()->test(Token::IDENTIFIER, 'using'),
                $stream,
                $parser
            )
        );
        $expression = $node->getChild('expression');
        if(!$expression instanceof FunctionNode) {
            throw new \UnexpectedValueException("An instance of FunctionNode was expected");
        }

        $expression->addArgument(new DataNode(true));

        return $node;
    }
}

Fix line endings and check returned type.


<?php namespace Zara4\API\ImageProcessing;

use Zara4\API\Communication\Util;

class Usage {

  public static function cumulativeUsageForCurrentBillingUsage($accessToken) {

    $url = Util::url("/api/usage/image-processing/cumulative-count/current-billing-period");
    $data = ["query" => [
      "access_token" => $accessToken,
    ]];

    $responseData = Util::get($url, $data);
    return (array)($responseData->{"day-data"});
  }

}

<?php namespace Zara4\API\ImageProcessing;

use Zara4\API\Communication\Util;

class Usage {

  public static function cumulativeUsageForCurrentBillingUsage($accessToken) {

    $url = Util::url("/api/usage/image-processing/cumulative-count/current-billing-period");
    $data = ["query" => [
      "access_token" => $accessToken,
    ]];

    $responseData = Util::get($url, $data);

    $personalDayData = (array)$responseData->{"day-data"};
    ksort($personalDayData);

    $response = [
      "quota" => $responseData->{"quota"},
      "personal-day-data" => $personalDayData,
    ];

    //
    // Add team data
    //
    if(isset($responseData->{"team-day-data"})) {
      $teamDayData = (array)$responseData->{"team-day-data"};
      ksort($teamDayData);
      $response["team-day-data"] = $teamDayData;
    }

    return $response;
  }

}

Update usage to read team usage where available


<?php
/**
 * Definition of class LanguageServiceTest
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justtexts\test
 */

namespace justso\justtexts\test;

use justso\justapi\Bootstrap;
use justso\justapi\testutil\ServiceTestBase;
use justso\justtexts\service\Language;

/**
 * Class LanguageServiceTest
 * @package justso\justtexts\test
 */
class LanguageServiceTest extends ServiceTestBase
{

    public function testGetLanguages()
    {
        $config = array(
            'environments' => array('test' => array('approot' => '/var/www')),
            'languages' => array('de', 'en'),
        );
        Bootstrap::getInstance()->setTestConfiguration('/var/www', $config);
        $env = $this->createTestEnvironment();
        $service = new Language($env);
        $service->getAction();
        $this->assertJSONHeader($env);
        $this->assertSame('["de","en"]', $env->getResponseContent());
    }
}

<?php
/**
 * Definition of class LanguageServiceTest
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justtexts\test
 */

namespace justso\justtexts\test;

use justso\justapi\Bootstrap;
use justso\justapi\testutil\ServiceTestBase;
use justso\justtexts\service\Language;

/**
 * Class LanguageServiceTest
 * @package justso\justtexts\test
 */
class LanguageServiceTest extends ServiceTestBase
{

    public function testGetLanguages()
    {
        $env = $this->createTestEnvironment();
        $config = array(
            'environments' => array('test' => array('approot' => '/var/www')),
            'languages' => array('de', 'en'),
        );
        $env->getBootstrap()->setTestConfiguration('/var/www', $config);
        $service = new Language($env);
        $service->getAction();
        $this->assertJSONHeader($env);
        $this->assertSame('["de","en"]', $env->getResponseContent());
    }
}

Create test environment first to prevent the modified bootstrap configuration to be overwritten


<?php

/**
 * LICENSE: This source code is subject to the license that is available
 * in the LICENSE file distributed along with this package.
 *
 * @package    Penelope
 * @author     Matthew Caruana Galizia <mcg@karwana.com>
 * @copyright  Karwana Ltd
 * @since      File available since Release 1.0.0
 */

use Karwana\Penelope\Node;
use Karwana\Penelope\NodeSchema;
use Karwana\Penelope\Scripts\NodePropertyMapper;

function split_node_property(NodeSchema $node_schema, $property_name) {
	$mapper = new NodePropertyMapper($node_schema, $property_name, function(Node $node) use (&$mapper) {
		return $mapper->split($node);
	});

	$mapper->run();
}

if (empty($argv[1])) {
	throw new \InvalidArgumentException('Missing initialization script path.');
}

if (empty($argv[2])) {
	throw new \InvalidArgumentException('Missing schema name.');
}

if (empty($argv[3])) {
	throw new \InvalidArgumentException('Missing property name.');
}

require_once __DIR__ . '/Penelope/NodePropertyMapper.php';
require_once $argv[1];

if (!isset($schema)) {
	$schema = $penelope->getSchema();
}

split_node_property($schema->getNode($argv[2]), $argv[3]);

<?php

/**
 * LICENSE: This source code is subject to the license that is available
 * in the LICENSE file distributed along with this package.
 *
 * @package    Penelope
 * @author     Matthew Caruana Galizia <mcg@karwana.com>
 * @copyright  Karwana Ltd
 * @since      File available since Release 1.0.0
 */

use Karwana\Penelope\Node;
use Karwana\Penelope\NodeSchema;
use Karwana\Penelope\Scripts\NodePropertyMapper;

function split_node_property(NodeSchema $node_schema, $property_name, $delimeter) {
	$mapper = new NodePropertyMapper($node_schema, $property_name, function(Node $node) use (&$mapper, $delimeter) {
		return $mapper->split($node, $delimeter);
	});

	$mapper->run();
}

if (empty($argv[1])) {
	throw new \InvalidArgumentException('Missing initialization script path.');
}

if (empty($argv[2])) {
	throw new \InvalidArgumentException('Missing schema name.');
}

if (empty($argv[3])) {
	throw new \InvalidArgumentException('Missing property name.');
}

if (empty($argv[4])) {
	throw new \InvalidArgumentException('Missing delimeter.');
}

require_once __DIR__ . '/Penelope/NodePropertyMapper.php';
require_once $argv[1];

if (!isset($schema)) {
	$schema = $penelope->getSchema();
}

split_node_property($schema->getNode($argv[2]), $argv[3], $argv[4]);

Allow delimeter to be specified

Allow delimeter to be specified