<?php

namespace Aztech\Process;

class ProcessBuilder
{

    private $command;

    private $args = [];

    private $env = null;

    public function setCommand($executablePath)
    {
        $this->command = $executablePath;

        return $this;
    }

    public function getCommand()
    {
        return $this->command;
    }

    public function setArguments(array $args = null)
    {
        $this->args = $args ?: [];

        return $this;
    }

    public function getArguments()
    {
        return $this->args;
    }

    public function setEnvironment(array $env = null)
    {
        $this->env = $env;
    }

    public function getEnvironment()
    {
        return $this->env;
    }

    /**
     *
     * @throws \RuntimeException
     * @return AttachedProcess
     */
    public function run()
    {
        $cmd = trim(sprintf('%s %s', $this->command, implode(' ', $this->args)));
        $descriptorspec = [
            0 => [ 'pipe', 'r' ],
            1 => [ 'pipe', 'w' ],
            2 => [ 'file', 'php://stderr', 'a' ]
        ];
        $pipes = [];

        $process = proc_open($cmd, $descriptorspec, $pipes);

        if ($process !== false) {
            return new AttachedProcess($process, $pipes, (new InspectorFactory())->create());
        }

        throw new \RuntimeException('Unable to start process.');
    }
}

<?php

namespace Aztech\Process;

class ProcessBuilder
{

    private $command;

    private $args = [];

    private $env = null;

    private $workingDirectory = null;

    public function setCommand($executablePath)
    {
        $this->command = $executablePath;

        return $this;
    }

    public function getCommand()
    {
        return $this->command;
    }

    public function setArguments(array $args = null)
    {
        $this->args = $args ?: [];

        return $this;
    }

    public function getArguments()
    {
        return $this->args;
    }

    public function setEnvironment(array $env = null)
    {
        $this->env = $env;
    }

    public function getEnvironment()
    {
        return $this->env ?: $_ENV;
    }

    public function setWorkingDirectory($path)
    {
        $this->workingDirectory = $path;
    }

    public function getWorkingDirectory()
    {
        return $this->workingDirectory ?: getcwd();
    }

    /**
     *
     * @throws \RuntimeException
     * @return AttachedProcess
     */
    public function run()
    {
        $cmd = trim(sprintf('%s %s', $this->command, implode(' ', $this->args)));

        $descriptorspec = [
            0 => [ 'pipe', 'r' ],
            1 => [ 'pipe', 'w' ],
            2 => [ 'file', 'php://stderr', 'a' ]
        ];
        $pipes = [];

        $env = $this->getEnvironment();
        $cwd = $this->getWorkingDirectory();

        $process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env);

        if ($process !== false) {
            return new AttachedProcess($process, $pipes, (new InspectorFactory())->create());
        }

        throw new \RuntimeException('Unable to start process.');
    }
}

Use non default args for proc_open

Use non default args for proc_open


<?php

/**
 * Class DataObjectPreviewer
 */
class DataObjectPreviewer
{
    /**
     * @param DataObjectPreviewInterface $record
     * @return string
     */
    public function preview(DataObjectPreviewInterface $record)
    {
        $content = $record->getPreviewHtml();
        $contentMd5 = md5($content);

        $htmlFilepath = sprintf(
            '%s/%s.html',
            DATAOBJECTPREVIEW_CACHE_PATH,
            $contentMd5
        );

        if (!file_exists(DATAOBJECTPREVIEW_CACHE_PATH)) {
            mkdir(DATAOBJECTPREVIEW_CACHE_PATH);
        }

        if (!file_exists($htmlFilepath)) {
            file_put_contents($htmlFilepath, $content);
        }

        return sprintf(
            '

',
            str_replace(BASE_PATH, '', $htmlFilepath)
        );
    }
}

<?php

/**
 * Class DataObjectPreviewer
 */
class DataObjectPreviewer
{
    /**
     * @param DataObjectPreviewInterface $record
     * @return string
     */
    public function preview(DataObjectPreviewInterface $record)
    {
        $content = $record->getPreviewHtml();
        $contentMd5 = md5($content);

        $htmlFilepath = sprintf(
            '%s/%s.html',
            DATAOBJECTPREVIEW_CACHE_PATH,
            $contentMd5
        );

        if (!file_exists(DATAOBJECTPREVIEW_CACHE_PATH)) {
            mkdir(DATAOBJECTPREVIEW_CACHE_PATH);
        }

        if (!file_exists($htmlFilepath)) {
            file_put_contents($htmlFilepath, $content);
        }

        return sprintf(
            '

',
            str_replace(BASE_PATH . '/', '', $htmlFilepath)
        );
    }
}

Use relative paths for previews to support sites in sub dirs

The use of an absolute path caused the dataobject previewer iframe to
point to an incorrect path when a site was not located directly in the
document root. A 404 page would display in all preview iframes instead
of the preview that had been rendered.


<?php namespace Modules\Media\Image;

use Illuminate\Contracts\Config\Repository;
use Pingpong\Modules\Module;

class ThumbnailsManager
{
    /**
     * @var Module
     */
    private $module;
    /**
     * @var Repository
     */
    private $config;

    /**
     * @param Repository $config
     * @param Module $module
     */
    public function __construct(Repository $config, Module $module)
    {
        $this->module = $module;
        $this->config = $config;
    }

    /**
     * Return all thumbnails for all modules
     * @return array
     */
    public function all()
    {
        $thumbnails = [];
        foreach ($this->module->enabled() as $enabledModule) {
            $configuration = $this->config->get(strtolower($enabledModule) . '::thumbnails');
            $thumbnails = array_merge($thumbnails, $configuration);
        }

        return $thumbnails;
    }

    /**
     * Find the filters for the given thumbnail
     * @param $thumbnail
     */
    public function find($thumbnail)
    {
        foreach ($this->all() as $thumbName => $filters) {
            if ($thumbName == $thumbnail) {
                return $filters;
            }
        }
    }

}

<?php namespace Modules\Media\Image;

use Illuminate\Contracts\Config\Repository;
use Pingpong\Modules\Repository as Module;

class ThumbnailsManager
{
    /**
     * @var Module
     */
    private $module;
    /**
     * @var Repository
     */
    private $config;

    /**
     * @param Repository $config
     * @param Module $module
     */
    public function __construct(Repository $config, Module $module)
    {
        $this->module = $module;
        $this->config = $config;
    }

    /**
     * Return all thumbnails for all modules
     * @return array
     */
    public function all()
    {
        $thumbnails = [];
        foreach ($this->module->enabled() as $enabledModule) {
            $configuration = $this->config->get(strtolower($enabledModule) . '::thumbnails');
            $thumbnails = array_merge($thumbnails, $configuration);
        }

        return $thumbnails;
    }

    /**
     * Find the filters for the given thumbnail
     * @param $thumbnail
     */
    public function find($thumbnail)
    {
        foreach ($this->all() as $thumbName => $filters) {
            if ($thumbName == $thumbnail) {
                return $filters;
            }
        }
    }

}

Use the new PingPongModule Repository class


<?php

namespace Nin\Database\Results;

use Nin\Database\Result;

class Postgres extends Result
{
	private $res;

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

	public function fetch_assoc()
	{
		$ret = pg_fetch_assoc($this->res);

		if ($ret) {
			$numfields = pg_num_fields($this->res);
			for ($i = 0; $i < $numfields; $i++) {
				$fieldname = pg_field_name($this->res, $i);
				$fieldtype = pg_field_type($this->res, $i);

				switch ($fieldtype) {
					case 'int4': $ret[$fieldname] = intval($ret[$fieldname]); break;
					case 'bool': $ret[$fieldname] = ($ret[$fieldname] == 't'); break;
				}
			}
		}

		return $ret;
	}

	public function insert_id()
	{
		$row = pg_fetch_assoc($this->res);
		return $row['ID'];
	}

	public function num_rows()
	{
		return pg_num_rows($this->res);
	}
}

<?php

namespace Nin\Database\Results;

use Nin\Database\Result;

class Postgres extends Result
{
	private $res;

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

	public function fetch_assoc()
	{
		$ret = pg_fetch_assoc($this->res);

		if ($ret) {
			$numfields = pg_num_fields($this->res);
			for ($i = 0; $i < $numfields; $i++) {
				$fieldname = pg_field_name($this->res, $i);
				$fieldtype = pg_field_type($this->res, $i);

				switch ($fieldtype) {
					case 'int2':
					case 'int4':
					case 'int8':
						$ret[$fieldname] = intval($ret[$fieldname]);
						break;

					case 'bool':
						$ret[$fieldname] = ($ret[$fieldname] == 't');
						break;
				}
			}
		}

		return $ret;
	}

	public function insert_id()
	{
		$row = pg_fetch_assoc($this->res);
		return $row['ID'];
	}

	public function num_rows()
	{
		return pg_num_rows($this->res);
	}
}

Support all integer types on postgres

Support all integer types on postgres


<?php

use \photon\config\Container as Conf;

class SessionTest extends \photon\test\TestCase
{
    protected $conf;

    public function setup()
    {
        parent::setup();
        Conf::set('session_storage', '\photon\session\storage\MongoDB');
    }

    public function testEmptySession()
    {
        $req = \photon\test\HTTP::baseRequest();
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));

        $res = new \photon\http\Response('Hello!');
        $mid->process_response($req, $res);
        $this->assertEquals(false, isset($res->COOKIE['sid']));
        $this->assertEquals(false, isset($res->headers['Vary']));
    }

    public function testFilledSession()
    {
        // Receive a request, and store a counter in the answer
        $req = \photon\test\HTTP::baseRequest();
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));

        $req->session['cpt'] = 1234;
        $res = new \photon\http\Response('Hello!');
        $mid->process_response($req, $res);
        $this->assertEquals(true, isset($res->COOKIE['sid']));

        // Save the signed cookie
        $headers = $res->getHeaders();
        $rc = preg_match('/Set-Cookie: sid=([\w\.]+);/', $headers, $sid);
        $this->assertEquals($rc, 1);
        $sid = $sid[1];

        unset($req);
        unset($res);
        unset($mid);

        // Reload the session
        $req = \photon\test\HTTP::baseRequest('GET', '/', '', '', array(), array('cookie' => 'sid=' . $sid));
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));
        $cpt = $req->session['cpt'];
        $this->assertEquals(1234, $cpt);
    }
}

