<?php

namespace IAkumaI\SphinxsearchBundle\Twig;

use IAkumaI\SphinxsearchBundle\Search\Sphinxsearch;

/**
 * Twig extension for Sphinxsearch bundle
 */
class SphinxsearchExtension extends \Twig_Extension
{
    /**
     * @var Sphinxsearch
     */
    protected $searchd;

    /**
     * Constructor
     * @param Sphinxsearch $searchd
     */
    public function __construct(Sphinxsearch $searchd)
    {
        $this->searchd = $searchd;
    }

    /**
     * Highlight $text for the $query using $index
     * @param string $text Text content
     * @param string $index Sphinx index name
     * @param string $query Query to search
     * @param integer[optional] $trim If set to integer will return trimmed string of this length
     *
     * @return string
     */
    public function sphinx_highlight($text, $index, $query, $trim = false)
    {
        $result = $this->searchd->getClient()->BuildExcerpts(array($text), $index, $query);

        if (!empty($result[0])) {
            return $result[0];
        } else {
            return '';
        }
    }

    /**
     * Filters list
     * @return array
     */
    public function getFilters()
    {
        return array(
            'sphinx_highlight' => new \Twig_Filter_Function(array($this, 'sphinx_highlight')),
        );
    }
}

<?php

namespace IAkumaI\SphinxsearchBundle\Twig;

use IAkumaI\SphinxsearchBundle\Search\Sphinxsearch;

/**
 * Twig extension for Sphinxsearch bundle
 */
class SphinxsearchExtension extends \Twig_Extension
{
    /**
     * @var Sphinxsearch
     */
    protected $searchd;

    /**
     * Constructor
     * @param Sphinxsearch $searchd
     */
    public function __construct(Sphinxsearch $searchd)
    {
        $this->searchd = $searchd;
    }

    /**
     * Highlight $text for the $query using $index
     * @param string $text Text content
     * @param string $index Sphinx index name
     * @param string $query Query to search
     * @param integer[optional] $trim If set to integer will return trimmed string of this length
     *
     * @return string
     */
    public function sphinx_highlight($text, $index, $query, $trim = false)
    {
        $result = $this->searchd->getClient()->BuildExcerpts(array($text), $index, $query);

        if (!empty($result[0])) {
            return $result[0];
        } else {
            return '';
        }
    }

    /**
     * Filters list
     * @return array
     */
    public function getFilters()
    {
        return array(
            'sphinx_highlight' => new \Twig_Filter_Function(array($this, 'sphinx_highlight')),
        );
    }

    /**
     * Implement getName() method
     * @return string
     */
    public function getName()
    {
        return 'iakumai_sphinxsearch_extension_0';
    }
}

Implement getName() in twig extension

Implement getName() in twig extension


{!! Form::submit((isset($text)) ? $text : 'Submit', ['class' => 'btn btn-success form-control']) !!}

{!! Form::submit((isset($text)) ? $text : trans('mconsole::forms.submit'), ['class' => 'btn btn-success form-control']) !!}

Use translation from submit button

Use translation from submit button


<?php

/**
 * Magma ProRails Model v0.3.0 (http://getvilla.org/)
 * Copyright 2014-2015 Magma Fantastico
 * Licensed under MIT (https://github.com/noibe/villa/blob/master/LICENSE)
 */

class Category extends Thing {
	public $name;

	public function fill($a)
	{
		$this->_id = $a['_id'];
		$this->name = $a['name'];
	}
}

<?php

/**
 * Magma ProRails Model v0.3.0 (http://getvilla.org/)
 * Copyright 2014-2015 Magma Fantastico
 * Licensed under MIT (https://github.com/noibe/villa/blob/master/LICENSE)
 */

class Category extends Thing {
	public $name;

	public function __construct()
	{
		$this->setQueryLimit(0);
	}

	public function fill($a)
	{
		$this->_id = $a['_id'];
		$this->name = $a['name'];
	}
}

Fix Pull and Push servers

Fix Pull and Push servers


<?php

App::import('Lib', 'HuradHook');
$HuradHook = new HuradHook();
Configure::write('HuradHook.obj', $HuradHook);
require APPLIBS . 'filters.php';

App::uses('Functions', 'Lib');
App::uses('Formatting', 'Lib');
App::uses('HrNav', 'Lib');
App::uses('HuradPlugin', 'Lib');
App::uses('Hurad', 'Lib');
App::uses('HuradWidget', 'Lib');

/**
 * Load all active plugins
 */
HuradPlugin::loadAll();

/**
 * Include current theme bootstrap file.
 */
$theme_bootstrap = APP . 'View' . DS . 'Themed' . DS . Configure::read('template') . DS . 'Config' . DS . 'bootstrap.php';
if (is_file($theme_bootstrap) && file_exists($theme_bootstrap)) {
    include $theme_bootstrap;
}

<?php

/**
 * Load Options
 */
App::uses('ClassRegistry', 'Utility');

$options = ClassRegistry::init('Option')->find('all', array(
    'fields' => array(
        'Option.name',
        'Option.value',
    )
        ));
foreach ($options AS $option) {
    $_options[$option['Option']['name']] = $option['Option']['value'];
    Configure::write($option['Option']['name'], $option['Option']['value']);
}
//Write all options in "Options" key
Configure::write('Options', $_options);

/**
 * Import HuradHook Lib and write object in "HuradHook.obj" key
 */
App::import('Lib', 'HuradHook');
$HuradHook = new HuradHook();
Configure::write('HuradHook.obj', $HuradHook);
require APPLIBS . 'filters.php';

/**
 * Load Hurad Lib
 */
App::uses('Functions', 'Lib');
App::uses('Formatting', 'Lib');
App::uses('HrNav', 'Lib');
App::uses('HuradPlugin', 'Lib');
App::uses('Hurad', 'Lib');
App::uses('HuradWidget', 'Lib');

/**
 * Load all active plugins
 */
HuradPlugin::loadAll();

/**
 * Include current theme bootstrap file.
 */
$theme_bootstrap = APP . 'View' . DS . 'Themed' . DS . Configure::read('template') . DS . 'Config' . DS . 'bootstrap.php';
if (is_file($theme_bootstrap) && file_exists($theme_bootstrap)) {
    include $theme_bootstrap;
}

Move load option code to this file.

Move load option code to this file.


<?php

namespace nord\yii\filemanager\resources;

use finfo;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;

class FileResource extends Component implements ResourceInterface
{
    /**
     * @var string
     */
    public $uri;

    /** @var string */
    private $_contents;
    /** @var finfo  */
    private $_finfo;

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (!$this->uri) {
            throw new InvalidConfigException('FileResource::$uri must be set.');
        }
        $this->_contents = file_get_contents($this->uri);
        $this->_finfo = new finfo(FILEINFO_MIME_TYPE);
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return substr(basename($this->uri), 0, strrpos(basename($this->uri), '.'));
    }

    /**
     * @inheritdoc
     */
    public function getExtension()
    {
        return substr($this->uri, strrpos($this->uri, '.') + 1);
    }

    /**
     * @inheritdoc
     */
    public function getType()
    {
        return $this->_finfo->buffer($this->_contents);
    }

    /**
     * @inheritdoc
     */
    public function getSize()
    {
        return strlen($this->_contents);
    }

    /**
     * @inheritdoc
     */
    public function getHash()
    {
        return md5($this->_contents);
    }

    /**
     * @inheritDoc
     */
    public function getContents()
    {
        return $this->_contents;
    }

}

<?php

namespace nord\yii\filemanager\resources;

use finfo;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;

class FileResource extends Component implements ResourceInterface
{
    /**
     * @var string
     */
    public $uri;

    /** @var string */
    private $_contents;
    /** @var finfo  */
    private $_finfo;

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (!$this->uri) {
            throw new InvalidConfigException('FileResource::$uri must be set.');
        }
        $this->_contents = file_get_contents($this->uri);
        $this->_finfo = new finfo(FILEINFO_MIME_TYPE);
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        if (strpos($this->uri, '.') !== false) {
            return substr(basename($this->uri), 0, strrpos(basename($this->uri), '.'));
        } else {
            return basename($this->uri);
        }
    }

    /**
     * @inheritdoc
     */
    public function getExtension()
    {
        return substr($this->uri, strrpos($this->uri, '.') + 1);
    }

    /**
     * @inheritdoc
     */
    public function getType()
    {
        return $this->_finfo->buffer($this->_contents);
    }

    /**
     * @inheritdoc
     */
    public function getSize()
    {
        return strlen($this->_contents);
    }

    /**
     * @inheritdoc
     */
    public function getHash()
    {
        return md5($this->_contents);
    }

    /**
     * @inheritDoc
     */
    public function getContents()
    {
        return $this->_contents;
    }

}

Fix File::getName() when the file doesn't have an extension


<?php

RequestHandler::$responseMode = 'csv';
RequestHandler::respond('projects', array(
    'data' => array_map(function($Project) {
        preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches);
        return array(
            'name' => $Project->Title
            ,'description' => trim($matches[0])
            ,'link_url' => $Project->UsersUrl
            ,'code_url' => $Project->DevelopersUrl
            ,'tags' => implode(',',
                    array_map(
                        function($Tag) {
                            return $Tag->UnprefixedTitle;
                        }
                        ,Tag::getTagsWithPrefix($Project->Tags, 'topic')
                    )
                )
            ,'status' => $Project->Stage
        );
    }, Laddr\Project::getAll())
));

<?php

RequestHandler::$responseMode = 'csv';
RequestHandler::respond('projects', array(
    'data' => array_map(function($Project) {
        preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches);
        return array(
            'name' => $Project->Title
            ,'description' => trim($matches[0])
            ,'link_url' => $Project->UsersUrl
            ,'code_url' => $Project->DevelopersUrl
            ,'tags' => implode(',',
                    array_map(
                        function($Tag) {
                            return $Tag->UnprefixedTitle;
                        }
                        ,$Project->TopicTags
                    )
                )
            ,'status' => $Project->Stage
        );
    }, Laddr\Project::getAll())
));

