<?php

namespace ScoutElastic\Payloads;

use Exception;
use Illuminate\Database\Eloquent\Model;

class DocumentPayload extends TypePayload
{
    /**
     * @param Model $model
     * @throws Exception
     */
    public function __construct(Model $model)
    {
        if (!$model->getKey()) {
            throw new Exception(sprintf(
                'The key value must be set to construct a payload for the %s instance.',
                get_class($model)
            ));
        }

        parent::__construct($model);

        $this->payload['id'] = $model->getKey();
        $this->protectedKeys[] = 'id';
    }
}

<?php

namespace ScoutElastic\Payloads;

use Exception;
use Illuminate\Database\Eloquent\Model;

class DocumentPayload extends TypePayload
{
    /**
     * @param Model $model
     * @throws Exception
     */
    public function __construct(Model $model)
    {
        if ($model->getKey() === null) {
            throw new Exception(sprintf(
                'The key value must be set to construct a payload for the %s instance.',
                get_class($model)
            ));
        }

        parent::__construct($model);

        $this->payload['id'] = $model->getKey();
        $this->protectedKeys[] = 'id';
    }
}

Fix getKey check when ($model['id'] === 0)

I have inherited a project which has a row with an id of 0 which causes an exception to be thrown incorrectly.

Looking through $model->getKey() I noticed that it returns 'NULL' if a key doesn't exist but will return '(int) 0' if an 'id' key does exist with value of '(int) 0'.

'(int) 0' will evaluate as false even though it is in fact the correct value.


<?hh // strict

namespace HHVM\UserDocumentation;

use FredEmmott\DefinitionFinder\ScannedBase;
use FredEmmott\DefinitionFinder\ScannedFunctionAbstract;

abstract final class ScannedDefinitionFilters {
  public static function IsHHSpecific(ScannedBase $def): bool {
    $is_hh_specific =
      strpos($def->getName(), 'HH\\') === 0
      || strpos($def->getName(), '__SystemLib\\') === 0
      || $def->getAttributes()->containsKey('__HipHopSpecific')
      || strpos($def->getName(), 'fb_') === 0
      || strpos($def->getName(), 'hphp_') === 0;

    if ($is_hh_specific) {
      return true;
    }

    if (!$def instanceof ScannedFunctionAbstract) {
      return false;
    }

    if ($def->getReturnType()?->getTypeName() === 'Awaitable') {
      return true;
    }

    if (count($def->getGenericTypes()) > 0) {
      return true;
    }

    return false;
  }

  public static function ShouldNotDocument(ScannedBase $def): bool {
    return strpos($def->getName(), "__SystemLib\\") === 0;
  }
}

<?hh // strict

namespace HHVM\UserDocumentation;

use FredEmmott\DefinitionFinder\ScannedBase;
use FredEmmott\DefinitionFinder\ScannedFunctionAbstract;
use FredEmmott\DefinitionFinder\HasScannedGenerics;

abstract final class ScannedDefinitionFilters {
  public static function IsHHSpecific(ScannedBase $def): bool {
    $is_hh_specific =
      strpos($def->getName(), 'HH\\') === 0
      || strpos($def->getName(), '__SystemLib\\') === 0
      || $def->getAttributes()->containsKey('__HipHopSpecific')
      || strpos($def->getName(), 'fb_') === 0
      || strpos($def->getName(), 'hphp_') === 0;

    if ($is_hh_specific) {
      return true;
    }

    if ($def instanceof HasScannedGenerics && $def->getGenericTypes()) {
      return true;
    }

    if (!$def instanceof ScannedFunctionAbstract) {
      return false;
    }

    if ($def->getReturnType()?->getTypeName() === 'Awaitable') {
      return true;
    }

    return false;
  }

  public static function ShouldNotDocument(ScannedBase $def): bool {
    return strpos($def->getName(), "__SystemLib\\") === 0;
  }
}

Include classes and interfaces with generics


<?php

/*
 * @author Mirel Nicu Mitache <mirel.mitache@gmail.com>
 * @package MPF Framework
 * @link    http://www.mpfframework.com
 * @category core package
 * @version 1.0
 * @since MPF Framework Version 1.0
 * @copyright Copyright © 2011 Mirel Mitache
 * @license  http://www.mpfframework.com/licence
 *
 * This file is part of MPF Framework.
 *
 * MPF Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MPF Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MPF Framework.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace mpf\interfaces;

interface TranslatableObjectInterface {

    /**
     * Set a new translator; Must implement \mpf\translators\ITranslator
     */
    public function setTranslator($className);

    /**
     * Get current translator;
     */
    public function getTranslator();

    /**
     * Translate selected text;
     */
    public function translate($text);
}

<?php

/*
 * @author Mirel Nicu Mitache <mirel.mitache@gmail.com>
 * @package MPF Framework
 * @link    http://www.mpfframework.com
 * @category core package
 * @version 1.0
 * @since MPF Framework Version 1.0
 * @copyright Copyright © 2011 Mirel Mitache
 * @license  http://www.mpfframework.com/licence
 *
 * This file is part of MPF Framework.
 *
 * MPF Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MPF Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MPF Framework.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace mpf\interfaces;

interface TranslatableObjectInterface {

    /**
     * Set a new translator; Must implement \mpf\translators\ITranslator
     * @param string|TranslatorInterface $className
     */
    public function setTranslator($className);

    /**
     * Get current translator;
     */
    public function getTranslator() : TranslatorInterface;

    /**
     * Translate selected text;
     * @param string $text
     * @return string
     */
    public function translate(string $text) : string;
}

Change php version to 7

Change php version to 7


<?php
    // Use in the "Post-Receive URLs" section of your GitHub repo.
    if ( $_POST['payload'] && false ) {
        file_put_contents('log/payload.txt', print_r($_POST['payload']), FILE_APPEND);

        $exec_string = 'cd /var/customers/webs/jmm/weltengeschichte.de.repo/ && git reset --hard HEAD && git pull';
        exec ( $exec_string, $output);
        file_put_contents('log/output.txt', $output, FILE_APPEND);
    }

    file_put_contents('log/post.txt', print_r($_POST));
?>

<?php
    // Use in the "Post-Receive URLs" section of your GitHub repo.
    if ( $_POST['payload'] && false ) {
        file_put_contents('log/payload.txt', print_r($_POST['payload']), FILE_APPEND);

        $exec_string = 'cd /var/customers/webs/jmm/weltengeschichte.de.repo/ && git reset --hard HEAD && git pull';
        exec ( $exec_string, $output);
        file_put_contents('log/output.txt', $output, FILE_APPEND);
    }
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    print_r($obj);
    file_put_contents('log/post.txt', print_r($obj, true));
?>

Deploy on push, test 5

Deploy on push, test 5


<?php
use Cake\Routing\Router;

Router::plugin('FrontendBridge', function ($routes) {
	Router::connect('/json_action/:plugin/:controller/:action/*', array('jsonAction' => true));
	Router::connect('/json_action/:controller/:action/*', array('jsonAction' => true));
	$routes->fallbacks('InflectedRoute');
});

<?php
use Cake\Routing\Router;

Router::plugin('FrontendBridge', function ($routes) {
	Router::connect('/json_action/:plugin/:controller/:action/*', [
		'jsonAction' => true
	], [
		'routeClass' => 'DashedRoute'
	]);
	Router::connect('/json_action/:controller/:action/*', [
		'jsonAction' => true
	], [
		'routeClass' => 'DashedRoute'
	]);
	$routes->fallbacks('DashedRoute');
});

Switch to DashedRoute for jsonActions

Switch to DashedRoute for jsonActions


<?php

require_once('tests/php/base.php');

class CashSeedTests extends UnitTestCase {
	function testS3Seed(){
		$settings = new S3Seed(1,1);
		$this->assertIsa($settings, 'S3Seed');
	}
	function testTwitterSeed(){
		$user_id      = 1;
		$settings_id  = 1;
		$twitter      = new TwitterSeed($user_id,$settings_id);
		$this->assertIsa($twitter, 'TwitterSeed');
	}
	function testMailchimpSeed(){
		$settings = new MailchimpSeed('keyblarg-us2');
		$this->assertIsa($settings, 'MailchimpSeed');
		$this->assertTrue($settings->url);
		$this->assertTrue($settings->lists());
		$this->assertTrue($settings->listWebhooks(42));
	}
}
?>

<?php

require_once('tests/php/base.php');

class CashSeedTests extends UnitTestCase {
	function testS3Seed(){
		$settings = new S3Seed(1,1);
		$this->assertIsa($settings, 'S3Seed');
	}
	function testTwitterSeed(){
		$user_id      = 1;
		$settings_id  = 1;
		$twitter      = new TwitterSeed($user_id,$settings_id);
		$this->assertIsa($twitter, 'TwitterSeed');
	}
	function testMailchimpSeed(){
		if(array_key_exists('MAILCHIMP_API_KEY', $_ENV)) {
			$key = $_ENV['MAILCHIMP_API_KEY'];
			$settings = new MailchimpSeed($key);
			$this->assertIsa($settings, 'MailchimpSeed');
			$this->assertTrue($settings->url);
			$this->assertTrue($settings->lists());
			$this->assertTrue($settings->listWebhooks(42));
		} else {
			fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n");
			return;
		}
	}
}
?>

Make the mailchimp tests look for an api key in an environment variable, and skip if it isn't found


<?php

/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\GithubAutolink\Listener;

use Flarum\Event\ConfigureFormatter;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class FormatGithubAutolink
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

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

    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'addGithubAutokinkFormatter']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function addGithubAutokinkFormatter(ConfigureFormatter $event)
    {
        foreach (['CommitAutolink', 'IssueAutolink'] as $plugin) {
            $name = "Github{$plugin}";
            $event->configurator->plugins->set(
                $name,
                "Sijad\\GithubAutolink\\TextFormatter\\Plugins\\{$name}\\Configurator"
            );
        }
    }
}

<?php

/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\GithubAutolink\Listener;

use Flarum\Formatter\Event\Configuring;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class FormatGithubAutolink
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

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

    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(Configuring::class, [$this, 'addGithubAutokinkFormatter']);
    }

    /**
     * @param Configuring $event
     */
    public function addGithubAutokinkFormatter(Configuring $event)
    {
        foreach (['CommitAutolink', 'IssueAutolink'] as $plugin) {
            $name = "Github{$plugin}";
            $event->configurator->plugins->set(
                $name,
                "Sijad\\GithubAutolink\\TextFormatter\\Plugins\\{$name}\\Configurator"
            );
        }
    }
}

