<?php
return [
    \Sarcofag\View\Renderer\RendererInterface::class =>
        DI\get('Renderer'),

    \Sarcofag\View\Renderer\PsrHttpRendererInterface::class =>
        DI\get('Renderer'),

    \Sarcofag\View\Helper\HelperManagerInterface::class =>
        DI\get('HelperManager'),

    \Sarcofag\SPI\RegisterActionInterface::class =>
        DI\get('EventsRegistrator'),

    \Sarcofag\SPI\RegisterFilterInterface::class =>
        DI\get('EventsRegistrator'),

    \Sarcofag\SPI\EventManager\EventManagerInterface::class =>
        DI\get('EventManager')
];

<?php
return [
    \Sarcofag\View\Renderer\RendererInterface::class =>
        DI\get('Renderer'),

    \Sarcofag\View\Renderer\PsrHttpRendererInterface::class =>
        DI\get('Renderer'),

    \Sarcofag\View\Helper\HelperManagerInterface::class =>
        DI\get('HelperManager'),

    \Sarcofag\SPI\EventManager\EventManagerInterface::class =>
        DI\get('EventManager')
];

Remove forgoten pieces of configuration, which not in use anymore.


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:rollback:foundation {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Cortex Foundation Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/cortex/foundation')) {
            $this->call('migrate:reset', [
                '--step' => true,
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan cortex:publish:foundation</>');
        }
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:rollback:foundation {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Cortex Foundation Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/cortex/foundation')) {
            $this->call('migrate:reset', [
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan cortex:publish:foundation</>');
        }
    }
}

Fix `migrate:reset` args as it doesn't accept --step


<?php

namespace Faker\Provider\en_GB;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    protected static $formats = array(
        '+44(0)##########',
        '+44(0)#### ######',
        '+44(0)#########',
        '+44(0)#### #####',
        '0##########',
        '0#########',
        '0#### ######',
        '0#### #####',
        '(0####) ######',
        '(0####) #####',
    );

    /**
     * An array of en_GB mobile (cell) phone number formats
     * @var array
     */
    protected static $mobileFormats = array(
      // Local
      '07#########',
      '07### ######',
      '07### ### ###'
    );

    /**
     * Return a en_GB mobile phone number
     * @return string
     */
    public static function mobileNumber()
    {
      return static::numerify(static::randomElement(static::$mobileFormats));
    }

}

Add en_GB mobile phone number option

Add en_GB mobile phone number option


<?php

final class PhutilAuthAdapterRemoteUser extends PhutilAuthAdapter {

  public function getProviderName() {
    return pht('Uni Heidelberg - UniID');
  }

  public function getDescriptionForCreate() {
    return pht(
      'Configure a connection to use Uni Heidelberg\'s UniID '.
      'credentials to log in to Phabricator.');
  }

  public function getAdapterDomain() {
    return 'self';
  }

  public function getAdapterType() {
    return 'RemoteUser';
  }

  public function getAccountID() {
    return $_SERVER['REMOTE_USER'];
  }

  public function getAccountName() {
    return $this->getAccountID();
  }

}

<?php

function realname_to_username($realname) {
  $words = preg_split("/\b/", $realname, NULL, PREG_SPLIT_NO_EMPTY);

  $lowercase_trimmed_words = array_map( function($word) {
    return strtolower(trim($word));
  }, $words);

  $nonempty_words = array_filter($lowercase_trimmed_words, function($word) {
    return preg_match("/^[[:alpha:]]+$/", $word);
  });

  $words_without_last = array_slice($nonempty_words, 0, -1);
  $last_word = end($nonempty_words);

  $result = "";
  foreach ($words_without_last as $word) {
    $result .= $word[0];
  }

  return $result . $last_word;
}

final class PhutilAuthAdapterRemoteUser extends PhutilAuthAdapter {

  public function getProviderName() {
    return pht('Uni Heidelberg - UniID');
  }

  public function getDescriptionForCreate() {
    return pht(
      'Configure a connection to use Uni Heidelberg\'s UniID '.
      'credentials to log in to Phabricator.');
  }

  public function getAdapterDomain() {
    return 'self';
  }

  public function getAdapterType() {
    return 'RemoteUser';
  }

  public function getAccountID() {
    return $_SERVER['REMOTE_USER'];
  }

  public function getAccountName() {
    $username = explode("@", $this->getAccountID(), 2)[0];
    $provider = PhabricatorLDAPAuthProvider::getLDAPProvider();

    $adapter = $provider->getAdapter()
      ->setLoginUsername($username);

    $name = realname_to_username($adapter->getAccountRealName());

    return $name;
  }

  public function getAccountRealName() {
    $username = explode("@", $this->getAccountID(), 2)[0];
    $provider = PhabricatorLDAPAuthProvider::getLDAPProvider();

    $adapter = $provider->getAdapter()
      ->setLoginUsername($username);

    return $adapter->getAccountRealName();
  }

  public function getAccountEmail() {
    $username = explode("@", $this->getAccountID(), 2)[0];
    $provider = PhabricatorLDAPAuthProvider::getLDAPProvider();

    $adapter = $provider->getAdapter()
      ->setLoginUsername($username);

    return $adapter->getAccountEmail();
  }
}

Set default username, realname, email for UHD


<?php
/**
 * Copyright (c) 2017 shogogg <shogo@studiofly.net>
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
declare(strict_types = 1);

namespace ScalikePHP;

use ScalikePHP\Support\ArraySupport;
use ScalikePHP\Support\SeqSupport;

/**
 * A Seq implementation using array.
 */
class ArraySeq extends Seq
{

    use ArraySupport, SeqSupport;

    /**
     * Constructor.
     *
     * @param array $values
     */
    public function __construct(array $values)
    {
        $this->setArray(array_values($values));
    }

    /**
     * @inheritdoc
     */
    public function append(iterable $that): Seq
    {
        return is_array($that)
            ? new ArraySeq(array_merge($this->array, array_values($that)))
            : new TraversableSeq($this->mergeGenerator($this->array, $that));
    }

    /**
     * @inheritdoc
     */
    public function prepend(iterable $that): Seq
    {
        return is_array($that)
            ? new ArraySeq(array_merge($that, $this->array))
            : new TraversableSeq($this->mergeGenerator($that, $this->array));
    }

    /**
     * @inheritdoc
     */
    public function take(int $n): Seq
    {
        return new ArraySeq(array_slice($this->array, 0, $n));
    }

    /**
     * @inheritdoc
     */
    public function toSeq(): Seq
    {
        return $this;
    }

}

<?php
/**
 * Copyright (c) 2017 shogogg <shogo@studiofly.net>
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
declare(strict_types = 1);

namespace ScalikePHP;

use ScalikePHP\Support\ArraySupport;
use ScalikePHP\Support\SeqSupport;

/**
 * A Seq implementation using array.
 */
class ArraySeq extends Seq
{

    use ArraySupport, SeqSupport;

    /**
     * Constructor.
     *
     * @param array $values
     */
    public function __construct(array $values)
    {
        $this->setArray(array_values($values));
    }

    /**
     * @inheritdoc
     */
    public function append(iterable $that): Seq
    {
        return new TraversableSeq($this->mergeGenerator($this->array, $that));
    }

    /**
     * @inheritdoc
     */
    public function prepend(iterable $that): Seq
    {
        return new TraversableSeq($this->mergeGenerator($that, $this->array));
    }

    /**
     * @inheritdoc
     */
    public function take(int $n): Seq
    {
        return new ArraySeq(array_slice($this->array, 0, $n));
    }

    /**
     * @inheritdoc
     */
    public function toSeq(): Seq
    {
        return $this;
    }

}

:zap: Use generator even if `$that` is an array


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache('classes', '.php.cache');
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Change class cache extension in dev env

Change class cache extension in dev env


<?php

use Illuminate\Routing\Router;

/** @var Router $router */
$router->group(['prefix' => 'v1'], function (Router $router) {

    $router->get('pbbg', function () {
        return [
            'name' => 'OpenDominion',
            'born' => '2013-02-04',
            'registered_players' => \OpenDominion\Models\User::count(),
            'tags' => ['multiplayer', 'strategy', 'fantasy']
        ];
    });

});

Add API route for pbbg.site

Add API route for pbbg.site


<?php

namespace spec\Elfiggo\Brobdingnagian\Detector;

use PhpSpec\Event\SpecificationEvent;
use PhpSpec\Loader\Node\SpecificationNode;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DetectorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\Detector');
    }

    function it_should_analyse_the_class_size(SpecificationEvent $specificationEvent, SpecificationNode $specificationNode)
    {
        $specificationEvent->getSpecification()->willReturn($specificationNode);
        $specificationNode->getClassReflection()->willReturn(new \ReflectionClass(\DateTime::class));
        $this->shouldNotThrow('Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge');
        $this->analyse($specificationEvent);
    }

}

<?php

namespace spec\Elfiggo\Brobdingnagian\Detector;

use Elfiggo\Brobdingnagian\Detector\ClassSize;
use PhpSpec\Event\SpecificationEvent;
use PhpSpec\Loader\Node\SpecificationNode;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DetectorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\Detector');
    }

    function it_should_analyse_the_class_size(SpecificationEvent $specificationEvent, SpecificationNode $specificationNode)
    {
        $specificationEvent->getSpecification()->willReturn($specificationNode);
        $specificationNode->getClassReflection()->willReturn(new \ReflectionClass(ClassSize::class));
        $this->shouldNotThrow('Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge');
        $this->analyse($specificationEvent);
    }

}

Update spec to use real class, DateTime comes back as false size.


<?php

use \Moat\Models;

/**
 *
 *
 * @author      Tyler Menezes <tylermenezes@gmail.com>
 * @copyright   Copyright (c) Tyler Menezes. Released under the BSD license.
 *
 */
class cron {
    use \ThinTasks\Task;

