<?php
/**
 * Singleton class to manage Sutra-specific cache.
 *
 * @copyright Copyright (c) 2011 Poluza.
 * @author Andrew Udvare [au] <andrew@poluza.com>
 * @license http://www.opensource.org/licenses/mit-license.php
 *
 * @package Sutra
 * @link http://www.example.com/
 *
 * @version 1.0
 */
class sCache extends fCache {
  /**
   * The current working directory.
   *
   * @var string
   */
  private static $cwd = '';

  /**
   * Initialises the class.
   *
   * @return void
   */
  private static function initialize() {
    if (!self::$cwd) {
      self::$cwd = getcwd();
    }
  }

  /**
   * Get a key unique to the site.
   *
   * @param string $key Key to use.
   * @param string $class_prefix Class prefix to use. If not specified, sCache
   *   will be used.
   * @return string Key that can be used for cache storage.
   */
  public static function getSiteUniqueKey($key, $class_prefix = NULL) {
    self::initialize();

    if (is_null($class_prefix)) {
      $class_prefix = __CLASS__;
    }

    return $class_prefix.'::'.self::$cwd.'::'.$key;
  }
}

<?php
/**
 * Extension to sCache.
 *
 * @copyright Copyright (c) 2011 Poluza.
 * @author Andrew Udvare [au] <andrew@poluza.com>
 * @license http://www.opensource.org/licenses/mit-license.php
 *
 * @package Sutra
 * @link http://www.sutralib.com/
 *
 * @version 1.01
 */
class sCache extends fCache {
  /**
   * The current working directory.
   *
   * @var string
   */
  private static $cwd = '';

  /**
   * Initialises the class.
   *
   * @return void
   */
  private static function initialize() {
    if (!self::$cwd) {
      self::$cwd = getcwd();
    }
  }

  /**
   * Get a key unique to the site.
   *
   * @param string $key Key to use.
   * @param string $prefix Class prefix to use. If not specified, 'sCache' will
   *   be used.
   * @return string Key that can be used for cache storage.
   */
  public static function getSiteUniqueKey($key, $prefix = NULL) {
    self::initialize();

    if (is_null($prefix)) {
      $prefix = __CLASS__;
    }

    return $prefix.'::'.self::$cwd.'::'.$key;
  }
}

Update site URL; update documentation; simplify getSiteUniqueKey()


<?php

class Log
{
    const LOG_ERROR = 'error';
    const LOG_DEBUG = 'debug';

    public static function add($level, $tag, $message)
    {
        $vargs = array_slice(func_get_args(), 3);
        if (count($vargs) > 0) {
            $params = array_merge(array($message), $vargs);
            $message = call_user_func_array('sprintf', $params);
        }

        printf("%s: [%s][%s] %s\n", strtoupper($level), date('Y-m-d H:i:s'), $tag, $message);
    }

    public static function debug($tag, $message)
    {
        $args = array_merge(array(self::LOG_DEBUG), func_get_args());
        call_user_func_array('Log::add', $args);
    }

    public static function error($tag, $message)
    {
        $args = array_merge(array(self::LOG_ERROR), func_get_args());
        call_user_func_array('Log::add', $args);
    }
}

<?php

class Log
{
    const LOG_ERROR = 'error';
    const LOG_DEBUG = 'debug';

    public static function add($level, $tag, $message)
    {
        $vargs = array_slice(func_get_args(), 3);
        if (count($vargs) > 0) {
            $params = array_merge(array($message), $vargs);
            $message = call_user_func_array('sprintf', $params);
        }

        $fmt = "%s: [%s][%s] %s\n";

        if (substr(PHP_SAPI, 0, 3) != 'cli')
            $fmt = nl2br($fmt);

        printf($fmt, strtoupper($level), date('Y-m-d H:i:s'), $tag, $message);
    }

    public static function debug($tag, $message)
    {
        $args = array_merge(array(self::LOG_DEBUG), func_get_args());
        call_user_func_array('Log::add', $args);
    }

    public static function error($tag, $message)
    {
        $args = array_merge(array(self::LOG_ERROR), func_get_args());
        call_user_func_array('Log::add', $args);
    }
}

Update log to accomidate for web output

Update log to accomidate for web output

If running on a non-CLI system, print out <br> instead of \n


<?php defined('SYSPATH') OR die('No direct script access.');

abstract class Koi extends Kohana_Koi {
	// @see Kohana_Koi
}

<?php defined('SYSPATH') OR die('No direct script access.');

class Koi extends Kohana_Koi {
	// @see Kohana_Koi
}

Remove abstract from Koi class

Remove abstract from Koi class


#!/usr/bin/env php
<?php

/*
 * This file is part of the Certificationy CLI application.
 *
 * (c) Vincent Composieux <vincent.composieux@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use Certificationy\Cli\Command\StartCommand;
use KevinGH\Amend\Command;
use KevinGH\Amend\Helper;
use Symfony\Component\Console\Application;
use Symfony\Component\Yaml\Yaml;

const VERSION = 1.4;
const APPLICATION_NAME = 'Certificationy';

$application = new Application(self::APPLICATION_NAME, self::VERSION);

$config = Yaml::parse(file_get_contents('config.yml'));
$updateCommand = new Command('self-update');
$updateCommand->setManifestUri($config['manifest_uri']);
$application->add($updateCommand);
$application->getHelperSet()->set(new Helper());

$startCommand = new StartCommand();
$application->add($startCommand);
$application->setDefaultCommand($startCommand->getName());

$application->run();

#!/usr/bin/env php
<?php

/*
 * This file is part of the Certificationy CLI application.
 *
 * (c) Vincent Composieux <vincent.composieux@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use Certificationy\Cli\Command\StartCommand;
use KevinGH\Amend\Command;
use KevinGH\Amend\Helper;
use Symfony\Component\Console\Application;
use Symfony\Component\Yaml\Yaml;

const VERSION = 1.4;
const APPLICATION_NAME = 'Certificationy';

$application = new Application(APPLICATION_NAME, VERSION);

$config = Yaml::parse(file_get_contents('config.yml'));
$updateCommand = new Command('self-update');
$updateCommand->setManifestUri($config['manifest_uri']);
$application->add($updateCommand);
$application->getHelperSet()->set(new Helper());

$startCommand = new StartCommand();
$application->add($startCommand);
$application->setDefaultCommand($startCommand->getName());

$application->run();

Remove self (not in class scope)

Remove self (not in class scope)


<?php

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

class CreateMachinephotosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('machinephotos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('machine_id')->unsigned()->default(0);
            $table->string('machine_photo_path', 255)->nullable();
            $table->string('machine_photo_thumb', 255)->nullable();
            $table->string('photo_description', 255)->nullable();
            $table->softDeletes();
            $table->timestamps();
            $table->foreign('machine_id')->references('id')->on('machines');
        });
    }

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

<?php

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

class CreateMachinephotosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('machinephotos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('machine_id')->unsigned()->default(0);
            $table->text('machine_photo_path')->nullable();
            $table->text('machine_photo_thumb')->nullable();
            $table->text('photo_description',)->nullable();
            $table->softDeletes();
            $table->timestamps();
            $table->foreign('machine_id')->references('id')->on('machines');
        });
    }

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

Make path and description fields text fields instead of string fields


<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        $project_id = $querydata['id'];
        if (!isset($_SESSION)) {
            session_start();
        }
        $query_get_project_details = <<<EOF
SELECT project FROM full_webuser_data
    WHERE project->>'id' = :project_id AND provider = :provider AND oauth_id = :oauth_id
EOF;
        $stm_get_project_details = $db->prepare($query_get_project_details);
        $stm_get_project_details->bindValue('project_id', $project_id);
        $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']);
        $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']);
        $stm_get_project_details->execute();

        while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) {
            $result[$project_id] = $row['project'];
        }
        return $result;
    }
}

<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        $project_id = $querydata['id'];
        if (!isset($_SESSION)) {
            session_start();
        }
        $query_get_project_details = <<<EOF
SELECT project FROM full_webuser_data
    WHERE webuser_data_id = :project_id AND provider = :provider AND oauth_id = :oauth_id
EOF;
        $stm_get_project_details = $db->prepare($query_get_project_details);
        $stm_get_project_details->bindValue('project_id', $project_id);
        $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']);
        $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']);
        $stm_get_project_details->execute();

        while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) {
            $result[$project_id] = $row['project'];
        }
        return $result;
    }
}

Add correct project id to projects details webservice. The test fails


<?

$file = fopen($argv[1], 'r');

$msgid  = false;
$msgstr = false;

while( ($line = fgets($file)) ) {

    if(preg_match('/msgid\s"(.*)"/U', $line, $matches)) {
        $msgid = '"'.$matches[1].'"';

    } else if(preg_match('/msgstr\s"(.*)"/U', $line, $matches)) {
        $msgstr = '"'.$matches[1].'"';

        if($msgstr != '""' && $msgid != '""') {
            echo $msgid.';'.$msgstr."\n";
        } else {
            $msgid = false;
        }
    }
}

<?

$file = fopen($argv[1], 'r');

$msgid  = false;
$msgstr = false;

while( ($line = fgets($file)) ) {

    if(preg_match('/msgid\s"(.*)"/U', $line, $matches)) {
        $msgid = '"'.$matches[1].'"';

    } else if(preg_match('/msgstr\s"(.*)"/U', $line, $matches)) {
        $msgstr = '"'.$matches[1].'"';

        if($msgid != '""') {
            echo $msgid.';'.$msgstr."\n";
        } else {
            $msgid = false;
        }
    }
}

Write csv line even if msgstr is empty

Write csv line even if msgstr is empty


<?php
    include '_templates/sitewide.php';
    $page['name'] = '403';
    $page['title'] = 'Forbidden ⋅ elementary';
    include $template['header'];
?>

Access denied.

You don't have permission to view the requested resource.

        Go to Home Page

<?php
    include $template['footer'];
?>

<?php
    include '_templates/sitewide.php';
    $page['name'] = '403';
    $page['title'] = 'Access Denied ⋅ elementary';
    include $template['header'];
?>

Access Denied.

You don't have permission to view the requested resource.

        Go to Home Page

<?php
    include $template['footer'];
?>

Update page title to match others.

Update page title to match others.


<?php

/**
 * @file
 * Northstar OpenID Connect client.
 */