Remove use of deprecated getTagsWithPrefix method


<?php namespace Nord\Lumen\Cors;

use Illuminate\Support\ServiceProvider;

class CorsServiceProvider extends ServiceProvider
{

    /**
     * @inheritdoc
     */
    public function register()
    {
        $config = $this->app['config']['cors'];

        $this->app->bind('Nord\Lumen\Cors\CorsService', function () use ($config) {
            return new CorsService($config);
        });

        $this->app->alias('Nord\Lumen\Cors\CorsService', 'Nord\Lumen\Cors\Contracts\CorsService');

        class_alias('Nord\Lumen\Cors\CorsFacade', 'Cors');
    }
}

<?php namespace Nord\Lumen\Cors;

use Illuminate\Support\ServiceProvider;

class CorsServiceProvider extends ServiceProvider
{

    /**
     * @inheritdoc
     */
    public function register()
    {
        $config = $this->app['config']['cors'];

        $this->app->bind('Nord\Lumen\Cors\CorsService', function () use ($config) {
            return new CorsService($config);
        });

        $this->app->alias('Nord\Lumen\Cors\CorsService', 'Nord\Lumen\Cors\Contracts\CorsService');
        if (!class_exists('Cors')) {
            class_alias('Nord\Lumen\Cors\CorsFacade', 'Cors');
        }
    }
}

Check if Cors class already exists to prevent fatal error in test scenarios where app is instantiated more than once.

see https://github.com/laravel/lumen/blob/master/tests/TestCase.php


<?php

namespace Ddeboer\Imap;

use Ddeboer\Imap\Exception\AuthenticationFailedException;

class Server
{
    protected $hostname;
    protected $port;
    protected $connection;
    protected $mailboxes;

    public function __construct($hostname, $port = '993')
    {
        $this->server = '{' . $hostname . ':' . $port . '/imap}';
    }

    /**
     * Authenticate connection
     *
     * @param string $username Username
     * @param string $password Password
     *
     * @return \Ddeboer\Imap\Connection
     * @throws AuthenticationFailedException
     */
    public function authenticate($username, $password)
    {
        $resource = @\imap_open($this->server, $username, $password, null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));

        if (false === $resource) {
            throw new AuthenticationFailedException($username);
        }

        $check = imap_check($resource);
        $mailbox = $check->Mailbox;
        $this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1);

        // These are necessary to get rid of PHP throwing IMAP errors
        imap_errors();
        imap_alerts();

        return new Connection($resource, $this->connection);
    }
}

<?php

namespace Ddeboer\Imap;

use Ddeboer\Imap\Exception\AuthenticationFailedException;

class Server
{
    protected $hostname;
    protected $port;
    protected $connection;
    protected $mailboxes;

    public function __construct($hostname, $port = '993')
    {
        if ($port == 993) {
            $cert = 'ssl';
        } else {
            $cert = 'novalidate-cert';
        }
        $this->server = '{' . $hostname . ':' . $port . '/imap/' . $cert . '}';
    }

    /**
     * Authenticate connection
     *
     * @param string $username Username
     * @param string $password Password
     *
     * @return \Ddeboer\Imap\Connection
     * @throws AuthenticationFailedException
     */
    public function authenticate($username, $password)
    {
        $resource = @\imap_open($this->server, $username, $password, null, 1);

        if (false === $resource) {
            throw new AuthenticationFailedException($username);
        }

        $check = imap_check($resource);
        $mailbox = $check->Mailbox;
        $this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1);

        // These are necessary to get rid of PHP throwing IMAP errors
        imap_errors();
        imap_alerts();

        return new Connection($resource, $this->connection);
    }
}

Support both secure and insecure connections


<?php
/**
 * This file belongs to semtools project
 *
 * @copyright 2014 Vladimir Stračkovski
 * @license   The MIT License (MIT) <http://choosealicense.com/licenses/mit/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code or visit the link above.
 */
namespace nv\semtools\Classifiers\uClassify;

use nv\semtools;

/**
 * uClassify Response
 *
 * Encapsulates uClassify response specifics
 *
 * @package nv\semtools\Classifiers\uClassify
 * @author Vladimir Stračkovski <vlado@nv3.org>
 */
class UclassifyResponse extends semtools\Common\ApiResponseAbstract
{
    // @todo Encapsulate response data: parse XML
}

<?php
/**
 * This file belongs to semtools project
 *
 * @copyright 2014 Vladimir Stračkovski
 * @license   The MIT License (MIT) <http://choosealicense.com/licenses/mit/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code or visit the link above.
 */
namespace nv\semtools\Classifiers\uClassify;

use nv\semtools;

/**
 * uClassify Response
 *
 * Encapsulates uClassify response specifics
 *
 * @package nv\semtools\Classifiers\uClassify
 * @author Vladimir Stračkovski <vlado@nv3.org>
 */
class UclassifyResponse extends semtools\Common\ApiResponseAbstract
{
    /**
     * Get classification data as PHP array
     *
     * @return array
     * @throws \nv\semtools\Exception\ServiceReaderException
     */
    public function getClassification()
    {
        $xml = simplexml_load_string($this->response);
        $result = array();

        if ($xml instanceof \SimpleXMLElement) {
            if ((string) $xml->status->attributes()->success == 'true') {
                foreach ($xml->readCalls->classify as $classify) {
                    foreach ($classify->classification->class as $class) {
                        $result[strtolower($class->attributes()->className)] = (float) $class->attributes()->p;
                    }
                }
                return $result;
            }
            throw new semtools\Exception\ServiceReaderException($xml->status->attributes()->statusCode);
        }
        throw new semtools\Exception\ServiceReaderException('Failed parsing XML response.');
    }
}

Implement classification retrieval as array.


<?php

namespace VoyagerPolls\Models;

use Illuminate\Database\Eloquent\Model;

class PollQuestion extends Model
{
    protected $table = 'voyager_poll_questions';
    protected $fillable = ['poll_id', 'question', 'order'];
    protected $appends = ['answered'];

    public function answers(){
    	return $this->hasMany('VoyagerPolls\Models\PollAnswer', 'question_id')->orderBy('order', 'ASC');
    }

    public function totalVotes(){
    	$totalVotes = 0;
    	foreach($this->answers as $answers){
    		$totalVotes += $answers->votes;
    	}
    	return $totalVotes;
    }

    public function getAnsweredAttribute(){
    	return false;
    }

}

<?php

namespace VoyagerPolls\Models;

use Illuminate\Database\Eloquent\Model;

class PollQuestion extends Model
{
    protected $table = 'voyager_poll_questions';
    protected $fillable = ['poll_id', 'question', 'order'];
    protected $appends = ['answered'];

    public function answers(){
    	return $this->hasMany('VoyagerPolls\Models\PollAnswer', 'question_id')->orderBy('order', 'ASC');
    }

    public function poll() {
        return $this->belongsTo('VoyagerPolls\Models\Poll', 'poll_id');
    }

    public function totalVotes(){
    	$totalVotes = 0;
    	foreach($this->answers as $answers){
    		$totalVotes += $answers->votes;
    	}
    	return $totalVotes;
    }

    public function getAnsweredAttribute(){
    	return false;
    }

}

Fix relationship between question and poll.


<?php

use tests\_pages\LoginPage;

$I = new WebGuy($scenario);
$I->wantTo('ensure that login works');

$loginPage = LoginPage::openBy($I);

$I->see('Login', 'h1');

$I->amGoingTo('try to login with empty credentials');
$loginPage->login('', '');
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.');
$I->see('Password cannot be blank.');

$I->amGoingTo('try to login with wrong credentials');
$loginPage->login('admin', 'wrong');
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.');

$I->amGoingTo('try to login with correct credentials');
$loginPage->login('admin', 'admin');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see user info');
$I->see('Logout (admin)');

<?php

use tests\_pages\LoginPage;

$I = new WebGuy($scenario);
$I->wantTo('ensure that login works');

$loginPage = LoginPage::openBy($I);

$I->see('Login', 'h1');

$I->amGoingTo('try to login with empty credentials');
$loginPage->login('', '');
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.');
$I->see('Password cannot be blank.');

$I->amGoingTo('try to login with wrong credentials');
$loginPage->login('admin', 'wrong');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.');

$I->amGoingTo('try to login with correct credentials');
$loginPage->login('admin', 'admin');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see user info');
$I->see('Logout (admin)');

Add wait() to login test with wrong credentials to fix WebDriver test


<?php

return [
    // Class you want to use to represent sections
    'sectionClass' => \StartupPalace\Maki\Section::class,
    // Class you want to use to represent field values
    'fieldValueClass' => \StartupPalace\Maki\FieldValue::class,
    // Path to Maki's templates (from `resources/views`)
    'templatePath' => 'maki',
    // Describe the field types use in your application
    'fields' => [
        'content' => [
            'type' => 'wysiwyg',
        ],
        'title' => [
            'type' => 'input:text',
        ],
        'cover' => [
            'type' => 'input:file:image',
        ],
        'text' => [
            'type' => 'textarea',
        ],
        'button' => [
            'type' => 'link',
        ],
    ],
    // Describe the different section types used in your application
    'sectionTypes' => [
        'default' => [
            'template' => 'default',
            'fields' => [
                'title', 'cover', 'content', 'button',
            ],
        ],
    ],
];

<?php

return [
    // Class you want to use to represent sections
    'sectionClass' => \StartupPalace\Maki\Section::class,
    // Class you want to use to represent field values
    'fieldValueClass' => \StartupPalace\Maki\FieldValue::class,
    // Path to Maki's templates (from `resources/views`)
    'templatePath' => 'maki',
    // Describe the field types use in your application
    'fields' => [
        'title' => [
            'type' => 'input:text',
        ],
        'text' => [
            'type' => 'textarea',
        ],
        'content' => [
            'type' => 'wysiwyg',
        ],
    ],
    // Describe the different section types used in your application
    'sectionTypes' => [
        'default' => [
            'template' => 'default',
            'fields' => [
                'title', 'text', 'content',
            ],
        ],
    ],
];

Remove button and cover fields from default config