Update namespaces for beta 8

Update namespaces for beta 8


<?hh //strict
abstract class Page {
  abstract public function __construct(): void;
  abstract public function render(): :html;
}

<?hh //strict
abstract class Page {
  public string $Title = '';
  public array<Stringish> $Header = [];
  public array<Stringish> $Footer = [];
  abstract public function __construct(): void;
  abstract public function render(): :html;
}

Add Title, Header & Footer to Page

:new: Add Title, Header & Footer to Page


<?php

namespace Illuminated\Testing\Tests\Asserts;

use Illuminated\Testing\Tests\App\Post;
use Illuminated\Testing\Tests\TestCase;

class DatabaseAssertsTest extends TestCase
{
    /** @test */
    public function it_has_database_has_table_assertion()
    {
        $this->assertDatabaseHasTable('posts');
    }

    /** @test */
    public function it_has_database_missing_table_assertion()
    {
        $this->assertDatabaseMissingTable('unicorns');
    }

    /** @test */
    public function it_has_database_has_many_assertion()
    {
        Post::factory()->createMany([
            ['title' => 'First Post'],
            ['title' => 'Second Post'],
            ['title' => 'Third Post'],
        ]);

        $this->assertDatabaseHasMany('posts', [
            ['title' => 'First Post'],
            ['title' => 'Second Post'],
            ['title' => 'Third Post'],
        ]);
    }

    /** @test */
    public function it_has_database_missing_many_assertion()
    {
        $this->assertDatabaseMissingMany('posts', [
            ['title' => 'Fourth Post'],
            ['title' => 'Fifth Post'],
        ]);
    }
}

<?php

namespace Illuminated\Testing\Tests\Asserts;

use Illuminated\Testing\Tests\App\Post;
use Illuminated\Testing\Tests\TestCase;

class DatabaseAssertsTest extends TestCase
{
    /** @test */
    public function it_has_database_has_table_assertion()
    {
        $this->assertDatabaseHasTable('posts');
    }

    /** @test */
    public function it_has_database_missing_table_assertion()
    {
        $this->assertDatabaseMissingTable('unicorns');
    }

    /** @test */
    public function it_has_database_has_many_assertion()
    {
        Post::factory()->create(['title' => 'First Post']);
        Post::factory()->create(['title' => 'Second Post']);
        Post::factory()->create(['title' => 'Third Post']);

        $this->assertDatabaseHasMany('posts', [
            ['title' => 'First Post'],
            ['title' => 'Second Post'],
            ['title' => 'Third Post'],
        ]);
    }

    /** @test */
    public function it_has_database_missing_many_assertion()
    {
        $this->assertDatabaseMissingMany('posts', [
            ['title' => 'Fourth Post'],
            ['title' => 'Fifth Post'],
        ]);
    }
}

Fix tests for the `lowest` stability

Fix tests for the `lowest` stability


@extends('app')

@section('title', $candidate->name)
@section('meta_title', $candidate->name)
@section('meta_description', 'Vote for ' . $candidate->name . ' in ' . setting('site_title') . '.')
@section('meta_image', URL::to($candidate->thumbnail()))

@section('content')

                slug]) }}">

{{ $candidate->name }}

                    name }}" src="{{ $candidate->thumbnail() }}"/>

            @if($candidate->description)

{{ $candidate->description }}

            @endif
            @if ($candidate->photo_source)
                photo_source }}">Photo Credit
            @endif

            @include('votes.form', ['category' => $candidate->category, 'id' => $candidate->id])

            @if(Auth::user() && Auth::user()->admin && $vote_count)

This candidate has {{ $vote_count }} {{ str_plural('vote', $vote_count)}}.

                    slug]) }}">Edit Candidate

            @endif

@stop

@extends('app')

@section('title', $candidate->name)
@section('meta_title', $candidate->name)
@section('meta_description', 'Vote for ' . $candidate->name . ' in ' . setting('site_title') . '.')
@section('meta_image', URL::to($candidate->thumbnail))

@section('content')

                slug]) }}">

{{ $candidate->name }}

                    name }}" src="{{ $candidate->thumbnail }}"/>

            @if($candidate->description)

{{ $candidate->description }}

            @endif
            @if ($candidate->photo_source)
                photo_source }}">Photo Credit
            @endif

            @include('votes.form', ['category' => $candidate->category, 'id' => $candidate->id])

            @if(Auth::user() && Auth::user()->admin && $vote_count)

This candidate has {{ $vote_count }} {{ str_plural('vote', $vote_count)}}.

                    slug]) }}">Edit Candidate

            @endif

@stop

Fix errors with new thumbnail helper.

Fix errors with new thumbnail helper.


@extends('master')

@section('title')
Micropub Config «
@stop

@section('content')

The values for your micropub endpoint.

Me (your url)

{{ $data['me'] }}

Token

{{ $data['token'] }}

Syndication Targets

@foreach ($data['syndication'] as $syn)
{{ $syn['name'] }} ({{ $syn['target'] }})
@endforeach

Media Endpoint

{{ $data['media-endpoint'] }}

Re-query the endpoint.

@stop

@extends('master')

@section('title')
Micropub Config «
@stop

@section('content')

The values for your micropub endpoint.

Me (your url)

{{ $data['me'] }}

Token

{{ $data['token'] }}

Syndication Targets

@if(is_array($data['syndication']))
@foreach ($data['syndication'] as $syn)
{{ $syn['name'] }} ({{ $syn['target'] }})
@endforeach
@else{{ $data['syndication'] }}@endif

Media Endpoint

{{ $data['media-endpoint'] }}

Re-query the endpoint.

@stop

Allow string for when there are no syndication targets


<?php

/**
 * Holds the key for @{class:PhutilOpaqueEnvelope} in a logically distant
 * location so it will never appear in stack traces, etc. You should never need
 * to use this class directly. See @{class:PhutilOpaqueEnvelope} for
 * information about opaque envelopes.
 *
 * @task internal Internals
 */
final class PhutilOpaqueEnvelopeKey {

  private static $key;

/* -(  Internals  )---------------------------------------------------------- */

  /**
   * @task internal
   */
  private function __construct() {
    // <private>
  }

  /**
   * @task internal
   */
  public static function getKey() {
    if (self::$key === null) {
      try {
        self::$key = Filesystem::readRandomBytes(128);
      } catch (Exception $ex) {

        // NOTE: We can't throw here! Otherwise we might get a stack trace
        // including the string that was passed to PhutilOpaqueEnvelope's
        // constructor. Just die() instead.

        die(
          "Unable to read random bytes in PhutilOpaqueEnvelope. (This ".
          "causes an immediate process exit to avoid leaking the envelope ".
          "contents in a stack trace.)");
      }
    }
    return self::$key;
  }

}

<?php

/**
 * Holds the key for @{class:PhutilOpaqueEnvelope} in a logically distant
 * location so it will never appear in stack traces, etc. You should never need
 * to use this class directly. See @{class:PhutilOpaqueEnvelope} for
 * information about opaque envelopes.
 *
 * @task internal Internals
 */
final class PhutilOpaqueEnvelopeKey {

  private static $key;

/* -(  Internals  )---------------------------------------------------------- */

  /**
   * @task internal
   */
  private function __construct() {
    // <private>
  }

  /**
   * @task internal
   */
  public static function getKey() {
    if (self::$key === null) {
      // NOTE: We're using a weak random source because cryptographic levels
      // of security aren't terribly important here and it allows us to use
      // envelopes on systems which don't have a strong random source. Notably,
      // this lets us make it to the readbility check for `/dev/urandom` in
      // Phabricator on systems where we can't read it.
      self::$key = '';
      for ($ii = 0; $ii < 8; $ii++) {
        self::$key .= md5(mt_rand(), $raw_output = true);
      }
    }
    return self::$key;
  }

}

Use weak but dependency-free entropy source in PhutilOpaqueEnvelope

Summary:
If PHP doesn't have access to /dev/urandom, we currently fatal here before we can get to the setup check for it.

To avoid this, use a weaker random source. This doesn't need to be a strong random source, since it's only protecting against accidental disclosure through logs, etc.

Test Plan:
  - Dumped the resulting key and verified it "looked" random.
  - Dumped a bunch of them to a file and gzipped it, verified it got larger.
  - Had user in question apply patch and verified he got to the /dev/urandom setup check ("open_basedir configured crazy").

Reviewers: vrana, btrahan, asherkin

Reviewed By: asherkin

CC: aran

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


<?php

namespace Vision\Hydrator\Strategy;

use Vision\Annotation\Paragraph;
use Vision\Annotation\Symbol;
use Vision\Annotation\Word;
use Zend\Hydrator\Strategy\StrategyInterface;

class SymbolsStrategy implements StrategyInterface
{
    /**
     * @var TextPropertyStrategy
     */
    protected $textPropertyStrategy;

    /**
     * @var BoundingPolyStrategy
     */
    protected $boundingPolyStrategy;

    public function __construct()
    {
        $this->textPropertyStrategy = new TextPropertyStrategy;
        $this->boundingPolyStrategy = new BoundingPolyStrategy;
    }

    /**
     * @param Symbol[] $value
     * @return array
     */
    public function extract($value)
    {
        return array_map(function(Symbol $symbolEntity) {
            return array_filter([
                'property' => $this->textPropertyStrategy->extract($symbolEntity->getProperty()),
                'boundingBox' => $this->boundingPolyStrategy->extract($symbolEntity->getBoundingBox()),
                'text' => $symbolEntity->getSymbols(),
            ]);
        }, $value);
    }

    /**
     * @param array $value
     * @return Symbol[]
     */
    public function hydrate($value)
    {
        $symbolEntities = [];

        foreach ($value as $symbolEntityInfo) {
            $symbolEntities[] = new Symbol(
                $this->textPropertyStrategy->hydrate($symbolEntityInfo['property']),
                $this->boundingPolyStrategy->hydrate($symbolEntityInfo['boundingBox']),
                $symbolEntityInfo['text']
            );
        }

        return $symbolEntities;
    }
}

<?php

namespace Vision\Hydrator\Strategy;

use Vision\Annotation\Paragraph;
use Vision\Annotation\Symbol;
use Vision\Annotation\Word;
use Zend\Hydrator\Strategy\StrategyInterface;

class SymbolsStrategy implements StrategyInterface
{
    /**
     * @var TextPropertyStrategy
     */
    protected $textPropertyStrategy;