<?php

use \photon\config\Container as Conf;
use \photon\tests\sessionTest\SessionHighLevelTestCase;

class SessionFileTest extends SessionHighLevelTestCase
{
    public function setup()
    {
        parent::setup();
        Conf::set('session_storage', '\photon\session\storage\MongoDB');
    }
}

Move the generic session tests in photon to share the code with others backend


<?php
$vxml_library = __DIR__ . '/../' . 'library';
$vxml_tests = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $vxml_library . PATH_SEPARATOR . $vxml_library);

require_once 'VXML/Loader.php';
VXML\Loader::registerAutoload();

require_once 'PHPUnit\Framework\TestCase.php';

<?php
$vxml_library = dirname(__DIR__) . '/library';
$vxml_tests = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $vxml_library . PATH_SEPARATOR . $vxml_library);

require_once 'VXML/Loader.php';
VXML\Loader::registerAutoload();

require_once 'PHPUnit\Framework\TestCase.php';

Fix relative part of test include path

Fix relative part of test include path


<?php
namespace Rocketeer\Strategies\Dependencies;

use Rocketeer\TestCases\RocketeerTestCase;

class PolyglotStrategyTest extends RocketeerTestCase
{
	public function testCanInstallAllDependencies()
	{
		$this->usesComposer(true);
		$this->files->put($this->server.'/current/Gemfile', '');

		$polyglot = $this->builder->buildStrategy('Dependencies', 'Polyglot');
		$polyglot->install();

		$this->assertHistory(array(
			array(
				'cd {server}/releases/{release}',
				'{bundle} install',
			),
			array(
				'cd {server}/releases/{release}',
				'{composer} install --no-interaction --no-dev --prefer-dist',
			),
		));
	}
}

<?php
namespace Rocketeer\Strategies\Dependencies;

use Rocketeer\TestCases\RocketeerTestCase;

class PolyglotStrategyTest extends RocketeerTestCase
{
	public function testCanInstallAllDependencies()
	{
		$this->pretend();

		$this->usesComposer(true);
		$this->files->put($this->server.'/current/Gemfile', '');

		$polyglot = $this->builder->buildStrategy('Dependencies', 'Polyglot');
		$polyglot->install();

		$this->assertHistory(array(
			array(
				'cd {server}/releases/{release}',
				'{bundle} install',
			),
			array(
				'cd {server}/releases/{release}',
				'{composer} install --no-interaction --no-dev --prefer-dist',
			),
		));
	}
}

Switch dependencies test to pretend mode


<?php

/*
 * Functional tests for viewing the profile page
 */
class ProfileViewTest extends TestCase
{
    /**
     * Checks that the username is suitably reflected in the page subheading
     */
    public function testProfileTitle()
    {

    }

    /**
     * Checks that user information is reflected in the personal info section
     */
    public function testProfilePersonalInfo()
    {

    }

    /**
     * Checks that an empty skills matrix renders correctly
     */
    public function testProfileEmptySkillsMatrix()
    {

    }

    /**
     * Checks that skills/stars/flags are correct
     *
     * (Have to decide an ordering here - probably alphabetical on skill name, case-insensitive)
     */
    public function testProfileNonEmptySkillsMatrix()
    {

    }

    /**
     * Checks that the message box sends an email
     *
     * (I believe Laravel has a feature for this, so an email is not actually sent)
     */
    public function testProfileSendEmail()
    {

    }
}

<?php

/*
 * Functional tests for viewing the profile page
 */
class ProfileViewTest extends TestCase
{
    /**
     * Checks that the username is suitably reflected in the page subheading
     */
    public function testProfileTitle()
    {
        // @todo Finish this
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }

    /**
     * Checks that user information is reflected in the personal info section
     */
    public function testProfilePersonalInfo()
    {
        // @todo Finish this
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }

    /**
     * Checks that an empty skills matrix renders correctly
     */
    public function testProfileEmptySkillsMatrix()
    {
        // @todo Finish this
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }

    /**
     * Checks that skills/stars/flags are correct
     *
     * (Have to decide an ordering here - probably alphabetical on skill name, case-insensitive)
     */
    public function testProfileNonEmptySkillsMatrix()
    {
        // @todo Finish this
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }

    /**
     * Checks that the message box sends an email
     *
     * (I believe Laravel has a feature for this, so an email is not actually sent)
     */
    public function testProfileSendEmail()
    {
        // @todo Finish this
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }
}

Mark a new set of tests as incomplete

Mark a new set of tests as incomplete


<?php

$REGISTER_LTI2 = array(
"name" => "Participant Map using Google",
"short_name" => "Course Map",
"description" => "This provides a simple Google map for a course where participants can indicate their location and control how much information they release to those viewing the map."
);

<?php

$REGISTER_LTI2 = array(
"name" => "Participant Map using Google",
"FontAwesome" => "fa-map-marker",
"short_name" => "Course Map",
"description" => "This provides a simple Google map for a course where participants can indicate their location and control how much information they release to those viewing the map."
);

Add FontAwesome icons to the tool registration.


<?php

return

/*
|--------------------------------------------------------------------------
| Merchant Settings
|--------------------------------------------------------------------------
| All Merchant settings below are for example purposes only. for more info
| see www.payfast.co.za. The Merchant ID and Merchant Key can be obtained
| from your payfast.co.za account.
|
*/
[
    'testing' => true, // Set to false when in production.
    'merchant' => [
        'merchant_id' => env('PF_MERCHANT_ID', '10000100'), // TEST Credentials. Replace with your merchant ID from Payfast.
        'merchant_key' => env('PF_MERCHANT_KEY', '46f0cd694581a'), // TEST Credentials. Replace with your merchant key from Payfast.
        'return_url' => env('PF_RETURN_URL', 'http://your-domain.co.za/success'), // Redirect URL on Success.
        'cancel_url' => env('PF_CANCEL_URL', 'http://your-domain.co.za/cancel'), // Redirect URL on Cancellation.
        'notify_url' => env('PF_ITN_URL', 'http://your-domain.co.za/itn'), // ITN URL.
    ],

    'hosts' => [
        'www.payfast.co.za',
        'sandbox.payfast.co.za',
        'w1w.payfast.co.za',
        'w2w.payfast.co.za',
    ]

];

<?php

return

/*
|--------------------------------------------------------------------------
| Merchant Settings
|--------------------------------------------------------------------------
| All Merchant settings below are for example purposes only. for more info
| see www.payfast.co.za. The Merchant ID and Merchant Key can be obtained
| from your payfast.co.za account.
|
*/
[
    'testing'  => true, // Set to false when in production.
    'merchant' => [
        'merchant_id'  => env('PF_MERCHANT_ID', '10000100'),                        // TEST Credentials. Replace with your merchant ID from Payfast.
        'merchant_key' => env('PF_MERCHANT_KEY', '46f0cd694581a'),                  // TEST Credentials. Replace with your merchant key from Payfast.
        'return_url'   => env('PF_RETURN_URL', 'http://your-domain.co.za/success'), // Redirect URL on Success.
        'cancel_url'   => env('PF_CANCEL_URL', 'http://your-domain.co.za/cancel'),  // Redirect URL on Cancellation.
        'notify_url'   => env('PF_ITN_URL', 'http://your-domain.co.za/itn'),        // ITN URL.
    ],

    'hosts' => [
        'www.payfast.co.za',
        'sandbox.payfast.co.za',
        'w1w.payfast.co.za',
        'w2w.payfast.co.za',
    ],

    'passphrase' => env('PAYFAST_PASSPHRASE'), // set this in your payfast merchant settings

];

ADD passphrase to config file

ADD passphrase to config file


<?php

namespace Sabre\VObject;

/**
 * This class contains the version number for the VObject package
 *
 * @package Sabre
 * @subpackage VObject
 * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
 * @author Evert Pot (http://www.rooftopsolutions.nl/)
 * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
 */
class Version {

    /**
     * Full version number
     */
    const VERSION = '1.3.3';

    /**
     * Stability : alpha, beta, stable
     */
    const STABILITY = 'stable';

}

<?php

namespace Sabre\VObject;

/**
 * This class contains the version number for the VObject package
 *
 * @package Sabre
 * @subpackage VObject
 * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
 * @author Evert Pot (http://www.rooftopsolutions.nl/)
 * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
 */
class Version {

    /**
     * Full version number
     */
    const VERSION = '1.4.0';

    /**
     * Stability : alpha, beta, stable
     */
    const STABILITY = 'alpha';

}

Set some versions to 'alpha'

Set some versions to 'alpha'


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

namespace Zend\Text\Table\Exception;

use DomainException;

/**
 * @category Zend
 * @package  Zend_Text
 */
class UnexpectedValueException extends DomainException implements ExceptionInterface
{}

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

namespace Zend\Text\Table\Exception;

use DomainException;

/**
 * @category Zend
 * @package  Zend_Text
 */
class InvalidDecoratorException extends DomainException implements ExceptionInterface
{}

Fix exception name in Zend\Text

Fix exception name in Zend\Text


<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Settings\SettingsRepositoryInterface;

return [
    'up' => function (SettingsRepositoryInterface $settings) {
        $settings->set('flarum-tags.max_primary_tags', '1');
        $settings->set('flarum-tags.min_primary_tags', '1');
        $settings->set('flarum-tags.max_secondary_tags', '3');
        $settings->set('flarum-tags.min_secondary_tags', '0');
    },

    'down' => function (SettingsRepositoryInterface $settings) {
        $settings->delete('flarum-tags.max_primary_tags');
        $settings->delete('flarum-tags.max_secondary_tags');
        $settings->delete('flarum-tags.min_primary_tags');
        $settings->delete('flarum-tags.min_secondary_tags');
    }
];

