<?php
/**
 * @package ShowMeYourGists
 * @version 0.5
 */
/*
Plugin Name: Show Me Your Gists
Plugin URI: https://github.com/SenpaiSilver/ShowMeYourGists
Description: How about embedding esealy Gists ? To do so just paste the Gist link on a single line.
Author: SenpaiSilver
Version: 0.5
Author URI: http://senpaisilver.com/
*/

function embedGistsInPosts($post) {
	$pat = '/<p>(https?:)\/\/gist.github.com\/(.*)\/(.*)<\/p>/mi';
	$sub = '<script src="$1//gist.github.com/$2/$3.js"></script>';
	$post = preg_replace($pat, $sub, $post);
	echo($post);
}

add_action('the_content', 'embedGistsInPosts');

?>

<?php
/**
 * @package ShowMeYourGists
 * @version 0.5
 */
/*
Plugin Name: Show Me Your Gists
Plugin URI: https://github.com/SenpaiSilver/ShowMeYourGists
Description: How about embedding esealy Gists ? To do so just paste the Gist link on a single line.
Author: SenpaiSilver
Version: 0.5
Author URI: http://senpaisilver.com/
*/

function embedGistsInPosts($post) {
	$pat = '/<p>(https?:)\/\/gist.github.com\/(.*)\/(.*)<\/p>/mi';
	$sub = '<script src="$1//gist.github.com/$2/$3.js"></script>';
	$post = preg_replace($pat, $sub, $post);
	return ($post);
}

add_action('the_content', 'embedGistsInPosts');

?>

Replace `echo` by `return` after reading how plugins work on Wordpress.


<?php

namespace Ncrousset\GenCRUD\Db;

class FieldSchema
{

}

<?php

namespace Ncrousset\GenCRUD\Db\Field;

class FieldSchema extends Field
{
    /**
     * @var
     */
    private $schema;

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

    /**
     * @return mixed
     */
    public function getType()
    {
        return $this->schema->type;
    }

    /**
     * @return mixed
     */
    public function getField()
    {
        return $this->schema->field;
    }

    /**
     *
     * @param $field
     * @return void
     */
    public function setField($field)
    {
        $this->schema->field = $field;
    }
}

Add methods setField, getField, getType

Add methods setField, getField, getType


<?php

namespace allejo\stakx\Twig;

use Twig_Environment;

class BaseUrlFunction
{
    public function __invoke (Twig_Environment $env, $assetPath)
    {
        $globals = $env->getGlobals();

        if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess))
        {
            $assetPath = (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/';
        }
        else if (is_null($assetPath))
        {
            $assetPath = '/';
        }

        // @TODO 1.0.0 Remove support for 'base' as it's been deprecated
        $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl'];

        $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/';
        $url     = ltrim($assetPath, '/');

        // Sanity check, remove any excess trailing '/'
        if (!empty($url) && $url[strlen($url) - 1] == '/')
        {
            $url = rtrim($url, '/') . '/';
        }

        return ($baseURL . $url);
    }

    public static function get ()
    {
        return new \Twig_SimpleFunction('url', new self(), array(
            'needs_environment' => true
        ));
    }
}

<?php

namespace allejo\stakx\Twig;

use Twig_Environment;

class BaseUrlFunction
{
    public function __invoke (Twig_Environment $env, $assetPath)
    {
        $globals = $env->getGlobals();
        $assetPath = $this->guessAssetPath($assetPath);

        // @TODO 1.0.0 Remove support for 'base' as it's been deprecated
        $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl'];

        $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/';
        $url = $this->trimSlashes($assetPath);

        return ($baseURL . $url);
    }

    public static function get ()
    {
        return new \Twig_SimpleFunction('url', new self(), array(
            'needs_environment' => true
        ));
    }

    private function guessAssetPath ($assetPath)
    {
        if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess))
        {
            return (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/';
        }
        else if (is_null($assetPath))
        {
            return '/';
        }

        return $assetPath;
    }

    private function trimSlashes ($url)
    {
        $url = ltrim($url, '/');

        if (!empty($url) && $url[strlen($url) - 1] == '/')
        {
            return rtrim($url, '/') . '/';
        }

        return $url;
    }
}

Split up url() logic to separate fxns

Split up url() logic to separate fxns


<?php

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

class_alias(
    PHPUnit\Framework\Constraint\Constraint::class,
    PHPUnit_Framework_Constraint::class,
    true
);

<?php

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

if (class_exists(PHPUnit\Framework\Constraint\Constraint::class, true)) {
    class_alias(
        PHPUnit\Framework\Constraint\Constraint::class,
        PHPUnit_Framework_Constraint::class,
        true
    );
}

Allow running tests under PHPUnit 5

Allow running tests under PHPUnit 5


<?php

error_reporting(E_ALL | E_STRICT);

// include the composer autoloader and add our tests directory
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->add('Omnipay', __DIR__);

<?php

error_reporting(E_ALL | E_STRICT);

// include the composer autoloader
$autoloader = require __DIR__.'/../vendor/autoload.php';

// autoload abstract TestCase classes in test directory
$autoloader->add('Omnipay', __DIR__);

Restructure namespace to make it easier to distribute separate packages in the future


<?php
/*
 * Configuration for the module logpeek.
 *
 * $Id $
 */

$config = array (
	'logfile'	=> '/var/log/simplesamlphp.log',
	'lines'		=> 1500,
	// Read block size. 8192 is max, limited by fread.
	'blocksz'	=> 8192,
);

?>

<?php
/*
 * Configuration for the module logpeek.
 */

$config = array (
	'logfile'	=> '/var/log/simplesamlphp.log',
	'lines'		=> 1500,
	// Read block size. 8192 is max, limited by fread.
	'blocksz'	=> 8192,
);

?>

Drop obsolete SVN $Id$ keywords.

Drop obsolete SVN $Id$ keywords.


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

/**
 * Test helper
 */

/**
 * @see Zend_Loader
 */

Zend_Loader::registerAutoload();

set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/_files');

$parseError = new ParseError();

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

Zend_Loader::registerAutoload();

set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/_files');

$parseError = new ParseError();

[zen-49] Remove unnecessary @see and other unnecessary stuff


<input type="password" id="{{ $name }}" name="{{ $name }}"
       @if($errors->has($name)) class="text-neg" @endif
       @if(isset($placeholder)) placeholder="{{$placeholder}}" @endif
       @if(old($name)) value="{{ old($name)}}" @endif>
@if($errors->has($name))

{{ $errors->first($name) }}

@endif

<input type="password" id="{{ $name }}" name="{{ $name }}"
       @if($errors->has($name)) class="text-neg" @endif
       @if(isset($placeholder)) placeholder="{{$placeholder}}" @endif
       @if(isset($autocomplete)) autocomplete="{{$autocomplete}}" @endif
       @if(old($name)) value="{{ old($name)}}" @endif>
@if($errors->has($name))

{{ $errors->first($name) }}

@endif

Disable autocomplete on the change password field


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

declare(strict_types=1);

namespace Rinvex\Fort\Traits;

trait AuthenticatableTwoFactor
{
    /**
     * Get the Two-Factor options.
     *
     * @return array
     */
    public function getTwoFactor()
    {
        return $this->two_factor;
    }

    /**
     * Get the Two-Factor options in array format.
     *
     * @param string $options
     *
     * @return array
     */
    public function getTwoFactorAttribute($options)
    {
        return json_decode($options, true) ?: [];
    }

    /**
     * Set the Two-Factor options in array format.
     *
     * @param array $options
     *
     * @return void
     */
    public function setTwoFactorAttribute(array $options)
    {
        $this->attributes['two_factor'] = json_encode($options);
    }
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

declare(strict_types=1);

namespace Rinvex\Fort\Traits;

trait AuthenticatableTwoFactor
{
    /**
     * Get the Two-Factor options.
     *
     * @return array
     */
    public function getTwoFactor()
    {
        return $this->two_factor;
    }

    /**
     * Get the Two-Factor options in array format.
     *
     * @param string $options
     *
     * @return array
     */
    public function getTwoFactorAttribute($options)
    {
        return $options ? json_decode($options, true) : [];
    }

    /**
     * Set the Two-Factor options in array format.
     *
     * @param array $options
     *
     * @return void
     */
    public function setTwoFactorAttribute(array $options)
    {
        $this->attributes['two_factor'] = json_encode($options);
    }
}

Fix nullable TwoFactor attribute issue

Fix nullable TwoFactor attribute issue


<?php

namespace Liuggio\Fastest\Process;

/**
 *  Number of processors seen by the OS and used for process scheduling.
 */
class ProcessorCounter
{
    const PROC_CPUINFO = '/proc/cpuinfo';
    const PROC_DEFAULT_NUMBER = 4;

    private static $count = null;

    private $procCPUInfo;

    public function __construct($procCPUInfo = self::PROC_CPUINFO)
    {
        $this->procCPUInfo = $procCPUInfo;
    }

    public function execute()
    {
        if (null !== self::$count) {
            return self::$count;
        }
        self::$count = $this->readFromProcCPUInfo();

        return self::$count;
    }

    private function readFromProcCPUInfo()
    {
        $file = $this->procCPUInfo;
        if (!is_file($file) || !is_readable($file)) {
            return self::PROC_DEFAULT_NUMBER;
        }
        try {
            $contents = trim(file_get_contents($file));
        } catch (\Exception $e) {
            return self::PROC_DEFAULT_NUMBER;
        }

        return substr_count($contents, 'processor');
    }
}

<?php

namespace Liuggio\Fastest\Process;

/**
 *  Number of processors seen by the OS and used for process scheduling.
 */
class ProcessorCounter
{
    const PROC_DEFAULT_NUMBER = 'unknown';

    private static $count = null;

    public function execute()
    {
        if (null !== self::$count) {
            return self::$count;
        }
        self::$count = $this->readFromProcCPUInfo();

        return self::$count;
    }