    /**
     * @var BoundingPolyStrategy
     */
    protected $boundingPolyStrategy;

    public function __construct()
    {
        $this->textPropertyStrategy = new TextPropertyStrategy;
        $this->boundingPolyStrategy = new BoundingPolyStrategy;
    }

    /**
     * @param Symbol[] $value
     * @return array
     */
    public function extract($value)
    {
        return array_map(function(Symbol $symbolEntity) {
            return array_filter([
                'property' => $this->textPropertyStrategy->extract($symbolEntity->getProperty()),
                'boundingBox' => $this->boundingPolyStrategy->extract($symbolEntity->getBoundingBox()),
                'text' => $symbolEntity->getText(),
            ]);
        }, $value);
    }

    /**
     * @param array $value
     * @return Symbol[]
     */
    public function hydrate($value)
    {
        $symbolEntities = [];

        foreach ($value as $symbolEntityInfo) {
            $symbolEntities[] = new Symbol(
                $this->textPropertyStrategy->hydrate($symbolEntityInfo['property']),
                $this->boundingPolyStrategy->hydrate($symbolEntityInfo['boundingBox']),
                $symbolEntityInfo['text']
            );
        }

        return $symbolEntities;
    }
}

Fix issue detected by scrutinizer

Fix issue detected by scrutinizer


<?php

$config = null; // We're doing this here so it can be instantiated once but used everywhere

final class Config
{

    const MODE = 'staging'; // options are "development", "staging", "production"

    private static $instance;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new Config();
        }

        return self::$instance;
    }

    public function getDbSettings()
    {
        $host = 'MySQLHostStringHere';
        $user = 'UserName';
        $pass = 'TheSecretPassword';
        $database = 'TheDatabaseToUse';
        $supportDatabase = 'PVSupport_dev';

        return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
    }

}

<?php

$config = null; // We're doing this here so it can be instantiated once but used everywhere

final class Config
{

    const MODE = 'staging'; // options are "development", "staging", "production"

    private static $instance;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new Config();
        }

        return self::$instance;
    }

    public function getDbSettings()
    {
        $host = 'MySQLHostStringHere';
        $user = 'UserName';
        $pass = 'TheSecretPassword';
        $database = 'TheDatabaseToUse';
        $supportDatabase = 'PVSupport_dev';

        return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
    }

    public function getMaxPageSize()
    {
        return 10000;
    }

}

Put max page size limit in the config.php file


<?php declare(strict_types=1);

namespace Room11\Jeeves\Tests\Chat\Plugin;

use Room11\Jeeves\Chat\Plugin\Rebecca;

class RebeccaTest extends AbstractPluginTest
{
    /**
     * @inheritdoc
     */
    protected function setUp()
    {
        parent::setUp();

        $this->plugin = new Rebecca($this->client);
    }

    public function testCommandName()
    {
        $this->assertSame(['rebecca'], $this->plugin->getHandledCommands());
    }
}

<?php declare(strict_types=1);

namespace Room11\Jeeves\Tests\Chat\Plugin;

use Room11\Jeeves\Chat\Plugin\Rebecca;

class RebeccaTest extends AbstractPluginTest
{
    /**
     * @inheritdoc
     */
    protected function setUp()
    {
        parent::setUp();

        $this->plugin = new Rebecca($this->client);
    }

    public function testCommandName()
    {
        $this->assertSame('Rebecca', $this->plugin->getName());
        $this->assertSame([], $this->plugin->getEventHandlers());
        $this->assertSame(null, $this->plugin->getMessageHandler());
    }
}

Stop Rebecca test from failing

Stop Rebecca test from failing


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public static $AcceptTypes = array(
        'text/plain',
        'text/x-asm', // some css
        'text/x-php',
    );

    public static $InvalidFileNames = array(
        'nbproject/', // netbeans project files
        '__macosx/',  // mac .zip remnants
        '._'          // mac temp file
    );

    public static function IsValidNameName($name) {
        $lcName = strtolower($name);
        $valid = true;

        foreach (File::$InvalidFileNames as $invalidName) {
            if (strpos($lcName, $invalidName) !== false) {
                $valid = false;
            }
        }

        return $valid;
    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function reviews()
    {
        return $this->belongsTo('App\Review', 'review_id');
    }

}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public static $AcceptTypes = array(
        'text/plain',
        'text/x-asm', // some css
	'text/x-php',
	'text/x-Algol68'
    );

    public static $InvalidFileNames = array(
        'nbproject/', // netbeans project files
        '__macosx/',  // mac .zip remnants
        '._'          // mac temp file
    );

    public static function IsValidNameName($name) {
        $lcName = strtolower($name);
        $valid = true;

        foreach (File::$InvalidFileNames as $invalidName) {
            if (strpos($lcName, $invalidName) !== false) {
                $valid = false;
            }
        }

        return $valid;
    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function reviews()
    {
        return $this->belongsTo('App\Review', 'review_id');
    }

}

Add another file type to the AcceptTypes


<?php
declare(strict_types = 1);

namespace Apha\Saga;

use Apha\Domain\Identity;

class GenericSagaFactory implements SagaFactory
{
    /**
     * @param string $sagaType
     * @param Identity $identity
     * @param AssociationValues $associationValues
     * @return Saga
     * @throws \InvalidArgumentException
     */
    public function createSaga(string $sagaType, Identity $identity, AssociationValues $associationValues): Saga
    {
        return new $sagaType($identity, $associationValues);
    }

    /**
     * @param string $sagaType
     * @return bool
     */
    public function supports(string $sagaType): bool
    {
        // the naive way
        return true;
    }
}

<?php
declare(strict_types = 1);

namespace Apha\Saga;

use Apha\Domain\Identity;

class GenericSagaFactory implements SagaFactory
{
    /**
     * @param string $sagaType
     * @param Identity $identity
     * @param AssociationValues $associationValues
     * @return Saga
     * @throws \InvalidArgumentException
     */
    public function createSaga(string $sagaType, Identity $identity, AssociationValues $associationValues): Saga
    {
        if (!$this->supports($sagaType)) {
            throw new \InvalidArgumentException("This factory does not support Sagas of type '{$sagaType}'.");
        }

        return new $sagaType($identity, $associationValues);
    }

    /**
     * @param string $sagaType
     * @return bool
     */
    public function supports(string $sagaType): bool
    {
        return is_subclass_of($sagaType, Saga::class, true);
    }
}

Check for creating only Saga instances.

Check for creating only Saga instances.


<?php
namespace SimpleSAML\Metadata;

/**
 * Test SAML parsing
 */
class SAMLParserTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Test Registration Info is parsed
     */
    public function testRegistrationInfo()
    {
        $expected = array(
            'registrationAuthority' => 'https://incommon.org',
        );

        $document = \SAML2_DOMDocumentFactory::fromString(
            <<<XML
<EntityDescriptor entityID="theEntityID"
 xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi">
  <Extensions>
    <mdrpi:RegistrationInfo registrationAuthority="https://incommon.org"/>
     </Extensions>
  <SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
  </SPSSODescriptor>
</EntityDescriptor>
XML
        );

        $entities = \SimpleSAML_Metadata_SAMLParser::parseDescriptorsElement($document->documentElement);
        $this->assertArrayHasKey('theEntityID', $entities);
        // RegistrationInfo is accessible in the SP or IDP metadata accessors
        $this->assertEquals($expected, $entities['theEntityID']->getMetadata20SP()['RegistrationInfo']);

    }
}

<?php
namespace SimpleSAML\Metadata;

/**
 * Test SAML parsing
 */
class SAMLParserTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Test Registration Info is parsed
     */
    public function testRegistrationInfo()
    {
        $expected = array(
            'registrationAuthority' => 'https://incommon.org',
        );

        $document = \SAML2_DOMDocumentFactory::fromString(
            <<<XML
<EntityDescriptor entityID="theEntityID"
 xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi">
  <Extensions>
    <mdrpi:RegistrationInfo registrationAuthority="https://incommon.org"/>
     </Extensions>
  <SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
  </SPSSODescriptor>
</EntityDescriptor>
XML
        );

        $entities = \SimpleSAML_Metadata_SAMLParser::parseDescriptorsElement($document->documentElement);
        $this->assertArrayHasKey('theEntityID', $entities);
        // RegistrationInfo is accessible in the SP or IDP metadata accessors
        $metadata = $entities['theEntityID']->getMetadata20SP();
        $this->assertEquals($expected, $metadata['RegistrationInfo']);

    }
}

Fix php 5.3 syntax issue

Fix php 5.3 syntax issue


<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?>
<feed xmlns="http://www.w3.org/2005/Atom"
	  xml:lang="en"
	  xml:base="<?= PROTOCOL_HOST_PORT . \CWA\APP_ROOT ?>">

	<id><?= 'tag:' . DOMAIN . ',2015:' . $ControllerURL . ':feed/atom' ?></id>
	<link rel="self" type="<?= \CWA\Net\HTTP\HttpResponse::getContentType() ?>" href="<?= $ControllerURL ?>?format=atom" />
	<link rel="alternate" type="text/html" href="<?= $ControllerURL ?>" />
	<updated><?php
$lastUpdated = null;
$field = $Items[0]->getUpdatedFieldName();
foreach ($Items as $item) { // Use the timestamp of the most recently updated item. -- cwells
	if ($item->$field > $lastUpdated) $lastUpdated = $item->$field;
}
$lastUpdated = new DateTime($lastUpdated);
echo $lastUpdated->format(DateTime::ATOM);
?></updated>
	<title><?= SITE_NAME ?></title>
	<subtitle><?= SITE_SLOGAN ?></subtitle>
	<author>
		<name><?= SITE_AUTHOR ?></name>
		<uri><?= PROTOCOL_HOST_PORT ?></uri>
	</author>
	<rights>Copyright (c) 2014-<?= date('Y') . ', ' . SITE_AUTHOR ?></rights>

<?php
$idPrefix = 'tag:' . DOMAIN . ',2015:' . $ModelType . ':';
require_once $this->pathToPartial;
?>

</feed>