class OpenIDConnectClientNorthstar extends OpenIDConnectClientBase {

  /**
   * Overrides OpenIDConnectClientBase::settingsForm().
   */
  public function settingsForm() {
    $form = parent::settingsForm();

    // @TODO: Store public key here.

    return $form;
  }

  /**
   * Overrides OpenIDConnectClientBase::getEndpoints().
   */
  public function getEndpoints() {
    // @TODO: Build these from Northstar module settings.
    $url = 'http://northstar.dev:8000';

    return [
      'authorization' => $url . '/authorize',
      'token' => $url . '/v2/auth/token',
      'userinfo' => $url . '/v1/profile',
    ];
  }

  /**
   * Implements OpenIDConnectClientInterface::decodeIdToken().
   */
  public function decodeIdToken($id_token) {
    // @TODO: Verify JWT using public key.
    return parent::decodeIdToken($id_token);
  }

  /**
   * Overrides OpenIDConnectClientBase::retrieveUserInfo().
   */
  public function retrieveUserInfo($access_token) {
    $base = parent::retrieveUserInfo($access_token);
    if ($base) {
      return $base['data'];
    }

    return null;
  }
}

<?php

/**
 * @file
 * Northstar OpenID Connect client.
 */

class OpenIDConnectClientNorthstar extends OpenIDConnectClientBase {

  /**
   * Overrides OpenIDConnectClientBase::settingsForm().
   */
  public function settingsForm() {
    $form = parent::settingsForm();

    // @TODO: Store public key here.

    return $form;
  }

  /**
   * Overrides OpenIDConnectClientBase::getEndpoints().
   */
  public function getEndpoints() {
    // @TODO: Build these from Northstar module settings.
    $url = 'http://northstar.dev:8000';

    return [
      'authorization' => $url . '/authorize',
      'token' => $url . '/v2/auth/token',
      'userinfo' => $url . '/v2/auth/info',
    ];
  }

  /**
   * Implements OpenIDConnectClientInterface::decodeIdToken().
   */
  public function decodeIdToken($id_token) {
    // @TODO: Verify JWT using public key.
    return parent::decodeIdToken($id_token);
  }

  /**
   * Overrides OpenIDConnectClientBase::retrieveUserInfo().
   */
  public function retrieveUserInfo($access_token) {
    $base = parent::retrieveUserInfo($access_token);
    if ($base) {
      return $base['data'];
    }

    return null;
  }
}

Use new user info endpoint.

Use new user info endpoint.


<?php

namespace PhpTabs\Component;

use Exception;

use PhpTabs\Component\Tablature;
use PhpTabs\Component\Dumper\DumperBase;
use PhpTabs\Component\Serializer\Text;
use PhpTabs\Component\Serializer\Xml;

class Dumper extends DumperBase
{
  protected $song;

  public function __construct(Tablature $tablature)
  {
    $this->song = $tablature->getSong();
  }

  /**
   * Dumps a song into an array
   *  and returns a representation
   *
   * @param string $format array|xml|json|var_export|serialize|text
   *
   * @return array
   *
   * @throws Exception if format is not supported
   */
  public function dump($format = 'array')
  {
    switch($format)
    {
      case 'array':
        return $this->dumpSong();
      case 'xml':
        return (new Xml())->serialize($this->dump('array'));
      case 'json':
        return json_encode($this->dump('array'));
      case 'var_export':
        return var_export($this->dump('array'), true);
      case 'serialize':
        return serialize($this->dump('array'));
      case 'text':
        return (new Text())->serialize($this->dump('array'));
      default:
        $message = sprintf('%s does not support "%s" format', __METHOD__, $format);
        throw new Exception($message);
        break;
    }
  }
}

<?php

namespace PhpTabs\Component;

use Exception;
use PhpTabs\Component\Tablature;
use PhpTabs\Component\Dumper\DumperBase;
use PhpTabs\Component\Serializer\Text;
use PhpTabs\Component\Serializer\Xml;

class Dumper extends DumperBase
{
  /** @var \Phptabs\Model\Song */
  protected $song;

  /**
   * @param Tablature $tablature The tablature to dump
   */
  public function __construct(Tablature $tablature)
  {
    $this->song = $tablature->getSong();
  }

  /**
   * Returns a representation of the song into a desired format
   *
   * @param string $format array|xml|json|var_export|serialize|text
   *
   * @return mixed array|xml|json|var_export|serialize|text
   *
   * @throws Exception if format is not supported
   */
  public function dump($format = 'array')
  {
    switch($format)
    {
      case 'array':
        return $this->dumpSong();
      case 'xml':
        return (new Xml())->serialize($this->dump());
      case 'json':
        return json_encode($this->dump());
      case 'var_export':
        return var_export($this->dump(), true);
      case 'serialize':
        return serialize($this->dump());
      case 'text':
        return (new Text())->serialize($this->dump());
      default:
        $message = sprintf('%s does not support "%s" format', __METHOD__, $format);
        throw new Exception($message);
        break;
    }
  }
}

Update comments & use default output format


<?php

namespace Kregel\Radio\Commands;

use App\Models\User;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Illuminate\Console\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Database\Eloquent\Model;
use \Kregel\Radio\Models\Notification;
use Kregel\Radio\Models\Channel;

class Broadcast extends Command implements SelfHandling
{
    protected $signature = 'radio:broadcast';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->info('Firing up');
        $global = Channel::where('type', 'global')->first();

        $title = $this->ask('What is the title of this broadcast?');
        $message = $this->ask('What is your message to your users?');

        if(empty($message) || empty($title)) {
            $this->error('You must fillout both the title and the message.');
            return;
        }
        $this->info('Making your notification, please know if you have a lot of users this may take a while...');
        foreach($global->users as $user)
            Notification::create([
                'channel_id' => $global->id,
                'user_id' => $user->id,
                'is_unread' => true,
                'name' => $title,
                'description' => $message,
                'type' => 'general'
            ]);
        $this->info('Completed!');
    }

}

<?php

namespace Kregel\Radio\Commands;

use App\Models\User;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Illuminate\Console\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Database\Eloquent\Model;
use \Kregel\Radio\Models\Notification;
use Kregel\Radio\Models\Channel;

class Broadcast extends Command implements SelfHandling
{
    protected $signature = 'radio:broadcast';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->info('Firing up');
        $global = Channel::where('type', 'global')->first();

        $title = $this->ask('What is the title of this broadcast?');
        $message = $this->ask('What is your message to your users?');

        if(empty($message) || empty($title)) {
            $this->error('You must fillout both the title and the message.');
            return;
        }
        $this->info('Making your notification, please know if you have a lot of users this may take a while...');
        foreach($global->users as $user)
            Notification::create([
                'channel_id' => $user->channel->id,
                'user_id' => $user->id,
                'is_unread' => true,
                'name' => $title,
                'description' => $message,
                'type' => 'general'
            ]);
        $this->info('Completed!');
    }

}

Update broadcast command to use the user's own channel instead of the global channel due to an over whelming number of notifications


Use exposed enhance.ctm value instead of repeating the ctm check.


<?php declare(strict_types = 1);

namespace Apitte\Core\Annotation\Controller;

use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\AnnotationException;

/**
 * @Annotation
 * @Target({"CLASS", "METHOD"})
 */
final class Tag
{

	/** @var string */
	private $name;

	/** @var string|null */
	private $value;

	/**
	 * @param mixed[] $values
	 */
	public function __construct(array $values)
	{
		if (!isset($values['name'])) {
			throw new AnnotationException('No @Tag name given');
		}

		$name = $values['name'];
		if ($name === null || $name === '') {
			throw new AnnotationException('Empty @Tag name given');
		}

		$this->name = $name;
		$this->value = $values['value'] ?? null;
	}

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

	public function getValue(): ?string
	{
		return $this->value;
	}

}

<?php declare(strict_types = 1);

namespace Apitte\Core\Annotation\Controller;

use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\AnnotationException;

/**
 * @Annotation
 * @Target({"CLASS", "METHOD"})
 */
final class Tag
{

	/** @var string */
	private $name;

	/** @var string|null */
	private $value;

	/**
	 * @param mixed[] $values
	 */
	public function __construct(array $values)
	{
		if (isset($values['value']) && !isset($values['name'])) {
			$values['name'] = $values['value'];
		}

		if (!isset($values['name'])) {
			throw new AnnotationException('No @Tag name given');
		}

		$name = $values['name'];
		if ($name === null || $name === '') {
			throw new AnnotationException('Empty @Tag name given');
		}

		$this->name = $name;
		$this->value = $values['value'] ?? null;
	}

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

	public function getValue(): ?string
	{
		return $this->value;
	}

}

Simplify usage of tags with name only

Simplify usage of tags with name only


<?php

use FelixOnline\Exceptions;

class ValidationController extends BaseController
{
	function GET($matches)
	{
		try {
			$code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation')
				->filter('code = "%s"', array($matches['code']))
				->one();
		} catch (Exceptions\InternalException $e) {
			throw new NotFoundException(
				$e->getMessage(),
				$matches,
				'ValidationController',
				FrontendException::EXCEPTION_NOTFOUND,
				$e
			);
		}

		$code->setConfirmed(1)->save();

		try {
			$comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment')
				->filter('email = "%s"', array($code->getEmail()))
				->filter('rejected = 0')
				->filter('spam = 0')
				->values();

			foreach($comments as $comment) {
				if ($comment->getReply()) { // if comment is replying to an internal comment
					$comment->emailReply();
				}

				// email authors of article
				$comment->emailAuthors();
			}
		} catch (\Exception $e) {

		}

		$this->theme->appendData(array(
			'email' => $code->getEmail()
		));

		$this->theme->render('validation');
	}
}

<?php

use FelixOnline\Exceptions;