<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, [
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, array(
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

Update Sami theme as default.

Update Sami theme as default.


<?php
namespace SlaxWeb\Hooks;

class Hooks
{
    protected static $_hooks = [];

    public static function set(array $hook)
    {
        if ((isset($hook["name"]) && isset($hook["class"])) === false) {
            return false;
        }

        self::$_hooks[$hook["name"]] = $hook["class"];

        return true;
    }

    public static function call()
    {
        $params = func_get_args();

        $name = array_shift($params);
        if (isset(self::$_hooks[$name])) {
            $obj = new self::$_hooks[$name]();
            $obj->init(...$params);
        }
    }
}

<?php
namespace SlaxWeb\Hooks;

class Hooks
{
    protected static $_hooks = [];

    public static function set(array $hook)
    {
        if ((isset($hook["name"]) && isset($hook["class"])) === false) {
            return false;
        }

        self::$_hooks[$hook["name"]] = $hook["class"];

        return true;
    }

    public static function call()
    {
        $params = func_get_args();

        $name = array_shift($params);
        if (isset(self::$_hooks[$name])) {
            $obj = new self::$_hooks[$name]();
            return $obj->init(...$params);
        }
    }
}

Return hooks return to the caller of "call" method


<?php
/**
 * Performs simple keyword replacement on the email before sending.
 *
 * @package silverstripe-newsletter-keywords
 */
class NewsletterEmailKeywordsExtension extends Extension {

	public function onBeforeSend() {
		$body         = $this->owner->Body();
		$replacements = $this->owner->Newsletter()->getKeywordReplacements($this->owner);
		$keywords     = array();

		foreach ($replacements as $k => $v) {
			$keywords[] = "{\$$k}";
		}

		$this->owner->setBody(DBField::create('HTMLText', str_replace(
			$keywords,
			array_values($replacements),
			is_object($body) ? $body->forTemplate() : $body
		)));
	}

}

<?php
/**
 * Performs simple keyword replacement on the email before sending.
 *
 * @package silverstripe-newsletter-keywords
 */
class NewsletterEmailKeywordsExtension extends Extension {

	public function onBeforeSend() {
		$body         = $this->owner->Body();
		$replacements = $this->owner->Newsletter()->getKeywordReplacements($this->owner);
		$keywords     = array();

		$body = is_object($body) ? $body->forTemplate() : $body;
		$body = preg_replace('/"[^"]*%7B%24(\w+)%7D/', '"{\$$1}', $body);

		foreach ($replacements as $k => $v) {
			$keywords[] = "{\$$k}";
		}

		$this->owner->setBody(DBField::create('HTMLText', str_replace(
			$keywords, array_values($replacements), $body
		)));
	}
}

Replace escaped keywords in attributes.

Replace escaped keywords in attributes.


<?php

$__current_cwd = getcwd();
chdir(__DIR__);

$__data['__current_cwd'] = $__current_cwd;

$__container->writeCompiledEnvoyFile(
	$__compiler, __DIR__.'/Envoy.blade.php', $__serversOnly
);

include getcwd().'/Envoy.php';

@unlink(getcwd().'/Envoy.php');

chdir($__current_cwd);

<?php

$__current_cwd = getcwd();
chdir(__DIR__);

$__data['__current_cwd'] = $__current_cwd;

$__envoyPath = $__container->writeCompiledEnvoyFile(
	$__compiler, __DIR__.'/Envoy.blade.php', $__serversOnly
) ?: getcwd().'/Envoy.php';

include $__envoyPath;

@unlink($__envoyPath);

chdir($__current_cwd);

Fix the Blade include with Laravel v5.4

Fix the Blade include with Laravel v5.4


<?php

namespace Illuminate\Database\Eloquent;

use RuntimeException;

class JsonEncodingException extends RuntimeException
{
    /**
     * Create a new JSON encoding exception for the model.
     *
     * @param  mixed  $model
     * @param  string  $message
     * @return static
     */
    public static function forModel($model, $message)
    {
        return new static('Error encoding model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message);
    }

    /**
     * Create a new JSON encoding exception for an attribute.
     *
     * @param  mixed  $key
     * @param  string $message
     * @return static
     * @internal param mixed $key
     */
    public static function forAttribute($key, $message)
    {
        return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message);
    }
}

<?php

namespace Illuminate\Database\Eloquent;

use RuntimeException;

class JsonEncodingException extends RuntimeException
{
    /**
     * Create a new JSON encoding exception for the model.
     *
     * @param  mixed  $model
     * @param  string  $message
     * @return static
     */
    public static function forModel($model, $message)
    {
        return new static('Error encoding model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message);
    }

    /**
     * Create a new JSON encoding exception for an attribute.
     *
     * @param  mixed  $key
     * @param  string $message
     * @return static
     */
    public static function forAttribute($key, $message)
    {
        return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message);
    }
}

Remove leftover annotation after renaming parameters


<?php get_header(); ?>
<title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title>

			<?php if (have_posts()) : while(have_posts()) : the_post();?>

					<a href="<?php the_permalink();?>" title = "<?php the_title();?>">
<?php the_title();?>

Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?>

					<?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?>

<?php the_excerpt(); ?>

			<?php endwhile; else : ?>

<?php _e("We can't find what you are looking for."); ?>

			<?php endif; ?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

<?php get_header(); ?>
<title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title>

 <?php get_search_form(); ?>

			<?php if (have_posts()) : while(have_posts()) : the_post();?>

					<a href="<?php the_permalink();?>" title = "<?php the_title();?>">
<?php the_title();?>

Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?>

					<?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?>

<?php the_excerpt(); ?>

			<?php endwhile; else : ?>

<?php _e("We can't find what you are looking for."); ?>

			<?php endif; ?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

Add Search form for mobile devices

Add Search form for mobile devices


<?php

namespace Concise\Console\ResultPrinter\Utilities;

use Concise\Core\ArgumentChecker;

class ProportionalProgressBar extends ProgressBar
{
    /**
     * @param integer $size
     * @param integer $total
     * @param array   $parts
     * @return string
     */
    public function renderProportional($size, $total, array $parts)
    {
        ArgumentChecker::check($size, 'integer');
        ArgumentChecker::check($total, 'integer', 2);

        $this->calculateTotal($parts);
        if (0 === $total) {
            $total = $this->total;
        }
        if (0 === $total) {
            return str_repeat('_', $size);
        }
        $barSize = $size * $this->total / $total;
        $bar = parent::render((int)$barSize, $parts);
        $spaces = $size - substr_count($bar, ' ');

        return $bar . str_repeat('_', $spaces);
    }
}

<?php

namespace Concise\Console\ResultPrinter\Utilities;

use Concise\Core\ArgumentChecker;

class ProportionalProgressBar extends ProgressBar
{
    /**
     * @param integer $size
     * @param integer $total
     * @param array   $parts
     * @return string
     */
    public function renderProportional($size, $total, array $parts)
    {
        ArgumentChecker::check($size, 'integer');
        ArgumentChecker::check($total, 'integer', 2);

        $this->calculateTotal($parts);
        if (0 === $total) {
            $total = $this->total;
        }
        if (0 === $total) {
            return str_repeat('_', $size);
        }
        $barSize = min($size * $this->total / $total, $size);
        $bar = parent::render((int)$barSize, $parts);
        $spaces = max(0, $size - substr_count($bar, ' '));

        return $bar . str_repeat('_', $spaces);
    }
}

Fix bug where progress bar can be wider than the screen


<?php

#	Define our custom settings.
add_action('admin_init', function(){

	#	Skip Attachments Setting
	add_settings_field('skip-attach', ''.__('Skip Attachment Pages?').'', function(){
		?>
		<input type="checkbox" id="skip_attachments" name="skip_attachments" value="1"<?php checked(get_option('skip_attachments')); ?> />

			Attachment pages will redirect visitors to the actual attached file instead of a metadata page.
		<?php
	}, 'reading');

	register_setting('reading', 'skip_attachments');
});

if(get_option('skip_attachments'))
	add_action('template_redirect', function(){
		if(is_attachment()){
			wp_redirect(wp_get_attachment_url($GLOBALS['post']->ID));
			exit;
		}
	});

<?php

#	Define our custom settings.
add_action('admin_init', function(){

	#	Skip Attachments Setting
	add_settings_field('skip-attach', ''.__('Skip Attachment Pages?').'', function(){
		?>
		<input type="checkbox" id="skip_attachments" name="skip_attachments" value="1"<?php checked(get_option('skip_attachments')); ?> />

			Attachment pages will redirect visitors to the actual attached file instead of a metadata page.
		<?php
	}, 'reading');

	register_setting('reading', 'skip_attachments');

	#	Setting for removing the injected emoji-detection script and related styling added in WordPress 4.2+
	add_settings_field('disable-emoji', ''.__('Disable Emoji').'', function(){
		?>
		<input type="checkbox" id="disable_emoji" name="disable_emoji" value="1"<?php checked(get_option('disable_emoji', TRUE)); ?> />

			Disables WordPress's automatic emoji detection, which is useless unless emoji are being used on the site (or visitors can submit comments).
		<?php
	}, 'discussion');

	register_setting('discussion', 'disable_emoji');
});

# Disable WordPress's emoji DOM-juice if settings dictate we'll never need/want it.
if(get_option('disable_emoji', TRUE)){
	remove_action('wp_head', 'print_emoji_detection_script', 7);
	remove_action('wp_print_styles', 'print_emoji_styles');
}

if(get_option('skip_attachments'))
	add_action('template_redirect', function(){
		if(is_attachment()){
			wp_redirect(wp_get_attachment_url($GLOBALS['post']->ID));
			exit;
		}
	});

Add setting to toggle emoji-detection script

Since version 4.2, WordPress started injecting an emoji-detection script
with complementary CSS into each themed page's <head>. This does nothing
but add overhead to sites that aren't using emoji or discussion threads.
This behaviour currently isn't controllable by core settings, but it can
be circumvented by removing the default actions registered by WordPress.

Fixes #11.


<?php

include("file.php");

$experiment = new Experiment($_REQUEST['exp'], True);

$user = new User($experiment->owner);

$page_header = $experiment->getName();

if ($experiment->getStatus() != 'open') {
  $page = 'fully_subscribed';
}
else {
  foreach ($experiment->getCalendar() as $date=>$slots) {
    foreach ($slots as $slot) {
      if ($slot[1] == $_REQUEST['timeslot']) {
        $slot_date = $date;
        $slot_time = $slot[0];
      }
    }
  }

  // Double check that the timeslot is still free
  if (count($experiment->getSlot($_REQUEST['timeslot'])) < $experiment->getPerSlot()) {
    $experiment->setSlot($_REQUEST['timeslot'], $_REQUEST['name'], $_REQUEST['email'], $_REQUEST['phone']);
    $experiment->addExclusionEmails(array($_REQUEST['email']));
    if ($experiment->saveExperimentData() == False) {
      $page = 'error';
      $error = '100';
    }
  }
  else {
    // If not, send back to calendar page
    $page = 'calendar';
    $warning_message = True;
  }

  //$a = mail($_REQUEST['email'], $experiment->getName(), "Dear Jon", "From: {$user->getName()} <{$user->getEmail()}>");
}

?>

<?php

include("file.php");

$experiment = new Experiment($_REQUEST['exp'], True);

$user = new User($experiment->owner);

$page_header = $experiment->getName();

if ($experiment->getStatus() != 'open') {
  $page = 'fully_subscribed';
}
else {

  $excluded_email_addresses = $experiment->getExclusionEmails();
  foreach ($experiment->getExclusions() as $exclusion) {
    $alt_experiment = new Experiment($exclusion);
    $excluded_email_addresses = array_merge($excluded_email_addresses, $alt_experiment->getExclusionEmails());
  }
  if (in_array(strtolower($_REQUEST['email']), $excluded_email_addresses)) {
    $page = 'not_eligible';
  }

  else {
    foreach ($experiment->getCalendar() as $date=>$slots) {
      foreach ($slots as $slot) {
        if ($slot[1] == $_REQUEST['timeslot']) {
          $slot_date = $date;
          $slot_time = $slot[0];
        }
      }
    }

    // Double check that the timeslot is still free
    if (count($experiment->getSlot($_REQUEST['timeslot'])) < $experiment->getPerSlot()) {
      $experiment->setSlot($_REQUEST['timeslot'], $_REQUEST['name'], $_REQUEST['email'], $_REQUEST['phone']);
      $experiment->addExclusionEmails(array($_REQUEST['email']));
      if ($experiment->saveExperimentData() == False) {
        $page = 'error';
        $error = '100';
      }
    }
    else {
      // If not, send back to calendar page
      $page = 'calendar';
      $warning_message = True;
    }

    //$a = mail($_REQUEST['email'], $experiment->getName(), "Dear Jon", "From: {$user->getName()} <{$user->getEmail()}>");
  }
}

?>

Check exclusions before saving data

Check exclusions before saving data

Before writing out data, it is important to double check that the user
is not listed in the exclusion email addresses. This is to prevent
double sign ups (e.g. clicking back button and resubmitting form data).


<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once 'scripts/script.php';

use jlawrence\eos\Parser;
use jlawrence\eos\Graph;

class math extends Script
{
	public function run()
	{
		if(strtolower(split(' ', $this->matches[0])[0]) === 'math') {
			return $this->send($this->message->number, Parser::solve($this->matches[1]));
		} else {
			$filepath = __DIR__ . '/ouput.png';
			Graph::init(640, 840);
			Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10);

			if(file_exists($filepath)) {
				unlink($filepath);
			}
			imagepng(Graph::getImage(), $filepath);
			return $this->send($this->message->number, $filepath, 'image');
		}
	}
}

<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once 'scripts/script.php';

use jlawrence\eos\Parser;
use jlawrence\eos\Graph;

class math extends Script
{
	public function run()
	{
		if(strtolower(split(' ', $this->matches[0])[0]) === 'math') {
			return $this->send($this->message->number, Parser::solve($this->matches[1]));
		} else {
			$filepath = __DIR__ . '/ouput.png';
			Graph::init(640, 840);
			Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10);

			if(file_exists($filepath)) {
				unlink($filepath);
			}
			if(imagepng(Graph::getImage(), $filepath)) {
				return $this->send($this->message->number, $filepath, 'image');
			} else {
				return $this->send($this->message->number, 'Graph generation unsuccessful');
			}
		}
	}
}