<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?>
<feed xmlns="http://www.w3.org/2005/Atom"
	  xml:lang="en"
	  xml:base="<?= PROTOCOL_HOST_PORT . \CWA\APP_ROOT ?>">

	<id><?= 'tag:' . DOMAIN . ',2015:' . $ControllerURL . ':feed/atom' ?></id>
	<link rel="self" type="<?= \CWA\Net\HTTP\HttpResponse::getContentType() ?>" href="<?= $ControllerURL ?>?format=atom" />
	<link rel="alternate" type="text/html" href="<?= $ControllerURL ?>" />
	<updated><?= $LastUpdated->format(DateTime::ATOM) ?></updated>
	<title><?= SITE_NAME ?></title>
	<subtitle><?= SITE_SLOGAN ?></subtitle>
	<author>
		<name><?= SITE_AUTHOR ?></name>
		<uri><?= PROTOCOL_HOST_PORT ?></uri>
	</author>
	<rights>Copyright (c) 2014-<?= date('Y') . ', ' . SITE_AUTHOR ?></rights>

<?php
$idPrefix = 'tag:' . DOMAIN . ',2015:' . $ModelType . ':';
require_once $this->pathToPartial;
?>

</feed>

Stop referencing Item and Items from view data.


<?php

namespace ChopBox\ChopBox\Repository;

use ChopBox\User;

class UserRepository
{
    public function findUserByEmail($email)
    {
        return $user = User::where('email', '=', $email)->first();
    }

    public function topUsers()
    {
        return User::orderBy('chops_count', 'DESC')->take(10)->get();
    }

}

<?php

namespace ChopBox\ChopBox\Repository;

use ChopBox\User;

class UserRepository
{
    /**
     * Find Users by their Emails
     * @param  string $email
     * @return Collection
     */
    public function findUserByEmail($email)
    {
        return $user = User::where('email', '=', $email)->first();
    }

    /**
     * Find top 10 Users that have posted the most chops
     * @return [type] [description]
     */
    public function topUsers()
    {
        return User::orderBy('chops_count', 'DESC')->take(10)->get();
    }

}

Add css fixes and docblocks

[Chopbox][Chore] Add css fixes and docblocks


<?php

namespace Coosos\TagBundle\Controller;

use Coosos\TagBundle\Entity\Tag;
use Coosos\TagBundle\Repository\TagRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * Class TagController
 * @package Coosos\TagBundle\Controller
 * @Route("/tag")
 */
class TagController extends Controller
{
    /**
     * @Route("/tag-list", name="coosos_tag_tag_tagList")
     * @Method("GET")
     * @param Request $request
     * @return Response
     */
    public function tagListAction(Request $request)
    {
        $searchTag = ($request->query->has("tag")) ? $request->query->get("tag") : null;
        $categoryTag = ($request->query->has("category")) ? $request->query->get("category") : null;

        $em = $this->getDoctrine()->getManager();
        /** @var TagRepository $repository */
        $repository = $em->getRepository("CoososTagBundle:Tag");
        $results = $repository->getTagList($searchTag,  $categoryTag, 5);

        $tags = [];
        /** @var Tag $result */
        foreach ($results as $result) {
            $tags[] = $result->getName();
        }

        return new JsonResponse(json_encode($tags), 200);
    }
}

<?php

namespace Coosos\TagBundle\Controller;

use Coosos\TagBundle\Entity\Tag;
use Coosos\TagBundle\Repository\TagRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * Class TagController
 * @package Coosos\TagBundle\Controller
 * @Route("/tag")
 */
class TagController extends Controller
{
    /**
     * @Route("/tag-list", name="coosos_tag_tag_tagList")
     * @Method("GET")
     * @param Request $request
     * @return Response
     */
    public function tagListAction(Request $request)
    {
        $searchTag = ($request->query->has("term")) ? $request->query->get("term") : null;
        $categoryTag = ($request->query->has("category")) ? $request->query->get("category") : "default";

        $em = $this->getDoctrine()->getManager();
        /** @var TagRepository $repository */
        $repository = $em->getRepository("CoososTagBundle:Tag");
        $results = $repository->getTagList($searchTag,  $categoryTag, 5);

        $tags = [];
        /** @var Tag $result */
        foreach ($results as $result) {
            $tags[] = $result->getName();
        }

        return new JsonResponse($tags, 200);
    }
}

Return array, change param name

Return array, change param name


<?php

namespace Faker\Test\Provider\en_US;

use Faker\Provider\en_US\Company;
use Faker\Generator;

class CompanyTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new Company($faker));
        $this->faker = $faker;
    }

    public function testEin()
    {
        for ($i = 0; $i < 100; $i++) {
            $number = $this->faker->ein;

            // should be in the format ##-#######, with a valid prefix
            $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
        }
    }
}

<?php

namespace Faker\Test\Provider\en_US;

use Faker\Provider\en_US\Company;
use Faker\Generator;

class CompanyTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new Company($faker));
        $this->faker = $faker;
    }

    public function testEin()
    {
        $number = $this->faker->ein;

        // should be in the format ##-#######, with a valid prefix
        $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
    }
}

Drop loop in EIN test

Drop loop in EIN test


    <a class="brand" href="<?php echo home_url('/') ?>">

 <?

if (is_page() && !is_front_page()) { ?>

<?php echo roots_title(); ?>

 <?
}

if ('post' == get_post_type()) { ?>

Blog

 <?
} ?>

    <a class="brand" href="<?php echo home_url('/') ?>">

 <?

if ((is_page() && !is_front_page()) || is_post_type_archive('realisation') || $post_type == 'realisation') { ?>

<?php echo roots_title(); ?>

 <?
}

if ('post' == get_post_type()) { ?>

Blog

 <?
} ?>

Add ribbon to Realisations archive and single


<?php

class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag
{
    public function getTokenType()
    {
        return 'Tmpl';
    }

    public function getRegex()
    {
        return '/{{tmpl.*?}}/is';
    }

    public function getNestingValue()
    {
        return array(0,1);
    }

    public function parseTag($rawTagString)
    {
        $matches = array();
        preg_match('/^{{tmpl(\((.*?),(.*)\)(.*)|\((.*?)\)(.*)|(.*))}}$/is', $rawTagString, $matches);

        if (count($matches) == 8)
        {
            return array
            (
                'template' => $this->_extractId($matches[1])
            );
        }

        if (count($matches) == 7)
        {
            return array
            (
                'template' => $this->_extractId($matches[6]),
                'data' => trim($matches[5]),
            );
        }

        // Matched optional params as well
        return array
        (
            'template' => $this->_extractId($matches[4]),
            'data' => trim($matches[2]),
            'options' => trim($matches[3])
        );
    }

    private function _extractId($str)
    {
        return trim($str, "'\"# \t\n\r\0\x0B");
    }
}

<?php

class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag
{
    public function getTokenType()
    {
        return 'Tmpl';
    }

    public function getRegex()
    {
        return '/{{tmpl.*?}}/is';
    }

    public function getNestingValue()
    {
        return array(0,0);
    }

    public function parseTag($rawTagString)
    {
        $matches = array();
        preg_match('/^{{tmpl(\((.*?),(.*)\)(.*)|\((.*?)\)(.*)|(.*))}}$/is', $rawTagString, $matches);

        if (count($matches) == 8)
        {
            return array
            (
                'template' => $this->_extractId($matches[1])
            );
        }

        if (count($matches) == 7)
        {
            return array
            (
                'template' => $this->_extractId($matches[6]),
                'data' => trim($matches[5]),
            );
        }

        // Matched optional params as well
        return array
        (
            'template' => $this->_extractId($matches[4]),
            'data' => trim($matches[2]),
            'options' => trim($matches[3])
        );
    }

    private function _extractId($str)
    {
        return trim($str, "'\"# \t\n\r\0\x0B");
    }
}

Tag {{tmpl}} should not change nesting value


<?php

use Codeception\Util\Fixtures;
use Codeception\Util\Stub;
use Grav\Common\Grav;
use Grav\Common\Page\Pages;
use Grav\Common\Page\Page;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;

/**
 * Class PagesTest
 */
class PagesTest extends \Codeception\TestCase\Test
{
    /** @var Grav $grav */
    protected $grav;

    /** @var Pages $pages */
    protected $pages;

    /** @var Page $root_page */
    protected $root_page;

    protected function _before()
    {
        $this->grav = Fixtures::get('grav');
        $this->pages = $this->grav['pages'];

        /** @var UniformResourceLocator $locator */
//        $locator = $this->grav['locator'];
//        $locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false);
//        $this->pages->init();
    }

    public function testAll()
    {
        $this->assertTrue(is_object($this->pages->all()));
        $this->assertTrue(is_array($this->pages->all()->toArray()));
        $this->assertInstanceOf('Grav\Common\Page\Page', $this->pages->all()->first());
    }

    public function testGetList()
    {
        $list = $this->pages->getList();
        $this->assertTrue(is_array($list));
//        $this->assertSame($list['/home'], 'Home');
//        $this->assertSame($list['/blog'], 'Blog');
    }
}

<?php

use Codeception\Util\Fixtures;
use Codeception\Util\Stub;
use Grav\Common\Grav;
use Grav\Common\Page\Pages;
use Grav\Common\Page\Page;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;

/**
 * Class PagesTest
 */
class PagesTest extends \Codeception\TestCase\Test
{
    /** @var Grav $grav */
    protected $grav;

    /** @var Pages $pages */
    protected $pages;

    /** @var Page $root_page */
    protected $root_page;

    protected function _before()
    {
        $this->grav = Fixtures::get('grav');
        $this->pages = $this->grav['pages'];

        /** @var UniformResourceLocator $locator */
        $locator = $this->grav['locator'];
        $locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false);
        $this->pages->init();
    }

    public function testAll()
    {
        $this->assertTrue(is_object($this->pages->all()));
        $this->assertTrue(is_array($this->pages->all()->toArray()));
        $this->assertInstanceOf('Grav\Common\Page\Page', $this->pages->all()->first());
    }

    public function testGetList()
    {
        $list = $this->pages->getList();
        $this->assertTrue(is_array($list));
        $this->assertSame($list['/'], 'Home');
        $this->assertSame($list['/blog'], 'Blog');
    }
}

Add second set of pages to test

Add second set of pages to test


<?php
// this example executes some commands within the given running container and
// displays the streaming output as it happens.

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

use React\EventLoop\Factory as LoopFactory;
use Clue\React\Docker\Factory;
use React\Stream\Stream;

$container = 'asd';
//$cmd = array('echo', 'hello world');
//$cmd = array('sleep', '2');
$cmd = array('sh', '-c', 'echo -n hello && sleep 1 && echo world && sleep 1 && env');
//$cmd = array('cat', 'invalid-path');

if (isset($argv[1])) {
    $container = $argv[1];
    $cmd = array_slice($argv, 2);
}

$loop = LoopFactory::create();