class ValidationController extends BaseController
{
	function GET($matches)
	{
		try {
			$code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation')
				->filter('code = "%s"', array($matches['code']))
				->one();
		} catch (Exceptions\InternalException $e) {
			throw new NotFoundException(
				$e->getMessage(),
				$matches,
				'ValidationController',
				FrontendException::EXCEPTION_NOTFOUND,
				$e
			);
		}

		$code->setConfirmed(1)->save();

		try {
			$comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment')
				->filter('email = "%s"', array($code->getEmail()))
				->filter('active = 1')
				->filter('spam = 0')
				->values();

			foreach($comments as $comment) {
				if ($comment->getReply()) { // if comment is replying to an internal comment
					$comment->emailReply();
				}

				// email authors of article
				$comment->emailAuthors();
			}
		} catch (\Exception $e) {

		}

		$this->theme->appendData(array(
			'email' => $code->getEmail()
		));

		$this->theme->render('validation');
	}
}

Fix a SQL error in email validation

Fix a SQL error in email validation


<?php

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;

class CanBuildBaseStringTest extends TestCase
{
    private $canBuildBaseString;

    function setUp()
    {
        $this->canBuildBaseString = $this->getMockForTrait(CanBuildBaseString::class);
    }

    /** @test */
    function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
    {
        $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseString->getBaseStringBuilder());
    }

    /** @test */
    function can_build_base_string_trait_can_build_base_string()
    {
        $baseString = $this->canBuildBaseString->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');
        $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $baseString);
    }
}

<?php

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;

class CanBuildBaseStringTest extends TestCase
{
    private $canBuildBaseStringStub;

    function setUp()
    {
        $this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class);
    }

    /** @test */
    function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
    {
        $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder());
    }

    /** @test */
    function can_build_base_string_trait_can_build_base_string()
    {
        $baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');

        $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $canBuildBaseStringStub);
    }
}

:white_check_mark: Update the CanBuildBaseString test trait.


<?php

use Illuminate\Database\Seeder;
use Northstar\Models\Client;
use Northstar\Auth\Scope;

class ClientTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('clients')->delete();

        // For easy testing, we'll seed one client with all scopes...
        Client::create([
            'title' => 'Trusted Test Client',
            'description' => 'This is an example OAuth client seeded with your local Northstar installation. It was automatically given all scopes that were defined when it was created.',
            'client_id' => 'trusted-test-client',
            'client_secret' => 'secret1',
            'redirect_uri' => [
                'http://northstar.dev:8000',
                'http://dev.dosomething.org:8888/openid-connect/generic',
            ],
            'allowed_grants' => ['authorization_code', 'password', 'client_credentials'],
            'scope' => collect(Scope::all())->keys()->toArray(),
        ]);

        // ..and one with limited scopes.
        Client::create([
            'title' => 'Untrusted Test Client',
            'description' => 'This is an example OAuth client seeded with your local Northstar installation. It is only given the user scope, and can be used to simulate untrusted clients (for example, the mobile app).',
            'client_id' => 'untrusted-test-client',
            'client_secret' => 'secret2',
            'allowed_grants' => ['password'],
            'scope' => ['user'],
        ]);
    }
}

<?php

use Illuminate\Database\Seeder;
use Northstar\Models\Client;
use Northstar\Auth\Scope;

class ClientTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('clients')->delete();

        // For easy testing, we'll seed one client with all scopes...
        Client::create([
            'title' => 'Trusted Test Client',
            'description' => 'This is an example OAuth client seeded with your local Northstar installation. It was automatically given all scopes that were defined when it was created.',
            'client_id' => 'trusted-test-client',
            'client_secret' => 'secret1',
            'redirect_uri' => [
                'http://northstar.dev:8000',
                'http://dev.dosomething.org:8888/openid-connect/northstar',
            ],
            'allowed_grants' => ['authorization_code', 'password', 'client_credentials'],
            'scope' => collect(Scope::all())->keys()->toArray(),
        ]);

        // ..and one with limited scopes.
        Client::create([
            'title' => 'Untrusted Test Client',
            'description' => 'This is an example OAuth client seeded with your local Northstar installation. It is only given the user scope, and can be used to simulate untrusted clients (for example, the mobile app).',
            'client_id' => 'untrusted-test-client',
            'client_secret' => 'secret2',
            'allowed_grants' => ['password'],
            'scope' => ['user'],
        ]);
    }
}

Update redirect URI for custom provider.


<?php
/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nietonfir\Google\ReCaptcha\Api;

/**
 * Defines the interface for validating the API response.
 *
 * @link https://developers.google.com/recaptcha/docs/verify Official API Documentation
 *
 * @author nietonfir <nietonfir@gmail.com>
 */
interface ResponseInterface
{
    /**
     * Decodes the JSON encoded response from the API and assigns the values
     * to the corresponding attributes.
     *
     * @param  string $response
     * @return ResponseInterface
     */
    public function verify($response);

    /**
     * Returns the validation state of the response.
     *
     * @return boolean
     */
    public function isValid();

    /**
     * Returns the errors of the response
     * The following error-codes are currently in use:
     *   Error code              Description
     *   missing-input-secret    The secret parameter is missing.
     *   invalid-input-secret    The secret parameter is invalid or malformed.
     *   missing-input-response  The response parameter is missing.
     *   invalid-input-response  The response parameter is invalid or malformed.
     *
     * @return array
     */
    public function getErrors();
}

<?php
/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nietonfir\Google\ReCaptcha\Api;

/**
 * Defines the interface for validating the API response.
 *
 * @link https://developers.google.com/recaptcha/docs/verify Official API Documentation
 *
 * @author nietonfir <nietonfir@gmail.com>
 */
interface ResponseInterface
{
    /**
     * Decodes the JSON encoded response from the API and assigns the values
     * to the corresponding attributes.
     *
     * @param  string $response
     * @return ResponseInterface
     */
    public function verify($response);

    /**
     * Returns the validation state of the response.
     *
     * @return boolean
     */
    public function isValid();

    /**
     * Returns the errors of the response
     * The following error-codes are currently in use:
     *   Error code              Description
     *   missing-input-secret    The secret parameter is missing.
     *   invalid-input-secret    The secret parameter is invalid or malformed.
     *   missing-input-response  The response parameter is missing.
     *   invalid-input-response  The response parameter is invalid or malformed.
     *   bad-request             The request is invalid or malformed.
     *
     * @return array
     */
    public function getErrors();
}

Add missing upstream bad-request error code


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

// Run this command every minute through a cron-tab to enable auto-deploy of
// Sonium. It builds upon the auto-deploy mechanism included in sa-mp.nl.

$file = '/home/lvp/domains/sa-mp.nl/private_html/tools/auto-deploy/bot-sonium.push';
if (!file_exists($file))
    exit;

unlink($file);

// Do not start pulling updates every minute if the |$file| becomes undeletable for some reason.
// Instead, fail silently, at some point somebody might notice that auto-deploy failed.
if (file_exists($file))
    exit;

$directory = __DIR__;
$commands = [
    'git fetch --all',
    'git reset --hard origin/master',
    'git rev-parse HEAD > VERSION'
];

foreach ($commands as $command)
    echo shell_exec('cd ' . $directory . ' && ' . $command);

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

// Run this command every minute through a cron-tab to enable auto-deploy of
// Sonium. It builds upon the auto-deploy mechanism included in sa-mp.nl.

$file = '/home/lvp/domains/sa-mp.nl/private_html/tools/auto-deploy/bot-sonium.push';
if (!file_exists($file))
    exit;

unlink($file);

// Do not start pulling updates every minute if the |$file| becomes undeletable for some reason.
// Instead, fail silently, at some point somebody might notice that auto-deploy failed.
if (file_exists($file))
    exit;

$directory = __DIR__;
$commands = [
    'git fetch --all',
    'git reset --hard origin/master',
    'composer update',
    'git rev-parse HEAD > VERSION'
];

foreach ($commands as $command)
    echo shell_exec('cd ' . $directory . ' && ' . $command);

Update composer when pulling in a new version


<?php

require_once 'Admin/pages/AdminApproval.php';
require_once 'Site/dataobjects/SiteComment.php';

/**
 * Abstract approval page
 *
 * @package   Site
 * @copyright 2008-2009 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SiteCommentApprovalPage extends AdminApproval
{
	// {{{ protected function approve()

	protected function approve()
	{
		$this->data_object->status = SiteComment::STATUS_PUBLISHED;
		$this->data_object->save();
	}

	// }}}
}

?>

<?php

require_once 'Admin/pages/AdminApproval.php';
require_once 'Site/dataobjects/SiteComment.php';

/**
 * Abstract approval page
 *
 * @package   Site
 * @copyright 2008-2009 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SiteCommentApprovalPage extends AdminApproval
{
	// {{{ protected function initInternal()

	protected function initInternal()
	{
		parent::initInternal();
		$this->ui->getWidget('delete_button')->title = Site::_('Deny');
	}

	// }}}

	// {{{ protected function approve()

	protected function approve()
	{
		$this->data_object->status = SiteComment::STATUS_PUBLISHED;
		$this->data_object->save();
	}

	// }}}
	// {{{ protected function delete()

	protected function delete()
	{
		$this->data_object->status = SiteComment::STATUS_UNPUBLISHED;
		$this->data_object->save();
	}

	// }}}
}

?>

Make SiteComment review actions the same as the actions displayed on the comment index.

svn commit r69356


<?php

/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Clastic\TextBundle\Form\Module;

use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * NodeTypeExtension.
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class TextFormExtension extends AbstractNodeTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->getTabHelper($builder)->findTab('general')
            ->add('body', 'wysiwyg', array(
                'label' => 'text.form.tab.general.field.body',
            ));
    }
}

<?php

/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Clastic\TextBundle\Form\Module;

use Clastic\BackofficeBundle\Form\Type\WysiwygType;
use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * NodeTypeExtension.
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class TextFormExtension extends AbstractNodeTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->getTabHelper($builder)->findTab('general')
            ->add('body', WysiwygType::class, array(
                'label' => 'text.form.tab.general.field.body',
            ));
    }
}

Remove deprecated calls to prepare for 3.0


<?php

namespace Yusef\Channels;

use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * Class FirebaseChannel
 * @package Yusef\Channels
 */