    public function main()
    {
        // Event reminders
        $upcoming_unnotified_hours = Models\OfficeHours\Slot::find()
            ->where('NOW() < starts_at')
            ->where('NOW() > DATE_SUB(starts_at, INTERVAL 1 HOUR)')
            ->where('sent_reminder = 0')
            ->where('userID IS NOT NULL')
            ->order_by('starts_at ASC')
            ->all();

        foreach ($upcoming_unnotified_hours as $slot) {
            mail($slot->user->email, 'Hours on '.date('M j', $slot->starts_at).' at '.date('g:i a', $slot->starts_at),
                \Moat::$twig->render('emails/hours_reminder.txt.twig', ['slot' => $slot]),
                'From: "Moat" <moat@studentrnd.org>');
            $slot->sent_reminder = true;
        }
    }
}

<?php

use \Moat\Models;

/**
 *
 *
 * @author      Tyler Menezes <tylermenezes@gmail.com>
 * @copyright   Copyright (c) Tyler Menezes. Released under the BSD license.
 *
 */
class cron {
    use \ThinTasks\Task;

    public function main()
    {
        // Event reminders
        $upcoming_unnotified_hours = Models\OfficeHours\Slot::find()
            ->where('NOW() < starts_at')
            ->where('NOW() > DATE_SUB(starts_at, INTERVAL 2 HOUR)')
            ->where('sent_reminder = 0')
            ->where('userID IS NOT NULL')
            ->order_by('starts_at ASC')
            ->all();

        foreach ($upcoming_unnotified_hours as $slot) {
            mail($slot->user->email, 'Hours on '.date('M j', $slot->starts_at).' at '.date('g:i a', $slot->starts_at),
                \Moat::$twig->render('emails/hours_reminder.txt.twig', ['slot' => $slot]),
                'From: "Moat" <moat@studentrnd.org>');
            $slot->sent_reminder = true;
        }
    }
}

Change reminder interval to 2 hours

Change reminder interval to 2 hours


<?php

namespace estvoyage\statsd;

use
	estvoyage\statsd\world as statsd
;

class packet implements statsd\packet
{
	private
		$metrics
	;

	function __construct()
	{
		$this->metrics = [];
	}

	function writeOn(statsd\connection $connection, callable $callback)
	{
		$callback = function($connection) use ($callback) {
			$connection->endPacket($callback);
		};

		$metric = end($this->metrics);

		while ($metric)
		{
			$callback = function($connection) use ($metric, $callback) {
				$connection->writeData($metric, $callback);
			};

			$metric = prev($this->metrics);
		}

		$callback = function($connection) use ($callback) {
			$connection->startPacket($callback);
		};

		$callback($connection);

		return $this;
	}

	function add(statsd\metric $metric, callable $callback)
	{
		$packet = clone $this;
		$packet->metrics[] = $metric;

		$callback($packet);

		return $this;
	}
}

<?php

namespace estvoyage\statsd;

use
	estvoyage\statsd\world as statsd
;

class packet implements statsd\packet
{
	private
		$metrics
	;

	function __construct()
	{
		$this->metrics = [];
	}

	function writeOn(statsd\connection $connection, callable $callback)
	{
		$callback = function($connection) use ($callback) {
			$connection->endPacket($callback);
		};

		$callback = array_reduce($this->metrics, function($callback, $metric) { return function($connection) use ($metric, $callback) { $connection->writeData($metric, $callback); }; }, $callback);

		$callback = function($connection) use ($callback) {
			$connection->startPacket($callback);
		};

		$callback($connection);

		return $this;
	}

	function add(statsd\metric $metric, callable $callback)
	{
		$packet = clone $this;

		array_unshift($packet->metrics, $metric);

		$callback($packet);

		return $this;
	}
}

Use array_reduce() to generate pipeline of callbacks.


<?php

/**
 * @license     http://opensource.org/licenses/mit-license.php MIT
 * @link        https://github.com/nicoSWD
 * @since       0.3.4
 * @author      Nicolas Oelgart <nico@oelgart.com>
 */
namespace nicoSWD\Rules;

use SplObjectStorage;

/**
 * Class Stack
 * @package nicoSWD\Rules
 */
final class Stack extends SplObjectStorage
{
    /**
     * @return \nicoSWD\Rules\Tokens\BaseToken
     */
    public function current()
    {
        return parent::current();
    }

    /**
     * @return Stack
     */
    public function getClone()
    {
        $stackClone = clone $this;

        // This is ugly and needs to be fixed
        while ($stackClone->key() < $this->key()) {
            $stackClone->next();
        }

        return $stackClone;
    }
}

<?php

/**
 * @license     http://opensource.org/licenses/mit-license.php MIT
 * @link        https://github.com/nicoSWD
 * @since       0.3.4
 * @author      Nicolas Oelgart <nico@oelgart.com>
 */
namespace nicoSWD\Rules;

use SplObjectStorage;

/**
 * Class Stack
 * @package nicoSWD\Rules
 */
final class Stack extends SplObjectStorage
{
    /**
     * @return \nicoSWD\Rules\Tokens\BaseToken
     */
    public function current()
    {
        return parent::current();
    }

    /**
     * @return Stack
     */
    public function getClone()
    {
        $stackClone = clone $this;
        $stackClone->rewind();

        // This is ugly and needs to be fixed
        while ($stackClone->key() < $this->key()) {
            $stackClone->next();
        }

        return $stackClone;
    }
}

Fix build on PHP 7

Fix build on PHP 7


<?php

declare(strict_types=1);

namespace App\Nova\Metrics;

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Partition;
use Laravel\Nova\Metrics\PartitionResult;

class CreateReasonBreakdown extends Partition
{
    /**
     * The displayable name of the metric.
     *
     * @var string
     */
    public $name = 'User Create Reason';

    /**
     * Calculate the value of the metric.
     */
    public function calculate(Request $request): PartitionResult
    {
        return $this->count($request, User::class, 'create_reason')->label(static function (?string $value): string {
            switch ($value) {
                case 'phpunit':
                    return 'PHPUnit';
                case 'cas_login':
                    return 'CAS login';
                case 'factory':
                    return 'Database\Factories\UserFactory';
                case 'nova_action':
                    return 'Nova action';
                case 'attendance':
                    return 'Attendance';
                case 'historical_dues_import':
                    return 'Historical dues import';
                case null:
                    return 'Unknown';
                default:
                    return ucfirst($value);
            }
        });
    }

    /**
     * Get the URI key for the metric.
     */
    public function uriKey(): string
    {
        return 'create-reasons';
    }
}

<?php

declare(strict_types=1);

namespace App\Nova\Metrics;

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Partition;
use Laravel\Nova\Metrics\PartitionResult;

class CreateReasonBreakdown extends Partition
{
    /**
     * The displayable name of the metric.
     *
     * @var string
     */
    public $name = 'User Create Reason';

    /**
     * Calculate the value of the metric.
     */
    public function calculate(Request $request): PartitionResult
    {
        return $this->count($request, User::class, 'create_reason')->label(static function (?string $value): string {
            switch ($value) {
                case 'phpunit':
                    return 'PHPUnit';
                case 'cas_login':
                    return 'CAS login';
                case 'factory':
                    return 'Database\Factories\UserFactory';
                case 'nova_action':
                    return 'Nova action';
                case 'attendance':
                    return 'Attendance';
                case 'historical_dues_import':
                    return 'Historical dues import';
                // This isn't created by code, but a lot of records in prod have this.
                case 'buzzapi_job':
                    return 'BuzzAPI job';
                case null:
                    return 'Unknown';
                default:
                    return ucfirst($value);
            }
        });
    }

    /**
     * Get the URI key for the metric.
     */
    public function uriKey(): string
    {
        return 'create-reasons';
    }
}

Add buzzapi_job create reason text to the breakdown


    <li <?= $this->app->checkMenuSelection('ProjectOverviewController') ?>>
        <?= $this->url->icon('eye', t('Overview'), 'ProjectOverviewController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-overview', t('Keyboard shortcut: "%s"', 'v o')) ?>

    <li <?= $this->app->checkMenuSelection('BoardViewController') ?>>
        <?= $this->url->icon('th', t('Board'), 'BoardViewController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-board', t('Keyboard shortcut: "%s"', 'v b')) ?>

    <li <?= $this->app->checkMenuSelection('TaskListController') ?>>
        <?= $this->url->icon('list', t('List'), 'TaskListController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-listing', t('Keyboard shortcut: "%s"', 'v l')) ?>

    <?= $this->hook->render('template:project-header:view-switcher', array('project' => $project, 'filters' => $filters)) ?>

    <?= $this->hook->render('template:project-header:view-switcher-before-project-overview', array('project' => $project, 'filters' => $filters)) ?>

    <li <?= $this->app->checkMenuSelection('ProjectOverviewController') ?>>
        <?= $this->url->icon('eye', t('Overview'), 'ProjectOverviewController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-overview', t('Keyboard shortcut: "%s"', 'v o')) ?>

    <?= $this->hook->render('template:project-header:view-switcher-before-board-view', array('project' => $project, 'filters' => $filters)) ?>

    <li <?= $this->app->checkMenuSelection('BoardViewController') ?>>
        <?= $this->url->icon('th', t('Board'), 'BoardViewController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-board', t('Keyboard shortcut: "%s"', 'v b')) ?>

    <?= $this->hook->render('template:project-header:view-switcher-before-task-list', array('project' => $project, 'filters' => $filters)) ?>

    <li <?= $this->app->checkMenuSelection('TaskListController') ?>>
        <?= $this->url->icon('list', t('List'), 'TaskListController', 'show', array('project_id' => $project['id'], 'search' => $filters['search']), false, 'view-listing', t('Keyboard shortcut: "%s"', 'v l')) ?>

    <?= $this->hook->render('template:project-header:view-switcher', array('project' => $project, 'filters' => $filters)) ?>

Add new plugin hooks in view switcher

Add new plugin hooks in view switcher


<?php namespace Crawler\Flickr;