<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;

return Migration::addSettings([
    'flarum-tags.max_primary_tags' => '1',
    'flarum-tags.min_primary_tags' => '1',
    'flarum-tags.max_secondary_tags' => '3',
    'flarum-tags.min_secondary_tags' => '0',
]);

Use new shortcut for default settings migration


<?php

namespace Billplz\Three\Bill;

use Billplz\Three\Request;

class Transaction extends Request
{
    /**
     * Version namespace.
     *
     * @var string
     */
    protected $version = 'v3';

    /**
     * Show an existing bill transactions.
     *
     * @param  string  $id
     *
     * @return \Laravie\Codex\Response
     */
    public function show($id, array $optional = [])
    {
        return $this->send('GET', "bills/{$id}/transactions", [], $optional);
    }
}

<?php

namespace Billplz\Three\Bill;

use Billplz\Three\Request;

class Transaction extends Request
{
    /**
     * Version namespace.
     *
     * @var string
     */
    protected $version = 'v3';

    /**
     * Show an existing bill transactions.
     *
     * @param  string  $id
     * @param  array   $optional
     *
     * @return \Laravie\Codex\Response
     */
    public function show($id, array $optional = [])
    {
        return $this->send('GET', "bills/{$id}/transactions", [], $optional);
    }
}

Update also transaction for v4

Update also transaction for v4


<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ $title }}</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
    <meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">

    @foreach ($styles as $file)
      <link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
    @endforeach

    {!! $head !!}

    {!! $layout !!}

    @foreach ($scripts as $file)

    @endforeach

    @if ($content)

        {!! $content !!}

    @endif

    {!! $foot !!}

Use System.get instead of System.import

Use System.get instead of System.import

All of the modules we import should already be loaded, and we don't
want to ever attempt to import them anyway because we do not include a
Promise polyfill.


<?php
/**
 * Redis backend for storing failed Resque jobs.
 *
 * @package		Resque/Failure
 * @author		Chris Boulton <chris.boulton@interspire.com>
 * @copyright	(c) 2010 Chris Boulton
 * @license		http://www.opensource.org/licenses/mit-license.php
 */

class Resque_Failure_Redis implements Resque_Failure_Interface
{
	/**
	 * Initialize a failed job class and save it (where appropriate).
	 *
	 * @param object $payload Object containing details of the failed job.
	 * @param object $exception Instance of the exception that was thrown by the failed job.
	 * @param object $worker Instance of Resque_Worker that received the job.
	 * @param string $queue The name of the queue the job was fetched from.
	 */
	public function __construct($payload, $exception, $worker, $queue)
	{
		$data = new stdClass;
		$data->failed_at = strftime('%a %b %d %H:%M:%S %Z %Y');
		$data->payload = $payload;
		$data->exception = get_class($exception);
		$data->error = $exception->getMessage();
		$data->backtrace = explode("\n", $exception->getTraceAsString());
		$data->worker = (string)$worker;
		$data->queue = $queue;
		$data = json_encode($data);
		Resque::redis()->rpush('failed', $data);
	}
}
?>

<?php
/**
 * Redis backend for storing failed Resque jobs.
 *
 * @package		Resque/Failure
 * @author		Chris Boulton <chris.boulton@interspire.com>
 * @copyright	(c) 2010 Chris Boulton
 * @license		http://www.opensource.org/licenses/mit-license.php
 */

class Resque_Failure_Redis implements Resque_Failure_Interface
{
	/**
	 * Initialize a failed job class and save it (where appropriate).
	 *
	 * @param object $payload Object containing details of the failed job.
	 * @param object $exception Instance of the exception that was thrown by the failed job.
	 * @param object $worker Instance of Resque_Worker that received the job.
	 * @param string $queue The name of the queue the job was fetched from.
	 */
	public function __construct($payload, $exception, $worker, $queue)
	{
		$data = array();
		$data['failed_at'] = strftime('%a %b %d %H:%M:%S %Z %Y');
		$data['payload'] = $payload;
		$data['exception'] = get_class($exception);
		$data['error'] = $exception->getMessage();
		$data['backtrace'] = explode("\n", $exception->getTraceAsString());
		$data['worker'] = (string)$worker;
		$data['queue'] = $queue;
		Resque::Redis()->setex('failed:'.$payload['id'], 3600*14, function_exists('igbinary_serialize') ? igbinary_serialize($data) : serialize($data));
	}
}
?>

Edit Failure logging to auto-expire, and rename key to a more searchable one


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Collections\Artwork;

use App\Http\Controllers\Controller as BaseController;

class LinkedArtController extends BaseController
{
    public function artwork(Request $request, $id)
    {
        $artwork = Artwork::find($id);

        $item = [
            '@context' => 'https://linked.art/ns/v1/linked-art.json',
            'id' => route('ld.artwork', ['id' => $artwork]),
            'type' => 'HumanMadeObject',
        ];

        return $item;
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Collections\Artwork;

use App\Http\Controllers\Controller as BaseController;

class LinkedArtController extends BaseController
{
    public function artwork(Request $request, $id)
    {
        $artwork = Artwork::find($id);

        $item = [
            '@context' => 'https://linked.art/ns/v1/linked-art.json',
            'id' => route('ld.artwork', ['id' => $artwork]),
            'type' => 'HumanMadeObject',
        ];

        $item = array_merge(
            $item,
            $this->getArtworkType($artwork),
        );

        return $item;
    }

    private function getArtworkType($artwork)
    {
        if (!$artworkType = $artwork->artworkType) {
            return [];
        }

        if (!$artworkType->aat_id) {
            return [];
        }

        return [
            'classified_as' => [
                'id' => 'http://vocab.getty.edu/aat/' . $artworkType->aat_id,
                'type' => 'Type',
                '_label' => $artworkType->title,
            ],
        ];
    }
}

Add artwork type to LA output

Add artwork type to LA output [API-280]


<?php
    // $directory = "nfsshare/audiofiles/" //directory from where to read file
    $directory = "C:/Users/sus/Desktop/voicemail/device/999/INBOX/";
    // get all text files with a .txt extension.
    $texts = glob($directory . "*.txt");

    if(empty($texts)){
        echo "File not present";
        return;
    }
    foreach($texts as $filename){
        $my_array = array();
        $my_array['filename'] = basename($filename, ".txt");
        $file = fopen($filename, 'r');
        while(!feof($file)){
            $current_line = trim(fgets($file));
            $each_line = explode("=", $current_line);
            if($each_line[0] == "callerid"){
                $reg = '/<([0-9]+)>$/';
                preg_match($reg, $each_line[1], $matches);
                $my_array['caller_id'] = $matches[1];
            }
            elseif($each_line[0] == "origtime"){
                $my_array['origtime'] = $each_line[1];
            }
        }
        fclose($file);
        print_r($my_array);
    }

?>

<?php
    $host = "localhost";
    $user_name = "root";
    $password = "";
    $database_name = "vawhack";
    $db = mysql_connect($host, $user_name, $password);
    if (mysql_error() > ""){
        print_r(mysql_error());
    }
    mysql_select_db($database_name, $db);

    // $directory = "nfsshare/audiofiles/" //directory from where to read file
    $directory = "C:/Users/sus/Desktop/voicemail/device/999/INBOX/";
    // get all text files with a .txt extension.
    $texts = glob($directory . "*.txt");

    if(empty($texts)){
        echo "File not present";
        return;
    }
    foreach($texts as $filename){
        $my_array = array();
        $my_array['filename'] = basename($filename, ".txt");
        $file = fopen($filename, 'r');
        while(!feof($file)){
            $current_line = trim(fgets($file));
            $each_line = explode("=", $current_line);
            if($each_line[0] == "callerid"){
                $reg = '/<([0-9]+)>$/';
                preg_match($reg, $each_line[1], $matches);
                $my_array['caller_id'] = $matches[1];
            }
            elseif($each_line[0] == "origtime"){
                $my_array['origtime'] = $each_line[1];
            }
        }
        fclose($file);
        $query = "INSERT INTO vmf(afn, callerid, calltime) values ('".$my_array['filename']."','".$my_array['caller_id']."','".$my_array['origtime']."')";
        print_r($query);
        $qresult = mysql_query($query);
        print_r($my_array);
    }

?>

Store values from array to database

Store values from array to database


<?php

namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Dependency injection container compiler pass to register markup validation
 * processors. It finds all services having the "markup_validator.processor"
 * tag and adds them to the validator
 *
 * @author Antoine Hérault <antoine.herault@gmail.com>
 */
class RegisterValidatorsPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('markup_validator')) {
            return ;
        }

        foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
            if (isset($attributes[0]['alias'])) {
                $container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
            }
        }
    }
}

<?php

namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Dependency injection container compiler pass to register markup validation
 * processors. It finds all services having the "markup_validator.processor"
 * tag and adds them to the validator
 *
 * @author Antoine Hérault <antoine.herault@gmail.com>
 */
class RegisterValidatorsPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
            if (isset($attributes[0]['alias'])) {
                $container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
            }
        }
    }
}

Remove the need to define a default validator


<?php
namespace Aedart\Scaffold\Traits;

use Composer\Factory;

/**
 * Directories To Index
 *
 * Utility that tells what directories should be indexed by default
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Traits
 */
trait DirectoriesToIndex
{
    /**
     * Returns a list of directory paths in which scaffold files
     * are to be searched for, in order to build an index
     *
     * @return string[]
     */
    public function directories()
    {
        $composerConfig = Factory::createConfig(null, getcwd());

        $vendorDir = $composerConfig->get('vendor-dir');
        $globalVendorDir = Factory::createConfig(null, $composerConfig->get('home'))->get('vendor-dir');

        return [

            // The current working directory of where this command
            // is being executed from
            getcwd() . DIRECTORY_SEPARATOR,

            // The vendor folder inside the current working directory
            $vendorDir,

            // The "global" vendor directory inside the composer home
            $globalVendorDir
        ];
    }
}