Send an error-message, when the graph-generation is unsuccessful


<?php
namespace Omise\Payment\Gateway\Request\Offsite;

use Magento\Payment\Gateway\Request\BuilderInterface;
use Magento\Sales\Model\Order;

/**
 * This class requires 'initialize' command.
 *
 * A 'stateObject' will be assigned to an array
 * only when the command code is `initialize`.
 */
class OrderPendingPaymentStateBuilder implements BuilderInterface
{
    /**
     * @param  array $buildSubject
     *
     * @return array
     */
    public function build(array $buildSubject)
    {
        return [];
    }
}

<?php
namespace Omise\Payment\Gateway\Request\Offsite;

use Magento\Payment\Gateway\Request\BuilderInterface;
use Magento\Sales\Model\Order;

/**
 * This class requires 'initialize' command.
 *
 * A 'stateObject' will be assigned to an array
 * only when the command code is `initialize`.
 */
class OrderPendingPaymentStateBuilder implements BuilderInterface
{
    /**
     * @param  array $buildSubject
     *
     * @return array
     */
    public function build(array $buildSubject)
    {
        $stateObject = $buildSubject['stateObject'];
        $stateObject->setState(Order::STATE_PENDING_PAYMENT);
        $stateObject->setStatus(Order::STATE_PENDING_PAYMENT);
        $stateObject->setIsNotified(false);

        return [];
    }
}

Set an order's status, state to 'pending_payment' at the request builder class.

It does makes sense to go with 'pending payment' status, also, Magento has a cronjob that keep clean an expired pending patment order to 'canceled' order.


<?php
style('twofactor_totp', 'style');
?>

<form method="POST" class="totp-form">
	<input type="tel" minlength="6" maxlength="6" name="challenge" required="required" autofocus autocomplete="off" autocapitalize="off" placeholder="<?php p($l->t('Authentication code')) ?>">
	<button type="submit">
		Submit
	</button>

<?php p($l->t('Get the authentication code from the two-factor authentication app on your device.')) ?>

</form>

<?php
style('twofactor_totp', 'style');
?>

<form method="POST" class="totp-form">
	<input type="tel" minlength="6" maxlength="6" name="challenge" required="required" autofocus autocomplete="off" autocapitalize="off" placeholder="<?php p($l->t('Authentication code')) ?>">
	<button type="submit">
		<?php p($l->t('Submit')); ?>
	</button>

<?php p($l->t('Get the authentication code from the two-factor authentication app on your device.')) ?>

</form>

Make the submit button translatable

Make the submit button translatable

Signed-off-by: Christoph Wurst <7abde52c298496fa169fb750f91f213a282142af@winzerhof-wurst.at>


<?php

use App\Bootstrap\AppManager;
use DI\ContainerBuilder;
use Dotenv\Dotenv;

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

// Set file access restrictions
ini_set('open_basedir', __DIR__);

// Initialize environment variable handler
Dotenv::createUnsafeImmutable(__DIR__)->safeLoad();

// Initialize the container
$container = call_user_func_array(
    [new ContainerBuilder, 'addDefinitions'],
    glob(__DIR__ . '/app/config/*.php')
);

// Compile the container
if (filter_var(getenv('APP_DEBUG'), FILTER_VALIDATE_BOOLEAN) !== true) {
    $container->enableCompilation(__DIR__ . '/app/cache');
}

// Initialize the application
$app = $container->build()->call(AppManager::class);

// Engage!
$app->run();

<?php

use App\Bootstrap\AppManager;
use App\Support\Helpers;
use DI\ContainerBuilder;
use Dotenv\Dotenv;

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

// Set file access restrictions
ini_set('open_basedir', __DIR__);

// Initialize environment variable handler
Dotenv::createUnsafeImmutable(__DIR__)->safeLoad();

// Initialize the container
$container = call_user_func_array(
    [new ContainerBuilder, 'addDefinitions'],
    glob(__DIR__ . '/app/config/*.php')
);

// Compile the container
if (! Helpers::env('APP_DEBUG', false)) {
    $container->enableCompilation(__DIR__ . '/app/cache');
}

// Initialize the application
$app = $container->build()->call(AppManager::class);

// Engage!
$app->run();

Use Helper::env() to check if APP_DEBUG enabled


<?php
/*
 * This file is part of the Sonata project.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\BlockBundle\Model;

use Sonata\CoreBundle\Model\ManagerInterface;

interface BlockManagerInterface extends ManagerInterface
{
}

<?php
/*
 * This file is part of the Sonata project.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\BlockBundle\Model;

use Sonata\CoreBundle\Model\PageableManagerInterface;

interface BlockManagerInterface extends PageableManagerInterface
{
}

Use PageableManagerInterface instead of ManagerInterface


<?php

namespace Korobi\WebBundle\Util;

/**
 * Holds many navigation items.
 * @package Korobi\Util
 */
class NavigationCollection {

    private $items = [];

    public function __construct(array $korobiConfig) {
        $items = $korobiConfig['navigation']['items'];
        array_walk($items, function($value, $key) {
            die(json_encode($value));
        });
    }
}

<?php

namespace Korobi\WebBundle\Util;

/**
 * Holds many navigation items.
 * @package Korobi\Util
 */
class NavigationCollection {

    private $items = [];

    public function __construct(array $korobiConfig) {
        $items = $korobiConfig['navigation']['items'];
        array_walk($items, function($value, $key) {
            $this->items[$value['type']] = $value;
        });
    }

    public function getPrimary() {
        return $this->items['primary'];
    }

    public function getSecondary() {
        return $this->items['secondary'];
    }

    public function getFooter() {
        return $this->items['footer'];
    }
}

Add some convenience functions to make things convenient


<?php