use Crawler\Crawler;
use Console\Console;
use Console\Progressbar;

class Flickr extends Crawler
{

    public function getOriginalImageUrls($images)
    {

        $original_images = [];

        Console::info("Getting original image urls for " . count($images) . " flickr links...");
        $progress = new Progressbar();

        $counter = 0;

        foreach ($images as $url) {

            $percent = (++$counter / count($images)) * 100;

            $original_images[] = $this->getOriginalImageUrl($url);

            $progress->setProgress($percent);

        }

        return array_unique($original_images);

    }

    public function getOriginalImageUrl($url)
    {

        $url = $this->getSizesUrl($url);

        $contents = $this->fetchUrl($url);
        $url = $this->findOriginalImage($contents);

        if ($url === false) {
            Console::warning('No flickr image found on url ' . $url);
        }

        return $url;

    }

    private function getSizesUrl($url)
    {
        return trim($url, '/') . '/sizes/o';
    }

    private function findOriginalImage($content)
    {

        preg_match('#<img src="(http://[^\.]*.staticflickr.[^"]*)">#', $content, $matches);

        if (!isset($matches[1])) {
            return false;
        }

        return $matches[1];

    }

}

<?php namespace Crawler\Flickr;

use Crawler\Crawler;
use Console\Console;
use Console\Progressbar;

class Flickr extends Crawler
{

    public function getOriginalImageUrls($images)
    {

        $original_images = [];

        Console::info("Getting original image urls for " . count($images) . " flickr links...");
        $progress = new Progressbar(count($images));

        foreach ($images as $url) {

            $original_url = $this->getOriginalImageUrl($url);

            if ($original_url) {
                $original_images[] = $original_url;
            }

            $progress->increase();

        }

        return array_unique($original_images);

    }

    public function getOriginalImageUrl($url)
    {

        $url = $this->getSizesUrl($url);

        $contents = $this->fetchUrl($url, false, true);
        $original_url = $this->findOriginalImage($contents);

        if ($original_url === false) {
            Console::notice('No flickr image found for ' . $url);
        }

        return $original_url;

    }

    private function getSizesUrl($url)
    {
        return trim($url, '/') . '/sizes/o';
    }

    private function findOriginalImage($content)
    {

        preg_match('#<img src="(http://[^\.]*.staticflickr.[^"]*)">#', $content, $matches);

        if (!isset($matches[1])) {
            return false;
        }

        return $matches[1];

    }

}

Use new progressba interface, fixed console error, changed severity to notice, fixed error which caused empty urls to get fetched


<?php

//determine graph size

$count = 20;

if (isset($_GET["size"])) {
  $size = $_GET["size"];

  if ( (int)$size == $size) {
    $count = (int)$size;
  }
}

$sparse = 3;

if (isset($_GET["factor"])) {
  $factor = $_GET["factor"];

  if ( (int)$factor == $factor && $factor >= 0) {
    $sparse = $factor;
  }
}

//begin JSON generation

$json['nodes'] = array();

for ($i = 0; $i <= $count; $i++) {

  $node['name'] = $i;

  $node['influence'] = array();
  for ($j = $i-1; $j >= 0; $j--) {
    if ( rand(0,$sparse) == 0 ) {
      $node['influence'][] = array($j => rand(0,$count));
    }
  }

  $json['nodes'][] = $node;
}

echo(json_encode($json));

?>

<?php

//determine graph size

$count = 20;

if (isset($_GET["size"])) {
  $size = $_GET["size"];

  if ( (int)$size == $size) {
    $count = (int)$size;
  }
}

$sparse = 3;

if (isset($_GET["factor"])) {
  $factor = $_GET["factor"];

  if ( (int)$factor == $factor && $factor >= 0) {
    $sparse = $factor;
  }
}

//begin JSON generation

$json['nodes'] = array();

for ($i = 1; $i <= $count; $i++) {

  $node['name'] = $i;

  $node['influence'] = array();
  for ($j = $i-1; $j > 0; $j--) {
    if ( rand(0,$sparse) == 0 ) {
      $node['influence'][] = array($j => rand(0,$count));
    }
  }

  $json['nodes'][] = $node;
}

echo(json_encode($json));

?>

Revert "Start indices at zero."
Wrong Branch

This reverts commit fc5e21b30f4084a5375647049ddd76ae76c6f31b.


<?php

namespace Donquixote\Nicetrace\Tests;

use Donquixote\Nicetrace\Util\NicetraceUtil;

class NicetraceTest extends \PHPUnit_Framework_TestCase {

  /**
   * @dataProvider nicetraceProvider
   *
   * @param array $backtrace
   * @param array $expectedNicetrace
   */
  function testNicetrace(array $backtrace, array $expectedNicetrace) {

    $nicetrace = NicetraceUtil::backtraceGetNicetrace($backtrace);

    // Compare array contents.
    static::assertEquals($expectedNicetrace, $nicetrace);

    // Compare array contents and order of (nested) keys.
    static::assertEquals(var_export($expectedNicetrace, TRUE), var_export($nicetrace, TRUE));
  }

  /**
   * @return mixed[][]
   */
  function nicetraceProvider() {
    return array(
      array(
        include dirname(__DIR__) . '/fixtures/backtrace.php',
        include dirname(__DIR__) . '/fixtures/nicetrace.php',
      ),
    );
  }
}

<?php

namespace Donquixote\Nicetrace\Tests;

use Donquixote\Nicetrace\Util\NicetraceUtil;

class NicetraceTest extends \PHPUnit_Framework_TestCase {

  function testNicetrace() {

    $backtrace = include dirname(__DIR__) . '/fixtures/backtrace.php';
    $expectedNicetrace = include dirname(__DIR__) . '/fixtures/nicetrace.php';

    $nicetrace = NicetraceUtil::backtraceGetNicetrace($backtrace);

    // Compare array contents.
    static::assertEquals($expectedNicetrace, $nicetrace);

    // Compare array contents and order of (nested) keys.
    static::assertEquals(var_export($expectedNicetrace, TRUE), var_export($nicetrace, TRUE));
  }

}

Remove unnecessary provider stuff from tests


<!DOCTYPE html>

<?php include('functions.php')?>
<title>Title</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="<?php echo $site_url ?>/css/style.css" rel="stylesheet" type="text/css" charset="utf-8">

Header

<a href="<?php echo $site_url ?>">Index <a href="<?php echo $site_url ?>/page">page 1

<!DOCTYPE html>

	<?php include('functions.php')?>
	<title>Title</title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<meta name="mobile-web-app-capable" content="yes">
	<link rel="shortcut icon" sizes="196x196" href="<?php echo $site_url ?>/your-icon.png">
	<link rel="apple-touch-icon" sizes="196x196" href="<?php echo $site_url ?>/your-icon.png">

	<link href="<?php echo $site_url ?>/css/style.css" rel="stylesheet" type="text/css" charset="utf-8">

Header

<a href="<?php echo $site_url ?>">Index <a href="<?php echo $site_url ?>/page">page 1

Add mobile-web-app-capable meta to head

Add mobile-web-app-capable meta to head


<?php

namespace SerendipityHQ\Bundle\QueuesBundle;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use SerendipityHQ\Bundle\QueuesBundle\DependencyInjection\CompilerPass\DaemonDependenciesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * {@inheritdoc}
 */
class QueuesBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $modelDir = realpath(__DIR__ . '/Resources/config/doctrine/mappings');
        $mappings = [
            $modelDir => 'SerendipityHQ\Bundle\QueuesBundle\Model',
        ];

        $ormCompilerClass = DoctrineOrmMappingsPass::class;
        if (class_exists($ormCompilerClass)) {
            $container->addCompilerPass(
                $this->getYamlMappingDriver($mappings)
            );
        }

        $container->addCompilerPass(new DaemonDependenciesPass());
    }

    /**
     * @param array $mappings
     *
     * @return DoctrineOrmMappingsPass
     */
    private function getYamlMappingDriver(array $mappings)
    {
        return DoctrineOrmMappingsPass::createYamlMappingDriver(
            $mappings,
            ['queues.model_manager_name'],
            'queues.backend_orm',
            ['QueuesBundle' => 'SerendipityHQ\Bundle\QueuesBundle\Model']
        );
    }
}

<?php

namespace SerendipityHQ\Bundle\QueuesBundle;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use SerendipityHQ\Bundle\QueuesBundle\DependencyInjection\CompilerPass\DaemonDependenciesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\VarDumper\VarDumper;

/**
 * {@inheritdoc}
 */
class QueuesBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $modelDir = $this->getPath() . '/Resources/config/doctrine/mappings';
        $mappings = [
            $modelDir => 'SerendipityHQ\Bundle\QueuesBundle\Model',
        ];

        $ormCompilerClass = DoctrineOrmMappingsPass::class;
        if (class_exists($ormCompilerClass)) {
            $container->addCompilerPass(
                $this->getYamlMappingDriver($mappings)
            );
        }

        $container->addCompilerPass(new DaemonDependenciesPass());
    }

    /**
     * @param array $mappings
     *
     * @return DoctrineOrmMappingsPass
     */
    private function getYamlMappingDriver(array $mappings)
    {
        return DoctrineOrmMappingsPass::createYamlMappingDriver(
            $mappings,
            ['queues.model_manager_name'],
            'queues.backend_orm',
            ['QueuesBundle' => 'SerendipityHQ\Bundle\QueuesBundle\Model']
        );
    }
}

Remove the use of `__DIR__` constant.

Remove the use of `__DIR__` constant.


<?php

namespace MusicBrainz\Value;

/**
 * An area
 */
class Area
{
    /**
     * The MusikBrainz Identifier for the area
     *
     * @var string
     */
    private $id;

    /**
     * The area name
     *
     * @var Name
     */
    private $name;

    /**
     * Sort index
     *
     * @var string
     */
    private $sortName;