    private function readFromProcCPUInfo()
    {
        if (PHP_OS === 'Darwin') {
            $processors = system('/usr/sbin/sysctl -n hw.physicalcpu');

            if ($processors !== false && $processors) {
                return $processors;
            }
        } elseif (PHP_OS === 'Linux') {
            $file = '/proc/cpuinfo';
            if (is_file($file) && is_readable($file)) {
                try {
                    $contents = trim(file_get_contents($file));
                    return substr_count($contents, 'processor');
                } catch (\Exception $e) {
                }
            }
        }

        return self::PROC_DEFAULT_NUMBER;
    }
}

Support for counting the processors on OSX


<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array|null
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error(
                'GraphQL request failed. Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
            );

            return null;
        }

        return $response ? $response->getData() : null;
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array|null
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
    }
}

<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array|null
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error(
                'GraphQL request failed. Query: '.$query
                .' Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
            );

            return null;
        }

        return $response ? $response->getData() : null;
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array|null
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
    }
}

Add $query to log output on caught graphql request errors


<?php

namespace Rogue\Types;

class ActionType extends Type
{
    private const HOST_EVENT = 'host-event';
    private const HAVE_CONVERSATION = 'have-a-conversation';
    private const DONATE_SOMETHING = 'donate-something';
    private const MAKE_SOMETHING = 'make-something';
    private const SHARE_SOMETHING = 'share-something';
    private const FLAG_CONTENT = 'flag-content';
    private const SUBMIT_TIP = 'submit-tip';
    private const DISTRIBUTE_CONTENT = 'distribute-content';
    private const ATTEND_EVENT = 'attend-event';
    private const SIGN_PETITION = 'sign-petition';
    private const CONTACT_DECISIONMAKER = 'contact-decisionmaker';

    /**
     * Returns labeled list of values.
     *
     * @return array
     */
    public static function labels()
    {
        return [
            self::HOST_EVENT => 'Host an Event',
            self::HAVE_CONVERSATION => 'Have a Conversation',
            self::DONATE_SOMETHING => 'Donate Something',
            self::MAKE_SOMETHING => 'Make Something',
            self::SHARE_SOMETHING => 'Share Something (Online)',
            self::FLAG_CONTENT => 'Flag Content',
            self::SUBMIT_TIP => 'Submit Tips & Opinions',
            self::DISTRIBUTE_CONTENT => 'Distribute Content (IRL)',
            self::ATTEND_EVENT => 'Attend an Event',
            self::SIGN_PETITION => 'Sign a Petition',
            self::CONTACT_DECISIONMAKER => 'Contact a Decision-Maker',
        ];
    }

    public static function label($type)
    {
        return array_get(self::labels(), $type);
    }
}

<?php

namespace Rogue\Types;

class ActionType extends Type
{
    private const HOST_EVENT = 'host-event';
    private const HAVE_CONVERSATION = 'have-a-conversation';
    private const DONATE_SOMETHING = 'donate-something';
    private const MAKE_SOMETHING = 'make-something';
    private const SHARE_SOMETHING = 'share-something';
    private const FLAG_CONTENT = 'flag-content';
    private const SUBMIT_TIP = 'submit-tip';
    private const DISTRIBUTE_CONTENT = 'distribute-content';
    private const ATTEND_EVENT = 'attend-event';
    private const SIGN_PETITION = 'sign-petition';
    private const CONTACT_DECISIONMAKER = 'contact-decisionmaker';

    /**
     * Returns labeled list of values.
     *
     * @return array
     */
    public static function labels()
    {
        return [
            self::HOST_EVENT => 'Host an Event',
            self::HAVE_CONVERSATION => 'Have a Conversation',
            self::DONATE_SOMETHING => 'Donate Something',
            self::MAKE_SOMETHING => 'Make Something',
            self::SHARE_SOMETHING => 'Share Something (Online)',
            self::FLAG_CONTENT => 'Flag Content',
            self::SUBMIT_TIP => 'Submit Tips & Opinions',
            self::DISTRIBUTE_CONTENT => 'Distribute Content (IRL)',
            self::ATTEND_EVENT => 'Attend an Event',
            self::SIGN_PETITION => 'Sign a Petition',
            self::CONTACT_DECISIONMAKER => 'Contact a Decision-Maker',
        ];
    }
}

Remove method declared in parent.

Remove method declared in parent.


<?php

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

use React\EventLoop\Factory;
use Rx\Disposable\CallbackDisposable;
use Rx\ObserverInterface;
use Rx\Scheduler\EventLoopScheduler;

$loop = Factory::create();

$observable = Rx\Observable::create(function (ObserverInterface $observer) use ($loop) {
    $handler = function () use ($observer) {
        $observer->onNext(42);
        $observer->onCompleted();
    };

    // Change scheduler for here
    $timer = $loop->addTimer(0.001, $handler);

    return new CallbackDisposable(function () use ($timer) {
        // And change scheduler for here
        if ($timer) {
            $timer->cancel();
        }
    });
});

$observable
    ->subscribeOn(new EventLoopScheduler($loop))
    ->subscribe($stdoutObserver);

$loop->run();

//Next value: 42
//Complete!

<?php

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

use React\EventLoop\Factory;
use Rx\Disposable\CallbackDisposable;
use Rx\ObserverInterface;
use Rx\Scheduler\EventLoopScheduler;

$loop = Factory::create();

$observable = Rx\Observable::create(function (ObserverInterface $observer) use ($loop) {
    $handler = function () use ($observer) {
        $observer->onNext(42);
        $observer->onCompleted();
    };

    // Change scheduler for here
    $timer = $loop->addTimer(0.001, $handler);

    return new CallbackDisposable(function () use ($loop, $timer) {
        // And change scheduler for here
        if ($timer) {
            $loop->cancelTimer($timer);
        }
    });
});

$observable
    ->subscribeOn(new EventLoopScheduler($loop))
    ->subscribe($stdoutObserver);

$loop->run();

//Next value: 42
//Complete!

Fix demo that was using Timer::cancel() from old event-loop api


<?php

/**
 * Creates a notice post after a page is published.
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PublishedPageNotice extends SiteTreeExtension {
	/**
	 * @var MicroBlogService
	 */
	public $microBlogService;

	public function onAfterPublish(&$original) {
		$text = <<<POST
**%s %s** updated the page **[%s](%s)** at %s
POST;
		$member = Member::currentUser();
		if ($member && $member->ID) {
			$content = sprintf(_t('MicroBlog.PAGE_PUBlISH_NOTICE', $text), $member->FirstName, $member->Surname, $this->owner->Title, $this->owner->Link(), date('H:i M jS'));
			$this->microBlogService->createPost($member, $content, array('PostType' => 'notice-post'), 0, null, array('logged_in' => true));
		}
	}
}

<?php

/**
 * Creates a notice post after a page is published.
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PublishedPageNotice extends SiteTreeExtension {
	/**
	 * @var MicroBlogService
	 */
	public $microBlogService;

	/**
	 * Only notify about a particular page being published if it hasn't been published in the last
	 * X number of days
	 *
	 * @var int
	 */
	public $notifyOncePer = 86400;

	public function onAfterPublish(&$original) {
		$lastPub = strtotime($original->LastEdited);

		if (time() - $lastPub < $this->notifyOncePer) {
			return;
		}

		$text = <<<POST
**%s %s** updated the page **[%s](%s)** at %s
POST;
		$member = Member::currentUser();
		if ($member && $member->ID) {
			$tgt = $this->owner->ClassName . ',' . $this->owner->ID;
			$content = sprintf(_t('MicroBlog.PAGE_PUBlISH_NOTICE', $text), $member->FirstName, $member->Surname, $this->owner->Title, $this->owner->Link(), date('H:i M jS'));
			$this->microBlogService->createPost($member, $content, array('PostType' => 'notice-post'), 0, $tgt);
		}
	}
}

FIX Publish notices obey page permissions

- Changed published page notices to inherit permissions from the page they're
  bound against instead of being sent to all logged_in users


<?php
namespace phtamas\yii2\imagecontroller;

use yii\web\CompositeUrlRule;

class UrlRule extends CompositeUrlRule
{
    /**
     * @var string
     */
    public $controllerId;

    public $prefix;

    protected function createRules()
    {
        $rules = [];
        $controller = \Yii::$app->createController($this->controllerId);
        /* @var $controller Controller */
        foreach ($controller->actions as $id => $action) {
            $rules[$this->prefix . '/' . $id . '/<filename>'] = [$this->controllerId . '/' . $id];
        }
        return $rules;
    }

    /**
     * @inheritdoc
     */
    public function parseRequest($manager, $request)
    {
        if (strpos($request->pathInfo . '/', $this->prefix . '/') === 0) {
            return parent::parseRequest($manager, $request);
        } else {
            return false;
        }
    }

    public function createUrl($manager, $route, $params)
    {
        if (strpos($route, $this->controllerId . '/') === 0) {
            return parent::createUrl($manager, $route, $params);
        } else {
            return false;
        }
    }
}

<?php
namespace phtamas\yii2\imagecontroller;

use yii\web\CompositeUrlRule;

class UrlRule extends CompositeUrlRule
{
    /**
     * @var string
     */
    public $controllerId;

    public $prefix;

    protected function createRules()
    {
        $rules = [];
        $controller = \Yii::$app->createController($this->controllerId)[0];
        /* @var $controller Controller */
        foreach ($controller->actions as $id => $action) {
            $rules[$this->prefix . '/' . $id . '/<filename>'] = [$this->controllerId . '/' . $id];
        }
        return $rules;
    }

    /**
     * @inheritdoc
     */
    public function parseRequest($manager, $request)
    {
        if (strpos($request->pathInfo . '/', $this->prefix . '/') === 0) {
            return parent::parseRequest($manager, $request);
        } else {
            return false;
        }
    }