class FirebaseChannel
{
    /**
     * @const The API URL for Firebase
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

    /**
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * @param mixed $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        /** @var FcmMessage $message */
        $message = $notification->toFcm($notifiable);

        if (is_null($message->getTo())) {
            if (!$to = $notifiable->routeNotificationFor('fcm')) {
                return;
            }

            $message->to($to);
        }

        $response   = $this->client->post(self::API_URI, [
            'headers' => [
                'Authorization' => 'key=' . $this->getApiKey(),
                'Content-Type'  => 'application/json',
            ],
            'body' => $message->formatData(),
        ]);

        // dd(json_decode($data)->data, $response->getBody()->getContents());
    }

    /**
     * @return string
     */
    private function getApiKey()
    {
        return config('services.fcm.key');
    }
}

<?php

namespace Yusef\Channels;

use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * Class FirebaseChannel
 * @package Yusef\Channels
 */
class FirebaseChannel
{
    /**
     * @const The API URL for Firebase
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

    /**
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * @param mixed $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        /** @var FcmMessage $message */
        $message = $notification->toFcm($notifiable);

        if (is_null($message->getTo())) {
            if (!$to = $notifiable->routeNotificationFor('fcm')) {
                return;
            }

            $message->to($to);
        }

        $this->client->request('post', self::API_URI, [
            'verify' => false,
            'headers' => [
                'Authorization' => 'key=' . $this->getApiKey(),
                'Content-Type'  => 'application/json',
            ],
            'body' => $message->formatData(),
        ]);
    }

    /**
     * @return string
     */
    private function getApiKey()
    {
        return config('services.fcm.key');
    }
}

Set curl ssl verify to false.

Set curl ssl verify to false.


<?php

define('REQUEST_MICROTIME', microtime(true));
$basePath = dirname(__DIR__);
defined('BASE_PATH') || define('BASE_PATH', $basePath);
chdir($basePath);

// Composer autoloading
if (file_exists($basePath . '/vendor/autoload.php')) {
    $loader = include $basePath . '/vendor/autoload.php';
}
$modules = array();
if ($handle = opendir(BASE_PATH . '/test/module')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry !== "." && $entry !== "..") {
            $modules[] = $entry;
        }
    }
    closedir($handle);
}
foreach ($modules as $dir) {

    if ($dir !== "Bootstrap.php") {
        $loader->add($dir, BASE_PATH . '/test/module/' . $dir . '/src/' . $dir);
        if (file_exists(BASE_PATH . '/test/module/' . $dir . '/autoload_classmap.php')) {
            $classMap = require BASE_PATH . '/test/module/' . $dir . '/autoload_classmap.php';
            if ($classMap) {
                $loader->addClassMap($classMap);
            }
        }
    }
}
Zend\Mvc\Application::init(require $basePath . '/test/config/application.config.php');

<?php

$basePath = dirname(__DIR__);
defined('BASE_PATH') || define('BASE_PATH', $basePath);
chdir($basePath);

// Composer autoloading
if (file_exists($basePath . '/vendor/autoload.php')) {
    $loader = include $basePath . '/vendor/autoload.php';
}
$modules = array();
if ($handle = opendir(BASE_PATH . '/test/module')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry !== "." && $entry !== "..") {
            $modules[] = $entry;
        }
    }
    closedir($handle);
}
foreach ($modules as $dir) {

    if ($dir !== "Bootstrap.php") {
        $loader->add($dir, BASE_PATH . '/test/module/' . $dir . '/src/' . $dir);
        if (file_exists(BASE_PATH . '/test/module/' . $dir . '/autoload_classmap.php')) {
            $classMap = require BASE_PATH . '/test/module/' . $dir . '/autoload_classmap.php';
            if ($classMap) {
                $loader->addClassMap($classMap);
            }
        }
    }
}
Zend\Mvc\Application::init(require $basePath . '/test/config/application.config.php');

Fix for test to pass build

Fix for test to pass build


<?php

namespace Amp\Loop;

// @codeCoverageIgnoreStart
class DriverFactory {
    /**
     * Creates a new loop instance and chooses the best available driver.
     *
     * @return Driver
     *
     * @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER
     */
    public function create(): Driver {
        if ($driver = $this->createDriverFromEnv()) {
            return $driver;
        }

        if (UvDriver::isSupported()) {
            return new UvDriver;
        }

        if (EvDriver::isSupported()) {
            return new EvDriver;
        }

        if (EventDriver::isSupported()) {
            return new EventDriver;
        }

        return new NativeDriver;
    }

    private function createDriverFromEnv() {
        $driver = \getenv("AMP_LOOP_DRIVER");

        if (!$driver) {
            return null;
        }

        if (!\class_exists($driver)) {
            throw new \Error(\sprintf(
                "Driver '%s' does not exist, falling back to default driver.",
                $driver
            ));
        }

        if (!\is_subclass_of($driver, Driver::class)) {
            throw new \Error(\sprintf(
                "Driver '%s' is not a subclass of '%s', falling back to default driver.",
                $driver,
                Driver::class
            ));
        }

        return new $driver;
    }
}
// @codeCoverageIgnoreEnd

<?php

namespace Amp\Loop;

// @codeCoverageIgnoreStart
class DriverFactory {
    /**
     * Creates a new loop instance and chooses the best available driver.
     *
     * @return Driver
     *
     * @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER
     */
    public function create(): Driver {
        if ($driver = $this->createDriverFromEnv()) {
            return $driver;
        }

        if (UvDriver::isSupported()) {
            return new UvDriver;
        }

        if (EvDriver::isSupported()) {
            return new EvDriver;
        }

        if (EventDriver::isSupported()) {
            return new EventDriver;
        }

        return new NativeDriver;
    }

    private function createDriverFromEnv() {
        $driver = \getenv("AMP_LOOP_DRIVER");

        if (!$driver) {
            return null;
        }

        if (!\class_exists($driver)) {
            throw new \Error(\sprintf(
                "Driver '%s' does not exist.",
                $driver
            ));
        }

        if (!\is_subclass_of($driver, Driver::class)) {
            throw new \Error(\sprintf(
                "Driver '%s' is not a subclass of '%s'.",
                $driver,
                Driver::class
            ));
        }

        return new $driver;
    }
}
// @codeCoverageIgnoreEnd

Remove fallback part from error messages


<?php

namespace BringYourOwnIdeas\Maintenance\Tests\Util;

use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use PHPUnit_Framework_TestCase;
use SilverStripe\Dev\SapphireTest;

/**
 * @mixin PHPUnit_Framework_TestCase
 */
class ComposerLoaderTest extends SapphireTest
{
    public function testGetJson()
    {
        $loader = new ComposerLoader(__DIR__ . '/Fixtures');
        $this->assertNotEmpty(
            $loader->getJson()->name,
            'JSON file is loaded and parsed'
        );
    }

    public function testGetLock()
    {
        $loader = new ComposerLoader(__DIR__ . '/Fixtures');
        $this->assertNotEmpty(
            $loader->getLock()->packages,
            'Lock file is loaded and parsed'
        );
    }
}

<?php

namespace BringYourOwnIdeas\Maintenance\Tests\Util;

use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use PHPUnit_Framework_TestCase;
use SilverStripe\Dev\SapphireTest;

/**
 * @mixin PHPUnit_Framework_TestCase
 */
class ComposerLoaderTest extends SapphireTest
{
    public function testGetJson()
    {
        $loader = new ComposerLoader(__DIR__ . '/Fixtures');
        $this->assertNotEmpty(
            $loader->getJson()->require->{'silverstripe/framework'},
            'JSON file is loaded and parsed'
        );
    }

    public function testGetLock()
    {
        $loader = new ComposerLoader(__DIR__ . '/Fixtures');
        $this->assertNotEmpty(
            $loader->getLock()->packages,
            'Lock file is loaded and parsed'
        );
    }
}

Revert "FIX Assert not empty on something that actually is in every composer.json"

This reverts commit f8cf837f6b953713c86747803808e228c648a8a4.


<?php Plugins::act( 'theme_searchform_before' ); ?>
     <form method="get" id="searchform" action="<?php URL::out('search'); ?>">

<input type="text" id="s" name="criteria" value="<?php if ( isset( $criteria ) ) { echo htmlentities(utf8_decode($criteria)); } ?>"> <input type="submit" id="searchsubmit" value="Go!">

     </form>
<?php Plugins::act( 'theme_searchform_after' ); ?>

<?php Plugins::act( 'theme_searchform_before' ); ?>
     <form method="get" id="searchform" action="<?php URL::out('search'); ?>">

<input type="text" id="s" name="criteria" value="<?php if ( isset( $criteria ) ) { echo htmlentities($criteria, ENT_COMPAT, 'UTF-8'); } ?>"> <input type="submit" id="searchsubmit" value="Go!">

     </form>
<?php Plugins::act( 'theme_searchform_after' ); ?>

Fix the invalid characters shown in search form of K2 for mulit-byte characters.

git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@923 653ae4dd-d31e-0410-96ef-6bf7bf53c507


<?php

require 'predis-0.8.3/Autoloader.php';
Predis\Autoloader::register();

$redis_profile = Predis\Profile\ServerProfile::get('2.6');

//connect (by default 127.0.0.1:6379)
$redis = new Predis\Client(array(
		'host'     => '127.0.0.1',
		'port'     => 6379,
		'profile'  => $redis_profile
	)
);

//js command will execute JS script in redis
//return will be JSON encoded, predis will reencode in normal JS array
var_dump(
	$redis->js("return 2+2*2;")
);

//In JS we have a redis object, on this object we can call any redis command, like set, get, incr etc...
//So let`s make a "hello" key, with "world" value, and get it back to PHP
var_dump(
	$redis->js(
		'redis.set("hello","world"); return redis.get("hello");'
	)
);

?>

<?php

require 'predis-0.8.3/Autoloader.php';
Predis\Autoloader::register();

//connect (by default 127.0.0.1:6379)
$redis = new Predis\Client();