    /**
     * Constructs an area.
     *
     * @param array $area Array of values
     */
    public function __construct(array $area = [])
    {
        $this->id       = isset($area['id']) ? (string) $area['id'] : '';
        $this->name     = new Name(isset($area['name']) ? (string) $area['name'] : '');
        $this->sortName = isset($area['sort-name']) ? (string) $area['sort-name'] : '';
    }

    /**
     * Returns the area name.
     *
     * @return string
     */
    public function __toString(): string
    {
        return (string) $this->name;
    }
}

<?php

namespace MusicBrainz\Value;

/**
 * An area
 */
class Area
{
    use Accessor\GetMBIDTrait;
    use Accessor\GetNameTrait;
    use Accessor\GetSortNameTrait;

    /**
     * Constructs an area.
     *
     * @param array $area Array of values
     */
    public function __construct(array $area = [])
    {
        $this->MBID     = new MBID(isset($area['id']) ? (string) $area['id'] : '');
        $this->name     = new Name(isset($area['name']) ? (string) $area['name'] : '');
        $this->sortName = isset($area['sort-name']) ? (string) $area['sort-name'] : '';
    }

    /**
     * Returns the area name.
     *
     * @return string
     */
    public function __toString(): string
    {
        return (string) $this->name;
    }
}

Use traits and MBID value in the model of an area.


<?php

declare(strict_types=1);

namespace BEAR\Package\Provide\Error;

use BEAR\RepositoryModule\Annotation\Cacheable;
use BEAR\Resource\NullRenderer;
use BEAR\Resource\ResourceObject;

/**
 * @Cacheable
 */
#[Cacheable]
class NullPage extends ResourceObject
{
    public function __construct()
    {
        $this->renderer = new NullRenderer();
    }

    public function onGet(string $required, int $optional = 0): ResourceObject
    {
        unset($required, $optional);

        return $this;
    }
}

<?php

declare(strict_types=1);

namespace BEAR\Package\Provide\Error;

use BEAR\RepositoryModule\Annotation\Cacheable;
use BEAR\Resource\NullRenderer;
use BEAR\Resource\RenderInterface;
use BEAR\Resource\ResourceObject;
use Ray\Di\Di\Inject;

/**
 * @Cacheable
 */
#[Cacheable]
class NullPage extends ResourceObject
{
    /**
     * @return self
     *
     * @Inject(optional=true)
     */
    #[Inject(optional: true)]
    public function setRenderer(RenderInterface $renderer)
    {
        unset($renderer);
        $this->renderer = new NullRenderer();

        return $this;
    }

    public function onGet(string $required, int $optional = 0): ResourceObject
    {
        unset($required, $optional);

        return $this;
    }
}

Set null renderer with setter injection

Set null renderer with setter injection


<?php

namespace Bundle\DoctrineExtensionsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use DoctrineExtensions\Sluggable\SluggableListener;
use DoctrineExtensions\Timestampable\TimestampableListener;
use DoctrineExtensions\Tree\TreeListener;

class DoctrineExtensionsBundle extends Bundle
{
    public function boot()
    {
        try {
            $em = $this->container->get('doctrine.orm.entity_manager');
        } catch (\InvalidArgumentException $e){
            throw new \InvalidArgumentException('You must provide a Doctrine ORM Entity Manager');
        }
        $eventManager = $em->getEventManager();
        $treeListener = new TreeListener();
        $eventManager->addEventSubscriber($treeListener);
        $timestampableListener = new TimestampableListener();
        $eventManager->addEventSubscriber($timestampableListener);
        $sluggableListener = new SluggableListener();
        $eventManager->addEventSubscriber($sluggableListener);
        $translatableListener = new TranslationListener();
        $translatableListener->setTranslatableLocale('en_US');
        $eventManager->addEventSubscriber($translatableListener);
    }
}

<?php

namespace Bundle\DoctrineExtensionsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use DoctrineExtensions\Sluggable\SluggableListener;
use DoctrineExtensions\Timestampable\TimestampableListener;
use DoctrineExtensions\Tree\TreeListener;

class DoctrineExtensionsBundle extends Bundle
{
    public function boot()
    {
        try {
            $em = $this->container->get('doctrine.orm.entity_manager');
        } catch (\InvalidArgumentException $e){
            throw new \InvalidArgumentException('You must provide a Doctrine ORM Entity Manager');
        }
        $eventManager = $em->getEventManager();
        $treeListener = new TreeListener();
        $eventManager->addEventSubscriber($treeListener);
        $timestampableListener = new TimestampableListener();
        $eventManager->addEventSubscriber($timestampableListener);
        $sluggableListener = new SluggableListener();
        $eventManager->addEventSubscriber($sluggableListener);
        $translatableListener = new TranslationListener();
        $translatableListener->setTranslatableLocale($this->container->get('doctrine_extensions.default_locale'));
        $eventManager->addEventSubscriber($translatableListener);
    }
}

Use doctrine_extensions.default_locale instead of en_US as default locale


<?php

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

class CreateCityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('X');
            $table->integer('Y');
            $table->string('name')->nullable();
            $table->index('X');
            $table->index('Y');
        });
    }

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

<?php

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

class CreateCityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('X');
            $table->integer('Y');
            $table->string('name')->unique();
            $table->index('X');
            $table->index('Y');
        });
    }

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

Change the name to be a unique index.

Change the name to be a unique index.

 - this is bad practice, I should have migrated it properly.
 - Also, the reason I'm doing this is to make sure we don't duplicate X&Y.
 - This is just a bad way of doing this all around, but it's cheap.
 - right now cheap is good (given the time constraint)


<?php

return array(
  'extension_name'         => 'Allopass_Hipay',
  'summary'                => 'Official HiPay Fullservice payment extension.',
  'description'            => 'HiPay Fullservice is the first payment platform oriented towards merchants that responds to all matters related to online payment: transaction processing, risk management, relationship management with banks and acquirers, financial reconciliation or even international expansion.',
  'notes'                  => 'Official HiPay Fullservice payment extension',
  'extension_version'      => '0.1.0',
  'skip_version_compare'   => false,
  'auto_detect_version'    => true,

  'stability'              => 'stable',
  'license'                => 'General Public License (GPL)',
  'channel'                => 'community',

  'author_name'            => 'HiPay',
  'author_user'            => 'HiPay',
  'author_email'           => 'support.tpp@hipay.com',

  'base_dir'               => __DIR__.'/dist',
  'archive_files'          => 'Allopass_Hipay.tar',
  'path_output'            => __DIR__.'/dist',

  'php_min'                => '5.2.0',
  'php_max'                => '7.2.0',

  'extensions'             => array()
);

<?php

return array(
  'extension_name'         => 'Allopass_Hipay',
  'summary'                => 'Official HiPay Fullservice payment extension.',
  'description'            => 'HiPay Fullservice is the first payment platform oriented towards merchants that responds to all matters related to online payment: transaction processing, risk management, relationship management with banks and acquirers, financial reconciliation or even international expansion.',
  'notes'                  => 'Official HiPay Fullservice payment extension',
  'extension_version'      => '0.1.0',
  'skip_version_compare'   => false,
  'auto_detect_version'    => true,

  'stability'              => 'stable',
  'license'                => 'General Public License (GPL)',
  'channel'                => 'community',

  'author_name'            => 'HiPay',
  'author_user'            => 'HiPay',
  'author_email'           => 'support.tpp@hipay.com',

  'base_dir'               => __DIR__.'/dist',
  'archive_files'          => 'Allopass_Hipay.tar',
  'path_output'            => __DIR__.'/dist',

  'php_min'                => '5.2.0',
  'php_max'                => '7.3.0',

  'extensions'             => array()
);

Update php version for magento connect

Update php version for magento connect


<?php

namespace Platformsh\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Web UI');
        $this->addProjectOption()
             ->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Attempt to select the appropriate project and environment.
        try {
            $this->validateInput($input);
        }
        catch (\Exception $e) {
            // Ignore errors.
        }

        $project = $this->hasSelectedProject() ? $this->getSelectedProject() : false;

        $url = self::$config->get('service.accounts_url');
        if ($project) {
            $url = $project->getLink('#ui');
            if ($this->hasSelectedEnvironment()) {
                $environment = $this->getSelectedEnvironment();
                $url .= '/environments/' . $environment->id;
            }
        }

        $this->openUrl($url, $input, $output);
    }
}

<?php

namespace Platformsh\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Web UI');
        $this->addProjectOption()
             ->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Attempt to select the appropriate project and environment.
        try {
            $this->validateInput($input);
        } catch (\Exception $e) {
            // Ignore errors.
        }

        if ($this->hasSelectedEnvironment()) {
            $url = $this->getSelectedEnvironment()->getUri();
        } elseif ($this->hasSelectedProject()) {
            $url = $this->getSelectedProject()->getLink('#ui');
        } else {
            $url = self::$config->get('service.accounts_url');
        }

        $this->openUrl($url, $input, $output);
    }
}

Correct UI URL in 'web' command for envs with special characters


<?php

abstract class PingpongTestCase extends \Pingpong\Testing\TestCase {

    /**
     * @return string
     */
    public function getBasePath()
    {
        return realpath(__DIR__ . '/../fixture');
    }

    /**
     * @return \Illuminate\Foundation\Application
     */
    public function getApplication()
    {
        return $this->app;
    }

    /**
     * @return \Illuminate\Foundation\Application
     */
    public static function getLaravel()
    {
        return (new static)->getApplication();
    }

    protected function getPackageProviders()
    {
        return [
            'Pingpong\Modules\ModulesServiceProvider',
            'Pingpong\Modules\ModulesServiceProvider',
            'Pingpong\Trusty\TrustyServiceProvider',
            'Pingpong\Menus\MenusServiceProvider',
            'Pingpong\Widget\WidgetServiceProvider',
            'Pingpong\Themes\ThemesServiceProvider',
            'Pingpong\Shortcode\ShortcodeServiceProvider',
            'Pingpong\Oembed\OembedServiceProvider',
            'Pingpong\Generators\Providers\ConsoleServiceProvider',
        ];
    }