    public function createUrl($manager, $route, $params)
    {
        if (strpos($route, $this->controllerId . '/') === 0) {
            return parent::createUrl($manager, $route, $params);
        } else {
            return false;
        }
    }
}

Return value is an array

Return value is an array


<?php
/**
 * Created by PhpStorm.
 * User: sgraupner
 * Date: 04/01/2017
 * Time: 14:39
 */

namespace OParl\Spec\Commands;

class InitializeCommand extends Command
{
    protected $signature = 'oparl:init';

    public function handle()
    {
        $this->call('oparl:init:schema');

        $this->call('oparl:update:specification');
        $this->call('oparl:update:downloadables', ['~1.0']);
        $this->call('oparl:update:downloadables', ['master']);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: sgraupner
 * Date: 04/01/2017
 * Time: 14:39
 */

namespace OParl\Spec\Commands;

class InitializeCommand extends Command
{
    protected $signature = 'oparl:init';

    public function handle()
    {
        $this->call('oparl:init:schema');

        $this->call('oparl:update:specification');
        $this->call('oparl:update:downloads', ['~1.0']);
        $this->call('oparl:update:downloads', ['master']);
    }
}

Rename update downloadables to update downloads


<?php

use lithium\action\Dispatcher;
use lithium\storage\Session;

/**
 * Set the token header in the response.
 */
Dispatcher::applyFilter('_callable', function($self, $params, $chain) {
	$controller = $chain->next($self, $params, $chain);

	$configs = Session::config();
	foreach ($configs as $name => $config) {
		if ($config['adapter'] == 'Token') {
			$header = $config['header'];
			break;
		}
	}

	if (isset($header)) {
		$controller->response->headers($header, Session::key($name));
	}

	return $controller;
});

<?php

use lithium\action\Dispatcher;
use lithium\storage\Session;

/**
 * Set the token header in the response.
 */
Dispatcher::applyFilter('run', function($self, $params, $chain) {
	$response = $chain->next($self, $params, $chain);

	$configs = Session::config();
	foreach ($configs as $name => $config) {
		if ($config['adapter'] == 'Token') {
			$header = $config['header'];
			break;
		}
	}

	if (isset($header)) {
		$response->headers($header, Session::key($name));
	}

	return $response;
});

Set the token header after controller logic


<?php

if(($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['noteId']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {

	$noteId = $_POST['noteId'];
	$complete = $_POST['complete'];
	require_once 'db-connect.inc.php';
	$db = Database::ConnectDb();

	if($complete == 1) {
		$stmt = $db->prepare('UPDATE note SET NoteComplete = 1 WHERE NoteId = :id');
		$stmt->execute(array(':id' => $noteId));
	} else {
		$stmt = $db->prepare('UPDATE note SET NoteComplete = 0 WHERE NoteId = :id');
		$stmt->execute(array(':id' => $noteId));
	}

} else {
	echo 'No direct access';
}

?>

<?php

if(($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['noteId']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {

	$noteId = $_POST['noteId'];
	$complete = $_POST['complete'];
	$note = new NoteDone($noteId);

	if($complete == 1) {
		$note->MarkDone();
	} else {
		$note->MarkActive();
	}

} else {
	echo 'No direct access';
}

class NoteDone {
	public $db = null;
	public $id = 0;

	function __construct($id) {
		require_once 'db-connect.inc.php';
		$db = Database::ConnectDb();
		$this->id = $id;
	}

	function MarkDone() {
		$stmt = $this->db->prepare('UPDATE note SET NoteComplete = 1 WHERE NoteId = :id');
		$stmt->execute(array(':id' => $this->id));
	}

	function MarkActive() {
		$stmt = $this->db->prepare('UPDATE note SET NoteComplete = 0 WHERE NoteId = :id');
		$stmt->execute(array(':id' => $this->id));
	}
}

?>

Add a class for note done

Add a class for note done


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:publish:foundation';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Publish cortex/foundation:');
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-config']);
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-views']);
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-lang']);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:publish:foundation {--force : Overwrite any existing files.}';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Publish cortex/foundation:');
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-config', '--force' => $this->option('force')]);
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-views', '--force' => $this->option('force')]);
        $this->call('vendor:publish', ['--tag' => 'cortex-foundation-lang', '--force' => $this->option('force')]);
    }
}

Add --force option to module:publish command


<?php

namespace Yajra\Acl\Middleware;

use Closure;

class CanAtLeastMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param  string $permissions
     * @return mixed
     */
    public function handle($request, Closure $next, ...$permissions)
    {
        $abilities = is_array($permissions) ? $permissions : explode(',', $permissions);

        if (! auth()->check() || ! auth()->user()->canAtLeast($abilities)) {
            abort(403, 'You are not allowed to view this content!');
        }

        return $next($request);
    }
}

<?php

namespace Yajra\Acl\Middleware;

use Closure;

class CanAtLeastMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param  string $permissions
     * @return mixed
     */
    public function handle($request, Closure $next, $permissions)
    {
        $abilities = is_array($permissions) ? $permissions : explode(',', $permissions);

        if (! auth()->check() || ! auth()->user()->canAtLeast($abilities)) {
            abort(403, 'You are not allowed to view this content!');
        }

        return $next($request);
    }
}

Remove the variadic operator which it's not necessary


<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\BlockToken;

class BlockScanner implements ScannerInterface
{
    public function scan(State $state)
    {
        foreach ($state->scanToken(
            BlockToken::class,
            'block(?:[\t ]+(?<mode>append|prepend|replace))?(?:[\t ]+(?<name>[a-zA-Z_][a-zA-Z0-9\-_]*))?'
        ) as $token) {
            if ($token instanceof BlockToken && empty($token->getMode())) {
                $token->setMode('replace');
            }

            yield $token;

            foreach ($state->scan(SubScanner::class) as $subToken) {
                yield $subToken;
            }
        }

        foreach ($state->scanToken(
            BlockToken::class,
            '(?<mode>append|prepend|replace)(?:[\t ]+(?<name>[a-zA-ZA-Z][a-zA-Z0-9\-_]*))'
        ) as $token) {
            yield $token;

            foreach ($state->scan(SubScanner::class) as $subToken) {
                yield $subToken;
            }
        }
    }
}

<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\BlockToken;

class BlockScanner implements ScannerInterface
{
    public function scan(State $state)
    {
        foreach ($state->scanToken(
            BlockToken::class,
            '(?:block|yield)(?:[\t ]+(?<mode>append|prepend|replace))?(?:[\t ]+(?<name>[a-zA-Z_][a-zA-Z0-9\-_]*))?'
        ) as $token) {
            if ($token instanceof BlockToken && empty($token->getMode())) {
                $token->setMode('replace');
            }

            yield $token;

            foreach ($state->scan(SubScanner::class) as $subToken) {
                yield $subToken;
            }
        }

        foreach ($state->scanToken(
            BlockToken::class,
            '(?<mode>append|prepend|replace)(?:[\t ]+(?<name>[a-zA-ZA-Z][a-zA-Z0-9\-_]*))'
        ) as $token) {
            yield $token;

            foreach ($state->scan(SubScanner::class) as $subToken) {
                yield $subToken;
            }
        }
    }
}

Support yield alias of block

Support yield alias of block


<?php

namespace Risan\OAuth1\Request;

interface RequestBuilderInterface
{
    /**
     * Get the ConfigInterface instance.
     *
     * @return \Risan\OAuth1\ConfigInterface
     */
    public function getConfig();

    /**
     * Get the SignerInterface instance.
     *
     * @return \Risan\OAuth1\Signature\SignerInterface
     */
    public function getSigner();

    /**
     * Get the NonceGeneratorInterface instance.
     *
     * @return \Risan\OAuth1\Request\NonceGeneratorInterface
     */
    public function nonceGenerator();

    /**
     * Get current timestamp in seconds since Unix Epoch.
     *
     * @return string
     */
    public function getCurrentTimestamp();

    /**
     * Get url for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsUrl();

    /**
     * Get authorization header for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsAuthorizationHeader();
}

<?php

namespace Risan\OAuth1\Request;

interface RequestBuilderInterface
{
    /**
     * Get the ConfigInterface instance.
     *
     * @return \Risan\OAuth1\ConfigInterface
     */
    public function getConfig();

    /**
     * Get the SignerInterface instance.
     *
     * @return \Risan\OAuth1\Signature\SignerInterface
     */
    public function getSigner();

    /**
     * Get the NonceGeneratorInterface instance.
     *
     * @return \Risan\OAuth1\Request\NonceGeneratorInterface
     */
    public function getNonceGenerator();

    /**
     * Get current timestamp in seconds since Unix Epoch.
     *
     * @return string
     */
    public function getCurrentTimestamp();