//js command will execute JS script in redis
//return will be JSON encoded, predis will reencode in normal JS array
var_dump(
	$redis->js("return 2+2*2;")
);

//In JS we have a redis object, on this object we can call any redis command, like set, get, incr etc...
//So let`s make a "hello" key, with "world" value, and get it back to PHP
var_dump(
	$redis->js(
		'redis.set("hello","world"); return redis.get("hello");'
	)
);

?>

Revert "[*] Fix predis example"

Revert "[*] Fix predis example"

This reverts commit bd8eec1b176e07c19427b09f6c8b65f4527fd71c.


<?php
include_once('phpviddler.php');

class Php5viddler extends Phpviddler {
  function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) {
    $result = parent::sendRequest($method, $args, $postmethod);

    if($tryagain && is_null($result)) {
      $result = parent::sendRequest($method, $args, $postmethod, false);
    } elseif(is_null($result)) {
      throw new ViddlerException("No response", $method, 8888, 'n/a');
    }

    if(is_array($result) && $result['error']) {
      throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']);
    }

		return $result;
  }

}

class ViddlerException extends Exception {
  var $details;
  var $method;

  public function __construct($message, $method, $code=0, $details='') {
    $this->details = $details;
    $this->method = $method;
    parent::__construct($message, $code);
  }

  public function getDetails() {
    return $this->details;
  }

  public function __toString() {
    return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n";
  }
}

?>

<?php
include_once('phpviddler.php');
// uses('RequestCache');
loadModels();
$GLOBALS['total_requests'] = 0;
$GLOBALS['total_request_time'] = 0;

class Php5viddler extends Phpviddler {
  var $requireCache = false;

  function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) {
    $result = parent::sendRequest($method, $args, $postmethod);

    if($tryagain && is_null($result)) {
      $result = parent::sendRequest($method, $args, $postmethod, false);
    } elseif(is_null($result)) {
      throw new ViddlerException("No response", $method, 8888, 'n/a');
    }

    if(is_array($result) && $result['error']) {
      throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']);
    }

		return $result;
  }

}

class ViddlerException extends Exception {
  var $details;
  var $method;

  public function __construct($message, $method, $code=0, $details='') {
    $this->details = $details;
    $this->method = $method;
    parent::__construct($message, $code);
  }

  public function getDetails() {
    return $this->details;
  }

  public function __toString() {
    return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n";
  }
}

?>

Revert "Removing a few lines that had to do with a different project"

This reverts commit 27252a00156f27a96df7acd8ae5f7450d84c7cc0.


<?php

include '../analytics-key.inc.php';

// Override any of the default settings below:

$config['site_title'] = 'schmitt.co';                 // Site title
$config['theme'] = 'default';                         // Set the theme (defaults to "default")

// adv-meta
$config['adv_meta_values'] = array('description' => 'Description', 'tags' => 'Tags');

// Google Analytics
$config['google_tracking_id'] = $ANALYTICS_TRACKING_ID;

/*
$config['base_url'] = '';                             // Override base URL (e.g. http://example.com)
$config['date_format'] = 'jS M Y';                // Set the PHP date format
$config['twig_config'] = array(                        // Twig settings
        'cache' => false,                                        // To enable Twig caching change this to CACHE_DIR
        'autoescape' => false,                                // Autoescape Twig vars
        'debug' => false                                        // Enable Twig debug
);
$config['pages_order_by'] = 'alpha';        // Order pages by "alpha" or "date"
$config['pages_order'] = 'asc';                        // Order pages "asc" or "desc"
$config['excerpt_length'] = 50;                        // The pages excerpt length (in words)

// To add a custom config setting:

$config['custom_setting'] = 'Hello';         // Can be accessed by {{ config.custom_setting }} in a theme

*/

?>

<?php

include '../paasswd/analytics-key.inc.php';

// Override any of the default settings below:

$config['site_title'] = 'schmitt.co';                 // Site title
$config['theme'] = 'default';                         // Set the theme (defaults to "default")

// adv-meta
$config['adv_meta_values'] = array('description' => 'Description', 'tags' => 'Tags');

// Google Analytics
$config['google_tracking_id'] = $ANALYTICS_TRACKING_ID;

/*
$config['base_url'] = '';                             // Override base URL (e.g. http://example.com)
$config['date_format'] = 'jS M Y';                // Set the PHP date format
$config['twig_config'] = array(                        // Twig settings
        'cache' => false,                                        // To enable Twig caching change this to CACHE_DIR
        'autoescape' => false,                                // Autoescape Twig vars
        'debug' => false                                        // Enable Twig debug
);
$config['pages_order_by'] = 'alpha';        // Order pages by "alpha" or "date"
$config['pages_order'] = 'asc';                        // Order pages "asc" or "desc"
$config['excerpt_length'] = 50;                        // The pages excerpt length (in words)

// To add a custom config setting:

$config['custom_setting'] = 'Hello';         // Can be accessed by {{ config.custom_setting }} in a theme

*/

?>

Update Google Analystics Key path

Update Google Analystics Key path


<?php
    class Country extends ActiveRecordBase {
        public $name;
        public $id;
        public $shortname;

        public static function findByName( $name ) {
            $res = db_select_one( "countries", array( 'id' ), compact( "name" ) );
            if ( $res == false ) {
                throw new ModelNotFoundException();
            }
            return new Country( $res[ 'id' ] );
        }

        public function __construct( $id = false ) {
            if ( $id ) {
                $row = db_select_one( "countries", array( 'name', 'shortname' ), compact( "id" ) );
                $this->name = $row[ 'name' ];
                $this->id = $id;
                $this->shortname = $row[ 'shortname' ];
            }
        }

        public static function findAll() {
            return db_select( 'countries' );
        }

        public static function onList( $country ) {
            $countries = Country::findAll();
            foreach ( $countries as $valid ) {
                if ( $valid[ 'name' ] === $country ) {
                    return true;
                }
            }
            return false;
        }
    }
?>