<?php
namespace Aedart\Scaffold\Traits;

use Composer\Factory;

/**
 * Directories To Index
 *
 * Utility that tells what directories should be indexed by default
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Traits
 */
trait DirectoriesToIndex
{
    /**
     * Returns a list of directory paths in which scaffold files
     * are to be searched for, in order to build an index
     *
     * @return string[]
     */
    public function directories()
    {
        $composerConfig = Factory::createConfig(null, getcwd());

        $vendorDir = $composerConfig->get('vendor-dir');
        $globalVendorDir = Factory::createConfig(null, $composerConfig->get('home'))->get('vendor-dir');

        return [

            // The "global" vendor directory inside the composer home
            $globalVendorDir,

            // The vendor folder inside the current working directory
            $vendorDir,

            // The current working directory of where this command
            // is being executed from
            getcwd() . DIRECTORY_SEPARATOR,
        ];
    }
}

Fix order of default index directories

Fix order of default index directories

When attempting to "extend" scaffolds, local required scaffolds might be
overwritten in the index if they exists in both local and global vendor.
This created unwanted situations.


<?php
namespace Aluc\Tools;

class Urls {
    private static function get_url() {
        $base_url = static::get_current_uri();
        return $base_url;
        // $routes = array();
        // $routes = explode('/', $base_url);
    }

    private static function get_current_uri() {
        // Copy & paste, no tocar!
        $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
        $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
        if (strstr($uri, '?')) {
            $uri = substr($uri, 0, strpos($uri, '?'));
        }
        $uri = '/' . trim($uri, '/');
        return $uri;
    }

    public static function serve_request($urls) {
        $base_url = static::get_url();
        foreach ($urls as $url => $func) {
            if (preg_match($url, $base_url)) {
                $func();
            }
        }
    }
}

<?php
namespace Aluc\Tools;

class Urls {
    private static function get_url() {
        $base_url = static::get_current_uri();
        return $base_url;
        // $routes = array();
        // $routes = explode('/', $base_url);
    }

    private static function get_current_uri() {
        // Copy & paste, no tocar!
        $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
        $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
        if (strstr($uri, '?')) {
            $uri = substr($uri, 0, strpos($uri, '?'));
        }
        $uri = '/' . trim($uri, '/');
        return $uri;
    }

    public static function serve_request($urls) {
        $base_url = static::get_url();
        foreach ($urls as $url => $func) {
            if (preg_match($url, $base_url)) {
                $func();
                break;
            }
        }
    }
}

Break bucle cuando encuentra una coincidencia


<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == "jamendo://") {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == "track/stream/") {
		$id = substr($url, 23);
		return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2";
	}

	if (substr($url, 10, 15) == "album/download/") {
		$id = substr($url, 25);
		return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3";
	}

	if (substr($url, 10, 10) == "album/art/") {
		$id = substr($url, 20);
		return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=400";
	}

	// We don't know what this is
	return $url;
}

?>

<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == "jamendo://") {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == "track/stream/") {
		$id = substr($url, 23);
		return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2";
	}

	if (substr($url, 10, 15) == "album/download/") {
		$id = substr($url, 25);
		return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3";
	}

	if (substr($url, 10, 10) == "album/art/") {
		$id = substr($url, 20);
		return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=200";
	}

	// We don't know what this is
	return $url;
}

?>

Reduce the size of the jamendo album cover images requested since we don't use them for anything larger than 160x160 at the moment


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

define('TIME_START', microtime(true));

require CAKE . 'basics.php';

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

define('TIME_START', microtime(true));

// Compatibility aliases. These will be removed for the first RC release.
class_alias('Cake\Error\Debugger', 'Cake\Utility\Debugger');

require CAKE . 'basics.php';

Add temporary class alias for Debugger.

Add temporary class alias for Debugger.


<?php
define('CLEANHOME', '/opt/clean');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_REQUEST['lib']) || !isset($_REQUEST['mod'])) {
	die('Add ?lib and ?mod.');
}

$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';

$highlight = isset($_REQUEST['hl']) ? true : false;

$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = str_replace('.', '/', $_REQUEST['mod']);
$mod = preg_replace('/[^\\w\\/]/', '', $mod);

$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);

if ($highlight) {
	$out = [];
	exec('pygmentize -l clean -f html -O full -O linenos ' . $efname, $out);
	$out = array_filter($out, function($str) { return $str != '

'; });
	echo implode("\n", $out);
} else {
	header('Content-Type: text/plain');
	echo file_get_contents($fname);
}

<?php
define('CLEANHOME', '/opt/clean');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_REQUEST['lib']) || !isset($_REQUEST['mod'])) {
	die('Add ?lib and ?mod.');
}

$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';

$highlight = isset($_REQUEST['hl']) ? true : false;

$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = str_replace('.', '/', $_REQUEST['mod']);
$mod = preg_replace('/[^\\w\\/]/', '', $mod);

$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);

if ($highlight) {
	$out = [];
	$code = -1;
	$cmd = 'pygmentize -v -l clean -f html -O full,linenos,encoding=iso8859';
	exec("$cmd $efname", $out, $code);
	$out = array_filter($out, function($str) { return $str != '

'; });
	echo implode("\n", $out);
} else {
	header('Content-Type: text/plain');
	echo file_get_contents($fname);
}

Fix highlighting of modules by László (encoding)


<?php
namespace MicroFW\Routing;

use MicroFW\Http\Response;

class Router
{
    /** @var array */
    private $routes;

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

    /**
     * Return response for request based on URL.
     *
     * @param $request MicroFW\Http\Request
     * @return MicroFW\Http\Response
     */
    public function getResponse($request)
    {
        $path = $request->getPath();
        $response = new Response('
404
', 404);
        foreach ($this->routes as $url => $res) {
            $matches = [];
            if (preg_match('/^\/' . $url . '/', $path, $matches)) {
                $response = $res;
                var_dump($matches);
                break;
            }
        }
        return $response;
    }
}

<?php
namespace MicroFW\Routing;

use MicroFW\Http\Response;

class Router
{
    /** @var array */
    private $routes;

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

    /**
     * Return response for request based on URL.
     *
     * @param $request MicroFW\Http\Request
     * @return MicroFW\Http\Response
     */
    public function getResponse($request)
    {
        $path = $request->getPath();
        $response = new Response('
404
', 404);
        foreach ($this->routes as $url => $res) {
            $matches = [];
            if (preg_match('/^\/' . $url . '/', $path, $matches)) {
                $response = $res;
                $matches = $this->cleanRoutesParameters($matches);
                var_dump($matches);
                break;
            }
        }
        return $response;
    }

    private function cleanRoutesParameters($parameters)
    {
        $cleanedParameters = [];
        foreach ($parameters as $name => $value) {
            if (is_string($name)) {
                $cleanedParameters[$name] = $value;
            }
        }

        return $cleanedParameters;
    }
}

Clean parameters from regex named groups


<?php

namespace Northstar\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;
use Northstar\Models\User;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine if the authorized user can see full profile details
     * for the given user account.
     *
     * @param User $user
     * @param User $profile
     * @return bool
     */
    public function viewFullProfile(User $user, User $profile)
    {
        return $user->id === $profile->id;
    }

    /**
     * Determine if the authorized user can edit the profile details
     * for the given user account.
     *
     * @param User $user
     * @param User $profile
     * @return bool
     */
    public function editProfile(User $user, User $profile)
    {
        return $user->id === $profile->id;
    }
}

<?php

namespace Northstar\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;
use Northstar\Models\User;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine if the authorized user can see full profile details
     * for the given user account.
     *
     * @param User $user
     * @param User $profile
     * @return bool
     */
    public function viewFullProfile(User $user, User $profile)
    {
        if (in_array($user->role, ['admin', 'staff'])) {
            return true;
        }

        return $user->id === $profile->id;
    }

    /**
     * Determine if the authorized user can edit the profile details
     * for the given user account.
     *
     * @param User $user
     * @param User $profile
     * @return bool
     */
    public function editProfile(User $user, User $profile)
    {
        if (in_array($user->role, ['admin', 'staff'])) {
            return true;
        }

        return $user->id === $profile->id;
    }
}

Check user role in policy.

Check user role in policy.

If a user is an admin or staff, we want to allow them to see/edit
everything!


<?php

namespace Politix\PolitikportalBundle\Model;

// use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Doctrine\DBAL\Connection;

class SourceModel extends Connection{

    public function getSources($start = 0, $max = 10) {

    	$sql = "SELECT * FROM sources LIMIT $start,$max";

		return $this->conn->query($sql);

    }

}

<?php

namespace Politix\PolitikportalBundle\Model;

// use Symfony\Bundle\FrameworkBundle\Controller\Controller;

// use Doctrine\DBAL\Connection;

class SourceModel {

    public function getSources($start = 0, $max = 10) {

        $conn = $this->container->get('database_connection');

    	$sql = "SELECT * FROM sources LIMIT $start,$max";

		return $conn->query($sql);

    }

}

Use simple get "database connection"

Use simple get "database connection"


<?php

namespace Admin\Controller;

class GroupController extends DefaultController
{

}

<?php

namespace Admin\Controller;

use Admin\Controller\Traits\Routes\LinkUnlinkTrait;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use App\Entity\Group;

class GroupController extends DefaultController
{
    use LinkUnlinkTrait;

    protected function handleLink($type, $parent, $link)
    {
        switch($type) {
            case 'group':
                $group = $link->getData();
                if(!$group instanceof Group) {
                    throw new BadRequestHttpException('Subresource of wrong type (expected: group)');
                }
                if(!$parent->getGroups()->contains($group)) {
                    $parent->addGroup($group);
                }
                break;
            default:
                throw new BadRequestHttpException('Invalid relationship (allowed: group)');
        }
    }

    protected function handleUnlink($type, $parent, $link)
    {
        switch($type) {
            case 'group':
                $group = $link->getData();
                if(!$group instanceof Group) {
                    throw new BadRequestHttpException('Subresource of wrong type (expected: group)');
                }
                $parent->removeGroup($group);
                break;
            default:
                throw new BadRequestHttpException('Invalid relationship (allowed: group)');
        }
    }

}

Add (UN)LINK support to admin group

Add (UN)LINK support to admin group


<?php
namespace Plitz\Bindings\Blitz;

class TemplateFunctions
{
    /**
     * Helper method which reduces a variable to its requested properties.
     *
     * This function takes a value and a non-empty array of properties as varargs.
     * It then tries to resolve the properties of this value, one-by-one recursively.
     *
     * Eg:
     *   $foo = ['bar' => ['foo' => 'foobar']];
     *   var_dump(TemplateFunctions::fetchProperty($foo, 'bar', 'foo')); // gives 'foobar'
     *
     * @return mixed
     */
    public static function fetchProperty()
    {
        $args = func_get_args();
        if (count($args) < 2) {
            throw new \InvalidArgumentException('Expected at least 2 arguments');
        }
        $variable = array_shift($args);

        foreach ($args as $arg) {
            if (is_object($variable)) {
                $variable = &$variable->{$arg};
            } else if (is_array($variable)) {
                $variable = &$variable[$arg];
            } else {
                throw new \InvalidArgumentException('$variable is neither an object nor an array');
            }
        }

        return $variable;
    }
}

<?php
namespace Plitz\Bindings\Blitz;

class TemplateFunctions
{
    /**
     * Helper method which reduces a variable to its requested properties.
     *
     * This function takes a value and a non-empty array of properties as varargs.
     * It then tries to resolve the properties of this value, one-by-one recursively.
     *
     * Eg:
     *   $foo = ['bar' => ['foo' => 'foobar']];
     *   var_dump(TemplateFunctions::fetchProperty($foo, 'bar', 'foo')); // gives 'foobar'
     *
     * @return mixed
     */
    public static function fetchProperty()
    {
        static $strictMode = false; // TODO: allow changing this at runtime

        $args = func_get_args();
        if (count($args) < 2) {
            throw new \InvalidArgumentException('Expected at least 2 arguments');
        }
        $variable = array_shift($args);

        foreach ($args as $arg) {
            if (is_object($variable)) {
                $variable = &$variable->{$arg};
            } else if (is_array($variable)) {
                $variable = &$variable[$arg];
            } else {
                if ($strictMode) {
                    throw new \InvalidArgumentException('Expected template variable to be either an object or an array, got a "' . gettype($variable) . '" instead.');
                } else {
                    return null;
                }
            }
        }

        return $variable;
    }
}

Clarify exception message + add a strict mode switch


<?php

final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {

  public function getAPIMethodName() {
    return 'conduit.query';
  }

  public function getMethodDescription() {
    return 'Returns the parameters of the Conduit methods.';
  }

  public function defineParamTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'dict<dict>';
  }

  public function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $classes = id(new PhutilSymbolLoader())
      ->setAncestorClass('ConduitAPIMethod')
      ->setType('class')
      ->loadObjects();

    $names_to_params = array();
    foreach ($classes as $class) {
      $names_to_params[$class->getAPIMethodName()] = array(
        'params' => $class->defineParamTypes(),
      );
    }

    return $names_to_params;
  }

}