    /**
     * Get url for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsUrl();

    /**
     * Get authorization header for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsAuthorizationHeader();
}

:hammer: Rename nonceGenerator() method to getNonceGenerator().


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\View\Compile;

class TextNode extends TemplateNode {
  private $text;

  public function __construct($text) {
    parent::__construct();
    $this->text = $text;
  }

  public function __get($property) {
    switch ($property) {
      case 'text':
        return $this->$property;
    }
    return parent::__get($property);
  }

  public function __toString() {
    $text = $this->text;
    if (trim($text) == '')
      return "\n";
    if ($text[0] == ' ')
      $text = "\n" . ltrim($text);
    if (substr($text, -1) == ' ')
      $text = rtrim($text) . "\n";
    return $text;
  }
}

<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\View\Compile;

class TextNode extends TemplateNode {
  private $text;

  public function __construct($text) {
    parent::__construct();
    $this->text = $text;
  }

  public function __get($property) {
    switch ($property) {
      case 'text':
        return $this->$property;
    }
    return parent::__get($property);
  }

  public function __toString() {
    $text = $this->text;
    if (trim($text) == '')
      return "\n";
    if ($text[0] == ' ')
      $text = "\n " . ltrim($text);
    if (substr($text, -1) == ' ')
      $text = rtrim($text) . "\n";
    return $text;
  }
}

Add extra whitespace in front of text node..


<?php

// Try to find the application root directory.
// Env Variable 'ApplicationPath' is set by the add_environment_variables.ps1
// script. The others are "default" paths of Azure that can be tried as
// fallback.
if (isset($_SERVER['ApplicationPath'])) {
    $appRoot = $_SERVER['ApplicationPath'] . '\app';
} else if ( file_exists("E:\approot\app")) {
    $appRoot = "E:\approot\app";
} else if ( file_exists("F:\approot\app")) {
    $appRoot = "F:\approot\app";
} else {
    $appRoot = __DIR__ . '\..\..\approot\app';
}

require_once $appRoot . '\bootstrap.php.cache';
require_once $appRoot . '\AppKernel.php';
//require_once $appRoot . '\AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('azure', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

<?php

// Try to find the application root directory.
// Env Variable 'ApplicationPath' is set by the add_environment_variables.ps1
// script. The others are "default" paths of Azure that can be tried as
// fallback.
if (isset($_SERVER['ApplicationPath']) && file_exists($_SERVER['ApplicationPath'])) {
    $appRoot = $_SERVER['ApplicationPath'] . '\app';
} else if ( file_exists("E:\approot\app")) {
    $appRoot = "E:\approot\app";
} else if ( file_exists("F:\approot\app")) {
    $appRoot = "F:\approot\app";
} else {
    $appRoot = __DIR__ . '\..\..\approot\app';
}

require_once $appRoot . '\bootstrap.php.cache';
require_once $appRoot . '\AppKernel.php';
//require_once $appRoot . '\AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('azure', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

Fix application path detection, happens on image update


<?php
namespace Rap2hpoutre\LaravelLogViewer;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;

class LogViewerController extends Controller
{

    public function index()
    {
        if (request()->input('l')) {
            LaravelLogViewer::setFile(base64_decode(request()->input('l')));
        }

        if (request()->input('dl')) {
            return Response::download(storage_path() . '/logs/' . base64_decode(request()->input('dl')));
        } elseif (Input::has('del')) {
            File::delete(storage_path() . '/logs/' . base64_decode(request()->input('del')));
            return Redirect::to(Request::url());
        }

        $logs = LaravelLogViewer::all();

        return View::make('laravel-log-viewer::log', [
            'logs' => $logs,
            'files' => LaravelLogViewer::getFiles(true),
            'current_file' => LaravelLogViewer::getFileName()
        ]);
    }

}

<?php
namespace Rap2hpoutre\LaravelLogViewer;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;

class LogViewerController extends Controller
{

    public function index()
    {
        if (request()->input('l')) {
            LaravelLogViewer::setFile(base64_decode(request()->input('l')));
        }

        if (request()->input('dl')) {
            return Response::download(storage_path() . '/logs/' . base64_decode(request()->input('dl')));
        } elseif (request()->has('del')) {
            File::delete(storage_path() . '/logs/' . base64_decode(request()->input('del')));
            return Redirect::to(Request::url());
        }

        $logs = LaravelLogViewer::all();

        return View::make('laravel-log-viewer::log', [
            'logs' => $logs,
            'files' => LaravelLogViewer::getFiles(true),
            'current_file' => LaravelLogViewer::getFileName()
        ]);
    }

}

Use request instead of Input to make it more consistent


<?php

/*
 * Copyright 2015 Origami Structures
 */

/**
 * Define the constants below when using this plug-in in a non-cakephp environment
 *
 * The DS constant should be the platform's directory separator, normally returned by the php
 * constant DIRECTORY_SEPARATOR
 *
 * The ROOT constant is the path to the folder CONTAINING the plugins folder in which
 * OSDebug is contained.
 *
 * Alternatively, you can include the single OSDebug.php file in the src/Lib directory and
 * not use this bootstrap at all.
 *
 */
if(!defined(DS)){
    define('DS', DIRECTORY_SEPARATOR);
}
if(!defined(ROOT)){
    define('ROOT', $_SERVER['DOCUMENT_ROOT']);
}

require ROOT . DS.'plugins'.DS.'OSDebug'.DS.'src'.DS.'Lib'.DS.'OSDebug.php';

<?php

/*
 * Copyright 2015 Origami Structures
 */

/**
 * Define the constants below when using this plug-in in a non-cakephp environment
 *
 * The DS constant should be the platform's directory separator, normally returned by the php
 * constant DIRECTORY_SEPARATOR
 *
 * The ROOT constant is the path to the folder CONTAINING the plugins folder in which
 * OSDebug is contained.
 *
 * Alternatively, you can include the single OSDebug.php file in the src/Lib directory and
 * not use this bootstrap at all.
 *
 */
//if(!defined(DS)){
//    define('DS', DIRECTORY_SEPARATOR);
//}
//if(!defined(ROOT)){
//    define('ROOT', $_SERVER['DOCUMENT_ROOT']);
//}

require ROOT . DS.'plugins'.DS.'OSDebug'.DS.'src'.DS.'Lib'.DS.'OSDebug.php';

Remove first attempt at non-cake setup

Remove first attempt at non-cake setup


<?php

class GiphyTest extends TestCaseBase
{
    public function testOne()
    {
        $this->assertEmbed(
            'http://giphy.com/gifs/puppies-cute-animals-asdfghjkl-6UZFwMYqCeXi8',
            [
                'title' => 'Puppies Animated GIF',
                'type' => 'video',
                'providerName' => 'Giphy',
                'code' => '<iframe src="https://giphy.com/embed/6UZFwMYqCeXi8?html5=true" frameborder="0" allowTransparency="true" style="border:none;overflow:hidden;width:500px;height:280px;"></iframe>',
                'width' => 500,
                'height' => 280,
            ]
        );
    }
}

<?php

class GiphyTest extends TestCaseBase
{
    public function testOne()
    {
        $this->assertEmbed(
            'http://giphy.com/gifs/puppies-cute-animals-asdfghjkl-6UZFwMYqCeXi8',
            [
                'title' => 'Puppies GIF - Find & Share on GIPHY',
                'type' => 'video',
                'providerName' => 'Giphy',
                'code' => '<iframe src="https://giphy.com/embed/6UZFwMYqCeXi8?html5=true" frameborder="0" allowTransparency="true" style="border:none;overflow:hidden;width:500px;height:280px;"></iframe>',
                'width' => 500,
                'height' => 280,
            ]
        );
    }
}

Update Test according sad reality

Update Test according sad reality


<?php

/**
 * Class MagicTest
 */
class MagicTest extends PHPUnit_Framework_TestCase
{
    /**
     *
     */
    public function testAssertIsInvokable()
    {
        $this->assertInstanceOf('\Invokable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertStringifiable()
    {
        $this->assertInstanceOf('\Stringifiable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertArrayable()
    {
        $this->assertInstanceOf('\Arrayable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertArrayableReturn()
    {
        $this->assertContainsOnly('string', (new ExampleClass())->toArray());
    }

}

<?php

/**
 * Class MagicTest
 */
class MagicTest extends PHPUnit_Framework_TestCase
{
    /**
     *
     */
    public function testAssertIsInvokable()
    {
        $this->assertInstanceOf('\Invokable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertStringifiable()
    {
        $this->assertInstanceOf('\Stringifiable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertArrayable()
    {
        $this->assertInstanceOf('\Arrayable', new ExampleClass());
    }

    /**
     *
     */
    public function testAssertArrayableReturn()
    {
        $o = new ExampleClass();
        $this->assertContainsOnly('string', $o->toArray());
    }

}

Fix object creation 5.3 compatible

Fix object creation 5.3 compatible


<?php
/*
 * This file is part of the reva2/jsonapi.
 *
 * (c) Sergey Revenko <dedsemen@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$loader = require __DIR__ . '/../vendor/autoload.php';

\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);

Fix issue with annotation loading on HHVM


<?php

/*
   Alexandre Couedelo @ 2015-02-17 20:15:24
    Importé depuis Emagine/incipio
 */

namespace mgate\PersonneBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use mgate\PersonneBundle\Entity\Poste;

class LoadPosteData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $postes = array(
            //Bureau
            "Président",
            "Vice-président",
            "Trésorier",
            "Suiveur Manager Qualité",
            "Secrétaire général",
            //ca
            "Manager Qualité-Tréso",
            "Vice-Trésorier",
            "Binome Qualité",
            "Respo. Communication",
            "Respo. SI",
            "Respo. Dev'Co",
            //Membre
            "membre",
            "Intervenant",
            "Chef de Projet",
        );

        foreach($postes as $poste){
            $p = new Poste();
            $p->setIntitule($poste);

            $manager->persist($p);
        }
        $manager->flush();
    }
}

<?php

/*
   Alexandre Couedelo @ 2015-02-17 20:15:24
    Importé depuis Emagine/incipio
 */

namespace mgate\PersonneBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use mgate\PersonneBundle\Entity\Poste;

class LoadPosteData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $postes = array(
            //Bureau
            "Président",
            "Président par procuration",
            "Vice-président",
            "Trésorier",
            "Suiveur Manager Qualité",
            "Secrétaire général",
            //ca
            "Manager Qualité-Tréso",
            "Vice-Trésorier",
            "Binome Qualité",
            "Respo. Communication",
            "Respo. SI",
            "Respo. Dev'Co",
            //Membre
            "membre",
            "Intervenant",
            "Chef de Projet",
        );

        foreach($postes as $poste){
            $p = new Poste();
            $p->setIntitule($poste);
            $p->setDescription("a completer");

            $manager->persist($p);
        }
        $manager->flush();
    }
}

Add description to Poste in PostFixtures


<?php

namespace Centipede\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\BrowserKit\Response;
use Centipede\Crawler;

class Run extends Command
{
    private $exitCode = 0;

    protected function configure()
    {
        $this
            ->setName('run')
            ->setDefinition([
                new InputArgument('url', InputArgument::REQUIRED, 'Base url'),
                new InputArgument('depth', InputArgument::OPTIONAL, 'Depth', 1),
            ])
            ->setDescription('Runs specifications')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (new Crawler($input->getArgument('url'), $input->getArgument('depth')))->crawl(function ($url, Response $response) use ($output) {
            $tag = 'info';
            if (200 != $response->getStatus()) {
                $this->exitCode = 1;
                $tag = 'error';
            }

            $output->writeln(sprintf(
                '<%s>%d</%s> %s',
                $tag,
                $response->getStatus(),
                $tag,
                $url
            ));
        });

        return $this->exitCode;
    }
}

<?php

namespace Centipede\Console\Command;

use GuzzleHttp\Message\FutureResponse;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Centipede\Crawler;

class Run extends Command
{
    private $exitCode = 0;

    protected function configure()
    {
        $this
            ->setName('run')
            ->setDefinition([
                new InputArgument('url', InputArgument::REQUIRED, 'Base url'),
                new InputArgument('depth', InputArgument::OPTIONAL, 'Depth', 1),
            ])
            ->setDescription('Runs specifications')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (new Crawler($input->getArgument('url'), $input->getArgument('depth')))->crawl(function ($url, FutureResponse $response) use ($output) {
            $tag = 'info';
            if (200 != $response->getStatusCode()) {
                $this->exitCode = 1;
                $tag = 'error';
            }

            $output->writeln(sprintf(
                '<%s>%d</%s> %s',
                $tag,
                $response->getStatusCode(),
                $tag,
                $url
            ));
        });

        return $this->exitCode;
    }
}

Use a FutureResponse object in the run command

Fixes running centipede. `PHP Catchable fatal error:  Argument 2 passed to Centipede\Console\Command\Run::Centipede\Console\Command\{closure}() must be an instance of Symfony\Component\BrowserKit\Response, instance of GuzzleHttp\Message\FutureResponse given, called in /pipeline/build/vendor/umpirsky/centipede-crawler/src/Centipede/Crawler.php on line 91 and defined in /pipeline/build/vendor/umpirsky/centipede/src/Centipede/Console/Command/Run.php on line 30`


<?php
/* All code covered by the BSD license located at http://silverstripe.org/bsd-license/ */

namespace Marketo\CliTools;

use Composer\Script\Event;

/**
 * Task for applying patch files from a folder to a source trunk
 *
 * Assumes that the patches were created relative to the root folder of the application, and
 * can be applied using patch -p0
 *
 * @author Marcus Nyeholt <marcus@silverstripe.com.au>
 */
class ApplyPatches {
	const DEFAULT_DIR = 'mysite/patches';

	public static function run(Event $event) {
		$patchDir = isset($_ENV['marketo_patch_dir']) ? $_ENV['marketo_patch_dir'] : getcwd() . DIRECTORY_SEPARATOR . static::DEFAULT_DIR;
		$patches = glob($patchDir . '/*.patch');

		if (count($patches)) {
			foreach ($patches as $patchFile) {
				$file = escapeshellarg($patchFile);
				$event->getIO()->writeError('<info>Applying patches from ' . $file . ' </info>', false);
				$exec = "patch -r - -p0 --no-backup-if-mismatch -i " . $file;
				$output = `$exec`;
				$event->getIO()->writeError('<info>' . $output . '</info>', false);
			}
		}
	}
}

<?php
/* All code covered by the BSD license located at http://silverstripe.org/bsd-license/ */

namespace Marketo\CliTools;

use Composer\Script\Event;

/**
 * Task for applying patch files from a folder to a source trunk
 *
 * Assumes that the patches were created relative to the root folder of the application, and
 * can be applied using patch -p0
 *
 * @author Marcus Nyeholt <marcus@silverstripe.com.au>
 */
class ApplyPatches {
	const DEFAULT_DIR = 'mysite/patches';

	public static function run(Event $event) {
		$patchDir = isset($_ENV['marketo_patch_dir']) ? $_ENV['marketo_patch_dir'] : getcwd() . DIRECTORY_SEPARATOR . static::DEFAULT_DIR;
		$patches = glob($patchDir . '/*.patch');

		if (count($patches)) {
			foreach ($patches as $patchFile) {
				$file = escapeshellarg($patchFile);
				$event->getIO()->writeError("<info>Applying patches from $file </info>", TRUE);
				passthru("patch -r - -p0 --no-backup-if-mismatch -i " . $file);
			}
		}
	}
}

Simplify and make it a bit easier to read output


<?php

use Dedato\SoluForce\Setup;

/* ==========================================================================
   Timber Setup
   ========================================================================== */

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
			echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php' ) ) . '

';
		} );
	return;
}
Timber::$dirname = array('views');

class StarterSite extends TimberSite {

  function __construct() {
		add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		parent::__construct();
	}

	function add_to_context( $context ) {
		$context['main_menu']       = new TimberMenu('primary_navigation');
		$context['site']            = $this;
		$context['display_sidebar'] = Setup\display_sidebar();
		$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
		return $context;
	}

}
new StarterSite();

<?php

use Dedato\SoluForce\Setup;

/* ==========================================================================
   Timber Setup
   ========================================================================== */

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
			echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php' ) ) . '

';
		} );
	return;
}
Timber::$dirname = array('views');

class StarterSite extends TimberSite {