<?php
    class Country extends ActiveRecordBase {
        public $name;
        public $id;
        public $shortname;

        public static function findByName( $name ) {
            $res = db_select_one( "countries", array( 'id' ), compact( "name" ) );
            if ( $res == false ) {
                throw new ModelNotFoundException();
            }
            return new Country( $res[ 'id' ] );
        }

        public static function findAll() {
            return db_select( 'countries' );
        }

        public function __construct( $id = false ) {
            if ( $id ) {
                $row = db_select_one( "countries", array( 'name', 'shortname' ), compact( "id" ) );
                $this->name = $row[ 'name' ];
                $this->id = $id;
                $this->shortname = $row[ 'shortname' ];
            }
        }
?>

Remove useless function and move static methods on top


<?= $this->get('game')->name; ?>
<a href="<?= $this->get('edit-link'); ?>">Edit

    Created at: <?= $this->get('game')->created; ?>

    Last modified: <?= $this->get('game')->updated; ?>

Add a little bit more details

Add a little bit more details


<?php

/*
 * This file is part of the Active Collab Utils project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\ConfigLoader\Exception;

use Exception;
use RuntimeException;

class ValidationException extends RuntimeException
{
    private $missing_options = [];

    private $missing_option_values = [];

    public function __construct($message = '', $code = 0, Exception $previous = null)
    {
        if (empty($message)) {
            $message = 'Found config options do not match configured requirements.';
        }

        parent::__construct($message, $code, $previous);
    }

    public function &missing($option_name)
    {
        $this->missing_options[] = $option_name;

        return $this;
    }

    public function &missingValue($option_name)
    {
        $this->missing_option_values[] = $option_name;

        return $this;
    }

    public function hasErrors()
    {
        return !empty($this->missing_options) || !empty($this->missing_option_values);
    }
}

<?php

/*
 * This file is part of the Active Collab Utils project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\ConfigLoader\Exception;

use Exception;
use RuntimeException;

class ValidationException extends RuntimeException
{
    private $missing_options = [];

    private $missing_option_values = [];

    public function __construct($message = '', $code = 0, Exception $previous = null)
    {
        if (empty($message)) {
            $message = 'Found config options do not match configured requirements.';
        }

        parent::__construct($message, $code, $previous);
    }

    public function &missing($option_name)
    {
        if (!in_array($option_name, $this->missing_options)) {
            $this->missing_options[] = $option_name;
            $this->rebuildExceptionMessage();
        }

        return $this;
    }

    public function &missingValue($option_name)
    {
        if (!in_array($option_name, $this->missing_option_values)) {
            $this->missing_option_values[] = $option_name;
            $this->rebuildExceptionMessage();
        }

        return $this;
    }

    public function hasErrors()
    {
        return !empty($this->missing_options) || !empty($this->missing_option_values);
    }

    private function rebuildExceptionMessage()
    {
        $this->message = 'Found config options do not match configured requirements.';

        if (!empty($this->missing_options)) {
            $this->message .= ' Options not present: ' . implode(', ', $this->missing_options) . '.';
        }

        if (!empty($this->missing_option_values)) {
            $this->message .= ' Options not present, or empty: ' . implode(', ', $this->missing_option_values) . '.';
        }
    }
}

Improve config validation exception message


<?php namespace SchemaExtended;

use Illuminate\Database\Schema\Blueprint as IlluminateBlueprint;
use Illuminate\Support\Fluent;

/**
 * Extended version of Blueprint with
 * support of 'set' data type
 */
class Blueprint extends IlluminateBlueprint
{
    /**
     * Create a new integer (4-byte) column on the table.
     *
     * @param  string  $column
     * @param  bool  $autoIncrement
     * @param  bool  $unsigned
     * @return \Illuminate\Support\Fluent
     */
    public function integer($column, $autoIncrement = false, $unsigned = false, $length)
    {
        return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned', 'length'));
    }

}

<?php
namespace SchemaExtended;

use Illuminate\Database\Schema\Blueprint as IlluminateBlueprint;
use Illuminate\Support\Fluent;

/**
 * Extended version of Blueprint with
 * support of 'set' data type
 */
class Blueprint extends IlluminateBlueprint
{
    /**
     * Create a new integer (4-byte) column on the table.
     *
     * @param  string  $column
     * @param  bool  $autoIncrement
     * @param  bool  $unsigned
     * @param  int  $length
     * @return \Illuminate\Support\Fluent
     */
    public function integer($column, $autoIncrement = false, $unsigned = false, $length = null)
    {
        return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned', 'length'));
    }

    /**
     * Create a new auto-incrementing integer (4-byte) column on the table.
     *
     * @param  string  $column
     * @param  int  $length
     * @return \Illuminate\Support\Fluent
     */
    public function increments($column, $length = null)
    {
        return $this->unsignedInteger($column, true, $length);
    }

    /**
     * Create a new unsigned integer (4-byte) column on the table.
     *
     * @param  string  $column
     * @param  bool  $autoIncrement
     * @param  int  $length
     * @return \Illuminate\Support\Fluent
     */
    public function unsignedInteger($column, $autoIncrement = false, $length = null)
    {
        return $this->integer($column, $autoIncrement, true, $length);
    }
}

Add feature to change increments length

Add feature to change increments length


<?php

namespace JGM\TableBundle\Table\Pagination\Strategy;

/**
 * The StrategyFactory will choose the right pagination
 * strategy in dependency of total pages and maximal pages.
 *
 * @author	Jan Mühlig <mail@janmuehlig.de>
 * @since	1.0
 */
class StrategyFactory
{
	/**
	 * Creates the proper strategy considered by total and maximal pages.
	 *
	 * @param int $totalPages		Number of total pages.
	 * @param int $maxPages			Number of maximal pages.
	 *
	 * @return StrategyInterface	Proper strategy.
	 */
	public static function getStrategy($totalPages, $maxPages)
	{
		if($totalPages > $maxPages)
		{
			return new SimpleLimitStrategy();
		}
		else
		{
			return new AllPagesStrategy();
		}
	}
}

<?php

namespace JGM\TableBundle\Table\Pagination\Strategy;

/**
 * The StrategyFactory will choose the right pagination
 * strategy in dependency of total pages and maximal pages.
 *
 * @author	Jan Mühlig <mail@janmuehlig.de>
 * @since	1.0
 */
class StrategyFactory
{
	/**
	 * Creates the proper strategy considered by total and maximal pages.
	 *
	 * @param int $totalPages		Number of total pages.
	 * @param int $maxPages			Number of maximal pages.
	 *
	 * @return StrategyInterface	Proper strategy.
	 */
	public static function getStrategy($totalPages, $maxPages)
	{
		if($maxPages !== null && $totalPages > $maxPages)
		{
			return new SimpleLimitStrategy();
		}
		else
		{
			return new AllPagesStrategy();
		}
	}
}

Bugifx: Use all pages strategy, if no max is defined.


<?php

namespace Z38\SwissPayment;

/**
 * This class holds a unstructured representation of a postal address
 */
class UnstructuredPostalAddress implements PostalAddressInterface
{
    /**
     * @var string
     */
    protected $adrLine1;

    /**
     * @var string
     */
    protected $adrLine2;

    /**
     * @var string
     */
    protected $country;

    /**
     * Constructor
     *
     * @param string    $adrLine1   Street name and house number
     * @param string    $ardLine2   Postcode and town
     * @param string    $country    Country code (ISO 3166-1 alpha-2)
     */
    public function __construct($adrLine1 = null, $ardLine2, $country = 'CH')
    {
        $this->adrLine1 = $adrLine1;
        $this->adrLine2 = $ardLine2;
        $this->country = (string) $country;
    }

    /**
     * {@inheritdoc}
     */
    public function asDom(\DOMDocument $doc)
    {
        $root = $doc->createElement('PstlAdr');

        $root->appendChild($doc->createElement('Ctry', $this->country));
        if (null !== $this->adrLine1) {
            $root->appendChild($doc->createElement('AdrLine', $this->adrLine1));
        }
        $root->appendChild($doc->createElement('AdrLine', $this->adrLine2));

        return $root;
    }
}

<?php

namespace Z38\SwissPayment;

/**
 * This class holds a unstructured representation of a postal address
 */
class UnstructuredPostalAddress implements PostalAddressInterface
{
    /**
     * @var array
     */
    protected $addressLines;

    /**
     * @var string
     */
    protected $country;

    /**
     * Constructor
     *
     * @param string $addressLine1 Street name and house number
     * @param string $addressLine2 Postcode and town
     * @param string $country      Country code (ISO 3166-1 alpha-2)
     */
    public function __construct($addressLine1 = null, $addressLine2 = null, $country = 'CH')
    {
        $this->addressLines = array();
        if ($addressLine1 !== null) {
            $this->addressLines[] = $addressLine1;
        }
        if ($addressLine2 !== null) {
            $this->addressLines[] = $addressLine2;
        }
        $this->country = (string) $country;
    }

    /**
     * {@inheritdoc}
     */
    public function asDom(\DOMDocument $doc)
    {
        $root = $doc->createElement('PstlAdr');

        $root->appendChild($doc->createElement('Ctry', $this->country));
        foreach ($this->addressLines as $line) {
            $root->appendChild($doc->createElement('AdrLine', $line));
        }

        return $root;
    }
}

Allow any address line to be null

Allow any address line to be null


<?php

namespace MovingImage\Client\VMPro\Entity;

use JMS\Serializer\Annotation\Type;
use MovingImage\Meta\Interfaces\VideoManagerInterface;

/**
 * Class VideoManager.
 */
class VideoManager implements VideoManagerInterface
{
    /**
     * @Type("string")
     */
    private $id;

    /**
     * @Type("string")
     */
    private $name;

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

    /**
     * @param $id
     *
     * @return VideoManager
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

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

    /**
     * @param $name
     *
     * @return VideoManager
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }
}

<?php

namespace MovingImage\Client\VMPro\Entity;

use JMS\Serializer\Annotation\Type;
use MovingImage\Meta\Interfaces\VideoManagerInterface;

/**
 * Class VideoManager.
 */
class VideoManager implements VideoManagerInterface
{
    /**
     * @Type("integer")
     */
    private $id;

    /**
     * @Type("string")
     */
    private $name;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param $id integer
     *
     * @return VideoManager
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

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

    /**
     * @param $name string
     *
     * @return VideoManager
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }
}

Change return type of ID to integer

Change return type of ID to integer


<?php

namespace Code16\Sharp\Http\Api;

class EntityListController extends ApiController
{

    /**
     * @param string $entityKey
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($entityKey)
    {
        sharp_check_ability("entity", $entityKey);

        $list = $this->getListInstance($entityKey);
        $list->buildListConfig();

        return response()->json([
            "containers" => $list->dataContainers(),
            "layout" => $list->listLayout(),
            "data" => $list->data(),
            "config" => $list->listConfig()
        ]);
    }

    /**
     * Call for reorder instances.
     *
     * @param string $entityKey
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($entityKey)
    {
        sharp_check_ability("update", $entityKey);

        $list = $this->getListInstance($entityKey);
        $list->reorderHandler()->reorder(
            request("instances")
        );

        return response()->json([
            "ok" => true
        ]);
    }
}

<?php

namespace Code16\Sharp\Http\Api;

class EntityListController extends ApiController
{

    /**
     * @param string $entityKey
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($entityKey)
    {
        sharp_check_ability("entity", $entityKey);

        $list = $this->getListInstance($entityKey);
        $list->buildListConfig();

        return response()->json([
            "containers" => $list->dataContainers(),
            "layout" => $list->listLayout(),
            "data" => $list->data(),
            "config" => $list->listConfig()
        ]);
    }

    /**
     * Call for reorder instances.
     *
     * @param string $entityKey
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($entityKey)
    {
        sharp_check_ability("update", $entityKey);

        $list = $this->getListInstance($entityKey);
        $list->buildListConfig();

        $list->reorderHandler()->reorder(
            request("instances")
        );

        return response()->json([
            "ok" => true
        ]);
    }
}

Fix reorder call in controller

Fix reorder call in controller


<?php

/**
 * This file is part of endobox.
 *
 * (c) 2015-2016 YouniS Bensalah <younis.bensalah@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace endobox;

/**
 *
 */
class EvalRendererDecorator extends RendererDecorator
{

    /**
     *
     */
    public function render(Renderable $input, array &$data = null, array $shared = null) : string
    {
        $code = parent::render($input, $data, $shared);
        if (\strpos($code, '<?php') !== false) {
            return (function (&$_) use (&$data, &$shared) {
                if ($data !== null) {
                    \extract($data, EXTR_SKIP | EXTR_REFS);
                }
                if ($shared !== null) {
                    foreach ($shared as &$x) {
                        \extract($x, EXTR_SKIP | EXTR_REFS);
                    }
                }
                \ob_start();
                eval('?>' . $_);
                return \ob_get_clean();
            })($code);
        }
        return $code;
    }

}

<?php

/**
 * This file is part of endobox.
 *
 * (c) 2015-2016 YouniS Bensalah <younis.bensalah@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace endobox;

/**
 *
 */
class EvalRendererDecorator extends RendererDecorator
{

    /**
     *
     */
    public function render(Renderable $input, array &$data = null, array $shared = null) : string
    {
        $code = parent::render($input, $data, $shared);
        if (\strpos($code, '<?php') !== false) {
            return (function (&$_) use (&$data, &$shared) {
                if ($data !== null) {
                    \extract($data, EXTR_SKIP | EXTR_REFS);
                    unset($data);
                }
                if ($shared !== null) {
                    foreach ($shared as &$x) {
                        \extract($x, EXTR_SKIP | EXTR_REFS);
                    }
                    unset($shared);
                }
                \ob_start();
                eval('?>' . $_);
                return \ob_get_clean();
            })($code);
        }
        return $code;
    }

}

Clean the variable space by unsetting $data and $shared


<?php namespace Archon\Tests\DataFrame\CSV;

use Archon\DataFrame;

class CSVDataFrameExceptionsTest extends \PHPUnit_Framework_TestCase {

    public function testOverwriteFailCSV() {
        $fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';

        $df = DataFrame::fromArray([
            ['a' => 1, 'b' => 2, 'c' => 3],
            ['a' => 4, 'b' => 5, 'c' => 6],
            ['a' => 7, 'b' => 8, 'c' => 9],
        ]);

        $this->setExpectedException('RuntimeException');
        $df->toCSV($fileName);
    }

}

<?php namespace Archon\Tests\DataFrame\CSV;

use Archon\DataFrame;

class CSVDataFrameExceptionsTest extends \PHPUnit_Framework_TestCase {

    public function testOverwriteFailCSV() {
        $fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';

        $df = DataFrame::fromArray([
            ['a' => 1, 'b' => 2, 'c' => 3],
            ['a' => 4, 'b' => 5, 'c' => 6],
            ['a' => 7, 'b' => 8, 'c' => 9],
        ]);

        $this->setExpectedException('RuntimeException');
        $df->toCSV($fileName);
    }

    public function testInvalidOption() {
        $fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';

        $this->setExpectedException('Archon\Exceptions\UnknownOptionException');
        DataFrame::fromCSV($fileName, ['invalid_option' => 0]);

    }

}

Test coverage for unknown options

Test coverage for unknown options


<?php

namespace MatthiasMullie\Scrapbook\Tests\Providers;

use MatthiasMullie\Scrapbook\Exception\Exception;
use MatthiasMullie\Scrapbook\Tests\AdapterProvider;

class CouchbaseProvider extends AdapterProvider
{
    public function __construct()
    {
        if (!class_exists('CouchbaseCluster')) {
            throw new Exception('ext-couchbase is not installed.');
        }

        $authenticator = new \Couchbase\PasswordAuthenticator();
        $authenticator->username('Administrator')->password('password');

        $cluster = new \CouchbaseCluster('couchbase://couchbase:11210?detailed_errcodes=1');
        $cluster->authenticate($authenticator);
        $bucket = $cluster->openBucket('default');

        // wait 10 seconds should nodes not be healthy; they may be warming up
        for ($i = 0; $i < 10; $i++) {
            $info = $bucket->manager()->info();
            foreach ($info['nodes'] as $node) {
                if ($node['status'] !== 'healthy') {
                    sleep(1);
                }
            }
        }

        parent::__construct(new \MatthiasMullie\Scrapbook\Adapters\Couchbase($bucket));
    }
}

<?php

namespace MatthiasMullie\Scrapbook\Tests\Providers;

use MatthiasMullie\Scrapbook\Exception\Exception;
use MatthiasMullie\Scrapbook\Tests\AdapterProvider;

class CouchbaseProvider extends AdapterProvider
{
    public function __construct()
    {
        if (!class_exists('CouchbaseCluster')) {
            throw new Exception('ext-couchbase is not installed.');
        }

        $authenticator = new \Couchbase\PasswordAuthenticator();
        $authenticator->username('Administrator')->password('password');

        $cluster = new \CouchbaseCluster('couchbase://couchbase:11210?detailed_errcodes=1');
        $cluster->authenticate($authenticator);
        $bucket = $cluster->openBucket('default');

        // wait 10 seconds should nodes not be healthy; they may be warming up
        for ($i = 0; $i < 10; $i++) {
            $healthy = true;
            $info = $bucket->manager()->info();
            foreach ($info['nodes'] as $node) {
                $healthy = $healthy && $node['status'] === 'healthy';
            }
            if (!$healthy) {
                sleep(1);
            }
        }

        parent::__construct(new \MatthiasMullie\Scrapbook\Adapters\Couchbase($bucket));
    }
}

Improve Couchbase health check in tests

Improve Couchbase health check in tests


<?php

namespace MockaTests;

use Mocka\MethodMock;

class MethodMockTest extends \PHPUnit_Framework_TestCase {

    public function testIntegrated() {
        $method = new MethodMock();
        $method->set(function () {
            return 'foo';
        });
        $method->at(1, function () {
            return 'bar';
        });
        $method->at([2, 5], function () {
            return 'zoo';
        });

        $this->assertSame('foo', $method->invoke());
        $this->assertSame('bar', $method->invoke());
        $this->assertSame('zoo', $method->invoke());
        $this->assertSame('foo', $method->invoke());

        $method->set(function () {
            return 'def';
        });
        $this->assertSame('def', $method->invoke());
        $this->assertSame('zoo', $method->invoke());
    }
}

<?php

namespace MockaTests;

use Mocka\MethodMock;

class MethodMockTest extends \PHPUnit_Framework_TestCase {

    public function testIntegrated() {
        $method = new MethodMock();
        $method->set(function () {
            return 'foo';
        });
        $method->at(1, function () {
            return 'bar';
        });
        $method->at([2, 5], function () {
            return 'zoo';
        });

        $this->assertSame('foo', $method->invoke());
        $this->assertSame('bar', $method->invoke());
        $this->assertSame('zoo', $method->invoke());
        $this->assertSame('foo', $method->invoke());

        $method->set(function () {
            return 'def';
        });
        $this->assertSame('def', $method->invoke());
        $this->assertSame('zoo', $method->invoke());
    }

    public function testAssertingArguments() {
        $method = new MethodMock();
        $method->set(function($foo) {
            $this->assertSame('bar', $foo);
        });
        $method->invoke(['bar']);
    }
}

Add test for asserting method arguments

Add test for asserting method arguments


<?php

namespace Knp\JsonSchemaBundle\DependencyInjection\Compiler;

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

class RegisterPropertyHandlerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('json_schema.builder')) {
            return;
        }

        $definition = $container->getDefinition(
            'json_schema.builder'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'json_schema.builder.handler'
        );

        foreach ($taggedServices as $id => $attributes) {
            $definition->addMethodCall(
                'registerPropertyHandler',
                array(new Reference($id), $this->getPriority($attributes))
            );
        }
    }

    private function getPriority(array $attributes = array())
    {
        if (isset($attributes['priority'])) {
            return $attributes['priority'];
        }

        return 0;
    }
}