<?php

final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {

  public function getAPIMethodName() {
    return 'conduit.query';
  }

  public function getMethodDescription() {
    return 'Returns the parameters of the Conduit methods.';
  }

  public function defineParamTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'dict<dict>';
  }

  public function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $classes = id(new PhutilSymbolLoader())
      ->setAncestorClass('ConduitAPIMethod')
      ->setType('class')
      ->loadObjects();

    $names_to_params = array();
    foreach ($classes as $class) {
      $names_to_params[$class->getAPIMethodName()] = array(
        'params' => $class->defineParamTypes(),
        'return' => $class->defineReturnType(),
      );
    }

    return $names_to_params;
  }

}

Add return type to `conduit.query`

Add return type to `conduit.query`

Summary: Fixes T6950. Adds the return type of Conduit API methods to the `conduit.query` call.

Test Plan: Called `echo '{}' | arc call-conduit conduit.query` and verified that the return types were present in the response.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: Korvin, epriestley

Maniphest Tasks: T6950

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


<?php
function smarty_function_call_webservice($params, &$smarty) {
    $service = WebService::factory($params['path']);
    if ($service[0] != null) {
        $ret = $service[0]->execute($params['data']);
        $smarty->assign($params['assign'], $ret);
    }
}
?>

<?php
function smarty_function_call_webservice($params, &$smarty) {
    $service = fennecweb\WebService::factory($params['path']);
    if ($service[0] != null) {
        $ret = $service[0]->execute($params['data']);
        $smarty->assign($params['assign'], $ret);
    }
}
?>

Add fennecweb namespace to call of webservice in smarty plugin


<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/vendor/ElFinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

Update the path and the url

Update the path and the url


<?php
/**
 * @link https://github.com/nezhelskoy/yii2-highlight
 * @copyright Copyright (c) 2014 Dmitry Nezhelskoy
 * @license "BSD-3-Clause"
 */

namespace nezhelskoy\highlight;

use yii\web\AssetBundle;

/**
 * Asset bundle for the Highlight.js library.
 *
 * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru>
 */
class BootstrapAsset extends AssetBundle
{
    public $sourcePath = '@vendor/isagalaev/highlight.js/';
    public $css = [
        'src/styles/default.css',
    ];
    public $js = [
        'build/highlight.pack.js',
    ];
    public $depends = [
        'app\assets\AppAsset',
    ];
}

<?php
/**
 * @link https://github.com/nezhelskoy/yii2-highlight
 * @copyright Copyright (c) 2014 Dmitry Nezhelskoy
 * @license "BSD-3-Clause"
 */

namespace nezhelskoy\highlight;

use yii\web\AssetBundle;

/**
 * Asset bundle for the Highlight.js library.
 *
 * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru>
 */
class BootstrapAsset extends AssetBundle
{
    public $sourcePath = '@vendor/isagalaev/highlight.js/';
    public $css = [
        'dist/styles/default.css',
    ];
    public $js = [
        'dist/highlight.pack.js',
    ];
    public $depends = [
        'app\assets\AppAsset',
    ];
}

Fix path to dist files

Fix path to dist files


<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AlterTableComponentGroupsMakeColumnInteger extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('component_groups', function (Blueprint $table) {
            $table->dropcolumn('collapsed');
        });

        Schema::table('component_groups', function (Blueprint $table) {
            $table->integer('collapsed')->unsigned()->default(2)->after('order');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('component_groups', function (Blueprint $table) {
            $table->boolean('collapsed')->change();
        });
    }
}

<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AlterTableComponentGroupsMakeColumnInteger extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('component_groups', function (Blueprint $table) {
            $table->dropcolumn('collapsed');
        });

        Schema::table('component_groups', function (Blueprint $table) {
            $table->integer('collapsed')->unsigned()->default(1)->after('order');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('component_groups', function (Blueprint $table) {
            $table->boolean('collapsed')->change();
        });
    }
}

Set default component group view to 1

Set default component group view to 1


<?php
namespace Craft;

class WistiaPlugin extends BasePlugin
{
	public function getName()
	{
		return 'Wistia';
	}

	public function getDescription()
	{
		return 'Manage videos and output data using the Wistia API.';
	}

	public function getVersion()
	{
		return '0.1.0';
	}

	public function getDeveloper()
	{
		return 'Caddis';
	}

	public function getDeveloperUrl()
	{
		return 'https://www.caddis.co';
	}

	public function getDocumentationUrl()
	{
		return 'https://www.caddis.co/software/craft/wistia';
	}

	public function getSchemaVersion()
	{
		return '1.0.0';
	}

	public function hasCpSection()
	{
		return true;
	}

	protected function defineSettings()
	{
		return array(
			'apiKey' => AttributeType::String,
			'cacheDuration' => [
				AttributeType::Number,
				'default' => 24
			],
			'thumbnailPath' => [
				AttributeType::String,
				'default' => '/images/videos/'
			]
		);
	}

	public function getSettingsHtml()
	{
		return craft()->templates->render('wistia/plugin/settings', [
			'settings' => $this->getSettings()
		]);
	}
}

<?php
namespace Craft;

class WistiaPlugin extends BasePlugin
{
	public function getName()
	{
		return 'Wistia';
	}

	public function getDescription()
	{
		return 'Manage videos and output data using the Wistia API.';
	}

	public function getVersion()
	{
		return '0.1.0';
	}

	public function getDeveloper()
	{
		return 'Caddis';
	}

	public function getDeveloperUrl()
	{
		return 'https://www.caddis.co';
	}

	public function getDocumentationUrl()
	{
		return 'https://www.caddis.co/software/craft/wistia';
	}

	public function getSchemaVersion()
	{
		return '1.0.0';
	}

	// TODO: Add CP section once fully fleshed out
	// public function hasCpSection()
	// {
	// 	return true;
	// }

	protected function defineSettings()
	{
		return array(
			'apiKey' => AttributeType::String,
			'cacheDuration' => [
				AttributeType::Number,
				'default' => 24
			],
			'thumbnailPath' => [
				AttributeType::String,
				'default' => '/images/videos/'
			]
		);
	}

	public function getSettingsHtml()
	{
		return craft()->templates->render('wistia/plugin/settings', [
			'settings' => $this->getSettings()
		]);
	}
}

Add comment to main plugin file

Add comment to main plugin file


<?php
namespace MathPHP\Probability\Distribution;