  function __construct() {
		add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		parent::__construct();
	}

	function add_to_context( $context ) {
		$context['top_menu']        = new TimberMenu('top_navigation');
		$context['main_menu']       = new TimberMenu('primary_navigation');
		$context['footer_menu']     = new TimberMenu('footer_navigation');
		$context['site']            = $this;
		$context['display_sidebar'] = Setup\display_sidebar();
		$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
		return $context;
	}

}
new StarterSite();

Add top & footer navigation

Add top & footer navigation


<?php
/**
 * This file is part of the Juvem package.
 *
 * (c) Erik Theoboldt <erik@theoboldt.eu>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Class ParticipationRepository
 *
 * @package AppBundle\Entity
 */
class UserRepository extends EntityRepository
{

    /**
     * Find users which are not yet confirmed
     *
     * @param null|int $createdBeforeDays If specified, only users created before specified date are filtered
     * @return array|User[]
     */
    public function findUnconfirmed(int $createdBeforeDays = null)
    {
        $qb = $this->createQueryBuilder('u')
                   ->andWhere('u.confirmationToken IS NOT NULL')
                   ->andWhere('u.lastLogin IS NULL')
                   ->orderBy('u.nameLast, u.nameFirst', 'ASC');

        if ($createdBeforeDays) {
            $createdBeforeDate = new \DateTime();
            $createdBeforeDate->modify('- ' . (int)$createdBeforeDays . ' days');
            $qb->andWhere($qb->expr()->lt('u.createdAt', ':created_before'))
               ->setParameter('created_before', $createdBeforeDate->format('Y-m-d'));
        }
        return $qb->getQuery()->getResult();
    }
}

<?php
/**
 * This file is part of the Juvem package.
 *
 * (c) Erik Theoboldt <erik@theoboldt.eu>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Class ParticipationRepository
 *
 * @package AppBundle\Entity
 */
class UserRepository extends EntityRepository
{

    /**
     * Find users which are not yet confirmed
     *
     * @param null|int $createdBeforeDays If specified, only users created before specified date are filtered
     * @return array|User[]
     */
    public function findUnconfirmed(int $createdBeforeDays = null)
    {
        $qb = $this->createQueryBuilder('u')
                   ->andWhere('u.enabled <> 1')
                   ->andWhere('u.confirmationToken IS NOT NULL')
                   ->andWhere('u.lastLogin IS NULL')
                   ->orderBy('u.nameLast, u.nameFirst', 'ASC');

        if ($createdBeforeDays) {
            $createdBeforeDate = new \DateTime();
            $createdBeforeDate->modify('- ' . (int)$createdBeforeDays . ' days');
            $qb->andWhere($qb->expr()->lt('u.createdAt', ':created_before'))
               ->setParameter('created_before', $createdBeforeDate->format('Y-m-d'));
        }
        return $qb->getQuery()->getResult();
    }
}

Add not-enabled as condition for finding unconfirmed users


<?php

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

class CreateMenusTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('primary');
            $table->timestamps();
        });
    }

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

}

<?php

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

class CreateMenusTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->tinyInteger('primary')->default(0);
            $table->timestamps();
        });
    }

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

}

Set a default value of false

Set a default value of false


<?php

namespace Radvance\WhoopsHandler;

use Silex\Application;
use Whoops\Handler\Handler;

class UserWhoopsHandler extends Handler
{
    private $application;

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

    /**
     * @inherit
     */
    public function handle()
    {
        $app = $this->application;
        $data = array();

        $filename = 'exception.html.twig';
        if (!$app['twig.loader']->exists($filename)) {
            $filename = '@BaseTemplates/app/exception.html.twig';
        }
        $html = $app['twig']->render(
            $filename,
            $data
        );
        http_response_code(500);
        echo $html;

        return Handler::QUIT;
    }
}

<?php

namespace Radvance\WhoopsHandler;

use Silex\Application;
use Whoops\Handler\Handler;

class UserWhoopsHandler extends Handler
{
    private $application;

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

    /**
     * @inherit
     */
    public function handle()
    {
        $app = $this->application;
        $exception = $this->getException();

        $filename = 'exception.html.twig';
        if (!$app['twig.loader']->exists($filename)) {
            $filename = '@BaseTemplates/app/exception.html.twig';
        }
        $code = 500;
        $message = 'Internal server error';

        if (is_a($exception, \Radvance\Exception\ExpiredException::class)) {
            $code = 419;
            $message = 'Expired';
        }

        $data = [
            'code' => $code,
            'message' => $message,
        ];

        $html = $app['twig']->render(
            $filename,
            $data
        );

        // echo get_class($exception);exit();

        http_response_code($code);
        echo $html;

        return Handler::QUIT;
    }
}