<?php

namespace Knp\JsonSchemaBundle\DependencyInjection\Compiler;

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

class RegisterPropertyHandlerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('json_schema.builder')) {
            return;
        }

        $definition = $container->getDefinition(
            'json_schema.builder'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'json_schema.builder.handler'
        );

        foreach ($taggedServices as $id => $attributes) {
            $definition->addMethodCall(
                'registerPropertyHandler',
                array(new Reference($id), $this->getPriority($attributes))
            );
        }
    }

    private function getPriority(array $attributes = array())
    {
        if (isset($attributes[0]['priority'])) {
            return $attributes[0]['priority'];
        }

        return 0;
    }
}

Fix priority handling that prevents it to work


<?php
namespace DreadLabs\Vantomas\Mailer;

use DreadLabs\VantomasWebsite\Mail\ComposerInterface;
use DreadLabs\VantomasWebsite\Mail\ConveyableInterface;
use DreadLabs\VantomasWebsite\Mail\Exception\FailedRecipientsException;
use DreadLabs\VantomasWebsite\Mail\LoggerInterface;
use DreadLabs\VantomasWebsite\MailInterface;

class Mail implements MailInterface {

	/**
	 * @var ComposerInterface
	 */
	private $composer;

	/**
	 *
	 * @var LoggerInterface
	 */
	private $logger;

	/**
	 *
	 * @param ComposerInterface $composer
	 * @param LoggerInterface $logger
	 */
	public function __construct(
		ComposerInterface $composer,
		LoggerInterface $logger
	) {
		$this->composer = $composer;
		$this->logger = $logger;
	}

	/**
	 *
	 * @param ConveyableInterface $conveyable
	 */
	public function convey(ConveyableInterface $conveyable) {
		try {
			$message = $this->composer->compose($conveyable);
			$message->send();
		} catch (FailedRecipientsException $e) {
			$this->logger->alert('The mail could not been sent.',
				array(
					'sender' => $e->getSenderList(),
					'receiver' => $e->getReceiverList(),
					'failedRecipients' => $e->getFailedRecipients(),
				)
			);
		}
	}
}

<?php
namespace DreadLabs\VantomasWebsite;

use DreadLabs\VantomasWebsite\Mail\ComposerInterface;
use DreadLabs\VantomasWebsite\Mail\ConveyableInterface;
use DreadLabs\VantomasWebsite\Mail\Exception\FailedRecipientsException;
use DreadLabs\VantomasWebsite\Mail\LoggerInterface;

class Mail implements MailInterface {

	/**
	 * @var ComposerInterface
	 */
	private $composer;

	/**
	 *
	 * @var LoggerInterface
	 */
	private $logger;

	/**
	 *
	 * @param ComposerInterface $composer
	 * @param LoggerInterface $logger
	 */
	public function __construct(
		ComposerInterface $composer,
		LoggerInterface $logger
	) {
		$this->composer = $composer;
		$this->logger = $logger;
	}

	/**
	 *
	 * @param ConveyableInterface $conveyable
	 */
	public function convey(ConveyableInterface $conveyable) {
		try {
			$message = $this->composer->compose($conveyable);
			$message->send();
		} catch (FailedRecipientsException $e) {
			$this->logger->alert('The mail could not been sent.',
				array(
					'sender' => $e->getSenderList(),
					'receiver' => $e->getReceiverList(),
					'failedRecipients' => $e->getFailedRecipients(),
				)
			);
		}
	}
}

Fix mail namespace + usage

[TASK] Fix mail namespace + usage


<?php
include( '../config.php' );

$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;

$data = file_get_contents( $url );

$shows = new SimpleXMLElement( $data );

$items = array();

foreach( $shows->channel->item as $show ):
    preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
    $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );

    if( !isset( $items[ $dateString ] ) ):
        $items[ $dateString ] = array();
    endif;

    $item = array();

    $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );

    $item[ 'name' ] = trim( $matches[ 1 ] );

    $items[ $dateString ][] = $item;
endforeach;

header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );

<?php
include( '../config.php' );

$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;

$data = file_get_contents( $url );

$shows = new SimpleXMLElement( $data );

$items = array();

foreach( $shows->channel->item as $show ):
    preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
    $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );

    if( !isset( $items[ $dateString ] ) ):
        $items[ $dateString ] = array();
    endif;

    $item = array();

    $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );

    $items[ $dateString ][] = $item;