    protected function getPackageAliases()
    {
        return [
            'Module' => 'Pingpong\Modules\Facades\Module',
        ];
    }

}

<?php

abstract class PingpongTestCase extends \Pingpong\Testing\TestCase {

    /**
     * @return string
     */
    public function getBasePath()
    {
        return realpath(__DIR__ . '/../fixture');
    }

    /**
     * @return \Illuminate\Foundation\Application
     */
    public function getApplication()
    {
        return $this->app;
    }

    /**
     * @return \Illuminate\Foundation\Application
     */
    public static function getLaravel()
    {
        return (new static)->getApplication();
    }

    protected function getPackageProviders()
    {
        return [
            'Pingpong\Modules\ModulesServiceProvider',
            'Pingpong\Modules\ModulesServiceProvider',
            'Pingpong\Trusty\TrustyServiceProvider',
            'Pingpong\Menus\MenusServiceProvider',
            'Pingpong\Widget\WidgetServiceProvider',
            'Pingpong\Themes\ThemesServiceProvider',
            'Pingpong\Shortcode\ShortcodeServiceProvider',
            'Pingpong\Oembed\OembedServiceProvider',
            'Pingpong\Generators\GeneratorsServiceProvider',
        ];
    }

    protected function getPackageAliases()
    {
        return [
            'Module' => 'Pingpong\Modules\Facades\Module',
        ];
    }

}

Fix service provider not found

Fix service provider not found


<?php
namespace Simox;

class Url extends SimoxServiceBase
{
	protected $base_uri;

	public function __construct()
    {
        $this->base_uri = "/";
    }

    /**
     * Sets the base uri
     *
     * @param string $base_uri
     */
	public function setBaseUri( $base_uri )
	{
		$this->base_uri = $base_uri;
	}

    /**
     * Returns the base uri
     *
     * @return string
     */
	public function getBaseUri()
	{
		return $this->base_uri;
	}

    /**
     * Generate a URL appending the URI to the base URI
     *
     * @param string $path
     * @return string
     */
    public function get( $path )
    {
        return $this->base_uri . $path;
    }

    /**
     * NOT IMPLEMENTED
     * Generate a URL for a static resource
     *
     * @param string $path
     */
    public function getStatic( $path )
    {

    }

    public function getInstallPath()
    {
        return __DIR__;
    }
}

<?php
namespace Simox;

class Url extends SimoxServiceBase
{
    /**
     * Base path is the path to the project install folder relative to the server root
     */
	private $_base_uri;

    /**
     * Base path prepend is prepended to the base path
     */
    private $_base_uri_prepend;

	public function __construct()
    {
        /**
         * This is the base path prepend when using composer
         */
        $this->_base_uri_prepend = "/../../../../../";
    }

    /**
     * Sets the base uri
     *
     * @param string $base_uri
     */
	public function setBaseUri( $base_uri )
	{
        /**
         * If there is no appending slash, add it
         */
        if ($base_uri[strlen($base_uri)-1] !== "/")
        {
            $base_uri = $base_uri . "/";
        }

		$this->_base_uri = $base_uri;
	}

    /**
     * Returns the base path
     *
     * @return string
     */
	public function getBaseUri()
	{
		return $this->_base_uri;
	}

    public function setBaseUriPrepend( $path )
    {
        $this->_base_uri_prepend = $path;
    }

    public function getBaseUriPrepend()
    {
        return $this->_base_uri_prepend;
    }

    public function getBasePath()
    {
        return $this->_base_uri_prepend . $this->_base_uri;
    }

    /**
     * Appends a given path to the base path
     *
     * @param string $path
     * @return string
     */
    public function get( $path )
    {
        return $this->getBasePath() . $path;
    }
}

Make url class work with composer/folder changes


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Mapping\Annotation;

/**
 * Custom object annotation
 *
 * @Annotation
 * @Target("PROPERTY")
 */
final class CustomObject
{
    const ANNOTATION = __CLASS__;

    /**
     * @var string
     */
    public $class;

    /**
     * @var string
     */
    public $classPropertyPath;

    /**
     * @var string
     */
    public $initProperty;

    /**
     * @var string
     */
    public $initPropertyValuePath;
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Mapping\Annotation;

/**
 * Custom object annotation
 *
 * @Annotation
 * @Target("PROPERTY")
 */
final class CustomObject
{
    const ANNOTATION = __CLASS__;

    /**
     * @var string
     */
    public $class;

    /**
     * @var string
     */
    public $classPropertyPath;

    /**
     * @var string
     */
    public $initProperty = 'id';

    /**
     * @var string
     */
    public $initPropertyValuePath;
}

Set default value of property "initProperty" of custom object annotation.


<?php

namespace App\Listeners;

use App\Events\SomeEvent;
use App\Events\SongChanged;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SongChangedEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SomeEvent  $event
     * @return void
     */
    public function handle(SongChanged $event)
    {
        //
        //\Log::alert('song change event fired');
        echo "song change event fired" . PHP_EOL;

        if(($event->status['nextsongid'] == 0) && (config('jukebox.jukebox_mode')) ){
            //todo: queue song from playlist
        }
    }
}

<?php

namespace App\Listeners;

use App\Events\SomeEvent;
use App\Events\SongChanged;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use lxmpd;

class SongChangedEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SomeEvent  $event
     * @return void
     */
    public function handle(SongChanged $event)
    {
        //
        //\Log::alert('song change event fired');
        echo "song change event fired" . PHP_EOL;

        if(($event->status['nextsongid'] == 0) && (config('jukebox.jukebox_mode')) ){
            if(lxmpd::playlistExists('jukebox.jukebox_mode')){
                //todo: queue song from playlist

            } else {

            }
        }
    }
}

Check config for jukebox mode

Check config for jukebox mode


<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

<form name="loginform" action="<?php echo wp_login_url(home_url());?>" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

Fix incorrect login url for sign in form on frontpage


<?php namespace Pingpong\Admin\Observers;

class VisitorObserver {

    /**
     * Handle the specified event.
     *
     * @return void
     */
    public function handle()
    {
        $isOnAdmin = Request::is('admin') || Request::is('admin/*');

        if ( ! $isOnAdmin) Visitor::track();
    }

}

<?php namespace Pingpong\Admin\Observers;

use Pingpong\Admin\Entities\Visitor;
use Illuminate\Support\Facades\Request;

class VisitorObserver {

    /**
     * Handle the specified event.
     *
     * @return void
     */
    public function handle()
    {
        $isOnAdmin = Request::is('admin') || Request::is('admin/*');

        if ( ! $isOnAdmin) Visitor::track();
    }

}

Fix Visitor class not found

Fix Visitor class not found


<?php

class ClientPublicConstructorForTest extends \Delighted\Client
{
    public function __construct($arg = [])
    {
        parent::__construct($arg);
    }
}

class ClientTest extends Delighted\TestCase
{

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInstantiatingClientRequiresApiKey()
    {
        $client = new ClientPublicConstructorForTest([]);
    }

    public function testInstantiatingClientWithApiKey()
    {
        $client = Delighted\Client::getInstance(['apiKey' => '123abc']);
        $this->assertInstanceOf('Delighted\\Client', $client);
    }
}

<?php

class ClientPublicConstructorForTest extends \Delighted\Client
{
    public function __construct($arg = [])
    {
        parent::__construct($arg);
    }
}

class ClientTest extends Delighted\TestCase
{

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInstantiatingClientRequiresApiKey()
    {
        $client = new ClientPublicConstructorForTest([]);
    }

    public function testInstantiatingClientWithApiKey()
    {
        $client = Delighted\Client::getInstance(['apiKey' => '123abc']);
        $this->assertInstanceOf('Delighted\\Client', $client);
    }

    public function testAggregate()
    {
        $value = [
            'num'   => ['a', 'b', 'c'],
            'assoc' => ['a' => 'Ann', 'b' => 'Bob'],
        ];

        $query_string = $this->client->convertQueryStringToRubyStyle($value);

        $this->assertEquals('num[]=a&num[]=b&num[]=c&assoc[a]=Ann&assoc[b]=Bob', $query_string);
    }
}

Add test for query string to ruby style converter


<?php
	require('../sql/database.php');

	if(isset($_GET["postid"])){
		$postid = $_GET["postid"];

		$sql = "DELETE from postdata WHERE POSTID='$postid'";
		$result = mysqli_query($conn, $sql);

	}
	else{
		header("Location: ../admin/admin_page.php");
		die();
	}

	$conn->close();
	header("Location: ../admin/admin_page.php");
	die();
?>

<?php

	require('../sql/database.php');

	if(isset($_GET["postid"])){
		$postid = $_GET["postid"];

		$sql = "DELETE from postdata WHERE POSTID='$postid'";
		$result = mysqli_query($conn, $sql);

	}

	$conn->close();
	header("Location: ../static_homepage.php");
	die();
?>

Remove direct, add .htaccess to prevent access to includes


<?php