require( get_template_directory() . '/null/null.html.php' );
require( get_template_directory() . '/null/null.breadcrumb.php' );
require( get_template_directory() . '/null/null.postmeta.php' );
require( get_template_directory() . '/null/null.post.php' );
require( get_template_directory() . '/null/null.loop.php' );
require( get_template_directory() . '/null/null.widgets.php' );
require( get_template_directory() . '/null/null.layout.php' );
require( get_template_directory() . '/null/null.archive.php' );
require( get_template_directory() . '/null/null.site.php' );
require( get_template_directory() . '/null/null.search.php' );
require( get_template_directory() . '/null/null.util.php' );
require( get_template_directory() . '/null/null.parser.php' );

?>

<?php

require( 'null.html.php' );
require( 'null.breadcrumb.php' );
require( 'null.postmeta.php' );
require( 'null.post.php' );
require( 'null.loop.php' );
require( 'null.widgets.php' );
require( 'null.layout.php' );
require( 'null.archive.php' );
require( 'null.site.php' );
require( 'null.search.php' );
require( 'null.util.php' );
require( 'null.parser.php' );

?>

Use relative paths in includes

Use relative paths in includes


<?php

class CM_ExceptionHandling_Formatter_Html extends CM_ExceptionHandling_Formatter_Abstract {

    public function getHeader(CM_ExceptionHandling_SerializableException $exception) {
        return '
' . $exception->getClass() . '

' . $exception->getMessage() . '
' . $exception->getFile() . ' on line ' .
        $exception->getLine() . '
';
    }

    public function getTrace(CM_ExceptionHandling_SerializableException $exception) {
        $traceString = '
';
        $indent = strlen(count($exception->trace)) + 4;
        foreach ($exception->trace as $number => $entry) {
            $traceString .= str_pad($number, $indent, ' ', STR_PAD_LEFT) . '. ';
            $traceString .= $entry['code'] . ' ' . $entry['file'];
            if (null !== $entry['line']) {
                $traceString .= ':' . $entry['line'];
            }
            $traceString .= PHP_EOL;
        }
        $traceString .= '
';
        return $traceString;
    }

    public function getMetaInfo(CM_ExceptionHandling_SerializableException $exception) {
        if (empty($exception->metaInfo)) {
            return '';
        }

        $metaInfoString = '
';
        foreach ($exception->metaInfo as $key => $value) {
            $metaInfoString .= $key . ': ' . $value . PHP_EOL;
        }
        $metaInfoString .= '
';
        return $metaInfoString;
    }
}

Use same tag for exception location

Use same tag for exception location


        <?php echo formOpen('user/signin'); ?>

Sign In

            <?php echo inputText('username', 'Username'); ?>

            <?php echo inputPassword('password', 'Password'); ?>

            <?php echo inputCheckbox('keep', 'Remember Me'); ?>

            <?php echo inputSubmit('Sign In'); ?>

            Don't have an account yet? <a href="<?php echo baseUrl(); ?>user/signup">Create an Account

        <?php echo formClose(); ?>

Add form (forgot at commit before)

Add form (forgot at commit before)


<?php

namespace Forestry\Orm;

class Storage {

	/**
	 * @var array
	 */
	private static $instances = ['default' => []];

    /**
     * Set a new connection with the given name.
     *
     * @param string $name
     * @param array $config
     * @return mixed
     * @throws \LogicException
     * @throws \PDOException
     */
    public static function set($name = 'default', array $config = []) {
        if(isset(self::$instances[$name]) && self::$instances[$name] instanceof \PDO) {
            throw new \LogicException(sprintf('Connection "%s" already set', $name));
        }

        self::$instances[$name] = new \PDO(
            isset($config['dsn']) ? $config['dsn'] : 'mysql:host=localhost',
            isset($config['user']) ? $config['user'] : 'root',
            isset($config['password']) ? $config['password']: '',
            isset($config['option']) ? $config['option'] : array()
        );

        return self::$instances[$name];
    }

}

<?php

namespace Forestry\Orm;

class Storage {

	/**
	 * @var array
	 */
	private static $instances = ['default' => []];

    /**
     * Set a new connection with the given name.
     *
     * @param string $name
     * @param array $config
     * @return mixed
     * @throws \LogicException
     * @throws \PDOException
     */
    public static function set($name = 'default', array $config = []) {
        if(isset(self::$instances[$name]) && self::$instances[$name] instanceof \PDO) {
            throw new \LogicException(sprintf('Connection "%s" already set', $name));
        }

        self::$instances[$name] = new \PDO(
            isset($config['dsn']) ? $config['dsn'] : 'mysql:host=localhost',
            isset($config['user']) ? $config['user'] : 'root',
            isset($config['password']) ? $config['password']: '',
            isset($config['option']) ? $config['option'] : array()
        );

        return self::$instances[$name];
    }

    /**
     * Creates a new instance of PDO or returns an existing one.
     *
     * @param string $name
     * @return \PDO
     * @throws \OutOfBoundsException
     */
    public static function get($name) {
        if(!isset(self::$instances[$name])) {
            throw new \OutOfBoundsException(sprintf('Storage "%s" not set', $name));
        }

        return self::$instances[$name];
    }

}

Add method to get a connection

Add method to get a connection


<?php

namespace Victoire\Widget\PollBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class VictoireWidgetPollExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

<?php

namespace Victoire\Widget\PollBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class VictoireWidgetPollExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter(
            'victoire_widget_poll.victoire_menu_item', $config['victoire_menu_item']
        );
    }
}

Add config in Bundle Extension

Add config in Bundle Extension


<?php

/*
 * This file is part of PHPExifTool.
 *
 * (c) 2012 Romain Neutron <imprec@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPExiftool;

use \Symfony\Component\Process\Process;

abstract class Exiftool
{

    /**
     * Execute a command and return the output
     *
     * @param  string     $command
     * @return string
     * @throws \Exception
     */
    protected static function executeCommand($command)
    {
        $process = new Process($command);
        $process->run();

        if ( ! $process->isSuccessful()) {
            throw new Exception\RuntimeException(sprintf('Command %s failed : %s', $command, $process->getErrorOutput()));
        }

        return $process->getOutput();
    }

    /**
     *
     * @return string
     */
    protected static function getBinary()
    {
        $dev = __DIR__ . '/../../vendor/phpexiftool/exiftool/exiftool';
        $packaged = __DIR__ . '/../../../../phpexiftool/exiftool/exiftool';

        foreach (array($packaged, $dev) as $location) {

            if (defined('PHP_WINDOWS_VERSION_BUILD')) {
                $location .= '.exe';
            }

            if (is_executable($location)) {
                return realpath($location);
            }
        }
    }
}

<?php

/*
 * This file is part of PHPExifTool.
 *
 * (c) 2012 Romain Neutron <imprec@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPExiftool;

use \Symfony\Component\Process\Process;

abstract class Exiftool
{

    /**
     * Execute a command and return the output
     *
     * @param  string     $command
     * @return string
     * @throws \Exception
     */
    protected static function executeCommand($command)
    {
        $process = new Process($command);
        $process->run();

        if ( ! $process->isSuccessful()) {
            throw new Exception\RuntimeException(sprintf('Command %s failed : %s, exitcode %s', $command, $process->getErrorOutput(), $process->getExitCode()));
        }

        return $process->getOutput();
    }

    /**
     *
     * @return string
     */
    protected static function getBinary()
    {
        $dev = __DIR__ . '/../../vendor/phpexiftool/exiftool/exiftool';
        $packaged = __DIR__ . '/../../../../phpexiftool/exiftool/exiftool';

        foreach (array($packaged, $dev) as $location) {

            if (defined('PHP_WINDOWS_VERSION_BUILD')) {
                $location .= '.exe';
            }

            if (is_executable($location)) {
                return realpath($location);
            }
        }
    }
}

Add exit code to exception

Add exit code to exception


<?php

namespace Incenteev\HashedAssetBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Flex\Recipe;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('incenteev_hashed_asset');

        $rootNode->children()
            ->scalarNode('web_root')->defaultValue(\class_exists(Recipe::class) ? '%kernel.project_dir%/public' : '%kernel.root_dir%/../web')->end()
            ->scalarNode('version_format')->defaultValue('%%s?%%s')->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace Incenteev\HashedAssetBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Flex\Recipe;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('incenteev_hashed_asset');

        if (\method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('incenteev_hashed_asset');
        }

        $rootNode->children()
            ->scalarNode('web_root')->defaultValue(\class_exists(Recipe::class) ? '%kernel.project_dir%/public' : '%kernel.root_dir%/../web')->end()
            ->scalarNode('version_format')->defaultValue('%%s?%%s')->end()
        ;

        return $treeBuilder;
    }
}

Update the configuration class to use the new TreeBuilder API on 4.2


<?php

namespace Metrique\Building\Services;

use Metrique\Building\Models\Page;
use Metrique\Building\Support\Component;

interface BuildingServiceInterface
{
    public function fetchContent($page): array;
    public function createComponentOnPage(Component $component, Page $page): bool;
    public function readComponentOnPage(string $componentId, Page $page): Component;
    public function updateComponentOnPage(Component $component, Page $page): Component;
    public function deleteComponentOnPage(string $componentId, Page $page): bool;
    public function validateComponent(string $class): bool;
    public function buildComponentForm(string $componentId, Page $page): FormBuilderInterface;
    public function upgradeComponentOnPage(Component $component, Page $page): bool;
}

<?php

namespace Metrique\Building\Services;

use Metrique\Building\Models\Page;
use Metrique\Building\Support\Component;

interface BuildingServiceInterface
{
    public function fetchContent($page): array;
    public function createComponentOnPage(Component $component, Page $page): bool;
    public function readComponentOnPage(string $componentId, Page $page): Component;
    public function updateComponentOnPage(Component $component, Page $page): Component;
    public function deleteComponentOnPage(string $componentId, Page $page): bool;
    public function validateComponent(string $class): bool;
    public function buildComponentForm(string $componentId, Page $page): FormBuilderInterface;
    public function renameComponentOnPage(Component $from, Component $to, Page $page): bool;
    public function upgradeComponentOnPage(Component $component, Page $page): bool;
    public function isAComponentClass(string $class): bool;
}