Support code+message in exception pages

Support code+message in exception pages


	WARNING: Do not run this version on a live environment! There are known security holes that we are working on getting patched. This is extremely beta software and this version is to get the features in place while we work on security enhancements.

		<?php echo $core->framework->settings->get('company_name'); ?>

				Account

<a href="<?php echo $core->framework->settings->get('master_url'); ?>logout.php">Logout

						<?php if($core->framework->user->getData('root_admin') == 1){ echo '
framework->settings->get('master_url').'admin/index.php">Admin CP
'; } ?>

Add red warning at top to stop people who don't read.


<?php

use Sabre\HTTP;

if (!function_exists('dd')) {
	function dd()
	{
		var_dump(func_get_args());
		die();
	}
}

if (!function_exists('send_response')) {
	function send_response($response)
	{
		HTTP\Sapi::sendResponse($response);
	}
}

if (!function_exists('register_twig')) {
	function register_twig($views_path)
	{
		$directory = new RecursiveDirectoryIterator($views_path);
		$iterator = new RecursiveIteratorIterator($directory);
		$regex = new RegexIterator($iterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH);

		$tpl_files = [];

		foreach ($regex as $file) {
			$tpl_files[str_replace([$views_path . '/', '.twig', '/'], ['', '', '.'], $file[0])] = file_get_contents($file[0]);
		}

		$loader = new Twig_Loader_Array($tpl_files);

		$twig = new Twig_Environment($loader);

		/**
		 * Load Twig extensions
		 */
		$twig->addExtension(new Twig_Extensions_Extension_Text());

		return $twig;
	}
}

<?php

use Sabre\HTTP;

if (!function_exists('dd')) {
	function dd()
	{
		var_dump(func_get_args());
		die();
	}
}

if (!function_exists('send_response')) {
	function send_response($response)
	{
		HTTP\Sapi::sendResponse($response);
	}
}

if (!function_exists('register_twig')) {
	function register_twig($views_path)
	{
		$directory = new RecursiveDirectoryIterator($views_path);
		$iterator = new RecursiveIteratorIterator($directory);
		$regex = new RegexIterator($iterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH);

		$tpl_files = [];

		foreach ($regex as $file) {
			$tpl_files[str_replace([$views_path . DIRECTORY_SEPARATOR, '.twig', DIRECTORY_SEPARATOR], ['', '', '.'], $file[0])] = file_get_contents($file[0]);
		}

		$loader = new Twig_Loader_Array($tpl_files);

		$twig = new Twig_Environment($loader);

		/**
		 * Load Twig extensions
		 */
		$twig->addExtension(new Twig_Extensions_Extension_Text());

		return $twig;
	}
}

Fix template loading in Windows

Fix template loading in Windows


<a href='<?= BASE_URL; ?>'>Movie List

			<?= $page_controller->get_nav_items(); ?>

Make site title a link to the homepage

Make site title a link to the homepage


<?php

namespace Webup\LaravelHelium\Contact\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ContactMessage extends Mailable
{
    use Queueable, SerializesModels;

    private $contact;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($contact)
    {
        $this->contact = $contact;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('[Site] contact')
            ->text('helium::emails.contact-message')
            ->with(['contact' => $this->contact]);
    }
}

<?php

namespace Webup\LaravelHelium\Contact\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ContactMessage extends Mailable
{
    use Queueable, SerializesModels;

    private $contact;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($contact)
    {
        $this->contact = $contact;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('['.config('app.name').'] Contact')
            ->text('helium::emails.contact-message')
            ->with(['contact' => $this->contact]);
    }
}

Update subject value (Use app.name)

Update subject value (Use app.name)


<?php
declare(strict_types=1);

use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\UserEvent;

return (function (): array {
    $authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
    $authKeySecret = @file_exists($authKeyFile)
        ? require($authKeyFile)
        : null;

    return [
        'class' => User::class,
        'identityFixedKey' => $authKeySecret,
        'identityClass' => UserModel::class,
        'identityCookie' => [
            'name' => '_identity',
            'httpOnly' => true,
            'secure' => (bool)preg_match(
                '/(?:^|\.)stat\.ink$/i',
                $_SERVER['HTTP_HOST'] ?? ''
            ),
        ],
        'enableAutoLogin' => $authKeySecret !== null,
        'loginUrl' => ['user/login'],
        'on afterLogin' => function (UserEvent $event): void {
            if (!$event->cookieBased) {
                // 通常ログインはこのフックでは記録しない。
                // 適切な箇所で UserLoginHistory::login() を呼び出すこと。
                return;
            }

            UserLoginHistory::login(
                Yii::$app->user->identity,
                LoginMethod::METHOD_COOKIE
            );
            UserModel::onLogin(
                Yii::$app->user->identity,
                LoginMethod::METHOD_COOKIE
            );
        },
    ];
})();

<?php
declare(strict_types=1);

use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\ServerErrorHttpException;
use yii\web\UserEvent;

return (function (): array {
    $authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
    $authKeySecret = @file_exists($authKeyFile)
        ? require($authKeyFile)
        : null;

    return [
        'class' => User::class,
        'identityFixedKey' => $authKeySecret,
        'identityClass' => UserModel::class,
        'identityCookie' => [
            'name' => '_identity',
            'httpOnly' => true,
            'secure' => (bool)preg_match(
                '/(?:^|\.)stat\.ink$/i',
                $_SERVER['HTTP_HOST'] ?? ''
            ),
        ],
        'enableAutoLogin' => $authKeySecret !== null,
        'loginUrl' => ['user/login'],
        'on afterLogin' => function (UserEvent $event): void {
            if (!$event->cookieBased) {
                // 通常ログインはこのフックでは記録しない。
                // 適切な箇所で UserLoginHistory::login() を呼び出すこと。
                return;
            }

            $identity = Yii::$app->user->getIdentity();
            if (!$identity) {
                // なんでやねん
                throw new ServerErrorHttpException('Internal error while auto-login process');
            }

            UserLoginHistory::login($identity, LoginMethod::METHOD_COOKIE);
            UserModel::onLogin($identity, LoginMethod::METHOD_COOKIE);
        },
    ];
})();

Update cookie-based login process event

Update cookie-based login process event

エラーログによると、クッキーベースのログインをしたとき、
ログイン履歴を保存するためのフック関数において
https://github.com/fetus-hina/stat.ink/blob/ec679de7b6402be34edbff51a4b54b8cd6046a87/config/web/user.php#L38
の identity プロパティが見つからない時があるらしい。

この identity は \yii\web\User によって提供される getIdentity() の呼び出しになるはずなので
見つからないはずがないのだが、記録されているものは仕方がない。

なので、getter を明示的に呼び出すようにしてみた。
もしなぜか identity が null だったりすると例外を飛ばす


<?php

/*
 * This file is part of By Night.
 * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Entity;

use App\Repository\ResetPasswordRequestRepository;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait;

/**
 * @ORM\Entity(repositoryClass=ResetPasswordRequestRepository::class)
 */
class ResetPasswordRequest implements ResetPasswordRequestInterface
{
    use ResetPasswordRequestTrait;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private int $id;

    /**
     * @ORM\ManyToOne(targetEntity=User::class)
     * @ORM\JoinColumn(nullable=false)
     */
    private User $user;

    public function __construct(User $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken)
    {
        $this->user = $user;
        $this->initialize($expiresAt, $selector, $hashedToken);
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUser(): User
    {
        return $this->user;
    }
}

<?php

/*
 * This file is part of By Night.
 * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Entity;

use App\Repository\ResetPasswordRequestRepository;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait;

/**
 * @ORM\Entity(repositoryClass=ResetPasswordRequestRepository::class)
 */
class ResetPasswordRequest implements ResetPasswordRequestInterface
{
    use EntityIdentityTrait;
    use ResetPasswordRequestTrait;

    /**
     * @var User
     * @ORM\ManyToOne(targetEntity=User::class)
     * @ORM\JoinColumn(nullable=false)
     */
    private User $user;

    public function __construct(User $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken)
    {
        $this->user = $user;
        $this->initialize($expiresAt, $selector, $hashedToken);
    }
    public function getUser(): User
    {
        return $this->user;
    }
}

Use traits in new entity

Use traits in new entity


<?php

// Edit the lines below to add your Flickr API Key and Secret
// You can get these from http://www.flickr.com/services/apps/create/apply/

$flickrApiKey = 'PUT_YOUR_FLICKR_API_KEY_HERE';
$flickrApiSecret = 'PUT_YOUR_FLICKR_API_SECRET_HERE';

// For the authentication example, put the URL of your web site here, together with the path to the DPZFlickr library
$flickrCallbackBaseUrl = 'http://www.mywebsite.com/path/to/DPZFlickr/';

Remove unneeded variable from sample config file


<?php return [

	/**
	 * The crumb implementation
	 */
	'crumb' => 'Coreplex\Crumbs\Components\Crumb',

	/**
	 * The renderer implementation
	 */
	'renderer' => 'Coreplex\Crumbs\Renderers\Renderer',

	/**
	 * The container implementation
	 */
	'container' => 'Coreplex\Crumbs\Container',

];

<?php return [

	/**
	 * The crumb implementation
	 */
	'crumb' => 'Coreplex\Crumbs\Components\Crumb',

	/**
	 * The renderer implementation
	 */
	'renderer' => 'Coreplex\Crumbs\Renderers\Basic',

	/**
	 * The container implementation
	 */
	'container' => 'Coreplex\Crumbs\Container',

];

Add correct renderer to Laravel config

Add correct renderer to Laravel config


{!! Button::normal($appointment->widget()->code(4))->withIcon(Icon::calendar())->asLinkTo(route('manager.business.agenda.index', $appointment->business->id)) !!}
{!! $appointment->widget()->dateLabel() !!}

Enhance Appointment search results view by adding links


<?php

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

namespace Sylius\Component\Attribute\AttributeType;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
interface AttributeTypeInterface
{
    /**
     * @return string
     */
    public function getStorageType();

    /**
     * @return string
     */
    public function getFormType();

    /**
     * @return string
     */
    public function getType();
}

<?php

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

namespace Sylius\Component\Attribute\AttributeType;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
interface AttributeTypeInterface
{
    /**
     * @return string
     */
    public function getStorageType();

    /**
     * @return string
     */
    public function getType();
}

Remove form type from attribute type

[Attribute] Remove form type from attribute type

Now it's autogenerated based on attributeType type


<?php

/*
 * This file contains calls to t(), tc() and t2() functions to let the translation system know about strings to be translated.
 * It is never loaded or executed.
 */
return;

// To translate the value of the VERSION_INITIAL_COMMENT constant
t('Initial Version');

// To translate the names of the autentication types
// @see \Concrete\Core\Package\StartingPointPackage::add_users
t('AuthenticationType', 'Standard');
t('AuthenticationType', 'concrete5.org');
t('AuthenticationType', 'Facebook');
t('AuthenticationType', 'Twitter');
t('AuthenticationType', 'Google');

<?php

/*
 * This file contains calls to t(), tc() and t2() functions to let the translation system know about strings to be translated.
 * It is never loaded or executed.
 */
return;

// To translate the value of the VERSION_INITIAL_COMMENT constant
t('Initial Version');

// To translate the names of the autentication types
// @see \Concrete\Core\Package\StartingPointPackage::add_users
tc('AuthenticationType', 'Standard');
tc('AuthenticationType', 'concrete5.org');
tc('AuthenticationType', 'Facebook');
tc('AuthenticationType', 'Twitter');
tc('AuthenticationType', 'Google');

Use tc instead of t to apply a translation context


<?php

class Scompany_Sign2pay_Block_RiskAssessment extends Mage_Core_Block_Template
{
    protected $_order;

    protected function __construct()
    {
        parent::__construct();
        $this->setTemplate('sign2pay/riskassessment.phtml');
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        Mage::helper('sign2pay')->attachPaymentScripts();
    }
}

<?php

class Scompany_Sign2pay_Block_RiskAssessment extends Mage_Core_Block_Template
{
    protected $_order;

    public function __construct()
    {
        parent::__construct();
        $this->setTemplate('sign2pay/riskassessment.phtml');
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        Mage::helper('sign2pay')->attachPaymentScripts();
    }
}

Fix concstructor visiblity in risk assessment block class


<?php

namespace Eluceo\iCal\Property;

class ArrayValue implements ValueInterface
{
    /**
     * The value.
     *
     * @var array
     */
    protected $values;

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

    public function setValues(array $values)
    {
        $this->values = $values;

        return $this;
    }

    public function getEscapedValue()
    {
        $escapedValues = array_map(function ($value) {
            return (new StringValue($value))->getEscapedValue();
        }, $this->values);

        return implode(',', $escapedValues);
    }
}

<?php

namespace Eluceo\iCal\Property;

class ArrayValue implements ValueInterface
{
    /**
     * The value.
     *
     * @var array
     */
    protected $values;

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

    public function setValues($values)
    {
        $this->values = $values;

        return $this;
    }

    public function getEscapedValue()
    {
        $escapedValues = array_map(function ($value) {
            return (new StringValue($value))->getEscapedValue();
        }, $this->values);

        return implode(',', $escapedValues);
    }
}

Make implementation compatible with PHP 5.3


<?php

namespace OpsWay\ZohoBooks\Api;

class Invoices extends BaseApi
{
    const API_PATH = 'invoices';
    const API_KEY = 'invoice';

    public function applyCredits($invoiceId, $data)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/credits', $this->organizationId, $data);

        return true;
    }

    public function markAsSent($invoiceId)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/sent', $this->organizationId);

        return true;
    }

    public function markAsVoid($invoiceId)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/void', $this->organizationId);

        return true;
    }
}