/*
 * This file is part of the PhpJobQueue package.
 *
 * (c) Mark Fullbrook <mark.fullbrook@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require __DIR__.'/vendor/symfony/Symfony/Component/ClassLoader/UniversalClassLoader.php';
require __DIR__.'/vendor/symfony/Symfony/Component/ClassLoader/DebugUniversalClassLoader.php';

$classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$classLoader->registerNamespaces(array(
    'PhpJobQueue' => __DIR__.'/lib',
    'Symfony'     => __DIR__.'/vendor/symfony/src',
    'Predis'      => __DIR__.'/vendor/predis/lib',
    'Monolog'     => __DIR__.'/vendor/monolog/src',
));
$classLoader->register();

// enable Debug loader
Symfony\Component\ClassLoader\DebugUniversalClassLoader::enable();

<?php

/*
 * This file is part of the PhpJobQueue package.
 *
 * (c) Mark Fullbrook <mark.fullbrook@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require __DIR__.'/vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
require __DIR__.'/vendor/symfony/src/Symfony/Component/ClassLoader/DebugUniversalClassLoader.php';

$classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$classLoader->registerNamespaces(array(
    'PhpJobQueue' => __DIR__.'/lib',
    'Symfony'     => __DIR__.'/vendor/symfony/src',
    'Predis'      => __DIR__.'/vendor/predis/lib',
    'Monolog'     => __DIR__.'/vendor/monolog/src',
));
$classLoader->register();

// enable Debug loader
Symfony\Component\ClassLoader\DebugUniversalClassLoader::enable();

// define the root of the project
define('PHPJOBQUEUE_ROOT', __DIR__);

Add in missing src to path. Add project root constant.


<?php
if (!defined('3DS_DEPOT')) die('Private area.');

// Define DB Constants
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', '3ds_depot');

// Define secure constants
define('COOKIE_PRIV', "");

// Define folder paths
define('SITE_ROOT', '');
define('TEMPLATES_ROOT', '')

// Define URL config
define('HTTP_SITE', '3ds-depot.dev');
define('FORCE_HTTPS', true); // Set this to false if you terminate SSL early.

<?php
if (!defined('3DS_DEPOT')) die('Private area.');

// Define DB Constants
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', '3ds_depot');

// Define secure constants
define('COOKIE_PRIV', "");

// Define folder paths
define('SITE_ROOT', '');
define('TEMPLATES_ROOT', SITE_ROOT . '\templates');

// Define URL config
define('HTTP_SITE', '3ds-depot.dev');
define('FORCE_HTTPS', true); // Set this to false if you terminate SSL early.

Fix syntax error in config and make it "work"


<?php

use Symfony\Component\HttpFoundation\Request;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array(
        '127.0.0.1',
        '::1',
    ))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array(
        '127.0.0.1',
        'fe80::1',
        '::1',
    ))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Add fe80::1 to list of loopback addresses.

On my Mac, my loopback interface is configured (via `/etc/hosts`, out of the box) to have both a link-local and a node-local loopback address, with the link-local address taking precedence:

```
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
	options=3<RXCSUM,TXCSUM>
	inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
	inet 127.0.0.1 netmask 0xff000000
	inet6 ::1 prefixlen 128
```

That obviously results in a `REMOTE_ADDR` of "fe80::1" rather than just "::1".


<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataCountrys */

$this->title = Yii::t('app', 'Update {modelClass}: ', [
    'modelClass' => 'Ctt Staticdata Countrys',
]) . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys(Language List)'),
									'url' => ['lang-list', 'id' => $model->id]];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="ctt-staticdata-countrys-update">

    <?= $this->render('_form', [
        'model' => $model,
        'title' => Html::encode($this->title),
        'model' => $model,
        'mode' => 'edit',
    ]) ?>

</div>

<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataCountrys */

$this->title = Yii::t('app', 'Update {modelClass}: ', [
    'modelClass' => 'Ctt Staticdata Countrys',
]) . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Ctt Staticdata Countrys(Language List)'),
									'url' => ['lang-list', 'id' => $model->id]];
$this->params['breadcrumbs'][] = [
									'label' => $model->name,
									'url' => [
												'view',
												'id' => $model->id,
												'lang_id' => $model->lang_id,
											]
								];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="ctt-staticdata-countrys-update">

    <?= $this->render('_form', [
        'model' => $model,
        'title' => Html::encode($this->title),
        'model' => $model,
        'mode' => 'edit',
    ]) ?>

</div>

Add lang_id parameter into breadcrumbs.

Add lang_id  parameter into breadcrumbs.

:)


<?php

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

abstract class AbstractTest implements \mre\PHPench\TestInterface
{
    protected $test;

    function setUp($arrSize)
    {
    }
}

class TestSingleQuotes extends AbstractTest
{
    public function execute() {
      $test = 'hello' . 'this' . 'is' . 'a' . 'test';
    }
}

class TestDoubleQuotes extends AbstractTest
{
    public function execute() {
      $test = 'hello' . 'this' . 'is' . 'a' . 'test';
    }
}

// Create a new benchmark instance
$phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator);

$output = new \mre\PHPench\Output\GnuPlotOutput('test4.png',  1024, 768);
$output->setTitle('Compare single quote and double quote strings');
$phpench->setOutput($output);

// Add your test to the instance
$phpench->addTest(new TestSingleQuotes, 'single_quotes');
$phpench->addTest(new TestDoubleQuotes, 'double_quotes');

// Run the benchmark and plot the results in realtime.
// With the second parameter you can specify
// the start, end and step for each call
$phpench->setInput(range(1,pow(2,16), 1024));
$phpench->setRepetitions(4);
$phpench->run(True);

<?php

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

abstract class AbstractTest implements \mre\PHPench\TestInterface
{
    protected $test;

    function setUp($arrSize)
    {
    }
}

class TestSingleQuotes extends AbstractTest
{
    public function execute() {
      $test = 'hello' . 'this' . 'is' . 'a' . 'test';
    }
}

class TestDoubleQuotes extends AbstractTest
{
    public function execute() {
      $test = "hello" . "this" . "is" . "a" . "test";
    }
}

// Create a new benchmark instance
$phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator);

$output = new \mre\PHPench\Output\GnuPlotOutput('test4.png',  1024, 768);
$output->setTitle('Compare single quote and double quote strings');
$phpench->setOutput($output);

// Add your test to the instance
$phpench->addTest(new TestSingleQuotes, 'single_quotes');
$phpench->addTest(new TestDoubleQuotes, 'double_quotes');

// Run the benchmark and plot the results in realtime.
// With the second parameter you can specify
// the start, end and step for each call
$phpench->setInput(range(1,pow(2,16), 1024));
$phpench->setRepetitions(4);
$phpench->run(True);

Fix whoopsie in single quotes vs double quotes example


<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ContentNegotiation;

use Zend\Mvc\MvcEvent;

class Module
{
    /**
     * {@inheritDoc}
     */
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/',
                ),
            ),
        );
    }

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

    /**
     * {@inheritDoc}
     */
    public function onBootstrap($e)
    {
        $app      = $e->getApplication();
        $services = $app->getServiceManager();
        $em       = $app->getEventManager();

        $em->attach(MvcEvent::EVENT_ROUTE, new ContentTypeListener(), -99);

        $sem = $em->getSharedManager();
        $sem->attach(
            'Zend\Stdlib\DispatchableInterface',
            MvcEvent::EVENT_DISPATCH,
            $services->get('ZF\ContentNegotiation\AcceptListener'),
            -10
        );
        $sem->attachAggregate($services->get('ZF\ContentNegotiation\AcceptFilterListener'));
        $sem->attachAggregate($services->get('ZF\ContentNegotiation\ContentTypeFilterListener'));
    }
}

<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ContentNegotiation;

use Zend\Mvc\MvcEvent;

class Module
{
    /**
     * {@inheritDoc}
     */
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/',
                ),
            ),
        );
    }

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

    /**
     * {@inheritDoc}
     */
    public function onBootstrap($e)
    {
        $app      = $e->getApplication();
        $services = $app->getServiceManager();
        $em       = $app->getEventManager();

        $em->attach(MvcEvent::EVENT_ROUTE, new ContentTypeListener(), -625);

        $sem = $em->getSharedManager();
        $sem->attach(
            'Zend\Stdlib\DispatchableInterface',
            MvcEvent::EVENT_DISPATCH,
            $services->get('ZF\ContentNegotiation\AcceptListener'),
            -10
        );
        $sem->attachAggregate($services->get('ZF\ContentNegotiation\AcceptFilterListener'));
        $sem->attachAggregate($services->get('ZF\ContentNegotiation\ContentTypeFilterListener'));
    }
}

Update priority of Content-Type listener

- Should happen between authorization (-600) and validation (-650)


<?php
namespace Concrete\Package\CommunityStore\Src\CommunityStore\Utilities;

use \Concrete\Core\User\Group\Group;
use \Concrete\Core\Support\Facade\Config;

class Wholesale {

    public static function isUserWholesale(){
        $user = new \User();
        $wholesale = Group::getByName('Wholesale Customer');

        $wholesaleCustomerGroupID = Config::get('community_store.wholesaleCustomerGroup');

        if ($wholesaleCustomerGroupID) {
            $wholesaleCustomerGroup = Group::getByID($wholesaleCustomerGroupID);

            if ($wholesaleCustomerGroup && is_object($wholesaleCustomerGroup)) {
                return $user->inGroup($wholesale);
            }
        }

        return false;

    }
}

<?php
namespace Concrete\Package\CommunityStore\Src\CommunityStore\Utilities;

use \Concrete\Core\User\Group\Group;
use \Concrete\Core\Support\Facade\Config;

class Wholesale {

    public static function isUserWholesale(){
        $user = new \User();

        $wholesaleCustomerGroupID = Config::get('community_store.wholesaleCustomerGroup');

        if ($wholesaleCustomerGroupID) {
            $wholesaleCustomerGroup = Group::getByID($wholesaleCustomerGroupID);

            if ($wholesaleCustomerGroup && is_object($wholesaleCustomerGroup)) {
                return $user->inGroup($wholesaleCustomerGroup);
            }
        }

        return false;
    }
}

Fix to wholesale group detection

Fix to wholesale group detection


<?php

namespace Edujugon\GoogleAds\Providers;

use Edujugon\GoogleAds\Console\RefreshTokenCommand;
use Edujugon\GoogleAds\GoogleAds;
use Illuminate\Support\ServiceProvider;

class GoogleAdsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php';

        $this->publishes([
            __DIR__.'/../Config/config.php' => $config_path,
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // Console commands
        $this->commands([
            RefreshTokenCommand::class,
        ]);

        $this->app->singleton(GoogleAds::class, function ($app) {
            return new GoogleAds();
        });

    }
}