use MathPHP\Functions\Support;

abstract class Distribution
{
    /**
     * Constructor
     *
     * @param number ...$params
     */
    public function __construct(...$params)
    {
        $new_params = static::PARAMETER_LIMITS;
        $i = 0;

        foreach ($new_params as $key => $value) {
            $this->$key       = $params[$i];
            $new_params[$key] = $params[$i];
            $i++;
        }
        Support::checkLimits(static::PARAMETER_LIMITS, $new_params);
    }
}

<?php
namespace MathPHP\Probability\Distribution;

use MathPHP\Functions\Support;

abstract class Distribution
{
    // Overridden by implementing classes
    const PARAMETER_LIMITS = [];

    /**
     * Constructor
     *
     * @param number ...$params
     */
    public function __construct(...$params)
    {
        $new_params = static::PARAMETER_LIMITS;
        $i = 0;

        foreach ($new_params as $key => $value) {
            $this->$key       = $params[$i];
            $new_params[$key] = $params[$i];
            $i++;
        }
        Support::checkLimits(static::PARAMETER_LIMITS, $new_params);
    }
}

Add default parameter limits to distribution to be overridden by implementing classes.


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

/**
 * Entry point of the PropertyAccess component.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
final class PropertyAccess
{
    /**
     * Creates a property accessor with the default configuration.
     *
     * @return PropertyAccessor
     */
    public static function createPropertyAccessor()
    {
        return self::createPropertyAccessorBuilder()->getPropertyAccessor();
    }

    /**
     * Creates a property accessor builder.
     *
     * @return PropertyAccessorBuilder
     */
    public static function createPropertyAccessorBuilder()
    {
        return new PropertyAccessorBuilder();
    }

    /**
     * Alias of {@link createPropertyAccessor}.
     *
     * @return PropertyAccessor
     *
     * @deprecated since version 2.3, to be removed in 3.0.
     *             Use {@link createPropertyAccessor()} instead.
     */
    public static function getPropertyAccessor()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the createPropertyAccessor() method instead.', E_USER_DEPRECATED);

        return self::createPropertyAccessor();
    }

    /**
     * This class cannot be instantiated.
     */
    private function __construct()
    {
    }
}

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

/**
 * Entry point of the PropertyAccess component.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
final class PropertyAccess
{
    /**
     * Creates a property accessor with the default configuration.
     *
     * @return PropertyAccessor
     */
    public static function createPropertyAccessor()
    {
        return self::createPropertyAccessorBuilder()->getPropertyAccessor();
    }

    /**
     * Creates a property accessor builder.
     *
     * @return PropertyAccessorBuilder
     */
    public static function createPropertyAccessorBuilder()
    {
        return new PropertyAccessorBuilder();
    }

    /**
     * Alias of {@link createPropertyAccessor}.
     *
     * @return PropertyAccessor
     *
     * @deprecated since version 2.3, to be removed in 3.0.
     *             Use {@link createPropertyAccessor()} instead.
     */
    public static function getPropertyAccessor()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.3 and will be removed in 3.0. Use the createPropertyAccessor() method instead.', E_USER_DEPRECATED);

        return self::createPropertyAccessor();
    }

    /**
     * This class cannot be instantiated.
     */
    private function __construct()
    {
    }
}

[2.7][DX] Use constant message contextualisation for deprecations


<?php
/*
 * This file bootstraps the test environment.
 */
namespace Doctrine\Tests;

error_reporting(E_ALL | E_STRICT);

if (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    // dependencies were installed via composer - this is the main project
    $classLoader = require __DIR__ . '/../../../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../../autoload.php')) {
    // installed as a dependency in `vendor`
    $classLoader = require __DIR__ . '/../../../../../autoload.php';
} else {
    throw new \Exception('Can\'t find autoload.php. Did you install dependencies via composer?');
}

/* @var $classLoader \Composer\Autoload\ClassLoader */
$classLoader->add('Doctrine\\Tests\\', __DIR__ . '/../../');
unset($classLoader);

<?php
/*
 * This file bootstraps the test environment.
 */
error_reporting(E_ALL | E_STRICT);

if (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    // dependencies were installed via composer - this is the main project
    $classLoader = require __DIR__ . '/../../../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../../autoload.php')) {
    // installed as a dependency in `vendor`
    $classLoader = require __DIR__ . '/../../../../../autoload.php';
} else {
    throw new Exception('Can\'t find autoload.php. Did you install dependencies via Composer?');
}

/* @var $classLoader \Composer\Autoload\ClassLoader */
$classLoader->add('Doctrine\\Tests\\', __DIR__ . '/../../');
unset($classLoader);

Remove not needed stuff from PHPUnit bootstrap


<?php
/**
 * DronePHP (http://www.dronephp.com)
 *
 * @link      http://github.com/Pleets/DronePHP
 * @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
 * @license   http://www.dronephp.com/license
 */

namespace Drone\Db;

abstract class AbstractTableGateway
{
    /**
     * Handle
     *
     * @var Driver
     */
    private static $db;

    /**
     * Constructor
     *
     * @param string  $abstract_connection_string
     * @param boolean $auto_connect
     *
     * @return null
     */
    public function __construct($abstract_connection_string = "default", $auto_connect = true)
    {
		$dbsettings = include(__DIR__ . "/../../../config/database.config.php");

        $drivers = array(
            "Oci8"          => "Drone\Sql\Oracle",
            "Mysqli"        => "Drone\Sql\MySQL",
            "Sqlsrv"        => "Drone\Sql\SQLServer",
        );

        $drv = $dbsettings[$abstract_connection_string]["driver"];

        if (array_key_exists($drv, $drivers))
            self::$db = new $drivers[$drv]($dbsettings[$abstract_connection_string]);
        else
            throw new Exception("The Database driver '$drv' does not exists");
	}

    /**
     * Returns the handle instance
     *
     * @return Driver
     */
    public function getDb()
    {
        return self::$db;
    }
}

<?php
/**
 * DronePHP (http://www.dronephp.com)
 *
 * @link      http://github.com/Pleets/DronePHP
 * @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
 * @license   http://www.dronephp.com/license
 */

namespace Drone\Db;

abstract class AbstractTableGateway
{
    /**
     * Handle
     *
     * @var Driver
     */
    private static $db;

    /**
     * Constructor
     *
     * @param string  $abstract_connection_string
     * @param boolean $auto_connect
     *
     * @return null
     */
    public function __construct($abstract_connection_string = "default", $auto_connect = true)
    {
		$dbsettings = include(__DIR__ . "/../../../config/database.config.php");

        $drivers = array(
            "Oci8"          => "Drone\Sql\Oracle",
            "Mysqli"        => "Drone\Sql\MySQL",
            "Sqlsrv"        => "Drone\Sql\SQLServer",
        );

        $drv = $dbsettings[$abstract_connection_string]["driver"];

        if (!array_key_exists($drv, $drivers))
            throw new Exception("The Database driver '$drv' does not exists");

        if (array_key_exists($drv, $drivers) && !isset(self::$db))
            self::$db = new $drivers[$drv]($dbsettings[$abstract_connection_string]);
	}

    /**
     * Returns the handle instance
     *
     * @return Driver
     */
    public static function getDb()
    {
        return self::$db;
    }
}

Fix static db connection. Singleton pattern.


<?php

namespace Amp\Internal;

use Interop\Async\Loop;

/**
 * Stores a set of functions to be invoked when an awaitable is resolved.
 *
 * @internal
 */
class WhenQueue {
    /**
     * @var callable[]
     */
    private $queue = [];

    /**
     * @param callable|null $callback Initial callback to add to queue.
     */
    public function __construct(callable $callback = null) {
        if (null !== $callback) {
            $this->push($callback);
        }
    }

    /**
     * Calls each callback in the queue, passing the provided values to the function.
     *
     * @param \Throwable|null $exception
     * @param mixed $value
     */
    public function __invoke($exception = null, $value = null) {
        foreach ($this->queue as $callback) {
            try {
                $callback($exception, $value);
            } catch (\Throwable $exception) {
                Loop::defer(static function () use ($exception) {
                    throw $exception;
                });
            }
        }
    }

    /**
     * Unrolls instances of self to avoid blowing up the call stack on resolution.
     *
     * @param callable $callback
     */
    public function push(callable $callback) {
        if ($callback instanceof self) {
            $this->queue = \array_merge($this->queue, $callback->queue);
            return;
        }

        $this->queue[] = $callback;
    }
}

<?php

namespace Amp\Internal;

use Interop\Async\Loop;

/**
 * Stores a set of functions to be invoked when an awaitable is resolved.
 *
 * @internal
 */
class WhenQueue {
    /**
     * @var callable[]
     */
    private $queue = [];

    /**
     * @param callable|null $callback Initial callback to add to queue.
     */
    public function __construct(callable $callback = null) {
        if (null !== $callback) {
            $this->push($callback);
        }
    }

    /**
     * Calls each callback in the queue, passing the provided values to the function.
     *
     * @param \Throwable|null $exception
     * @param mixed $value
     */
    public function __invoke($exception, $value) {
        foreach ($this->queue as $callback) {
            try {
                $callback($exception, $value);
            } catch (\Throwable $exception) {
                Loop::defer(static function () use ($exception) {
                    throw $exception;
                });
            }
        }
    }

    /**
     * Unrolls instances of self to avoid blowing up the call stack on resolution.
     *
     * @param callable $callback
     */
    public function push(callable $callback) {
        if ($callback instanceof self) {
            $this->queue = \array_merge($this->queue, $callback->queue);
            return;
        }

        $this->queue[] = $callback;
    }
}

Remove unnecessary default parameter values