<?php

namespace OpsWay\ZohoBooks\Api;

class Invoices extends BaseApi
{
    const API_PATH = 'invoices';
    const API_KEY = 'invoice';

    public function applyCredits($invoiceId, $data)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/credits', $this->organizationId, $data);

        return true;
    }

    public function markAsSent($invoiceId)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/sent', $this->organizationId);

        return true;
    }

    public function markAsVoid($invoiceId)
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/void', $this->organizationId);

        return true;
    }

    /**
     * Email an invoice to the customer
     *
     * @see: https://www.zoho.com/books/api/v3/invoices/#email-an-invoice
     *
     * @param string $invoiceId
     * @param array $data
     *
     * @return bool
     */
    public function email($invoiceId, array $data = [])
    {
        $this->client->post(static::API_PATH.'/'.$invoiceId.'/email', $this->organizationId, $data);

        return true;
    }
}

Add "email an invoice" method

Add "email an invoice" method

| Q             | A
| ------------- | ---
| Branch        | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | n/a
| License       | MIT
| Doc PR        | n/a

See: https://www.zoho.com/books/api/v3/invoices/#email-an-invoice


              @{{panel.libelle}}

            @if (!isset($disableAdd) || !$disableAdd)
                <button type="button" class="btn btn-circle red-sunglo " v-on:click='remove()'>
                     Supprimer </button>
                <button type="button" class="btn btn-circle btn-default" v-on:click='duplicate()'>
                     Dupliquer
                </button>
            @endif
            <button type="button" class="btn btn-circle btn-default" v-on:click='reset()' >
                 Reset
            </button>
            <button type="button" class="btn btn-circle btn-icon-only btn-default btn-draggable ">

            </button>
            <button type="button" class="btn btn-circle btn-icon-only btn-default fullscreen">
            </button>

              @{{panel.libelle}}

            @if (!isset($disableAdd) || !$disableAdd)
                <button type="button" class="btn btn-circle red-sunglo " v-on:click='remove()'>
                     Supprimer </button>
                <button type="button" class="btn btn-circle btn-default" v-on:click='duplicate()'>
                     Dupliquer
                </button>
            @endif
            <button type="button" class="btn btn-circle btn-default" v-on:click='reset()' >
                 Reset
            </button>
            @if (!isset($disableAdd) || !$disableAdd)
            <button type="button" class="btn btn-circle btn-icon-only btn-default btn-draggable ">

            </button>
            @endif
            <button type="button" class="btn btn-circle btn-icon-only btn-default fullscreen">
            </button>

Disable reordering when add is disabled

Disable reordering when add is disabled


<?php namespace Cub\CubLaravel;

use Config;

class CubWidget
{
    /**
     * Get Cub Widget header script
     *
     * @return string
     */
    public function headerScript()
    {
        $script = '';

        return $script;
    }

    /**
     * Get Cub Widget footer script
     *
     * @return string
     */
    public function footerScript()
    {
        $script = '';

        return $script;
    }

    /**
     * Get Cub Widget menu element
     *
     * @return string
     */
    public function menu()
    {
        return '

';
    }

    /**
     * Get Cub Widget app element
     *
     * @return string
     */
    public function app()
    {
        return '

';
    }
}

Use latest cub widget js

Use latest cub widget js


<?php

namespace RadDB\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'RadDB\Events\SomeEvent' => [
            'RadDB\Listeners\EventListener',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //
    }
}

<?php

namespace RadDB\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //
    }
}

Update Providers to match laravel/laravel repo


<?php

namespace PhpTabs\Component;

abstract class Config
{
  /**
   * @var array config options
   */
  private static $data = array();

  /**
   * Gets a defined option
   *
   * @param string $key option name
   * @param mixed $default optional return value if not defined
   */
  public static function get($key, $default = null)
  {
    return isset(self::$data[$key]) ? self::$data[$key] : $default;
  }

  /**
   * Sets an option
   *
   * @param string $key option name
   * @param mixed $value optional option value
   */
  public static function set($key, $value = null)
  {
    if (is_string($key))
    {
      self::$data[$key] = $value;
    }
  }

  /**
   * Gets all defined options
   *
   * @return array All defined options
   */
  public static function getAll()
  {
    return self::$data;
  }
}

<?php

namespace PhpTabs\Component;

abstract class Config
{
  /**
   * @var array config options
   */
  private static $data = array();

  /**
   * Gets a defined option
   *
   * @param string $key option name
   * @param mixed $default optional return value if not defined
   */
  public static function get($key, $default = null)
  {
    return is_string($key) && isset(self::$data[$key])
      ? self::$data[$key] : $default;
  }

  /**
   * Sets an option
   *
   * @param string $key option name
   * @param mixed $value optional option value
   */
  public static function set($key, $value = null)
  {
    if (is_string($key))
    {
      self::$data[$key] = $value;
    }
  }

  /**
   * Gets all defined options
   *
   * @return array All defined options
   */
  public static function getAll()
  {
    return self::$data;
  }
}

Fix bad key format for config component

Fix bad key format for config component


<?php
/**
 * Class KeylistsService
 *
 * @author del
 */

namespace Delatbabel\Keylists\Services;

use Delatbabel\Keylists\Models\Keyvalue;
use Illuminate\Support\Fluent;

/**
 * Class KeylistsService
 *
 * This class provides some utility functions for fetching keylist entries.
 *
 * ### Example
 *
 * <code>
 * $keyservice = new KeylistsService;
 * // @var Fluent $key
 * $key = $keyservice->getKeyValue('currencies', 'USD');
 * </code>
 */
class KeylistsService
{