endforeach;

header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );

Remove name from shows because we don't use it any more


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Command;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class HelpCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('help')
            ->setDescription('')
            ->setHelp(<<<EOT
<info>php composer.phar help</info>
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(<<<EOT
<info>Composer - Package Management for PHP</info>
<comment>Composer is a package manager tracking local dependencies of your projects and libraries.
See the "about page" on packagist.org for more information.</comment>
EOT
        );

    }
}

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Command;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class HelpCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('help')
            ->setDescription('')
            ->setHelp(<<<EOT
<info>php composer.phar help</info>
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(<<<EOT
<info>Composer - Package Management for PHP</info>
<comment>Composer is a package manager tracking local dependencies of your projects and libraries.
See http://packagist.org/about for more information.</comment>
EOT
        );

    }
}

Change the wording and link directly to packagist.org.


<?php namespace Exolnet\Database;

use Illuminate\Database\Query\Builder;

class QueryHelper
{
	public static function toSql(Builder $query)
	{
		$sql = $query->toSql();
		$connection = $query->getConnection();
		$pdo = $connection->getPdo();
		$bindings = $query->getBindings();
		$bindings = $connection->prepareBindings($bindings);
		if ( ! empty($bindings)) {
			foreach ($bindings as $binding) {
				$sql = preg_replace('/\?/', $pdo->quote($binding), $sql, 1);
			}
		}
		return $sql;
	}
}

<?php namespace Exolnet\Database;

use DB;
use Illuminate\Database\Query\Builder;

class QueryHelper
{
	/**
	 * @param \Illuminate\Database\Query\Builder $query
	 * @param string                             $alias
	 * @return \Illuminate\Database\Query\Expression
	 */
	public static function subQuery(Builder $query, $alias)
	{
		return DB::raw('(' . $query->toSql() . ') as ' . $alias);
	}

	/**
	 * @param \Illuminate\Database\Query\Builder $query
	 * @return string
	 */
	public static function toSql(Builder $query)
	{
		$sql = $query->toSql();
		$connection = $query->getConnection();
		$pdo = $connection->getPdo();
		$bindings = $query->getBindings();
		$bindings = $connection->prepareBindings($bindings);
		if ( ! empty($bindings)) {
			foreach ($bindings as $binding) {
				$sql = preg_replace('/\?/', $pdo->quote($binding), $sql, 1);
			}
		}
		return $sql;
	}
}

Add a query helper to add subQuery to Eloquent queries


<?php

namespace Driebit\Prepper\Cache\Store;

class FileStore implements StoreInterface
{
    private $path;

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

    public function has($key)
    {
        return file_exists($this->getPath($key));
    }

    public function get($key)
    {
        return new FileBackup($this->getPath($key));
    }

    public function getPath($key)
    {
        return $this->path . DIRECTORY_SEPARATOR . $key;
    }
}

<?php

namespace Driebit\Prepper\Cache\Store;

class FileStore implements StoreInterface
{
    private $path;

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

        if (!file_exists($path)) {
            mkdir($path, 0775, true);
        }
    }

    public function has($key)
    {
        return file_exists($this->getPath($key));
    }

    public function get($key)
    {
        return new FileBackup($this->getPath($key));
    }

    public function getPath($key)
    {
        return $this->path . DIRECTORY_SEPARATOR . $key;
    }
}

Create dir if it doesn't exist yet

Create dir if it doesn't exist yet


<?php

namespace GrowthBeatUnOfficial\GrowthPush;

class GrowthPush
{
    /** @var \GrowthPush $_growthPush */
    private $_growthPush = null;

    public function __construct($aplicationId, $secret, $env = \GrowthPush::ENVIRONMENT_PRODUCTION)
    {
        $growthPush        = new \GrowthPush($aplicationId, $secret, $env);
        $this->_growthPush = $growthPush;
    }

    /**
     * @param $token
     * @param $os
     *
     * @return \GrowthPush\Client
     */
    public function createClient($token, $os)
    {
        /** @var \GrowthBeatUnOfficial\GrowthPush\Client $client */
        $client = new \GrowthBeatUnOfficial\GrowthPush\Client($client->getToken(), $client->getOs());

        return $client->save($this->_growthPush);
    }

    public function createTag($name, $value = null)
    {
        return $this->_growthPush->createTag($this->_growthPush, $name, $value);
    }

    public function createEvent($name, $value = null)
    {
        return $this->_growthPush->createEvent($this->_growthPush, $name, $value);
    }

    public function getGrowthPush()
    {
        return $this->_growthPush;
    }
}

<?php

namespace GrowthBeatUnOfficial\GrowthPush;

class GrowthPush
{
    /** @var \GrowthPush $_growthPush */
    private $_growthPush = null;

    public function __construct($aplicationId, $secret, $env = \GrowthPush::ENVIRONMENT_PRODUCTION)
    {
        $growthPush        = new \GrowthPush($aplicationId, $secret, $env);
        $this->_growthPush = $growthPush;
    }

    /**
     * @param string $token
     * @param string $os
     *
     * @return \GrowthPush\Client
     */
    public function createClient($token, $os)
    {
        /** @var \GrowthBeatUnOfficial\GrowthPush\Client $client */
        $client = new \GrowthBeatUnOfficial\GrowthPush\Client($token, $os);

        return $client->save($this->_growthPush);
    }

    /**
     * @param \GrowthPush\Client|string $client string の場合はtoken
     * @param string                    $name
     * @param string                    $value
     *
     * @return \GrowthBeatUnOfficial\GrowthPush\Tag
     */
    public function createTag($client, $name, $value = null)
    {
        $tag = new \GrowthBeatUnOfficial\GrowthPush\Tag($client, $name, $value);

        return $tag->save($this->_growthPush);
    }

    public function createEvent($name, $value = null)
    {
        return $this->_growthPush->createEvent($this->_growthPush, $name, $value);
    }

    public function getGrowthPush()
    {
        return $this->_growthPush;
    }
}

Fix parameters to instantiate Unofficial classes.


<?php namespace Flarum\Sticky;

use Flarum\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;

class StickyServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot(Dispatcher $events)
    {
        $events->subscribe('Flarum\Sticky\Handlers\StickySaver');
        $events->subscribe('Flarum\Sticky\Handlers\StickySearchModifier');
        $events->subscribe('Flarum\Sticky\Handlers\DiscussionStickiedNotifier');

        $this->forumAssets([
            __DIR__.'/../js/dist/extension.js',
            __DIR__.'/../less/sticky.less'
        ]);

        $this->postType('Flarum\Sticky\DiscussionStickiedPost');

        $this->serializeAttributes('Flarum\Api\Serializers\DiscussionSerializer', function (&$attributes, $model, $serializer) {
            $attributes['isSticky'] = (bool) $model->is_sticky;
            $attributes['canSticky'] = (bool) $model->can($serializer->actor->getUser(), 'sticky');
        });

        $this->discussionGambit('Flarum\Sticky\StickyGambit');

        $this->notificationType('Flarum\Sticky\DiscussionStickiedNotification', ['alert' => true]);

        $this->permission('discussion.sticky');
    }
}

<?php namespace Flarum\Sticky;

use Flarum\Support\ServiceProvider;
use Flarum\Extend\EventSubscribers;
use Flarum\Extend\ForumAssets;
use Flarum\Extend\PostType;
use Flarum\Extend\SerializeAttributes;
use Flarum\Extend\DiscussionGambit;
use Flarum\Extend\NotificationType;
use Flarum\Extend\Permission;

class StickyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->extend(
            new EventSubscribers([
                'Flarum\Sticky\Handlers\StickySaver',
                'Flarum\Sticky\Handlers\StickySearchModifier',
                'Flarum\Sticky\Handlers\DiscussionStickiedNotifier'
            ]),

            new ForumAssets([
                __DIR__.'/../js/dist/extension.js',
                __DIR__.'/../less/sticky.less'
            ]),

            new PostType('Flarum\Sticky\DiscussionStickiedPost'),

            new SerializeAttributes('Flarum\Api\Serializers\DiscussionSerializer', function (&$attributes, $model, $serializer) {
                $attributes['isSticky'] = (bool) $model->is_sticky;
                $attributes['canSticky'] = (bool) $model->can($serializer->actor->getUser(), 'sticky');
            }),

            new DiscussionGambit('Flarum\Sticky\StickyGambit'),

            (new NotificationType('Flarum\Sticky\DiscussionStickiedNotification'))->enableByDefault('alert'),

            new Permission('discussion.sticky')
        );
    }
}

Update for new extension API

Update for new extension API


      Item Name
      Borrower Name
      Borrower NetID
      Pickup Time
      Due Time

<?php
include '../config.php';
include '../db.php';

$fdb = new FlatFileDB($db_filename, $table_sep, $cell_sep);

foreach ($fdb->getTable($loans_table) as $rownum => $row) {
    $class = '';

    if (date($row[5]) < date($dt_fmt)) {
        $class = ' class="late"';
    } elseif ($rownum % 2 == 0) {
        $class = ' class="alt"';
    }

    echo '
';
    echo '' . $row[0] . '	';
    echo '' . $row[1] . '	';
    echo '' . $row[2] . '	';
    echo '' . $row[3] . '	';
    echo '' . $row[4] . '	';
    echo '
';
    $row++;
}

?>

      Item Name
      Borrower Name
      Borrower NetID
      Pickup Time
      Due Time

<?php
include '../config.php';
include '../db.php';

$fdb = new FlatFileDB($db_filename, $table_sep, $cell_sep);

foreach ($fdb->getTable($loans_table) as $rownum => $row) {
    $class = '';

    if (date($row[4]) < date($dt_fmt)) {
        $class = ' class="late"';
    } elseif ($rownum % 2 == 0) {
        $class = ' class="alt"';
    }

    echo '
';
    echo '' . $row[0] . '	';
    echo '' . $row[1] . '	';
    echo '' . $row[2] . '	';
    echo '' . $row[3] . '	';
    echo '' . $row[4] . '	';
    echo '
';
    $row++;
}

?>

Change the due datetime field for calculating late