$factory = new Factory($loop);
$client = $factory->createClient();

$out = new Stream(STDOUT, $loop);
$out->pause();

$client->execCreate($container, $cmd)->then(function ($info) use ($client, $out) {
    $stream = $client->execStartStream($info['Id']);
    $stream->pipe($out);

    $stream->on('error', 'printf');

    // exit with error code of executed command once it closes
    $stream->on('close', function () use ($client, $info) {
        $client->execInspect($info['Id'])->then(function ($info) {
            exit($info['ExitCode']);
        }, 'printf');
    });
}, 'printf');

$loop->run();

<?php
// this example executes some commands within the given running container and
// displays the streaming output as it happens.

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

use React\EventLoop\Factory as LoopFactory;
use Clue\React\Docker\Factory;
use React\Stream\Stream;

$container = 'asd';
//$cmd = array('echo', 'hello world');
//$cmd = array('sleep', '2');
$cmd = array('sh', '-c', 'echo -n hello && sleep 1 && echo world && sleep 1 && env');
//$cmd = array('cat', 'invalid-path');

if (isset($argv[1])) {
    $container = $argv[1];
    $cmd = array_slice($argv, 2);
}

$loop = LoopFactory::create();

$factory = new Factory($loop);
$client = $factory->createClient();

$out = new Stream(STDOUT, $loop);
$out->pause();

// unkown exit code by default
$exit = 1;

$client->execCreate($container, $cmd)->then(function ($info) use ($client, $out, &$exit) {
    $stream = $client->execStartStream($info['Id']);
    $stream->pipe($out);

    $stream->on('error', 'printf');

    // remember exit code of executed command once it closes
    $stream->on('close', function () use ($client, $info, &$exit) {
        $client->execInspect($info['Id'])->then(function ($info) use (&$exit) {
            $exit = $info['ExitCode'];
        }, 'printf');
    });
}, 'printf');

$loop->run();

exit($exit);

Exit streaming example once all streams have been flushed


@extends('layouts.blog')

@section('content')

Blog

                @if (isset($group_title) && $group_title !== '')

{{ucfirst(strtolower($group_title))}}

                @endif

                @if (isset($group) && $group !== '')
                    {{date_links($group, "li")}}
                @endif

            @foreach ($results as $result)
                @include('blog.item')
            @endforeach

        @include('layouts.pagination')

        @include('blog.sidebar')
@stop

Fix typo that broke inventory breadcrumb links


<?php
    /**
     * @author Manuel Thalmann <m@nuth.ch>
     * @license Apache-2.0
     */
    namespace ManuTh\TemPHPlate\Pages;
    use System\Web;
    use ManuTh\TemPHPlate\Templates\BootstrapTemplate;
    {
        /**
         * A page
         */
        class Page extends Web\Page
        {
            /**
             * Draws the object.
             *
             * @return void
             */
            protected function DrawInternal()
            {
                echo '

Hello

                        World

';
            }

            /**
             * @ignore
             */
            public function __Initialize() : array
            {
                return array('Template' => new BootstrapTemplate($this));
            }
        }
    }
?>

<?php
    /**
     * @author Manuel Thalmann <m@nuth.ch>
     * @license Apache-2.0
     */
    namespace ManuTh\TemPHPlate\Pages;
    use System\Web;
    use System\Web\Forms\Rendering\PaintEventArgs;
    use System\Web\Forms\MenuItem;
    use ManuTh\TemPHPlate\Templates\BootstrapTemplate;
    {
        /**
         * A page
         */
        class Page extends Web\Page
        {
            /**
             * Initializes a new instance of the `Page` class.
             */
            public function Page()
            {
                $this->Template = new BootstrapTemplate($this);
                $this->Renderer->Paint->Add(\Closure::fromCallable(array($this, 'OnItemPaint')));
            }

            private function OnItemPaint($sender, PaintEventArgs $e)
            {
                if ($e->Item instanceof MenuItem)
                {
                    if ($e->Item->Name == 'home')
                    {
                        $e->Cancel = true;
                    }
                }
            }

            /**
             * Draws the object.
             *
             * @return void
             */
            protected function DrawInternal()
            {
                echo '

Hello

                        World

';
            }
        }
    }
?>

Add a paint-event test to the main page

Add a paint-event test to the main page


<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;

/**
 * Web Service.
 * Returns Trait Entry information
 */
class TraitEntries
{
    private $manager;
    private $known_trait_formats;
    const ERROR_UNKNOWN_TRAIT_FORMAT = "Error. Unknown trait_format.";

    /**
     * TraitEntries constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getDataEntityManager();
        $this->known_trait_formats = array('categorical_free', 'numerical');
    }

    /**
     * @param $traitFormat
     * @param $traitEntryIds
     * @returns array with details of the requested trait entries
     */
    public function execute($traitEntryIds, $traitFormat)
    {
        if (!in_array($traitFormat, $this->known_trait_formats)) {
            return (array('error' => TraitEntries::ERROR_UNKNOWN_TRAIT_FORMAT));
        }
        if ($traitFormat === "categorical_free") {
            $result = $this->manager->getRepository(TraitCategoricalEntry::class)->getTraitEntry($traitEntryIds);
        } else {
            $result = $this->manager->getRepository(TraitNumericalEntry::class)->getTraitEntry($traitEntryIds);
        }
        return $result;
    }
}

<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;

/**
 * Web Service.
 * Returns Trait Entry information
 */
class TraitEntries
{
    private $manager;
    private $known_trait_formats;
    const ERROR_UNKNOWN_TRAIT_FORMAT = "Error. Unknown trait_format.";

    /**
     * TraitEntries constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getDataEntityManager();
        $this->known_trait_formats = array('categorical_free', 'numerical');
    }

    /**
     * @param $traitFormat
     * @param $traitEntryIds
     * @returns array with details of the requested trait entries
     */
    public function execute($traitEntryIds, $traitFormat)
    {
        if ($traitEntryIds === null || count($traitEntryIds) === 0){
            return (array());
        }
        if (!in_array($traitFormat, $this->known_trait_formats)) {
            return (array('error' => TraitEntries::ERROR_UNKNOWN_TRAIT_FORMAT));
        }
        if ($traitFormat === "categorical_free") {
            $result = $this->manager->getRepository(TraitCategoricalEntry::class)->getTraitEntry($traitEntryIds);
        } else {
            $result = $this->manager->getRepository(TraitNumericalEntry::class)->getTraitEntry($traitEntryIds);
        }
        return $result;
    }
}

Add quick return if no trait entry ids are provided


<?php

namespace Conner\Tagging\Console\Commands;

use Conner\Tagging\TaggingUtility;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class GenerateTagGroup extends Command
{
    protected $name = 'tagging:create-group';

    protected $signature = 'tagging:create-group {group}';

    protected $description = 'Create a laravel tag group';

    public function handle()
    {
        $groupName = $this->argument('group');

        $tagGroup = new ${TaggingUtility::tagGroupModelString()};
        $tagGroup->name = $groupName;
        $tagGroup->slug = TaggingUtility::normalize($groupName);

        $tagGroup->save();

        $this->info('Created tag group: '.$groupName);
    }

    protected function getArguments()
    {
        return [
            ['group', InputArgument::REQUIRED, 'Name of the group to create.'],
        ];
    }
}

<?php

namespace Conner\Tagging\Console\Commands;

use Conner\Tagging\TaggingUtility;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class GenerateTagGroup extends Command
{
    protected $name = 'tagging:create-group';

    protected $signature = 'tagging:create-group {group}';

    protected $description = 'Create a laravel tag group';

    public function handle()
    {
        $groupName = $this->argument('group');

        $tagGroupModel = TaggingUtility::tagGroupModelString();

        $tagGroup = new $tagGroupModel();
        $tagGroup->name = $groupName;
        $tagGroup->slug = TaggingUtility::normalize($groupName);

        $tagGroup->save();

        $this->info('Created tag group: '.$groupName);
    }

    protected function getArguments()
    {
        return [
            ['group', InputArgument::REQUIRED, 'Name of the group to create.'],
        ];
    }
}

Fix bug on generate tag group command

Fix bug on generate tag group command


<?php

use PHPUnit\Framework\TestCase;

class ControllerTest extends TestCase
{
    public function testGetDefaultParam()
    {
        $controller   = new \Frogg\Controller();
        $request      = null;
        $defaultValue = 'Default Value';
        $nameGET      = "Test Get";
        $_GET['name'] = $nameGET;

        $controller->request = $request;

        $this->markTestIncomplete(
            'This test has not been implemented, not possible inject [Request]. Phalcon not installed for circle CI'
        );
    }
}

<?php

use PHPUnit\Framework\TestCase;

class ControllerTest extends TestCase
{
    public function testGetDefaultParam()
    {
        $controller   = new \Frogg\Controller();
        $dispatcher   = new \Phalcon\Mvc\Dispatcher();
        $request      = new Phalcon\Http\Request();
        $defaultValue = 'Default Value';
        $nameGET      = "Test Get";
        $_GET['name'] = $nameGET;

        $controller->request    = $request;
        $controller->dispatcher = $dispatcher;

        $this->assertEquals($nameGET, $controller->getParam('name', $defaultValue));
        $this->assertEquals($defaultValue, $controller->getParam('color', $defaultValue));
    }
}

Complete test, Phalcon installed on CircleCi


<?php
namespace Plitz\Bindings\Blitz;

use Plitz\Lexer\Lexer;
use Plitz\Parser\Expressions;
use Plitz\Parser\Parser;

trait ResolveIncludeTrait
{
    protected $disableFunctionBoilerplate = false;

    public function startOfStream()
    {
        if (!$this->disableFunctionBoilerplate) {
            parent::startOfStream();
        }
    }

    public function endOfStream()
    {
        if (!$this->disableFunctionBoilerplate) {
            parent::endOfStream();
        }
    }

    protected function resolveIncludeCall(Expressions\MethodCall $expression)
    {
        assert($expression->getArguments()[0] instanceof Expressions\Scalar);
        $filename = $this->basePath . DIRECTORY_SEPARATOR . $expression->getArguments()[0]->getValue();
        $filehandle = fopen($filename, "r");
        assert(is_resource($filehandle));

        // make sure we don't write a new function header + footer
        $oldDisableFunctionBoilerPlate = $this->disableFunctionBoilerplate;
        $this->disableFunctionBoilerplate = true;

        $lexer = new Lexer($filehandle, $filename);
        $parser = new Parser($lexer->lex(), $this);
        $parser->parse();

        $this->disableFunctionBoilerplate = $oldDisableFunctionBoilerPlate;
    }
}