    /**
     * Fetches a single keyvalue by key type and key value
     *
     * @param string $keyType
     * @param string $keyValue
     * @return Fluent
     */
    public function getKeyValue($keyType, $keyValue)
    {
        $list = Keyvalue::getKeyvaluesByKeyType($keyType);
        return $list[$keyValue];
    }
}

<?php
/**
 * Class KeylistsService
 *
 * @author del
 */

namespace Delatbabel\Keylists\Services;

use Delatbabel\Keylists\Models\Keyvalue;
use Illuminate\Support\Fluent;

/**
 * Class KeylistsService
 *
 * This class provides some utility functions for fetching keylist entries.
 *
 * ### Example
 *
 * <code>
 * $keyservice = new KeylistsService;
 * // @var Fluent $key
 * $key = $keyservice->getKeyValue('currencies', 'USD');
 * </code>
 */
class KeylistsService
{

    /**
     * Fetches a single keyvalue by key type and key value
     *
     * @param string $keyType
     * @param string $keyValue
     * @return Fluent
     */
    public function getKeyValue($keyType, $keyValue)
    {
        $list = Keyvalue::getKeyvaluesByKeyType($keyType);
        if (isset($list[$keyValue])) {
            return $list[$keyValue];
        }
        return null;
    }
}

Return null rather than throw error on value not found


<?php

namespace Silktide\Reposition\Storage;

use Silktide\Reposition\QueryBuilder\TokenSequencerInterface;
use Silktide\Reposition\Metadata\EntityMetadataProviderInterface;

/**
 *
 */
interface StorageInterface
{

    const NEW_INSERT_ID_RETURN_FIELD = "pk";

    /**
     * @param TokenSequencerInterface $query
     * @param string $entityClass
     * @return object
     */
    public function query(TokenSequencerInterface $query, $entityClass);

    /**
     * @param EntityMetadataProviderInterface $provider
     */
    public function setEntityMetadataProvider(EntityMetadataProviderInterface $provider);

    /**
     * @return bool
     */
    public function hasEntityMetadataProvider();

}

<?php

namespace Silktide\Reposition\Storage;

use Silktide\Reposition\QueryBuilder\TokenSequencerInterface;
use Silktide\Reposition\Metadata\EntityMetadataProviderInterface;
use Silktide\Reposition\Storage\Logging\QueryLogProcessorInterface;
use Silktide\Reposition\Storage\Logging\ErrorLogProcessorInterface;

/**
 *
 */
interface StorageInterface
{

    const NEW_INSERT_ID_RETURN_FIELD = "pk";

    /**
     * @param TokenSequencerInterface $query
     * @param string $entityClass
     * @return object
     */
    public function query(TokenSequencerInterface $query, $entityClass);

    /**
     * @param EntityMetadataProviderInterface $provider
     */
    public function setEntityMetadataProvider(EntityMetadataProviderInterface $provider);

    /**
     * @return bool
     */
    public function hasEntityMetadataProvider();

    /**
     * @param QueryLogProcessorInterface $processor
     */
    public function setQueryLogProcessor(QueryLogProcessorInterface $processor);

    /**
     * @param ErrorLogProcessorInterface $processor
     */
    public function setErrorLogProcessor(ErrorLogProcessorInterface $processor);

}

Add methods to the storage interface to inject query an error log processors


<?php

class ExecutorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \MeadSteve\Console\Executor
     */
    protected $testedExecutor;

    protected function setUp()
    {
        $this->testedExecutor = new MeadSteve\Console\Executor();
    }

    function testExecute_ThrowsExceptionOnInvalidCommand()
    {
        $this->setExpectedException(
            'MeadSteve\Console\Exceptions\ExecutionError',
            "git: 'foobar' is not a git command. See 'git --help'."
        );
        $this->testedExecutor->execute("git foobar");
    }

    function testExecute_ReturnsArrayOnValidCommand()
    {
        $output = $this->testedExecutor->execute("git status");
        $this->assertInternalType('array', $output);
    }
}

<?php

class ExecutorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \MeadSteve\Console\Executor
     */
    protected $testedExecutor;

    protected function setUp()
    {
        $this->testedExecutor = new MeadSteve\Console\Executor();
    }

    function testExecute_ThrowsExceptionOnInvalidCommand()
    {
        $this->setExpectedException(
            'MeadSteve\Console\Exceptions\ExecutionError',
            "git: 'foobar' is not a git command. See 'git --help'."
        );
        $this->testedExecutor->execute("git foobar");
    }

    function testExecute_ThrowsCommandNotFoundErrorWhenNotFond()
    {
        $this->setExpectedException(
            'MeadSteve\Console\Exceptions\CommandNotFoundError'
        );
        $this->testedExecutor->execute("gitDSFGscvb foobar");
    }

    function testExecute_ReturnsArrayOnValidCommand()
    {
        $output = $this->testedExecutor->execute("git status");
        $this->assertInternalType('array', $output);
    }
}

Add test for CommandNotFoundError exception being thrown by Executor.


<?php

namespace CacheTool\Command;

use CacheTool\Console\Application;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\StreamOutput;

abstract class CommandTest extends \PHPUnit_Framework_TestCase
{
    public function runCommand($cmd)
    {
        $app = new Application;
        $app->setAutoExit(false);

        $fp = fopen('php://memory', 'a+');

        $input = new StringInput($cmdline);
        $output = new StreamOutput($fp);

        $app->run($input, $output);

        fseek($fp, 0);

        return stream_get_contents($fp);
    }
}

<?php

namespace CacheTool\Command;

use CacheTool\Console\Application;
use CacheTool\Console\Config;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\StreamOutput;

abstract class CommandTest extends \PHPUnit_Framework_TestCase
{
    public function runCommand($cmd)
    {
        $app = new Application(new Config(array('adapter' => 'cli')));
        $app->setAutoExit(false);

        $fp = fopen('php://memory', 'a+');

        $input = new StringInput($cmd);
        $output = new StreamOutput($fp);

        $app->run($input, $output);

        return stream_get_contents($fp, -1, 0);
    }
}

Use application with cli interface

Use application with cli interface


<?php
namespace Tests;

require __DIR__ . "/../src/Analyzer.php";

use PHPUnit\Framework\TestCase;
use AnalyzerNS\Analyzer;

class AnalyzerTest extends TestCase
{

    public function testTestMe()
    {
        $analyzer = new Analyzer();
        $analyzer->analyze("../src/test.php");
        $this->assertTrue($analyzer->testMe("searchNonASCIIChars") >0);
    }
}

<?php
namespace Tests;

require __DIR__ . "/../src/Analyzer.php";

use PHPUnit\Framework\TestCase;
use AnalyzerNS\Analyzer;

class AnalyzerTest extends TestCase
{

    public function testTestMe()
    {
        $analyzer = new Analyzer();
        $analyzer->analyze(__DIR__."/../src/test.php");
        $this->assertTrue($analyzer->testMe("searchNonASCIIChars") >0);
    }
}

Create basic test: file size

Create basic test: file size


<?php

namespace CascadeEnergy\DistributedOperations\Elasticsearch;

use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;

class ProviderIterator implements \Iterator
{
    /** @var SearchHitIterator */
    private $hitIterator;

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

    public function current()
    {
        $hit = $this->hitIterator->current();
        $source = $hit['_source'];

        $operation = new Operation($source['batchId'], $hit['_type'], $source['options']);
        $operation->setState($source['state']);
        $operation->setDisposition($source['disposition']);
        $operation->setId($hit['_id']);
        $operation->setStorageAttribute('indexName', $hit['_index']);

        return $operation;
    }

    public function next()
    {
        $this->hitIterator->next();
    }

    public function key()
    {
        return $this->hitIterator->key();
    }

    public function valid()
    {
        return $this->hitIterator->valid();
    }

    public function rewind()
    {
        $this->hitIterator->rewind();
    }
}

<?php

namespace CascadeEnergy\DistributedOperations\Elasticsearch;

use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;

class ProviderIterator implements \Iterator
{
    /** @var SearchHitIterator */
    private $hitIterator;

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

    public function current()
    {
        $hit = $this->hitIterator->current();
        $source = $hit['_source'];

        $operation = new Operation($hit['_type'], $source['batchId'], $source['options']);
        $operation->setState($source['state']);
        $operation->setDisposition($source['disposition']);
        $operation->setId($hit['_id']);
        $operation->setStorageAttribute('indexName', $hit['_index']);

        return $operation;
    }

    public function next()
    {
        $this->hitIterator->next();
    }

    public function key()
    {
        return $this->hitIterator->key();
    }

    public function valid()
    {
        return $this->hitIterator->valid();
    }

    public function rewind()
    {
        $this->hitIterator->rewind();
    }
}

Fix type / batchId parameter order bug

Fix type / batchId parameter order bug


<?php

class MailMandrillTransportTest extends PHPUnit_Framework_TestCase {

    public function testSend()
    {
        $message = new Swift_Message('Foo subject', 'Bar body');
        $message->setTo('me@example.com');
        $message->setBcc('you@example.com');

        $transport = new MandrillTransportStub('testkey');
        $client = $this->getMock('GuzzleHttp\Client', array('post'));
        $transport->setHttpClient($client);

        $client->expects($this->once())
            ->method('post')
            ->with($this->equalTo('https://mandrillapp.com/api/1.0/messages/send-raw.json'),
                $this->equalTo([
                    'body' => [
                        'key' => 'testkey',
                        'raw_message' => $message->toString(),
                        'async' => false,
                        'to' => ['me@example.com', 'you@example.com']
                    ]
                ])
            );

        $transport->send($message);
    }
}

class MandrillTransportStub extends \Illuminate\Mail\Transport\MandrillTransport
{
    protected $client;

    protected function getHttpClient()
    {
        return $this->client;
    }

    public function setHttpClient($client)
    {
        $this->client = $client;
    }
}

Replace some spaces with tabs

Replace some spaces with tabs