Add support for renaming components

Add support for renaming components


<?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">

<?php
		$job = $item->getAssocObject();
	?>
	<?php /* js: hide rush warning
	<?php if($job->RUSH){?>
		RUSH
	<?php } ?>
	*/ ?>
	<a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>">
		<?php echo CHtml::encode($job->NAME);?>

	<?php /* js: hide job score
	(<?php echo $job->score;?>)
	*/ ?>

	<?php echo CHtml::activeHiddenField($item, 'ID');?>
	<?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?>

<?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">

<?php
		$job = $item->getAssocObject();
	?>
	<?php /* js: hide rush warning, todo: rm red bg
	<?php if($job->RUSH){?>
		RUSH
	<?php } ?>
	*/ ?>
	<a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>">
		<?php echo CHtml::encode($job->NAME);?>

	<?php /* js: hide job score
	(<?php echo $job->score;?>)
	*/ ?>

	<?php echo CHtml::activeHiddenField($item, 'ID');?>
	<?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?>

Comment out rush warning and job score

Comment out rush warning and job score


<?php namespace Walisph\Merchant;

interface ProductInterface {

	public function getProductName();

	public function getDescription();

	public function getPrice();

	public function getManufacturer();

	public function getBrand();

	public function getProductModel();

}

<?php namespace Walisph\Merchant;

interface ProductInterface {

	public function getProductName();

	public function getDescription();

	public function getPrice();

	public function getManufacturer();

	public function getBrand();

	public function getProductModel();

	public function getType();

}

Add new interface for type

Add new interface for type


<?php

class sfRavenPluginConfiguration extends sfPluginConfiguration
{
  const CONFIG_PATH = 'config/raven.yml';

  /**
   * Initializes the plugin.
   *
   * This method is called after the plugin's classes have been added to sfAutoload.
   */
  public function initialize()
  {
    if ($this->configuration instanceof sfApplicationConfiguration)
    {
      $configCache = $this->configuration->getConfigCache();
      $configCache->registerConfigHandler(self::CONFIG_PATH, 'sfDefineEnvironmentConfigHandler', array(
        'prefix' => 'raven_',
      ));

      require $configCache->checkConfig(self::CONFIG_PATH);

      if (!sfConfig::get('raven_dsn'))
      {
        return;
      }

      $client = new sfRavenClient(sfConfig::get('raven_dsn'));

      $errorHandler = new Raven_ErrorHandler($client);
      $errorHandler->registerExceptionHandler();
      $errorHandler->registerErrorHandler(true, E_ERROR | E_PARSE | E_NOTICE | E_STRICT);
      $errorHandler->registerShutdownFunction();
    }
  }
}

<?php

class sfRavenPluginConfiguration extends sfPluginConfiguration
{
  const CONFIG_PATH = 'config/raven.yml';

  /**
   * Initializes the plugin.
   *
   * This method is called after the plugin's classes have been added to sfAutoload.
   */
  public function initialize()
  {
    if ($this->configuration instanceof sfApplicationConfiguration)
    {
      $configCache = $this->configuration->getConfigCache();
      $configCache->registerConfigHandler(self::CONFIG_PATH, 'sfDefineEnvironmentConfigHandler', array(
        'prefix' => 'raven_',
      ));

      require $configCache->checkConfig(self::CONFIG_PATH);

      if (!sfConfig::get('raven_dsn'))
      {
        return;
      }

      $client = new sfRavenClient(sfConfig::get('raven_dsn'));

      $errorHandler = new Raven_ErrorHandler($client);
      $errorHandler->registerExceptionHandler();
      $errorHandler->registerErrorHandler(true, E_ERROR | E_PARSE | E_NOTICE | E_STRICT);
      $errorHandler->registerShutdownFunction(500);
    }
  }
}

Increase reserved memory size for registerShutdownFunction handler


<?php

namespace PhpAbac\Manager;

use PhpAbac\Repository\AttributeRepository;

use PhpAbac\Model\AbstractAttribute;
use PhpAbac\Model\Attribute;
use PhpAbac\Model\EnvironmentAttribute;

class AttributeManager {
    /** @var AttributeRepository **/
    protected $repository;

    public function __construct() {
        $this->repository = new AttributeRepository();
    }

    /**
     * @param string $name
     * @param string $table
     * @param string $column
     * @param string $criteriaColumn
     * @return Attribute
     */
    public function create($name, $table, $column, $criteriaColumn) {
        return $this->repository->createAttribute($name, $table, $column, $criteriaColumn);
    }

    /**
     * @param AbstractAttribute $attribute
     * @param string $attributeType
     * @param int $userId
     * @param int $objectId
     */
    public function retrieveAttribute(AbstractAttribute $attribute, $attributeType, $userId, $objectId) {
        // The switch is important.
        // Even if we call the same method for the two first cases,
        // the given argument isn't the same.
        switch($attributeType) {
            case 'user':
                $this->repository->retrieveAttribute($attribute, $userId);
                break;
            case 'object':
                $this->repository->retrieveAttribute($attribute, $objectId);
                break;
            case 'environment':
                $attribute->setValue(getenv($attribute->getVariableName()));
                break;
        }
    }
}

<?php

namespace PhpAbac\Manager;

use PhpAbac\Repository\AttributeRepository;

use PhpAbac\Model\AbstractAttribute;
use PhpAbac\Model\Attribute;

class AttributeManager {
    /** @var AttributeRepository **/
    protected $repository;

    public function __construct() {
        $this->repository = new AttributeRepository();
    }

    /**
     * @param string $name
     * @param string $table
     * @param string $column
     * @param string $criteriaColumn
     * @return Attribute
     */
    public function create($name, $table, $column, $criteriaColumn) {
        return $this->repository->createAttribute($name, $table, $column, $criteriaColumn);
    }

    /**
     * @param AbstractAttribute $attribute
     * @param string $attributeType
     * @param int $userId
     * @param int $objectId
     */
    public function retrieveAttribute(AbstractAttribute $attribute, $attributeType, $userId, $objectId) {
        // The switch is important.
        // Even if we call the same method for the two first cases,
        // the given argument isn't the same.
        switch($attributeType) {
            case 'user':
                $this->repository->retrieveAttribute($attribute, $userId);
                break;
            case 'object':
                $this->repository->retrieveAttribute($attribute, $objectId);
                break;
            case 'environment':
                $attribute->setValue(getenv($attribute->getVariableName()));
                break;
        }
    }

    /**
     * @param string $slug
     * @param array $dynamicAttributes
     * @return mixed
     * @throws \InvalidArgumentException
     */
    public function getDynamicAttribute($slug, $dynamicAttributes = []) {
        if(!isset($dynamicAttributes[$slug])) {
            throw new \InvalidArgumentException('The "'.$slug.'" attribute is dynamic and its value must be given');
        }
        return $dynamicAttributes[$slug];
    }
}

Add method to retrieve dynamic attributes


<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

class OrganismsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('listing/Organisms');

        $results = ($service->execute(array('limit' => 2)));
        $this->assertEquals(1, count($results));

        $results = ($service->execute(array()));
        $this->assertEquals(1, count($results));

        $results = ($service->execute(array('limit' => 10000000)));
        $this->assertEquals(1, count($results));

    }
}
?>

<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

class OrganismsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('listing/Organisms');

        $results = ($service->execute(array('limit' => 2)));
        $this->assertEquals(2, count($results));

        $results = ($service->execute(array()));
        $this->assertEquals(5, count($results));

        $results = ($service->execute(array('limit' => 10000000)));
        $this->assertEquals(12, count($results));

    }
}
?>

Make the failing tests pass

Make the failing tests pass


<?php

namespace PhpSpec\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class DescribeCommand extends Command
{
    public function __construct()
    {
        parent::__construct('describe');

        $this->setDefinition(array(
            new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'),
        ));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getContainer();
        $container->configure();

        $classname = $input->getArgument('class');
        $pattern   = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/';

        if (!preg_match($pattern, $classname)) {
            throw new \InvalidArgumentException(
                sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL .
                'Please see reference document:' .
                'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md'
            );
        }

        $resource = $container->get('locator.resource_manager')->createResource($classname);

        $container->get('code_generator')->generate($resource, 'specification');
    }
}

<?php

namespace PhpSpec\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class DescribeCommand extends Command
{
    public function __construct()
    {
        parent::__construct('describe');

        $this->setDefinition(array(
            new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'),
        ));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getContainer();
        $container->configure();

        $classname = $input->getArgument('class');
        $pattern   = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/';

        if (!preg_match($pattern, $classname)) {
            throw new \InvalidArgumentException(
                sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL .
                'Please see reference document: ' .
                'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md'
            );
        }

        $resource = $container->get('locator.resource_manager')->createResource($classname);

        $container->get('code_generator')->generate($resource, 'specification');
    }
}

Update class name validator implementation.


<?php

// configure your app for the production environment

$app['twig.path'] = array(__DIR__.'/../templates');
$app['twig.options'] = array('cache' => __DIR__.'/../var/cache/twig');
$app['db.options'] = array(
    'driver' => 'pdo_mysql',
    'host' => 'localhost',
    'dbname' => 'geocaching',
    'user' => 'user',
    'password' => 'password',
    'port' => 3306
);
$app['google.options'] = array(
    'api_key' => 'YOUR_GOOGLE_API_KEY'
);
$app['github_url'] = 'https://github.com/eibt/geocaching-tool';
$app['version'] = '0.1';
$app['require_https'] = true;

<?php

// configure your app for the production environment

$app['twig.path'] = array(__DIR__.'/../templates');
$app['twig.options'] = array('cache' => __DIR__.'/../var/cache/twig');
$app['db.options'] = array(
    'driver' => 'pdo_mysql',
    'host' => 'localhost',
    'dbname' => 'geocaching',
    'user' => 'user',
    'password' => 'password',
    'port' => 3306,
    'charset' => 'utf8'
);
$app['google.options'] = array(
    'api_key' => 'YOUR_GOOGLE_API_KEY'
);
$app['github_url'] = 'https://github.com/eibt/geocaching-tool';
$app['version'] = '0.1';
$app['require_https'] = true;