<?php
namespace Plitz\Bindings\Blitz;

use Plitz\Lexer\Lexer;
use Plitz\Parser\Expressions;
use Plitz\Parser\Parser;

trait ResolveIncludeTrait
{
    protected $disableFunctionBoilerplate = false;

    public function startOfStream()
    {
        if (!$this->disableFunctionBoilerplate) {
            parent::startOfStream();
        }
    }

    public function endOfStream()
    {
        if (!$this->disableFunctionBoilerplate) {
            parent::endOfStream();
        }
    }

    protected function resolveIncludeCall(Expressions\MethodCall $expression)
    {
        assert($expression->getArguments()[0] instanceof Expressions\Scalar);
        $filename = $this->basePath . DIRECTORY_SEPARATOR . $expression->getArguments()[0]->getValue();
        $filehandle = fopen($filename, "r");
        assert(is_resource($filehandle));

        // make sure we don't write a new function header + footer
        $oldDisableFunctionBoilerPlate = $this->disableFunctionBoilerplate;
        $this->disableFunctionBoilerplate = true;

        $lexer = new Lexer($filehandle, $filename);
        $parser = new Parser($lexer->lex(), $this);

        $this->comment('@@START OF TEMPLATE ' . $filename . ' @@');
        $parser->parse();
        $this->comment('@@END OF TEMPLATE ' . $filename . ' @@');

        $this->disableFunctionBoilerplate = $oldDisableFunctionBoilerPlate;
    }
}

Print start and end of template includes


<?php

namespace OhMyBrew\ShopifyApp\Observers;

use OhMyBrew\ShopifyApp\Models\Shop;

class ShopObserver
{
    /**
     * Listen to the shop creating event.
     *
     * @param Shop $shop
     *
     * @return void
     */
    public function creating(Shop $shop)
    {
        if (!isset($shop->namespace)) {
            // Automatically add the current namespace to new records
            $shop->namespace = config('shopify-app.namespace');
        }

        if (config('shopify-app.billing_freemium_enabled') === true) {
            // Add the freemium flag to the shop
            $shop->freemium = true;
        }
    }
}

<?php

namespace OhMyBrew\ShopifyApp\Observers;

use OhMyBrew\ShopifyApp\Models\Shop;

class ShopObserver
{
    /**
     * Listen to the shop creating event.
     *
     * @param Shop $shop
     *
     * @return void
     */
    public function creating(Shop $shop)
    {
        if (!isset($shop->namespace)) {
            // Automatically add the current namespace to new records
            $shop->namespace = config('shopify-app.namespace');
        }

        if (config('shopify-app.billing_freemium_enabled') === true && !isset($shop->freemium)) {
            // Add the freemium flag to the shop
            $shop->freemium = true;
        }
    }
}

Allow for override of freemium

Allow for override of freemium


        © 2009 Nicolas HOIZEY

	      <a href="<?php echo $casimir->base_url; ?>">Home |
        <a href="<?php echo $casimir->base_url; ?>stats.php">Stats |
	about

Add a link to the github wiki

Add a link to the github wiki


<?php
namespace Haystack\Container;

use Haystack\HArray;

class HaystackArraySlice
{
    private $arr;

    /**
     * @param HArray $array
     */
    public function __construct(HArray $array)
    {
        $this->arr = $array->toArray();
    }

    /**
     * @param $start
     * @param null $length
     * @return array
     */
    public function slice($start, $length = null)
    {
        if (is_null($start) || !is_numeric($start)) {
            throw new \InvalidArgumentException("Slice parameter 1, \$start, must be an integer");
        }

        if (!is_null($length) && !is_numeric($length)) {
            throw new \InvalidArgumentException("Slice parameter 2, \$length, must be null or an integer");
        }

        $maintainIndices = false;

        return array_slice($this->arr, $start, $length, $maintainIndices);
    }

}

<?php
namespace Haystack\Container;

use Haystack\HArray;

class HaystackArraySlice
{
    private $arr;

    /**
     * @param HArray $array
     */
    public function __construct(HArray $array)
    {
        $this->arr = $array->toArray();
    }

    /**
     * @param $start
     * @param integer|null $length
     * @return array
     */
    public function slice($start, $length)
    {
        if (is_null($start) || !is_numeric($start)) {
            throw new \InvalidArgumentException("Slice parameter 1, \$start, must be an integer");
        }

        if (!is_null($length) && !is_numeric($length)) {
            throw new \InvalidArgumentException("Slice parameter 2, \$length, must be null or an integer");
        }

        $maintainIndices = false;

        return array_slice($this->arr, $start, $length, $maintainIndices);
    }

}

Remove default slice length of null

Remove default slice length of null

There's already a check if it's null, so this seems superfluous.


<?php
/**
 * @author        "Michael Collette" <metrol@metrol.net>
 * @package       Metrol/DBSql
 * @version       1.0
 * @copyright (c) 2016, Michael Collette
 */

namespace Metrol\DBSql\PostgreSQL;

/**
 * Provides the functionality that statements and various helpers use from the
 * Quotable object
 *
 */
trait QuoterTrait
{
    /**
     * The object that handles auto quoting field and table names.
     *
     */
    protected Quotable $quotable;

    /**
     * Provide the quoting utility to use on Table and Field names
     *
     */
    public function quoter(): Quotable
    {
        if ( !is_object($this->quotable) )
        {
            $this->quotable = new Quotable;
        }

        return $this->quotable;
    }

    /**
     * Tell the quoter engine whether to try and automatically quote
     * field and table names.  When turned off, quoting is manual.
     *
     */
    public function enableQuoting(bool $flag): static
    {
        $this->quoter()->enableQuoting($flag);

        return $this;
    }
}

<?php
/**
 * @author        "Michael Collette" <metrol@metrol.net>
 * @package       Metrol/DBSql
 * @version       1.0
 * @copyright (c) 2016, Michael Collette
 */

namespace Metrol\DBSql\PostgreSQL;

/**
 * Provides the functionality that statements and various helpers use from the
 * Quotable object
 *
 */
trait QuoterTrait
{
    /**
     * The object that handles auto quoting field and table names.
     *
     */
    protected Quotable $quotable;

    /**
     * Provide the quoting utility to use on Table and Field names
     *
     */
    public function quoter(): Quotable
    {
        if ( ! isset($this->quotable) )
        {
            $this->quotable = new Quotable;
        }

        return $this->quotable;
    }

    /**
     * Tell the quoter engine whether to try and automatically quote
     * field and table names.  When turned off, quoting is manual.
     *
     */
    public function enableQuoting(bool $flag): static
    {
        $this->quoter()->enableQuoting($flag);

        return $this;
    }
}

Fix a problem with checking for a set value


<?php

declare(strict_types=1);

namespace Issei\SimpleJobSchedule\TimeKeeper;

use Issei\SimpleJobSchedule\TimeKeeperInterface;
use Predis\Client as Redis;

/**
 * @author Issei Murasawa <issei.m7@gmail.com>
 */
class RedisTimeKeeper implements TimeKeeperInterface
{
    /**
     * @var Redis
     */
    private $redis;

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

    /**
     * {@inheritdoc}
     */
    public function getLastRanTime(string $key): ?\DateTimeInterface
    {
        $lastRanAtAsEpoch = $this->redis->get($key);

        return $lastRanAtAsEpoch
            ? (new \DateTimeImmutable())->setTimestamp((int) $lastRanAtAsEpoch)
            : null
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function attemptToKeepRunTime(string $key, \DateTimeInterface $runTime): bool
    {
        $script = <<< 'LUA'
local last_run_at = redis.call('GET', KEYS[1])

if last_run_at ~= ARGV[1] then
    redis.call('SET', KEYS[1], ARGV[1])
    return 1
else
    return 0
end
LUA;

        return (bool) $this->redis->eval($script, 1, $key, $runTime->getTimestamp());
    }
}

<?php

declare(strict_types=1);

namespace Issei\SimpleJobSchedule\TimeKeeper;

use Issei\SimpleJobSchedule\TimeKeeperInterface;
use Predis\Client as Redis;

/**
 * @author Issei Murasawa <issei.m7@gmail.com>
 */
class RedisTimeKeeper implements TimeKeeperInterface
{
    /**
     * @var Redis
     */
    private $redis;

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

    public function __construct(Redis $redis, string $baseKey)
    {
        $this->redis = $redis;
        $this->baseKey = $baseKey;
    }

    /**
     * {@inheritdoc}
     */
    public function getLastRanTime(string $key): ?\DateTimeInterface
    {
        $lastRanAtAsEpoch = $this->redis->get($this->getKeyFor($key));

        return $lastRanAtAsEpoch
            ? (new \DateTimeImmutable())->setTimestamp((int) $lastRanAtAsEpoch)
            : null
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function attemptToKeepRunTime(string $key, \DateTimeInterface $runTime): bool
    {
        $script = <<< 'LUA'
local last_run_at = redis.call('GET', KEYS[1])

if last_run_at ~= ARGV[1] then
    redis.call('SET', KEYS[1], ARGV[1])
    return 1
else
    return 0
end
LUA;

        return (bool) $this->redis->eval($script, 1, $this->getKeyFor($key), $runTime->getTimestamp());
    }

    private function getKeyFor(string $key): string
    {
        return $this->baseKey . ':' . $key;
    }
}

[SimpleJobSchedule] Add base key to redis backed time keeper


<?php
declare(strict_types=1);

namespace PerFi\Domain;

use Money\Currencies\ISOCurrencies;
use Money\Money;
use Money\Parser\DecimalMoneyParser;

class MoneyFactory
{
    /**
     * Create a Money value object with the provided amount and currency
     *
     * @param string $amount
     * @param string $currency
     * @return Money
     */
    public static function amountInCurrency(string $amount, string $currency) : Money
    {
        $currencies = new ISOCurrencies();
        $moneyParser = new DecimalMoneyParser($currencies);

        return $moneyParser->parse($amount, $currency);
    }
}

<?php
declare(strict_types=1);

namespace PerFi\Domain;

use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Money;
use Money\Parser\DecimalMoneyParser;

class MoneyFactory
{
    /**
     * Create a Money value object with the provided amount and currency
     *
     * @param string $amount
     * @param string $currency
     * @return Money
     */
    public static function amountInCurrency(string $amount, string $currency) : Money
    {
        $currencies = new ISOCurrencies();
        $moneyParser = new DecimalMoneyParser($currencies);

        return $moneyParser->parse($amount, $currency);
    }