<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::model('user_list');
$av = Loader::helper('concrete/avatar');
$ul = new UserList();
$ul->filterByGroup('Staff');
$ul->sortBy('uName');
$content = $controller->getContent();
print $content;
?>

  <?php foreach($ul->get(100) as $staffMember) { ?>

      <?php if($avatar = $av->getImagePath($staffMember)) { ?>
        <div class='u-avatar' style='background-image:url(<?=$avatar?>)'>

      <?php } else { ?>
        <div class='u-avatar placeholder<?=ord($staffMember->getUserID()) % 3?>'>

      <?php } ?>

<?="{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk');?>

        <a href="mailto:<?=($email = $staffMember->getUserEmail())?>"><?=$email?>

<?=$staffMember->getAttribute('bio')?>

  <?php } ?>

<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::model('user_list');
$av = Loader::helper('concrete/avatar');
$ul = new UserList();
$ul->filterByGroup('Staff');
$ul->sortBy('ak_order','asc');
$content = $controller->getContent();
print $content;
?>

  <?php foreach($ul->get(100) as $staffMember) { ?>

      <?php if($avatar = $av->getImagePath($staffMember)) { ?>
        <div class='u-avatar' style='background-image:url(<?=$avatar?>)'>

      <?php } else { ?>
        <div class='u-avatar placeholder<?=ord($staffMember->getUserID()) % 3?>'>

      <?php } ?>

<?="{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk');?>

        <a href="mailto:<?=($email = $staffMember->getUserEmail())?>"><?=$email?>

<?=$staffMember->getAttribute('bio')?>

  <?php } ?>

Sort the staff by their order attr

Sort the staff by their order attr


<?php

	/*
	 * Inquire all SYSTEM channels from queuemanager PIGEON.
	 * MQWeb runs on localhost and is listening on port 8081.
	 */
	$url = "http://localhost:8081/api/channel/inquire/PIGEON/SYSTEM*";
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	$response = curl_exec($curl);
	$data = json_decode($response, true);
	print_r($data);

<?php

	/*
	 * Inquire all client channels from queuemanager PIGEON.
	 * MQWeb runs on localhost and is listening on port 8081.
	 */
	$url = "http://localhost:8081/api/channel/inquire/PIGEON/*/Server-connection";

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	if ( ($response = curl_exec($curl) ) === false ) {
		$err = curl_error($curl);
		echo "An HTTP error occurred while getting queue information: $err\n";
	}
	else {
		$json = json_decode($response);
		if ( isset($json->error) ) {
			echo "An MQ error occurred while inquiring channels.\n";
			echo "Reason Code: {$json->error->reason->code} - {$json->error->reason->desc}\n";
		}
		else {
			if ( isset($json->channels) && count($json->channels) > 0 ) {
				foreach($json->channels as $channel)
				{
					echo $channel->ChannelName->value;
					echo "\n";
				}
			}
			else
			{
				echo "No client channels found\n";
			}
		}
	}

Make the example more realistic ...

Make the example more realistic ...


<?

defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion562Helper {

	public $dbRefreshTables = array(
		'Queues',
		'QueueMessages',
		'QueuePageDuplicationRelations',
		'Jobs',
		'JobSets',
		'JobSetJobs',
		'Blocks'
	);

	public function run() {
		$j = Job::getByHandle('index_search_all');
		if (!is_object($j)) {
			Job::installByHandle('index_search_all');
		}

		$js = JobSet::getByName('Default');
		if (!is_object($js)) {
			$js = JobSet::add('Default');
		}
		$js->clearJobs();
		$jobs = Job::getList();
		foreach($jobs as $j) {
			if (!$j->supportsQueue()) {
				$js->addJob($j);
			}
		}
	}

}

<?

defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion562Helper {

	public $dbRefreshTables = array(
		'Queues',
		'QueueMessages',
		'QueuePageDuplicationRelations',
		'Jobs',
		'JobSets',
		'JobSetJobs',
		'Blocks',
		'Pages'
	);

	public function run() {
		$j = Job::getByHandle('index_search_all');
		if (!is_object($j)) {
			Job::installByHandle('index_search_all');
		}

		$js = JobSet::getByName('Default');
		if (!is_object($js)) {
			$js = JobSet::add('Default');
		}
		$js->clearJobs();
		$jobs = Job::getList();
		foreach($jobs as $j) {
			if (!$j->supportsQueue()) {
				$js->addJob($j);
			}
		}
	}

}

Add Pages to Refresh Tables for Upgrade

Add Pages to Refresh Tables for Upgrade

Add Pages to Refresh Tables for Upgrade


<?php

  function getDb() {
    $mongoClient = new MongoClient();
    $db = $mongoClient->actuary;
    return $db;
  }

?>

<?php

  function getDb() {
    $dbUser = getenv('MONGO_DB_USER');
    $dbPass = getenv('MONGO_DB_PASS');
    $dbHost = getenv('MONGO_DB_HOST');
    $dbPort = getenv('MONGO_DB_PORT');
    $dbName = getenv('MONGO_DB_NAME');

    if (!$dbHost) {
      $dbHost = 'localhost';
    }

    if ($dbUser && $dbPass) {
      $dbCredentials = "$dbUser:$dbPass@";
    } else {
      $dbCredentials = '';
    }

    if ($dbPort) {
      $dbPort = ":$dbPort";
    }

    if (!$dbName) {
      $dbName = 'actuary';
    }

    $dbConnectionString = "mongodb://${dbCredentials}${dbHost}${dbPort}";
    $m = new MongoClient($dbConnectionString, array("db" => $dbName));

    return $m->$dbName;
  }

?>

Generalize database component to work in dev and in prod


use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class {{ucfirst($first)}}{{ucfirst($second)}} extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('{{$first}}_{{$second}}',function (Blueprint $table){
			$table->increments('id')->unique()->index()->unsigned();
			$table->integer('{{str_singular($first)}}_id')->unsigned()->index();
			$table->foreign('{{str_singular($first)}}_id')->references('id')->on('{{$first}}')->onDelete('cascade');
			$table->integer('{{str_singular($second)}}_id')->unsigned()->index();
			$table->foreign('{{str_singular($second)}}_id')->references('id')->on('{{$second}}')->onDelete('cascade');
			/**
			 * Type your addition here
			 *
			 */
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('{{$first}}_{{$second}}');
    }
}

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class {{ucfirst($first)}}{{ucfirst($second)}} extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('{{str_singular($first)}}_{{str_singular($second)}}',function (Blueprint $table){
			$table->increments('id')->unique()->index()->unsigned();
			$table->integer('{{str_singular($first)}}_id')->unsigned()->index();
			$table->foreign('{{str_singular($first)}}_id')->references('id')->on('{{$first}}')->onDelete('cascade');
			$table->integer('{{str_singular($second)}}_id')->unsigned()->index();
			$table->foreign('{{str_singular($second)}}_id')->references('id')->on('{{$second}}')->onDelete('cascade');
			/**
			 * Type your addition here
			 *
			 */
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('{{str_singular($first)}}_{{str_singular($second)}}');
    }
}

Use singular table naming in Many To Many migration


<?php
namespace wapmorgan\PhpCodeFixer;

/**
 * @test 5.3
 * @param array $usage_tokens
 * @param $function
 * @return bool
 */
function call_with_passing_by_reference(array $usage_tokens, $function) {
    if (count($usage_tokens) === 1)
        return false;
    $tree = PhpCodeFixer::makeFunctionCallTree($usage_tokens);
    if (!isset($tree[0])) // when first argument in call is something like `split(($a + $b))`
        return false;
    $data = PhpCodeFixer::divideByComma($tree[0]);
    $data = PhpCodeFixer::trimSpaces($data);

    foreach ($data as $argI => $arg) {
        if (isset($arg[0]) && $arg[0] === '&')
            return true;
    }

    return false;
}

<?php
namespace wapmorgan\PhpCodeFixer;

/**
 * @test 5.3
 * @param array $usage_tokens
 * @param $function
 * @return bool
 */
function call_with_passing_by_reference(array $usage_tokens, $function) {
    if (count($usage_tokens) === 1)
        return false;
    $tree = PhpCodeFixer::makeFunctionCallTree($usage_tokens);
    if (!isset($tree[0])) // when first argument in call is something like `split(($a + $b))`
        return false;
    $data = PhpCodeFixer::divideByComma($tree[0]);
    $data = PhpCodeFixer::trimSpaces($data);

    foreach ($data as $argI => $arg) {
        if (isset($arg[0]) && $arg[0] === '&'
            && isset($data[$argI + 1]) && is_array($data[$argI + 1]) && $data[$argI + 1][0] === T_VARIABLE) {
            return true;
        }
    }

    return false;
}

Update checker of pass-by-reference problem.


<?php
include('./requires.inc.php');

include('./config/loadConfiguration.php');

include('./header.inc.php');
?>

<?php
include('./navigation.inc.php');
?>

<?php
        if ($_SESSION["admin"] == 1) {
?>

Add Post

<?php
        }
        $blogDao = new BlogDAO();
        echo $blogDao->getBlogInformation()->toHTML();
?>

<?php
include('./utilities.inc.php');
?>
<?php
include('./footer.inc.php');
?>

Set the main section of the page to align with the responsive web design changes.


<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
    }
}

<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
    }

    public static function tearDownAfterClass()
    {
      FactoryMuffin::deleteSaved();
    }
}

Delete saved methods after tests finish

Delete saved methods after tests finish


<?php

namespace account\base;

class Controller extends \luya\web\Controller
{
    public function getRules()
    {
        return [
            [
                'allow' => true,
                'actions' => [], // apply to all actions by default
                'roles' => ['@'],
            ],
        ];
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'user' => $this->module->getUserIdentity(),
                'rules' => $this->getRules(),
            ],
        ];
    }

    public function isGuest()
    {
        return $this->module->getUserIdentity()->isGuest;
    }
}

<?php

namespace account\base;

use Yii;