Fix the charset used when connecting to the database

- Use utf8 by default


<?php

/*
 * This file is part of Laravel Markdown.
 *
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | Enable View Integration
    |--------------------------------------------------------------------------
    |
    | This option specifies if the view integration is enabled so you can write
    | markdown views and have them rendered as html. The following extensions
    | are currently supported: ".md", ".md.php", and ".md.blade.php". You may
    | disable this integration if it is conflicting with another package.
    |
    | Default: true
    |
    */
    'views' => true,

    'allow_unsafe_links' => false,
    'max_nesting_level' => 20,

    'extensions' => [
        Webuni\CommonMark\TableExtension\TableExtension::class,
    ],

];

<?php

/*
 * This file is part of Laravel Markdown.
 *
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | Enable View Integration
    |--------------------------------------------------------------------------
    |
    | This option specifies if the view integration is enabled so you can write
    | markdown views and have them rendered as html. The following extensions
    | are currently supported: ".md", ".md.php", and ".md.blade.php". You may
    | disable this integration if it is conflicting with another package.
    |
    | Default: true
    |
    */
    'views' => true,

    'allow_unsafe_links' => false,
    'max_nesting_level' => 20,

    'renderer' => [
        'soft_break' => '<br />',
    ],

    'extensions' => [
        Webuni\CommonMark\TableExtension\TableExtension::class,
    ],

];

Use <br> for soft breaks.

Use <br> for soft breaks.


<?php

class CMService_Amazon_S3Test extends CMTest_TestCase {

	public function testConstructor() {
		new CMService_Amazon_S3();
		$this->assertTrue(true);
	}
}

<?php

class CMService_Amazon_S3Test extends CMTest_TestCase {

	public function tearDown() {
		CMTest_TH::clearEnv();
	}

	public function testConstructor() {
		$config = CM_Config::get();
		$config->CMService_Amazon_Abstract->accessKey = 'accessKey';
		$config->CMService_Amazon_Abstract->secretKey = 'secretKey';
		CM_Config::set($config);
		new CMService_Amazon_S3();
		$this->assertTrue(true);
	}

	/**
	 * @expectedException CM_Exception_Invalid
	 * @expectedExceptionMessage Amazon S3 `accessKey` not set
	 */
	public function testConstructorMissingAccessKey() {
		new CMService_Amazon_S3();
	}

	/**
	 * @expectedException CM_Exception_Invalid
	 * @expectedExceptionMessage Amazon S3 `secretKey` not set
	 */
	public function testConstructorMissingSecretKey() {
		$config = CM_Config::get();
		$config->CMService_Amazon_Abstract->accessKey = 'accessKey';
		CM_Config::set($config);
		new CMService_Amazon_S3();
	}
}

Set Amazon S3 config for tests

Set Amazon S3 config for tests

- Added tests for missing config


<?php

namespace Nikoms\FailLover\Listener;

use Nikoms\FailLover\Tests\FilterTestMock;

class LoggerListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testAddFailure_WhenLogIsActive_RecorderIsCalled()
    {
        $this->assertRecorderInvocationWithParameters(array('-d', 'fail-lover=log'), $this->once());
    }

    public function testAddFailure_WhenLogIsNotActive_RecorderIsNotCalled()
    {
        $this->assertRecorderInvocationWithParameters(array(), $this->never());
    }

    private function assertRecorderInvocationWithParameters(
        array $arguments,
        \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
    ) {
        $_SERVER['argv'] = $arguments;
        $recorder = $this->getMock('Nikoms\FailLover\TestCaseResult\RecorderInterface', array('add'));
        $recorder->expects($invocation)->method('add');
        $listener = new LoggerListener($recorder);
        $listener->addFailure(new FilterTestMock('testSimple'), new \PHPUnit_Framework_AssertionFailedError(), 0);
    }

}

<?php

namespace Nikoms\FailLover\Listener;

use Nikoms\FailLover\Tests\FilterTestMock;

class LoggerListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @param string $arguments
     * @param \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
     * @return LoggerListener
     */
    private function getListener($arguments, \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation)
    {
        $_SERVER['argv'] = explode(' ', $arguments);
        $recorder = $this->getMock('Nikoms\FailLover\TestCaseResult\RecorderInterface', array('add'));
        $recorder->expects($invocation)->method('add');
        $listener = new LoggerListener($recorder);
        return $listener;
    }

    /**
     * @param string $arguments
     * @param \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
     */
    private function assertRecorderInvocationWithParametersOnFailure(
        $arguments,
        \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
    ) {
        $listener = $this->getListener($arguments, $invocation);
        $listener->addFailure(new FilterTestMock('testSimple'), new \PHPUnit_Framework_AssertionFailedError(), 0);
    }

    /**
     * @param string $arguments
     * @param \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
     */
    private function assertRecorderInvocationWithParametersOnError(
        $arguments,
        \PHPUnit_Framework_MockObject_Matcher_Invocation $invocation
    ) {
        $listener = $this->getListener($arguments, $invocation);
        $listener->addError(new FilterTestMock('testSimple'), new \Exception(), 0);
    }

    public function testFailingTests_WhenLogIsActive_RecorderIsCalled()
    {
        $this->assertRecorderInvocationWithParametersOnFailure('-d fail-lover=log', $this->once());
        $this->assertRecorderInvocationWithParametersOnError('-d fail-lover=log', $this->once());
    }

    public function testFailingTests_WhenLogIsNotActive_RecorderIsNotCalled()
    {
        $this->assertRecorderInvocationWithParametersOnFailure('', $this->never());
        $this->assertRecorderInvocationWithParametersOnError('', $this->never());
    }
}

Test "addError" of Listener too

Test "addError" of Listener too


<?php
use Migrations\AbstractMigration;

class RenameGroupsTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('groups')
            ->rename('qobo_groups');
    }
}

<?php
use Migrations\AbstractMigration;

class RenameGroupsTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('groups')
            ->rename('qobo_groups')
            ->update();
    }
}

Fix compatibility isssues with Phinx 0.11


<?php
error_reporting('E_ALL');
dl('php_gtk.so');

$window = &new GtkWindow(GTK_WINDOW_TOPLEVEL);
$scrolledwindow = &new GtkScrolledWindow();

$sheet   = &new GtkSheet(400,400,"test");

$scrolledwindow->add($sheet);

$window->add($scrolledwindow);

//$scrolledwindow->show();
//$sheet->show();
$window->show_all();
echo "MAIN";
gtk::main();

echo "DONE?";

?>

<?php
error_reporting('E_ALL');
if (!extension_loaded('gtk')) {
	dl( 'php_gtk.' . PHP_SHLIB_SUFFIX);
}

$window = &new GtkWindow(GTK_WINDOW_TOPLEVEL);
$scrolledwindow = &new GtkScrolledWindow();

$sheet   = &new GtkSheet(400,400,"test");

$scrolledwindow->add($sheet);

$window->add($scrolledwindow);

//$scrolledwindow->show();
//$sheet->show();
$window->show_all();
echo "MAIN";
gtk::main();

echo "DONE?";

?>

Allow loading of gtk on Win32

Allow loading of gtk on Win32


<?php
/**
 * Created by PhpStorm.
 * User: warhuhn
 * Date: 06.02.16
 * Time: 18:36
 */

namespace LogBlogBundle\ORM\Repository;

class PostRepository extends AbstractDefaultRepository
{
    public function createPublishedQueryBuilder()
    {
        return $this->createDefaultQueryBuilder()
            ->where($this->getDefaultAlias().'.published = :isPublished')
            ->setParameter('isPublished', true);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: warhuhn
 * Date: 06.02.16
 * Time: 18:36
 */

namespace LogBlogBundle\ORM\Repository;

class PostRepository extends AbstractDefaultRepository
{
    public function createPublishedQueryBuilder()
    {
        return $this->createDefaultQueryBuilder()
            ->where($this->getDefaultAlias().'.published = :isPublished')
            ->setParameter('isPublished', true)
            ->orderBy($this->getDefaultAlias().'.publishedAt', 'DESC');
    }
}

Add sort order by published date

Add sort order by published date


<?php

namespace ryancco\forker;

interface JobInterface
{
    public function __invoke($instanceNumber);

    public function __destruct();
}

<?php

namespace ryancco\forker;

interface JobInterface
{
    public function __invoke($instanceNumber = 1);

    public function __destruct();
}

Add default val for param

Add default val for param


<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section Useful Informations For Connection With Login/Password." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section Informations utiles pour la connexion via utilisateur/mot de passe.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";

<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section Useful Informations For Connection With Login/Password." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section Informations utiles pour la connexion via utilisateur/mot de passe.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
"Connectivity Checks" => "Vérifications des connections",
"No problems found" => "Aucun problème trouvé",
"Please double check the installation guides." => "Merci de bien vérifier les guides d'installation."
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";

Add translation for 'Connectivity checks' section.


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Cache\Adapter;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;

/**
 * Interface for adapters managing instances of Symfony's CacheItem.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface AdapterInterface extends CacheItemPoolInterface
{
    /**
     * {@inheritdoc}
     *
     * @return CacheItem
     */
    public function getItem($key);

    /**
     * {@inheritdoc}
     *
     * return \Traversable|CacheItem[]
     */
    public function getItems(array $keys = array());
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Cache\Adapter;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;

/**
 * Interface for adapters managing instances of Symfony's CacheItem.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface AdapterInterface extends CacheItemPoolInterface
{
    /**
     * {@inheritdoc}
     *
     * @return CacheItem
     */
    public function getItem($key);

    /**
     * {@inheritdoc}
     *
     * @return \Traversable|CacheItem[]
     */
    public function getItems(array $keys = array());
}

Add missing @ in phpdoc return statement


<?php

namespace FlexModel\FlexModelBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * FlexModelExtension loads and manages the bundle configuration.
 *
 * @author Niels Nijens <niels@connectholland.nl>
 */
class FlexModelExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('flex_model.resource', $config['resource']);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}