    /**
     * Create a Money value object from the cent amounts in currency
     *
     * @param string $cents
     * @param string $currency
     * @return Money
     */
    public static function centsInCurrency(string $cents, string $currency) : Money
    {
        return new Money($cents, new Currency($currency));
    }
}

Add factory method to create Money from cents


<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Core\Exception;

/**
 * Base exception interface.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface ExceptionInterface
{
}

<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Core\Exception;

/**
 * Base exception interface.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface ExceptionInterface extends \Throwable
{
}

Make the base exception extend throwable

This makes it more clear this interface can be 'caught'


<?php

namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class ServiceProvider extends BaseServiceProvider
{
    use Traits\PackageProvider;

    /**
     * Register a database migration path.
     *
     * @param  array|string  $paths
     *
     * @return void
     */
    protected function loadMigrationsFrom($paths)
    {
        if ($this->app->bound('migrator')) {
            parent::loadMigrationsFrom($paths);
        }
    }
}

<?php

namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class ServiceProvider extends BaseServiceProvider
{
    use Traits\PackageProvider;
}

Remove redundant method. Laravel core have solve the underlying issue.

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


<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class AlertMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.alert';

    /**
     * The type of alert.
     *
     * @var string|null
     */
    public $alertType = null;

    /**
     * The text of the alert.
     *
     * @var string|null
     */
    public $alertText = null;

    /**
     * Set the alert type and text for the message.
     *
     * @param string $type
     * @param string $text
     * @return $this
     */
    public function alert($type, $text)
    {
        $this->alertType = $type;
        $this->alertText = $text;

        return $this;
    }
}

<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class AlertMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.alert';

    /**
     * The type of alert.
     *
     * @var string|null
     */
    public $type = null;

    /**
     * The text of the alert.
     *
     * @var string|null
     */
    public $message = null;

    /**
     * Set the type of alert for the message.
     *
     * @param string $type
     * @return $this
     */
    public function type($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Set the alert "message" for the message.
     *
     * @param string $message
     * @return $this
     */
    public function message($message)
    {
        $this->message = $message;

        return $this;
    }
}

Split `alert` method into two different methods


<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\CodeBlock;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class CodeBlockParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '{
                ^
                (?:                 # Ensure blank line before (or beginning of subject)
                    \A\s*\n?|
                    \n\s*\n
                )
                [ ]{4}              # four leading spaces
                .+
                (?:                 # optionally more spaces
                    (?:             # blank lines in between are okay
                        \n[ ]*
                    )*
                    \n
                    [ ]{4}
                    .+
                )*
                $
            }mx',
            function (Text $code) use ($target) {
                // Remove leading blank lines
                $code->replace('/^(\s*\n)*/', '');

                // Remove indent
                $code->replace('/^[ ]{1,4}/m', '');
                $code->append("\n");

                $target->acceptCodeBlock(new CodeBlock($code));
            },
            function(Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\CodeBlock;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class CodeBlockParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '{
                (?:                 # Ensure blank line before (or beginning of subject)
                    \A\s*\n?|
                    \n\s*\n
                )
                [ ]{4}              # four leading spaces
                .+
                (?:                 # optionally more spaces
                    (?:             # blank lines in between are okay
                        \n[ ]*
                    )*
                    \n
                    [ ]{4}
                    .+
                )*
                $
            }mx',
            function (Text $code) use ($target) {
                // Remove leading blank lines
                $code->replace('/^(\s*\n)*/', '');

                // Remove indent
                $code->replace('/^[ ]{1,4}/m', '');
                $code->append("\n");

                $target->acceptCodeBlock(new CodeBlock($code));
            },
            function(Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

Remove anchor from start of code block regex.


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

use \Curl\Curl;

$myfile = curl_file_create('cats.jpg', 'image/png', 'test_name');

$curl = new Curl();

// HINT: If API documentation refers to using something like curl -F "myimage=image.png",
// curl --form "myimage=image.png", or the html form is similar to <form enctype="multipart/form-data" method="post">,
// then try uncommenting the following line:
// $curl->setHeader('Content-Type', 'multipart/form-data');

$curl->post('https://httpbin.org/post', array(
    'myfile' => $myfile,
));

if ($curl->error) {
    echo 'Error: ' . $curl->errorMessage . "\n";
} else {
    echo 'Success' . "\n";
}

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

use \Curl\Curl;

$myfile = curl_file_create('cats.jpg', 'image/png', 'test_name');

$curl = new Curl();

// HINT: If API documentation refers to using something like curl -F "myimage=image.png",
// curl --form "myimage=image.png", or the html form is similar to <form enctype="multipart/form-data" method="post">,
// then try uncommenting the following line:
// $curl->setHeader('Content-Type', 'multipart/form-data');

$curl->post('https://httpbin.org/post', array(
    'myfile' => $myfile,
));

if ($curl->error) {
    echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
} else {
    echo 'Success' . "\n";
}

Include error code in output on error

Include error code in output on error


<?php

/*
 * This file is part of Slim JSON Web Token Authentication middleware
 *
 * Copyright (c) 2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-jwt-auth
 *
 */

namespace Slim\Middleware\JwtAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

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

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getPath())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
    }
}

<?php

/*
 * This file is part of Slim JSON Web Token Authentication middleware
 *
 * Copyright (c) 2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-jwt-auth
 *
 */

namespace Slim\Middleware\JwtAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

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

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
    }
}

Use resource uri instead so rule will also work in subfolder installations


<?php

class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
    /**
     * @var BMAttackSurrender
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = BMAttackSurrender::get_instance();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers BMAttackSurrender::validate_attack
     */
    public function testValidate_attack()
    {
//        $game = new TestDummyGame;
//
//        $die1 = new BMDie;
//        $die1->init(6);
//        $die1->value = 6;
//
//        $die2 = new BMDie;
//        $die2->init(6);
//        $die2->value = 1;
//
//        // Basic error handling
//        $this->assertTrue($this->object->validate_attack($game, array(), array()));
//        $this->assertFalse($this->object->validate_attack($game, array($die1), array()));
//        $this->assertFalse($this->object->validate_attack($game, array(), array($die1)));
//        $this->assertFalse($this->object->validate_attack($game, array($die1), array($die2)));
    }
}

?>

<?php

class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
    /**
     * @var BMAttackSurrender
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = BMAttackSurrender::get_instance();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers BMAttackSurrender::validate_attack
     */
    public function testValidate_attack()
    {
        $game = new TestDummyGame;

        $die1 = new BMDie;
        $die1->init(6);
        $die1->value = 6;

        $die2 = new BMDie;
        $die2->init(6);
        $die2->value = 1;

        // Basic error handling
        $this->assertTrue($this->object->validate_attack($game, array(), array()));
        $this->assertFalse($this->object->validate_attack($game, array($die1), array()));
        $this->assertFalse($this->object->validate_attack($game, array(), array($die1)));
        $this->assertFalse($this->object->validate_attack($game, array($die1), array($die2)));
    }
}

?>

Add basic unit tests for BMAttackSurrender


<?php declare(strict_types = 1);
namespace PharIo\Phive;

use PharIo\FileSystem\Filename;

class UnixoidPharInstaller extends PharInstaller {
    protected function link(Filename $phar, Filename $destination): void {
        $this->getOutput()->writeInfo(
            \sprintf('Linking %s to %s', $phar->asString(), $destination->asString())
        );
        \symlink($phar->asString(), $destination->asString());
    }
}

<?php declare(strict_types = 1);
namespace PharIo\Phive;

use PharIo\FileSystem\Filename;

class UnixoidPharInstaller extends PharInstaller {
    protected function link(Filename $phar, Filename $destination): void {
        $this->getOutput()->writeInfo(
            \sprintf('Linking %s to %s', $phar->asString(), $destination->asString())
        );

        \symlink(
            $phar->withAbsolutePath()->asString(),
            $destination->withAbsolutePath()->asString()
        );
    }
}

Use absolute path for symlinks

Use absolute path for symlinks


<?php foreach ($query as $row): { ?>

<?php echo $row['name'];?> Admin

<?php } ?>
<?php endforeach; ?>

<?php foreach ($query2 as $row): { ?>

<?php echo $row['fname'] . " " . $row['mname'] . " " . $row['lname'];?> User

<?php } ?>
<?php endforeach; ?>

<?php foreach ($query as $row): { ?>

<?php echo $row['name'];?> Admin

<?php } ?>
<?php endforeach; ?>

<?php foreach ($query2 as $row): { ?>

<?php echo $row['fname'] . " " . $row['mname'] . ". " . $row['lname'];?> User

<?php } ?>
<?php endforeach; ?>

Add period after middle name of users.

Add period after middle name of users.


<?php

/**
 * ConfigMerge
 *
 * @link https://github.com/kanellov/config-merge
 * @copyright Copyright (c) 2015 Vassilis Kanellopoulos - contact@kanellov.com
 * @license https://raw.githubusercontent.com/kanellov/config-merge/master/LICENSE
 */

namespace Knlv;

/**
 * Merges configuration arrays.
 *
 * Merges files in the existing path that match given suffix. Files should
 * return array. Last suffix in array has greater priority than previous.
 *
 * @param  string $path the path containing the configuration files
 * @param  array  $suffixes array with file name suffixes
 * @param  array  $init initial configuration
 * @return array  the merged configuration array
 */
function config_merge($path, array $suffixes, array $init = array())
{
    return array_reduce(
        glob(
            realpath($path) . '/{,*.}{' . implode(',', $suffixes) . '}.php',
            GLOB_BRACE
        ),
        function ($config, $file) {
            return array_replace_recursive($config, include $file);
        },
        $init
    );
}

<?php

/**
 * ConfigMerge
 *
 * @link https://github.com/kanellov/config-merge
 * @copyright Copyright (c) 2015 Vassilis Kanellopoulos - contact@kanellov.com
 * @license https://raw.githubusercontent.com/kanellov/config-merge/master/LICENSE
 */

namespace Knlv;

/**
 * Merges configuration arrays.
 *
 * Merges files in the existing path that match given suffix. Files should
 * return array. Last suffix in array has greater priority than previous.
 *
 * @param  string $path the path containing the configuration files
 * @param  array  $suffixes array with file name suffixes
 * @param  array  $init initial configuration
 * @return array  the merged configuration array
 */