<?php

namespace Edujugon\GoogleAds\Providers;

use Edujugon\GoogleAds\Console\RefreshTokenCommand;
use Edujugon\GoogleAds\GoogleAds;
use Illuminate\Support\ServiceProvider;

class GoogleAdsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php';

        $this->publishes([
            __DIR__.'/../Config/config.php' => $config_path,
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // Console commands
        $this->commands([
            RefreshTokenCommand::class,
        ]);

        $this->app->bind(GoogleAds::class, function ($app) {
            return new GoogleAds();
        });

    }
}

Replace singleton to bind for our main class in service provider


<?php

/**
 * For Linux filename compatibility, this file needs to be named Sip.php, or
 * camelize() needs to be special cased in setupSubresources
 */
class Services_Twilio_Rest_SIP extends Services_Twilio_InstanceResource {
    protected function init($client, $uri) {
        $this->setupSubresources(
            'domains',
            'ip_access_control_lists',
            'credential_lists'
        );
    }

    public function getResourceName($camelized = false) {
        return "SIP";
    }
}

<?php

/**
 * For Linux filename compatibility, this file needs to be named Sip.php, or
 * camelize() needs to be special cased in setupSubresources
 */
class Services_Twilio_Rest_Sip extends Services_Twilio_InstanceResource {
    protected function init($client, $uri) {
        $this->setupSubresources(
            'domains',
            'ip_access_control_lists',
            'credential_lists'
        );
    }

    public function getResourceName($camelized = false) {
        return "SIP";
    }
}

Change class name to match filename

Change class name to match filename

This is required in Linux for PSR-0.


<?php

namespace App;

use Layer\Blog\BlogPlugin;
use Layer\Cms\CmsPlugin;
use Layer\Pages\PagesPlugin;
use Layer\Users\UsersPlugin;

class Application extends \Layer\Application {

	public function __construct() {

		parent::__construct();

		/**
		 * Set the app name
		 */
		$this['name'] = 'My App';

		/**
		 * Register plugins
		 */
		$this
			->register(new CmsPlugin())
			->register(new PagesPlugin())
			->register(new BlogPlugin())
			->register(new UsersPlugin());

	}

}

<?php

namespace App;

use Layer\Blog\BlogPlugin;
use Layer\Cms\CmsPlugin;
use Layer\Pages\PagesPlugin;
use Layer\Users\UsersPlugin;

class Application extends \Layer\Application {

	public function __construct() {

		parent::__construct();

		$app = $this;

		/**
		 * Set the app name
		 */
		$app['name'] = 'My App';

		/**
		 * Register plugins
		 */
		$app
			->register(new CmsPlugin())
			->register(new PagesPlugin())
			->register(new BlogPlugin())
			->register(new UsersPlugin());

	}

}

Use $app instead of $this

Use $app instead of $this


<?php

// Define a constant to indicate that this is a testing environment.
define('APPLICATION_ENV', 'testing');

require_once __DIR__.'/../utils/Utils.php';

// Bring in the Yii framework.
$yiit = dirname(__FILE__).'/../../vendor/yiisoft/yii/framework/yiit.php';
require_once($yiit);

// simpleSAMLphp autoloading
if (file_exists(__DIR__ . '/../../simplesamlphp/lib/_autoload.php')) {
    $loader = include_once __DIR__ . '/../../simplesamlphp/lib/_autoload.php';
} else {
    die('Unable to find simpleSAMLphp autoloader file.');
}

// Composer autoloading
if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
    $loader = include_once __DIR__ . '/../../vendor/autoload.php';
} else {
    die('Unable to find Composer autoloader file.');
}

// Assemble the path to the appropriate config data.
$config = dirname(__FILE__) . '/../config/test.php';

require_once(dirname(__FILE__) . '/WebTestCase.php');

// Configure Phake.
\Phake::setClient(Phake::CLIENT_PHPUNIT);

// Run the application.
Yii::createWebApplication($config);

<?php

// Define a constant to indicate that this is a testing environment.
define('APPLICATION_ENV', 'testing');

require_once __DIR__.'/../utils/Utils.php';

// simpleSAMLphp autoloading
if (file_exists(__DIR__ . '/../../simplesamlphp/lib/_autoload.php')) {
    $loader = include_once __DIR__ . '/../../simplesamlphp/lib/_autoload.php';
} else {
    die('Unable to find simpleSAMLphp autoloader file.');
}

// Composer autoloading
if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
    $loader = include_once __DIR__ . '/../../vendor/autoload.php';
} else {
    die('Unable to find Composer autoloader file.');
}

// Bring in the Yii framework.
$yiit = dirname(__FILE__) . '/../../vendor/yiisoft/yii/framework/yiit.php';
require_once($yiit);

// Assemble the path to the appropriate config data.
$config = dirname(__FILE__) . '/../config/test.php';

require_once(dirname(__FILE__) . '/WebTestCase.php');

// Configure Phake.
\Phake::setClient(Phake::CLIENT_PHPUNIT);

// Run the application.
Yii::createWebApplication($config);

Set up saml's autoloader before yii's (for tests, too).


<?php

/*
 * Mustache PHP Compiler
 *
 * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com
 */

namespace Mustache;

require_once(dirname(__FILE__).'/Parser.php');
require_once(dirname(__FILE__).'/Generator.php');

class Template {
  protected $data = "";
  protected $compiled = null;

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

  public function render($context) {
    if ($this->compiled == null) {
      $code = $this->compile($this->data);
      //      echo "code: ".print_r($code, true)."\n";
      $this->compiled = eval("return function (\$ctx) { $code };");
    }

    $f = $this->compiled;
    return $f($context);
  }

  public function compile($src = null) {
    if ($src == null) {
      $src = $this->data;
    }
    $generator = new Generator();
    $tokens = $this->getTokens($src);
    //    echo "tokens: ".print_r($tokens, true)."\n";
    return $generator->compile($tokens);
  }

  public function getTokens($src = null) {
    if ($src == null) {
      $src = $this->data;
    }
    $parser = new Parser();
    return $parser->compile($src);
  }
};

?>

<?php

/*
 * Mustache PHP Compiler
 *
 * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com
 */

namespace Mustache;

require_once(dirname(__FILE__).'/Parser.php');
require_once(dirname(__FILE__).'/Generator.php');

class Template {
  protected $data = "";
  protected $compiled = null;

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

  public function render($context) {
    debug_log("current context ".print_r($context, true), 'COMPILER');
    debug_log("render template ".print_r($this->data, true).", compiled: ".print_r($this->compiled, true), 'COMPILER');
    if ($this->compiled == null) {
      $this->code = $this->compile($this->data);
      debug_log("template code ".print_r($this->code, true), 'COMPILER');
      $this->compiled = eval("return function (\$ctx) { ".$this->code." };");
    }

    $f = $this->compiled;
    $res = $f($context);
    debug_log("template evaluation: ".print_r($res, true), 'COMPILER');
    return $res;
  }

  public function compile($src = null) {
    if ($src == null) {
      $src = $this->data;
    }
    $generator = new Generator();
    $tokens = $this->getTokens($src);
    //    echo "tokens: ".print_r($tokens, true)."\n";
    return $generator->compile($tokens);
  }

  public function getTokens($src = null) {
    if ($src == null) {
      $src = $this->data;
    }
    $parser = new Parser();
    return $parser->compile($src);
  }
};

?>

Add debug information to compiler

Add debug information to compiler


<?php

namespace Vend\Statsd;

use \PHPUnit_Framework_TestCase as BaseTest;

abstract class MetricInterfaceTest extends BaseTest
{
    /**
     * @param string $key
     * @param mixed $value
     * @param string $type
     * @return MetricInterface
     */
    abstract protected function getSut($key, $value, $type);

    public function testGetData()
    {
        $metric = $this->getSut('key', 'value', 'c');
        $this->assertEquals($metric->getData(), 'key:value|c');

        $metric = $this->getSut('key', -1, 'c');
        $this->assertEquals($metric->getData(), 'key:-1|c');
    }
}

<?php

namespace Vend\Statsd;

use \PHPUnit_Framework_TestCase as BaseTest;

abstract class MetricInterfaceTest extends BaseTest
{
    /**
     * @param string $key
     * @param mixed $value
     * @param string $type
     * @return MetricInterface
     */
    abstract protected function getSut($key, $value, $type);

    public function testGetData()
    {
        $metric = $this->getSut('key', 'value', 'c');
        $this->assertEquals($metric->getData(), 'key:value|c');

        $metric = $this->getSut('key', -1, 'c');
        $metric->setSampleRate(0.1);
        $this->assertEquals($metric->getData(), 'key:-1|c|@0.1');
    }
}

Cover setting the sample rate

Cover setting the sample rate


  <a class="read-more" href="<?php the_permalink() ?>">Read more about this topic
  <?php if (get_comments_number() != 0) { ?>
      - <a href="<?php comments_link() ?>" class="govuk-link"><?php printf(_n('1 comment', '%1$s comments', get_comments_number(), 'roots'), number_format_i18n(get_comments_number())) ?>
    <?php } ?>

  <a class="govuk-link" href="<?php the_permalink() ?>">Read more about this topic
  <?php if (get_comments_number() != 0) { ?>
      - <a href="<?php comments_link() ?>" class="govuk-link"><?php printf(_n('1 comment', '%1$s comments', get_comments_number(), 'roots'), number_format_i18n(get_comments_number())) ?>
    <?php } ?>

Add visually hidden custom classes

Add visually hidden custom classes


<?php
/**
 * Bootstrapping unit tests.
 *
 * @package HylianShield
 * @subpackage Test
 * @copyright 2013 Jan-Marten "Joh Man X" de Boer
 */

// As of PHP 5.5, it is required to have a timezone defined.
date_default_timezone_set('Europe/Amsterdam');

require_once __DIR__ . '/Autoloader.php';

// Autoload our source files.
$autoloader = new Autoloader(__DIR__ . '/../src');
$autoloader->preload();