<?php

namespace FlexModel\FlexModelBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * FlexModelExtension loads and manages the bundle configuration.
 *
 * @author Niels Nijens <niels@connectholland.nl>
 */
class FlexModelExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('flex_model.resource', $config['resource']);

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        if (isset($config['file_upload_path'])) {
            $container->setParameter('flex_model.file_upload_path', $config['file_upload_path']);

            $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
            $loader->load('upload_services.xml');
        }
    }
}

Add the upload services based on file_upload_path configuration option


<?php
declare(strict_types=1);

namespace RoundingWell\Schematic;

/**
 * @codeCoverageIgnore
 */
class System
{
    public function writeFile(string $file, string $contents): int
    {
        return (int) file_put_contents($file, $contents);
    }
}

<?php
declare(strict_types=1);

namespace RoundingWell\Schematic;

/**
 * @codeCoverageIgnore
 */
class System
{
    public function writeFile(string $file, string $contents): int
    {
        $directory = pathinfo($file, PATHINFO_DIRNAME);

        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }

        return (int) file_put_contents($file, $contents);
    }
}

Create missing directories when writing files

Ensure that the directory exists before writing to it.


#!/usr/bin/php -q
<?php
require_once('lib/YleApi.php');

if (file_exists("config.ini"))
	$config=parse_ini_file("config.ini", true);
else
	die('Configuration file config.ini is missing');

$api=$config['Generic'];

$pid='1-2897178';

$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);

$a=$c->programs_item($pid);

$mid=$c->media_find_ondemand_publication_media_id($a);

if ($mid===false)
	die('Failed to find ondemand media!');

$a=$c->media_playouts($pid, $mid);
print_r($a);

$eurl=$a->data[0]->url;

$url=$c->media_url_decrypt($eurl);

printf("Media URL is:\n\n%s\n\n", $url);

system("mplayer \"$url\"");
?>

#!/usr/bin/php -q
<?php
require_once('lib/YleApi.php');

if (file_exists("config.ini"))
	$config=parse_ini_file("config.ini", true);
else
	die('Configuration file config.ini is missing');

$api=$config['Generic'];

// TV/Video
//$pid='1-2897178';
//$pid='1-3088770';

//$pid='26-44376';
//$pid='1-2347105';

// Radio
//$pid='1-3045411';

$pid='4-4746868';

$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);

$a=$c->programs_item($pid);
print_r($a);

$mid=$c->media_find_ondemand_publication_media_id($a);

if ($mid===false)
	die('Failed to find ondemand media!');

$a=$c->media_playouts($pid, $mid);
print_r($a);

$eurl=$a->data[0]->url;

$url=$c->media_url_decrypt($eurl);

printf("Media URL is:\n\n%s\n\n", $url);

system("mplayer \"$url\"");
?>

Add test program ids, unfortunately none seem to give a playable url


#!/usr/bin/php
<?php
/**
 * PHPSpec Composer Script
 */
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);

require_once 'vendor/.composer/autoload.php';
set_include_path(__DIR__.'/../src');
$phpspec = new \PHPSpec\PHPSpec($argv);
$phpspec->execute();

#!/usr/bin/php
<?php
/**
 * PHPSpec Composer Script
 */
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);

require_once 'vendor/autoload.php';
set_include_path(__DIR__.'/../src');
$phpspec = new \PHPSpec\PHPSpec($argv);
$phpspec->execute();

Update deprecated require path for autoload.php

The .composer/autoloader.php is considered deprecated and was causing
errors to be displayed when executing `phpspec-composer.php`. Updated
to the suggested path from the error output.


#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php')));
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

file_put_contents('php://stderr', "Code coverage was 100%\n");

#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration];
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

file_put_contents('php://stderr', "Code coverage was 100%\n");

Use PHP 5.4 short array syntax.

Use PHP 5.4 short array syntax.


<?php

namespace Phamda\Builder\Docs;

use Phamda\Builder\CommentExampleBuilder;
use Phamda\Builder\PhamdaFunction;
use Phamda\Phamda;

class ListDocFunctionBuilder
{
    public static function getSection(PhamdaFunction $function)
    {
        return implode("\n", [
            '',
            '',
            $function->getName(),
            str_repeat('-', strlen($function->getName())),
            sprintf('``%s``', ((new MethodSignatureBuilder($function))->getSignature())),
            '',
            self::getSummary($function),
            '',
            self::getExamples($function),
        ]);
    }

    private static function getSummary(PhamdaFunction $function)
    {
        $process = Phamda::pipe(
            Phamda::implode("\n"),
            Phamda::explode('`'),
            Phamda::implode('``')
        );

        return $process($function->getComment()->summary);
    }

    private static function getExamples(PhamdaFunction $function)
    {
        $process = Phamda::pipe(
            Phamda::construct(CommentExampleBuilder::class),
            Phamda::invoker(0, 'getRows'),
            Phamda::map(Phamda::concat('    ')),
            Phamda::ifElse(Phamda::isEmpty(), Phamda::identity(), Phamda::merge(['.. code-block:: php', ''])),
            Phamda::implode("\n")
        );

        return $process($function);
    }
}

<?php

namespace Phamda\Builder\Docs;

use Phamda\Builder\CommentExampleBuilder;
use Phamda\Builder\PhamdaFunction;
use Phamda\Phamda;

class ListDocFunctionBuilder
{
    public static function getSection(PhamdaFunction $function)
    {
        return implode("\n", [
            '',
            '',
            sprintf('.. _%s:', $function->getName()),
            '',
            $function->getName(),
            str_repeat('-', strlen($function->getName())),
            sprintf('``%s``', ((new MethodSignatureBuilder($function))->getSignature())),
            '',
            self::getSummary($function),
            '',
            self::getExamples($function),
        ]);
    }

    private static function getSummary(PhamdaFunction $function)
    {
        $process = Phamda::pipe(
            Phamda::implode("\n"),
            Phamda::explode('`'),
            Phamda::implode('``')
        );

        return $process($function->getComment()->summary);
    }

    private static function getExamples(PhamdaFunction $function)
    {
        $process = Phamda::pipe(
            Phamda::construct(CommentExampleBuilder::class),
            Phamda::invoker(0, 'getRows'),
            Phamda::map(Phamda::concat('    ')),
            Phamda::ifElse(Phamda::isEmpty(), Phamda::identity(), Phamda::merge(['.. code-block:: php', ''])),
            Phamda::implode("\n")
        );

        return $process($function);
    }
}

Add link references to function docs

Add link references to function docs


<?php

namespace haqqi\storm;

use yii\base\Application;
use yii\base\BootstrapInterface;
use yii\base\Event;
use yii\web\View;

class Bootstrap implements BootstrapInterface {

  public function bootstrap($app) {

    $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) {
      /**
       * @var $event Event
       */

      \Yii::$container->set('yii\web\JqueryAsset', [
        'js'        => ['jquery.min.js'],
        'jsOptions' => ['position' => View::POS_HEAD]
      ]);

      \Yii::$container->set('yii\bootstrap\BootstrapAsset', [
        'css' => ['css/bootstrap.min.css']
      ]);

      \Yii::$container->set('yii\bootstrap\BootstrapPluginAsset', [
        'js'        => ['js/bootstrap.min.js'],
        'jsOptions' => ['position' => View::POS_HEAD]
      ]);

      \Yii::$container->set('mimicreative\assets\MetisMenuAsset', [
        'css' => []
      ]);
    });
  }

}

<?php

namespace haqqi\storm;

use mimicreative\datatables\assets\DataTableAsset;
use yii\base\Application;
use yii\base\BootstrapInterface;
use yii\base\Event;
use yii\web\View;

class Bootstrap implements BootstrapInterface {

  public function bootstrap($app) {

    $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) {
      /**
       * @var $event Event
       */

      \Yii::$container->set('yii\web\JqueryAsset', [
        'js'        => ['jquery.min.js'],
        'jsOptions' => ['position' => View::POS_HEAD]
      ]);

      \Yii::$container->set('yii\bootstrap\BootstrapAsset', [
        'css' => ['css/bootstrap.min.css']
      ]);

      \Yii::$container->set('yii\bootstrap\BootstrapPluginAsset', [
        'js'        => ['js/bootstrap.min.js'],
        'jsOptions' => ['position' => View::POS_HEAD]
      ]);

      \Yii::$container->set('mimicreative\assets\MetisMenuAsset', [
        'css' => []
      ]);

      \Yii::$container->set('mimicreative\datatables\assets\DataTableAsset', [
        'styling' => DataTableAsset::STYLING_BOOTSTRAP
      ]);
    });
  }

}

Create styling by default to bootstrap

Create styling by default to bootstrap


<?php namespace Qia;

use Flarum\Support\Extension as BaseExtension;
use Illuminate\Events\Dispatcher;
use Flarum\Events\RegisterLocales;

class Extension extends BaseExtension
{
    public function listen(Dispatcher $events)
    {
        $events->listen(RegisterLocales::class, function (RegisterLocales $event) {
            $event->manager->addLocale('fr', 'Français');
            $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js');
            $event->manager->addConfig('fr', __DIR__.'/../locale/core.php');
            $event->addTranslations('fr', __DIR__.'/../locale/core.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/likes.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/lock.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/tags.yml');
        });
    }
}

<?php namespace Qia;

use Flarum\Support\Extension as BaseExtension;
use Illuminate\Events\Dispatcher;
use Flarum\Events\RegisterLocales;

class Extension extends BaseExtension
{
    public function listen(Dispatcher $events)
    {
        $events->listen(RegisterLocales::class, function (RegisterLocales $event) {
            $event->addLocale('fr', 'Français');
            $event->addJsFile('fr', __DIR__.'/../locale/core.js');
            $event->addConfig('fr', __DIR__.'/../locale/core.php');
            $event->addTranslations('fr', __DIR__.'/../locale/core.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/likes.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/lock.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/tags.yml');
        });
    }
}

Use new locale registration APIs.

Use new locale registration APIs.

https://github.com/flarum/core/commit/6e0bffe395265ed1d24b33987971eb5b6c97af40