function config_merge($path, array $suffixes, array $init = array())
{
    $merge = function (array $merged, array $new) use (&$merge) {
        foreach ($new as $key => $value) {
            if (array_key_exists($key, $merged)) {
                if (is_int($key)) {
                    $merged[] = $value;
                } elseif (is_array($value) && is_array($merged[$key])) {
                    $merged[$key] = $merge($merged[$key], $value);
                } else {
                    $merged[$key] = $value;
                }
            } else {
                $merged[$key] = $value;
            }
        }
        return $merged;
    };

    return array_reduce(glob(
        realpath($path) . '/{,*.}{' . implode(',', $suffixes) . '}.php',
        GLOB_BRACE
    ), function ($config, $file) use (&$merge) {
        return $merge($config, include $file);
    }, $init);
}

Update to merge list arrays

Update to merge list arrays


<?php

namespace Zeropingheroes\Lanager\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Event extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->name,
            'start' => $this->start->toIso8601String(),
            'end' => $this->end->toIso8601String(),
            'type' => new EventType($this->type),
            'lan' => new Lan($this->whenLoaded('lan')),
            'links' => [
                'self' => route('api.events.show', $this->id),
                'self_gui' => route('lans.events.show', ['lan' => $this->lan_id, 'event' => $this->id]),
            ],
        ];
    }
}

<?php

namespace Zeropingheroes\Lanager\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Event extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'start' => $this->start->toIso8601String(),
            'end' => $this->end->toIso8601String(),
            'type' => new EventType($this->type),
            'lan' => new Lan($this->whenLoaded('lan')),
            'links' => [
                'self' => route('api.events.show', $this->id),
                'self_gui' => route('lans.events.show', ['lan' => $this->lan_id, 'event' => $this->id]),
            ],
        ];
    }
}

Fix event name being returned instead of description in API


Change text for share twitter

Change text for share twitter


<?php

namespace OfxParser;

/**
 * @author Diogo Alexsander Cavilha <diogo@agenciasys.com.br>
 */
class Fix
{
    private $file;

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

    public function replaceStartDate($search, $replace = '20000101100000')
    {
        $fileContent = $this->getFileContent($this->file);

        $fileContent = str_replace(
            '<DTSTART>' . $search,
            '<DTSTART>' . $replace,
            $fileContent
        );

        $this->saveFileContent($this->file, $fileContent);

        return $this;
    }

    protected function getFileContent($file)
    {
        return file_get_contents($file);
    }

    protected function saveFileContent($file, $content)
    {
        file_put_contents($file, $content);
    }
}

<?php

namespace OfxParser;

/**
 * @author Diogo Alexsander Cavilha <diogo@agenciasys.com.br>
 */
class Fix
{
    private $file;

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

    public function replaceStartDate($search, $replace = '20000101100000')
    {
        $fileContent = $this->getFileContent($this->file);

        $fileContent = str_replace(
            '<DTSTART>' . $search,
            '<DTSTART>' . $replace,
            $fileContent
        );

        $this->saveFileContent($this->file, $fileContent);

        return $this;
    }

    protected function getFileContent($file)
    {
        return file_get_contents($file);
    }

    protected function saveFileContent($file, $content)
    {
        file_put_contents($file, $content);
    }

    public function removeSpecialChars()
    {
        $fileContent = $this->getFileContent($this->file);

        $fileContent = str_replace('&', 'e', $fileContent);

        $this->saveFileContent($this->file, $fileContent);

        return $this;
    }
}

Remove special chars from file and save

Remove special chars from file and save


<?php

return [
    // Request headers that must be present when requesting images
    'required_custom_headers'   => [
        // 'name' => 'value',
    ],
    // List of MIME types that are allowed when uploading files through a form
    'allowed_upload_mime_types' => [
        'image/gif',
        'image/jpeg',
        'image/png',
    ],
];

<?php

return [
    // Request headers that must be present when requesting images
    'required_custom_headers'   => [
        // 'name' => 'value',
    ],
    // List of MIME types that are allowed when uploading files through a form
    'allowed_upload_mime_types' => [
        'image/gif',
        'image/jpeg',
        'image/png',
        'image/svg+xml',
    ],
];

Add image/svg+xml to the default list of allowed MIME types

Closes #16


<?php

namespace AbleCore;

class TaxonomyTerm extends EntityExtension {

	/**
	 * Gets the entity type of the current class.
	 *
	 * @return string The entity type.
	 */
	static function getEntityType()
	{
		return 'taxonomy_term';
	}

	/**
	 * By Vocabulary
	 *
	 * Gets all taxonomy terms by the specified vocabulary.
	 *
	 * @param string $vocabulary_machine_name The machine name of the vocabulary.
	 *
	 * @return array An array of TaxonomyTerm items.
	 */
	public static function byVocabulary($vocabulary_machine_name)
	{
		$query = db_select('taxonomy_term_data', 'td');
		$query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid');
		$query->condition('tv.machine_name', $vocabulary_machine_name);
		$query->addField('td', 'tid');
		return static::mapQuery($query);
	}

}

<?php

namespace AbleCore;

class TaxonomyTerm extends EntityExtension {

	/**
	 * Gets the entity type of the current class.
	 *
	 * @return string The entity type.
	 */
	static function getEntityType()
	{
		return 'taxonomy_term';
	}

	/**
	 * By Vocabulary
	 *
	 * Gets all taxonomy terms by the specified vocabulary.
	 *
	 * @param string $vocabulary_machine_name The machine name of the vocabulary.
	 *
	 * @return array An array of TaxonomyTerm items.
	 */
	public static function byVocabulary($vocabulary_machine_name)
	{
		$query = db_select('taxonomy_term_data', 'td');
		$query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid');
		$query->condition('tv.machine_name', $vocabulary_machine_name);
		$query->addField('td', 'tid');
		$query->orderBy('weight');
		return static::mapQuery($query);
	}

}

Add ordering by weight when getting terms by vocabulary.


<?php

namespace Github\Api;

/**
 * Get rate limits
 *
 * @link   https://developer.github.com/v3/rate_limit/
 * @author Jeff Finley <quickliketurtle@gmail.com>
 */
class RateLimit extends AbstractApi
{
    /**
     * Get rate limits
     *
     * @return array
     */
    public function getRateLimits()
    {
        return $this->get('rate_limit');
    }

    /**
     * Get core rate limit
     *
     * @return integer
     */
    public function getCoreLimit()
    {
        $response = $this->getRateLimits();
        return $response['resources']['core']['limit'];
    }

    /**
     * Get search rate limit
     *
     * @return integer
     */
    public function getSearchLimit()
    {
        $response = $this->getRateLimits();
        return $response['resources']['search']['limit'];
    }
}

Add blank line before return statements.


<?php

class Rewards {

  static function addRoutes($f3) {
    $f3->route("POST /process-rewards", 'Rewards->process');
  }

  function process($f3, $args) {
    $db= $f3->get('DBH');

    $loyalty= new DB\SQL\Mapper($db, 'loyalty');

    $loyalty->name= $f3->get('REQUEST.name');
    $loyalty->email= $f3->get('REQUEST.email');
    $loyalty->phone= $f3->get('REQUEST.phone');
    $loyalty->loyalty_number=
      preg_replace('/\D+/', '', $f3->get('REQUEST.phone'));
    $loyalty->code= $f3->get('REQUEST.code');

    $loyalty->save();

    $page= new DB\SQL\Mapper($db, 'page');

    $page->load(array('slug=?', 'reward-thanks'))
      or $f3->error(404);

    $f3->set('PAGE', $page);

    echo Template::instance()->render('page.html');
  }
}

<?php

class Rewards {

  static function addRoutes($f3) {
    $f3->route("POST /process-rewards", 'Rewards->process');
  }

  function process($f3, $args) {
    $db= $f3->get('DBH');

    $loyalty= new DB\SQL\Mapper($db, 'loyalty');

    $loyalty->name= $f3->get('REQUEST.name');
    $loyalty->email= $f3->get('REQUEST.email');
    $loyalty->phone= $f3->get('REQUEST.phone');
    $loyalty->loyalty_number=
      preg_replace('/\D+/', '', $f3->get('REQUEST.phone'));
    $loyalty->code= $f3->get('REQUEST.code');

    $loyalty->save();

    // Sign them up for the newsletter
    if ($f3->get('REQUEST.subscribe')) {
      $key= $f3->get("MAILERLITE_KEY");
      $groupsApi= (new MailerLiteApi\MailerLite($key))->groups();

      $subscriber= [
          'email' => $loyalty->email,
          'fields' => [
              'name' => $loyalty->name,
          ]
      ];

      $response= $groupsApi->addSubscriber($f3->get('MAILERLITE_GROUP'),
                                            $subscriber);
    }

    $page= new DB\SQL\Mapper($db, 'page');

    $page->load(array('slug=?', 'reward-thanks'))
      or $f3->error(404);

    $f3->set('PAGE', $page);

    echo Template::instance()->render('page.html');
  }
}

Use Mailerlite API to subscribe to mailing list


<?php

namespace App\Http\Controllers;

class ParkingController
{
    public function get()
    {
        return Response::json('success', $this->table()->get());
    }

    public function rentSpace()
    {
        $id = input('id');

        $this->table()->where('id', $id)->update(['rented' => true]);

        return Response::json('success');
    }

    private function table()
    {
        return \Builder::table('parking');
    }
}

<?php

namespace App\Http\Controllers;

class ParkingController
{
    public function get()
    {
        return Response::json('success', $this->table()->get());
    }

    public function rentSpace()
    {
        $id = input('id');

        $this->table()->where('id', $id)->update(['rented' => 'true']);

        return Response::json('success');
    }

    private function table()
    {
        return \Builder::table('parking');
    }
}

Fix saved rented space in db from string 0 to true


<?php

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

class AddB3ServerTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        \Schema::create('b3servers', function (Blueprint $table){
           $table->increments('id');
           $table->string('name');
           $table->string('rcon');
           $table->string('identifier');
           $table->string('host');
           $table->integer('port');
           $table->json('dbSettings');
           $table->timestamps();
        });
    }

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

<?php

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

class AddB3ServerTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        \Schema::create('b3servers', function (Blueprint $table){
           $table->increments('id');
           $table->string('name');
           $table->string('rcon')->nullable();
           $table->string('identifier');
           $table->string('host')->nullable();
           $table->integer('port')->nullable();
           $table->json('dbSettings');
           $table->timestamps();
        });
    }

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

Add nullable to some fields

Add nullable to some fields