// Sadly we can't let this be autoloaded, because if we were to apply an
// autoloader to the Tests directory, PHPUnit would skip all loaded tests.
require_once __DIR__ . '/Tests/HylianShield/Serializer/TestBase.php';
require_once __DIR__ . '/Tests/HylianShield/Validator/TestBase.php';

<?php
/**
 * Bootstrapping unit tests.
 *
 * @package HylianShield
 * @subpackage Test
 * @copyright 2013 Jan-Marten "Joh Man X" de Boer
 */

// As of PHP 5.5, it is required to have a timezone defined.
date_default_timezone_set('Europe/Amsterdam');

require_once __DIR__ . '/Autoloader.php';

// Autoload our source files.
$autoloader = new Autoloader(__DIR__ . '/../src');
$autoloader->preload();

// Sadly we can't let this be autoloaded, because if we were to apply an
// autoloader to the Tests directory, PHPUnit would skip all loaded tests.
require_once __DIR__ . '/Tests/HylianShield/Validator/TestBase.php';

Remove include for migrated logic

Remove include for migrated logic


<?php

class GoogleCodePrettify {

  public static $prettified = false;

  public static function parserHook($text, $args = array(), $parser) {
    $pre_classes = '';
    if (isset($args['lang']) && $args['lang']) {
      $lang = $args['lang'];
      $pre_classes .= " lang-$lang";
    }
    if (isset($args['class']) && $args['class']) {
      $pre_classes .= ' '. $args['class'];
    }

    # Replace all < and > with their HTML entitites
    #
    $text = str_replace('<', '<', $text);
    $text = str_replace('>', '>', $text);

    self::$prettified = true;

    return "
$text
";
  }

  public static function beforePageDisplay(&$wgOut, &$sk) {
    $wgOut->addModules('ext.GoogleCodePrettify');
    // Continue
    return true;
  }
}

<?php

class GoogleCodePrettify {

  public static $prettified = false;

  public static function parserHook($text, $args = array(), $parser) {
    $pre_classes = '';
    if (isset($args['lang']) && $args['lang']) {
      $lang = $args['lang'];
      $pre_classes .= " lang-$lang";
    }
    if (isset($args['class']) && $args['class']) {
      $pre_classes .= ' '. $args['class'];
    }

    # Replace all '&', '<,' and '>' with their HTML entitites. Order is
    # important. You have to do '&' first.
    #
    $text = str_replace('&', '&', $text);
    $text = str_replace('<', '<', $text);
    $text = str_replace('>', '>', $text);

    self::$prettified = true;

    return "
$text
";
  }

  public static function beforePageDisplay(&$wgOut, &$sk) {
    $wgOut->addModules('ext.GoogleCodePrettify');
    // Continue
    return true;
  }
}

Replace & in source with & in output

Replace & in source with & in output

Avoid accidental HTML entitites by escaping '&' in input with '&' so
that the code output can really be treated as raw code.


<?php
/**
 * Plugin Name: Add Advance Custom Fields to JSON API
 * Description: Add Advance Custom Fields to JSON API - from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51
 * Author: @PanMan
 * Author URI: https://github.com/PanManAms/WP-JSON-API-ACF
 * Version: 0.1
 * Plugin URI: https://github.com/PanManAms/WP-JSON-API-ACF
 * Copied from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 - but a plugin is nicer
 */
function wp_api_encode_acf($data,$post,$context){
    $customMeta = (array) get_fields($post['ID']);

    $data['meta'] = array_merge($data['meta'], $customMeta );
    return $data;
}

if( function_exists('get_fields') ){
    add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}

<?php
/**
 * Plugin Name: Add Advance Custom Fields to JSON API
 * Description: Add Advance Custom Fields to JSON API - from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51
 * Author: @PanMan
 * Author URI: https://github.com/PanManAms/WP-JSON-API-ACF
 * Version: 0.1
 * Plugin URI: https://github.com/PanManAms/WP-JSON-API-ACF
 * Copied from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 - but a plugin is nicer
 */
function wp_api_encode_acf($data,$post,$context){
    $customMeta = (array) get_fields($post['ID']);

    $data['meta'] = array_merge($data['meta'], $customMeta );
    return $data;
}

add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);

Remove check for get_fields to fix loading order

This is check is unnecessary because the add_filter option just returns false if we're unable to hook into that function.
It will also cause the plugin to fail if it loads before Advanced Custom Fields


<?php

namespace Camspiers\StatisticalClassifier\Classifier;

interface ClassifierInterface
{
    // public function getSource();
    // public function prepare();
    public function classify($document);
    // public function train($category, $document);
}

<?php

namespace Camspiers\StatisticalClassifier\Classifier;

interface ClassifierInterface
{
    public function classify($document);
}

MINOR: Remove comments from classifier interface


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Webmozart\Assert\Assert;

final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int
    {
        Assert::keyExists($context, 'channel');

        $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']);

        if (null === $channelPricing) {
            throw new MissingChannelConfigurationException(sprintf(
                'Channel %s has no price defined for product variant %s',
                $context['channel']->getName(),
                $productVariant->getName()
            ));
        }

        return $channelPricing->getPrice();
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Webmozart\Assert\Assert;

final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int
    {
        Assert::keyExists($context, 'channel');

        $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']);

        if (null === $channelPricing) {
            throw new MissingChannelConfigurationException(sprintf(
                'Channel %s has no price defined for product variant %s (%s)',
                $context['channel']->getName(),
                $productVariant->getName(),
                $productVariant->getCode()
            ));
        }

        return $channelPricing->getPrice();
    }
}

Add code to exception message since name can be null


<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.3';
$suitecrm_timestamp    = '2015-08-14 17:00pm';

<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.3.1';
$suitecrm_timestamp    = '2015-08-25 17:00pm';

Update SuiteCRM version to SuiteCRM 7.3.1.


<?php

if (! function_exists('messages')) {
    /**
     * Add a message to the bag.
     *
     * @param  string  $key
     * @param  string  $message
     *
     * @return \Orchestra\Messages\MessageBag
     */
    function messages($key, $message)
    {
        return app('orchestra.messages')->add($key, $message);
    }
}

<?php

if (! function_exists('messages')) {
    /**
     * Add a message to the bag.
     *
     * @param  string  $key
     * @param  string  $message
     *
     * @return \Orchestra\Messages\MessageBag
     */
    function messages($key, $message)
    {
        return app('orchestra.messages')->add($key, value($message));
    }
}

Allow to use value as closure.

Allow to use value as closure.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
/**
 * This file is part of the nigelgreenway/demander package.
 *
 * (c) Nigel Greenway <nigel_greenway@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Demander;

/**
 * Interface for a Command Message
 *
 * @package Demander
 * @author  Nigel Greenway <nigel_greenway@me.com>
 */
interface CommandInterface
{
}

<?php
/**
 * This file is part of the nigelgreenway/demander package.
 *
 * (c) Nigel Greenway <nigel_greenway@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Demander;

/**
 * Interface for a Command Message
 *
 * @package Demander
 * @author  Nigel Greenway <nigel_greenway@me.com>
 */
interface CommandInterface
{}

Tidy up of class body

Tidy up of class body


<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../common/config/bootstrap.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../common/config/main.php'),
    require(__DIR__ . '/../common/config/main-local.php'),
    require(__DIR__ . '/config/main.php')
);

$application = new yii\web\Application($config);
$application->run();

<?php
// For more details debugging in development mode replace these 2 lines with the following 2
//defined('YII_DEBUG') or define('YII_DEBUG', true);
//defined('YII_ENV') or define('YII_ENV', 'dev');
defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../common/config/bootstrap.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../common/config/main.php'),
    require(__DIR__ . '/../common/config/main-local.php'),
    require(__DIR__ . '/config/main.php')
);

$application = new yii\web\Application($config);
$application->run();

Enable production mode in API responses

Enable production mode in API responses


<?php

final class PhabricatorOwnersPackageDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getBrowseTitle() {
    return pht('Browse Packages');
  }

  public function getPlaceholderText() {
    return pht('Type a package name...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorOwnersApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $results = array();

    $query = id(new PhabricatorOwnersPackageQuery())
      ->withNameNgrams($raw_query)
      ->setOrder('name');

    $packages = $this->executeQuery($query);
    foreach ($packages as $package) {
      $name = $package->getName();
      $monogram = $package->getMonogram();

      $results[] = id(new PhabricatorTypeaheadResult())
        ->setName("{$monogram}: {$name}")
        ->setURI($package->getURI())
        ->setPHID($package->getPHID());
    }

    return $this->filterResultsAgainstTokens($results);
  }

}

<?php

final class PhabricatorOwnersPackageDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getBrowseTitle() {
    return pht('Browse Packages');
  }

  public function getPlaceholderText() {
    return pht('Type a package name...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorOwnersApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $results = array();

    $query = id(new PhabricatorOwnersPackageQuery())
      ->setOrder('name');

    // If the user is querying by monogram explicitly, like "O123", do an ID
    // search. Otherwise, do an ngram substring search.
    if (preg_match('/^[oO]\d+\z/', $raw_query)) {
      $id = trim($raw_query, 'oO');
      $id = (int)$id;
      $query->withIDs(array($id));
    } else {
      $query->withNameNgrams($raw_query);
    }

    $packages = $this->executeQuery($query);
    foreach ($packages as $package) {
      $name = $package->getName();
      $monogram = $package->getMonogram();

      $results[] = id(new PhabricatorTypeaheadResult())
        ->setName("{$monogram}: {$name}")
        ->setURI($package->getURI())
        ->setPHID($package->getPHID());
    }

    return $this->filterResultsAgainstTokens($results);
  }

}

Allow "O42" to find packages by monogram in Owners typeaheads

Summary: When a user queries by package monogram explicitly, search by package ID.

Test Plan: {F2305075}

Reviewers: chad

Reviewed By: chad

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