class Controller extends \luya\web\Controller
{
    public function getRules()
    {
        return [
            [
                'allow' => true,
                'actions' => [], // apply to all actions by default
                'roles' => ['@'],
            ],
        ];
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'user' => Yii::$app->getModule('account')->getUserIdentity(),
                'rules' => $this->getRules(),
            ],
        ];
    }

    public function isGuest()
    {
        return Yii::$app->getModule('account')->getUserIdentity()->isGuest;
    }
}

Use fix module names to abstract from account base controller.


<?php

require('../../vendor.php');
require('ModuleTests.php');

\Phunit\Phunit::run();

<?php

require('../bower_components/Dephendency/index.php');
require('ModuleTests.php');

\Phunit\Phunit::run();

Use dephendency to load test dependencies.


<?php

use wcf\system\cronjob\CronjobScheduler;
use wcf\system\event\EventHandler;
use wcf\system\event\listener\PhraseChangedPreloadListener;
use wcf\system\event\listener\UserLoginCancelLostPasswordListener;
use wcf\system\language\event\PhraseChanged;
use wcf\system\language\LanguageFactory;
use wcf\system\language\preload\command\ResetPreloadCache;
use wcf\system\package\event\PackageListChanged;
use wcf\system\user\authentication\event\UserLoggedIn;
use wcf\system\WCF;

return static function (): void {
    WCF::getTPL()->assign(
        'executeCronjobs',
        CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && \defined('OFFLINE') && !OFFLINE
    );

    EventHandler::getInstance()->register(UserLoggedIn::class, UserLoginCancelLostPasswordListener::class);
    EventHandler::getInstance()->register(PackageListChanged::class, function () {
        foreach (LanguageFactory::getInstance()->getLanguages() as $language) {
            $command = new ResetPreloadCache($language);
            $command();
        }
    });
    EventHandler::getInstance()->register(PhraseChanged::class, PhraseChangedPreloadListener::class);
};

<?php

use wcf\system\cronjob\CronjobScheduler;
use wcf\system\event\EventHandler;
use wcf\system\event\listener\PhraseChangedPreloadListener;
use wcf\system\event\listener\UserLoginCancelLostPasswordListener;
use wcf\system\language\event\LanguageImported;
use wcf\system\language\event\PhraseChanged;
use wcf\system\language\LanguageFactory;
use wcf\system\language\preload\command\ResetPreloadCache;
use wcf\system\package\event\PackageListChanged;
use wcf\system\user\authentication\event\UserLoggedIn;
use wcf\system\WCF;

return static function (): void {
    WCF::getTPL()->assign(
        'executeCronjobs',
        CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && \defined('OFFLINE') && !OFFLINE
    );

    EventHandler::getInstance()->register(UserLoggedIn::class, UserLoginCancelLostPasswordListener::class);
    EventHandler::getInstance()->register(PackageListChanged::class, static function () {
        foreach (LanguageFactory::getInstance()->getLanguages() as $language) {
            $command = new ResetPreloadCache($language);
            $command();
        }
    });
    EventHandler::getInstance()->register(LanguageImported::class, static function (LanguageImported $event) {
        $command = new ResetPreloadCache($event->language);
        $command();
    });
    EventHandler::getInstance()->register(PhraseChanged::class, PhraseChangedPreloadListener::class);
};

Reset the preload cache when a language has been imported


<?php # -*- coding: utf-8 -*-

namespace Bueltge\Marksimple\Tests\Unit\Rule;

use Bueltge\Marksimple\Rule;
use Bueltge\Marksimple\Rule\ElementRuleInterface;
use Bueltge\Marksimple\Tests\Unit\AbstractRuleTestCase;

class UnorderedListTest extends AbstractRuleTestCase
{

    public function returnRule(): ElementRuleInterface
    {

        return new Rule\UnorderedList();
    }

    public function provideList()
    {

        yield 'asterix' => ['* List Element', '

List Element

'];

        $input    = '- List Element';
        $expected = '

List Element

';
        $text     = 'Lorum ipsum';
        yield 'minus' => [$input, $expected];

        yield 'text before' => ["$text\n$input", "$text\n$expected"];
        yield 'text after' => ["$input\n$text", "$expected\n$text"];
        yield 'text before and after' => ["$text\n$input\n$text", "$text\n$expected\n$text"];

        $input = <<<Markdown
* item 1
* item 2
* item 3
Markdown;

        $expected = '

item 1

item 2

item 3

';
        yield 'multiple items' => [$input, $expected];
    }
}

Fix ul list test; needs clean up for lists


<?php
class BinaryGap
{
    private $number;

    /**
     * BinaryGap constructor.
     * @param $number
     */
    public function __construct($number)
    {
        $this->number = $number;
    }

    /**
     * @return mixed
     */
    public function getNumber() {
        return $this->number;
    }

    private function convertToBinary($number) {
        return decbin($number);
    }

    /**
     * Find longest sequence of zeros in binary representation of an integer.
     */
    public function calculateBinaryGap() {
        $binaryNumber = $this->convertToBinary($this->getNumber());
        $binaryNumberArray = str_split($binaryNumber);
        $binaryCount = array();
        $counter = 0;
        foreach($binaryNumberArray as $index => $binNum) {
            if($binNum == "0")
                $counter++;
            else if($binNum == "1") {
                if($counter > 0)
                    $binaryCount[] = $counter;
                $counter = 0;
            }
        }
        return max($binaryCount);
    }
}

$binaryGap = new BinaryGap(209);
echo "The largest binary gap is " . $binaryGap->calculateBinaryGap() . "\n";

<?php
class BinaryGap
{
    private $number;

    /**
     * BinaryGap constructor.
     * @param $number
     */
    public function __construct($number)
    {
        $this->number = $number;
    }

    /**
     * @return mixed
     */
    public function getNumber() {
        return $this->number;
    }

    private function convertToBinary($number) {
        return decbin($number);
    }

    /**
     * Find longest sequence of zeros in binary representation of an integer.
     */
    public function calculateBinaryGap() {
        $binaryNumber = $this->convertToBinary($this->getNumber());
        $binaryNumberArray = str_split($binaryNumber);
        $binaryCount = array();
        $counter = 0;
        foreach($binaryNumberArray as $index => $binNum) {
            if($binNum == "0")
                $counter++;
            else if($binNum == "1") {
                if($counter > 0)
                    $binaryCount[] = $counter;
                $counter = 0;
            }
        }
        if(!empty($binaryCount))
            return max($binaryCount);
        else
            return 0;
    }
}

$binaryGap = new BinaryGap(1011);
echo "The largest binary gap is " . $binaryGap->calculateBinaryGap() . "\n";

Introduce additional empty array check.

Introduce additional empty array check.


<?php

namespace Plummer\Calendarful;

interface CalendarInterface
{
	public function addEvent(EventInterface $event);

	public function addRecurrenceType(RecurrenceInterface $recurrenceType);

	public function getEvents($fromDate, $toDate, $limit = null);
}

<?php

namespace Plummer\Calendarful;

interface CalendarInterface
{
	public function getName();

	public function populate(RegistryInterface $eventsRegistry, \DateTime $fromDate, \DateTime $toDate, $limit);
}

Change handling of events to later in the process.


<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP script admin
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */
class WPscriptAdmin extends WPscript
{
  protected $admin_page = array();

  public function __construct($admin_page, $handle, $src = false, $deps = array(),$ver = false, $in_footer = true)
  {
    parent::__construct($handle, $src, $deps, $ver, $in_footer);

    if(!is_array($admin_page))
    {
      $admin_page[] = $admin_page;
    }
    $this->admin_page = $admin_page;

  }

  public function is_needed($page)
  {
    if(empty($this->admin_page)) return true;

    return in_array($page, $this->admin_page);
  }

  public function enqueue($page)
  {
    if($this->is_needed($page))
    {
      parent::enqueue();
    }
  }
}

<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP script admin
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */
class WPscriptAdmin extends WPscript
{
  protected $admin_page = array();

  public function __construct($admin_page, $handle, $src = false, $deps = array(),$ver = false, $in_footer = true)
  {
    parent::__construct($handle, $src, $deps, $ver, $in_footer);

    if(!is_array($admin_page))
    {
      $admin_page[] = $admin_page;
    }
    $this->admin_page = $admin_page;

  }

  public function is_needed($page)
  {
    if(empty($this->admin_page)) return true;

    if(in_array($page, $this->admin_page))
    {
      return true;
    }
    elseif(isset($this->admin_page[$page]))
    {
      if(empty($this->admin_page[$page]))
      {
        return true;
      }
      elseif(isset($this->admin_page[$page]['post_type']))
      {

        global $post;
        if($post->post_type === $this->admin_page[$page]['post_type'])
        {
          return true;
        }
      }
    }
    return false;
  }

  public function enqueue()
  {
    $page = func_get_arg(0);
    if($this->is_needed($page))
    {
      parent::enqueue();
    }
  }
}

Remove bad argument to enqueue to prevent strict error. Added support of custom post type check to script loading conditions.


<?php

namespace filsh\yii2\oauth2server;

/**
 * Instead use bootstrap module
 * must be removed in v2.1
 *
 * @deprecated v2.0.1
 */
class Bootstrap implements \yii\base\BootstrapInterface
{
    use BootstrapTrait;

    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
        /** @var $module Module */
        if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) {
            $this->initModule($module);

            if ($app instanceof \yii\console\Application) {
                $module->controllerNamespace = 'filsh\yii2\oauth2server\commands';
            }
        }
    }
}

<?php

namespace filsh\yii2\oauth2server;

/**
 * Instead use bootstrap module
 * should be removed in v2.1 version
 *
 * @deprecated v2.0.1
 */
class Bootstrap implements \yii\base\BootstrapInterface
{
    use BootstrapTrait;

    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
        /** @var $module Module */
        if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) {
            $this->initModule($module);

            if ($app instanceof \yii\console\Application) {
                $module->controllerNamespace = 'filsh\yii2\oauth2server\commands';
            }
        }
    }
}

Remove a fixed module ID

Remove a fixed module ID