<?php

namespace FOQ\ElasticaBundle;

use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends Elastica_Client
{
    protected $logger;

    public function setLogger(ElasticaLogger $logger)
    {
        $this->logger = $logger;
    }

    public function request($path, $method, $data = array())
    {
        $start = microtime(true);
        $response = parent::request($path, $method, $data);

        if (null !== $this->logger) {
            $time = microtime(true) - $start;
            $this->logger->logQuery($path, $method, $data, $time);
        }

        return $response;
    }
}

<?php

namespace FOQ\ElasticaBundle;

use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends Elastica_Client
{
    protected $logger;

    public function setLogger(ElasticaLogger $logger)
    {
        $this->logger = $logger;
    }

    public function request($path, $method, $data = array())
    {
        $start = microtime(true);
        //this is ghetto, but i couldnt figure out another way of making our site continue to behave normally even if ES was not running.
        //Any improvements on this welcome. Perhaps another parameter that allows you to control if you want to ignore exceptions about ES not running
        try {
            $response = parent::request($path, $method, $data);
        } catch(\Exception $e) {
            //again, ghetto, but couldnt figure out how to return a default empty Elastica_Response
            return new \Elastica_Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
        }

        if (null !== $this->logger) {
            $time = microtime(true) - $start;
            $this->logger->logQuery($path, $method, $data, $time);
        }

        return $response;
    }
}

Hide exceptions if elasticsearch is not running. This needs some fixing and cleaning up by someone smarter than myself.


<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

Fix Caisse Iaaza Bug - Date : 07/11/2016


<?php namespace Illuminate\Database\Query\Processors;

use Illuminate\Database\Query\Builder;

class PostgresProcessor extends Processor {

	/**
	 * Process an "insert get ID" query.
	 *
	 * @param  Illuminate\Database\Query\Builder  $query
	 * @param  string  $sql
	 * @param  array   $values
	 * @param  string  $sequence
	 * @return int
	 */
	public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
	{
		$results = $query->getConnection()->select($sql, $values);

		$sequence = $sequence ?: 'id';

		return $results[0]->$sequence;
	}

}

<?php namespace Illuminate\Database\Query\Processors;

use Illuminate\Database\Query\Builder;

class PostgresProcessor extends Processor {

	/**
	 * Process an "insert get ID" query.
	 *
	 * @param  Illuminate\Database\Query\Builder  $query
	 * @param  string  $sql
	 * @param  array   $values
	 * @param  string  $sequence
	 * @return int
	 */
	public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
	{
		$results = $query->getConnection()->select($sql, $values);

		$sequence = $sequence ?: 'id';

		$result = (array) $results[0];

		return (int) $row[$sequence];
	}

}

Fix bug in postgres processor.

Fix bug in postgres processor.


<?php

namespace Ruler\Test\Fixtures;

class Fact
{
    public function __construct($value = null)
    {
        if ($value !== null) {
            $this->value = $value;
        }
    }
}

<?php

namespace Ruler\Test\Fixtures;

class Fact
{
    public $value;

    public function __construct($value = null)
    {
        if ($value !== null) {
            $this->value = $value;
        }
    }
}

Fix missing prop declaration in test fixture.


<?php

namespace Genj\FaqBundle\Entity;

/**
 * Class CategoryTest
 *
 * @package Genj\FaqBundle\Entity
 */
class CategoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Genj\FaqBundle\Entity\Category::__toString
     */
    public function testToString()
    {
        $category = new Category();
        $category->setHeadline('John Doe');

        $categoryToString = (string) $category;

        $this->assertSame('John Doe', $categoryToString);
    }
}

<?php

namespace Genj\FaqBundle\Entity;

/**
 * Class CategoryTest
 *
 * @package Genj\FaqBundle\Entity
 */
class CategoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Genj\FaqBundle\Entity\Category::__toString
     */
    public function testToString()
    {
        $category = new Category();
        $category->setHeadline('John Doe');

        $categoryToString = (string) $category;

        $this->assertSame('John Doe', $categoryToString);
    }

    /**
     * @covers Genj\FaqBundle\Entity\Category::getRouteName
     */
    public function testGetRouteName()
    {
        $category  = new Category();
        $routeName = $category->getRouteName();

        $this->assertSame('genj_faq', $routeName);
    }

    /**
     * @covers Genj\FaqBundle\Entity\Category::getRouteParameters
     */
    public function testGetRouteParameters()
    {
        $category = new Category();
        $category->setSlug('my-foo-slug');

        $routeParameters = $category->getRouteParameters();

        $this->assertSame(array('categorySlug' => 'my-foo-slug'), $routeParameters);
    }
}

Add some more tests for Entity\Category

Add some more tests for Entity\Category


<?php

namespace Yajra\Datatables\Html;

use Illuminate\Support\Fluent;

/**
 * Class Column
 *
 * @package Yajra\Datatables\Html
 * @see     https://datatables.net/reference/option/ for possible columns option
 */
class Column extends Fluent
{
    /**
     * @param array $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes['orderable']  = isset($attributes['orderable']) ? $attributes['orderable'] : true;
        $attributes['searchable'] = isset($attributes['searchable']) ? $attributes['searchable'] : true;

        // Allow methods override attribute value
        foreach($attributes as $attribute => $value) {
            $method = 'parse' . ucfirst(strtolower($attribute));
            if(method_exists($this, $method)) {
                $attributes[$attribute] = $this->$method($value);
            }
        }

        parent::__construct($attributes);
    }

    /**
     * Parse Render
     *
     * @param $value
     *
     * @return string
     */
    public function parseRender($value)
    {
        $value = $value ?: $this->config->get('datatables.render_template', 'datatables::action');

        if(is_callable($value)) {
            $value = value($value);
        } else {
            $value = view($value)->render();
        }

        $value = preg_replace("/\r|\n/", ' ', $value);

        return $value ?: null;
    }
}

<?php

namespace Yajra\Datatables\Html;

use Illuminate\Support\Fluent;

/**
 * Class Column
 *
 * @package Yajra\Datatables\Html
 * @see     https://datatables.net/reference/option/ for possible columns option
 */
class Column extends Fluent
{
    /**
     * @param array $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes['orderable']  = isset($attributes['orderable']) ? $attributes['orderable'] : true;
        $attributes['searchable'] = isset($attributes['searchable']) ? $attributes['searchable'] : true;

        // Allow methods override attribute value
        foreach ($attributes as $attribute => $value) {
            $method = 'parse' . ucfirst(strtolower($attribute));
            if (method_exists($this, $method)) {
                $attributes[$attribute] = $this->$method($value);
            }
        }

        parent::__construct($attributes);
    }

    /**
     * Parse render attribute.
     *
     * @param \Closure|string $value
     * @return string|null
     */
    public function parseRender($value)
    {
        $view = app('view');

        if (is_callable($value)) {
            return value($value);
        } elseif ($view->exists($value)) {
            return $view->make($value)->render();
        }

        return $value ? $this->parseRenderAsString($value) : null;
    }

    /**
     * Display render value as is.
     *
     * @param string $value
     * @return string
     */
    private function parseRenderAsString($value)
    {
        return "function(data,type,full,meta){return $value;}";
    }
}

Add capbility to render value as return on standard js render signature. Fix cs and doc blocks.


<?php

namespace NavJobs\LaravelApi;

use League\Fractal\TransformerAbstract;

class Transformer extends TransformerAbstract
{
    /**
     * Returns the includes that are available for eager loading.
     *
     * @param array|string $requestedIncludes Array of csv string
     *
     * @return $this
     */
    public function getEagerLoads($requestedIncludes)
    {
        if (is_string($requestedIncludes)) {
            $requestedIncludes = array_map(function ($value) {
                return trim($value);
            },  explode(',', $requestedIncludes));
        }

        $availableRequestedIncludes = array_intersect($this->getAvailableIncludes(), $requestedIncludes);
        $defaultIncludes = $this->getDefaultIncludes();

        return array_merge($availableRequestedIncludes, $defaultIncludes);
    }
}

<?php

namespace NavJobs\LaravelApi;

use League\Fractal\ParamBag;
use League\Fractal\TransformerAbstract;
use NavJobs\LaravelApi\Exceptions\InvalidParameters;

abstract class Transformer extends TransformerAbstract
{
    /**
     * An array of allowed parameters.
     *
     * @var array
     */
    protected $validParameters;

    /**
     * Checks if the provided parameters are valid.
     *
     * @param ParamBag $parameters
     * @return bool
     * @throws InvalidParameters
     */
    public function validateParameters(ParamBag $parameters)
    {
        $usedParameters = array_keys(iterator_to_array($parameters));
        if ($invalidParams = array_diff($usedParameters, $this->validParameters)) {
            throw new InvalidParameters(
                sprintf('Invalid param(s): "%s". Valid param(s): "%s"',
                    implode(',', $usedParameters),
                    implode(',', $this->validParameters)
                ));
        }

        return true;
    }

    /**
     * Returns the includes that are available for eager loading.
     *
     * @param array|string $requestedIncludes Array of csv string
     *
     * @return $this
     */
    public function getEagerLoads($requestedIncludes)
    {
        if (is_string($requestedIncludes)) {
            $requestedIncludes = array_map(function ($value) {
                return trim($value);
            },  explode(',', $requestedIncludes));
        }

        $availableRequestedIncludes = array_intersect($this->getAvailableIncludes(), $requestedIncludes);
        $defaultIncludes = $this->getDefaultIncludes();

        return array_merge($availableRequestedIncludes, $defaultIncludes);
    }
}

Add valid parameters array and the validate parameters method to the base transformer.


<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\View;

/**
 *
 * Factory to create View objects.
 *
 * @package Aura.View
 *
 */
class ViewFactory
{
    /**
     *
     * Returns a new View instance.
     *
     * @param object $helpers An arbitrary helper manager for the View; if not
     * specified, uses the HelperRegistry from this package.
     *
     * @return View
     *
     */
    public function newInstance(
        $helpers = null,
        $view_map = [],
        $view_paths = [],
        $layout_map = [],
        $layout_paths = [],
    ) {
        if (! $helpers) {
            $helpers = new HelperRegistry;
        }

        return new View(
            new TemplateRegistry($view_map, $view_paths),
            new TemplateRegistry($layout_map, $layout_paths),
            $helpers
        );
    }
}

<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\View;

/**
 *
 * Factory to create View objects.
 *
 * @package Aura.View
 *
 */
class ViewFactory
{
    /**
     *
     * Returns a new View instance.
     *
     * @param object $helpers An arbitrary helper manager for the View; if not
     * specified, uses the HelperRegistry from this package.
     *
     * @return View
     *
     */
    public function newInstance(
        $helpers = null,
        $view_map = [],
        $view_paths = [],
        $layout_map = [],
        $layout_paths = []
    ) {
        if (! $helpers) {
            $helpers = new HelperRegistry;
        }

        return new View(
            new TemplateRegistry($view_map, $view_paths),
            new TemplateRegistry($layout_map, $layout_paths),
            $helpers
        );
    }
}

Remove the comma on the end of method

Remove the comma on the end of method


<?php

namespace eien\Http\Controllers;

use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;

class TFAController extends Controller
{
    /**
     * @param Request $request
     */
    public function enable(Request $request)
    {
        $secret = $this->generateSecret();
        $user = $request->user();

        $user->twofa_secret = $secret;
        $user->save();

        $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret);

        return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
    }

    /**
     * @param Request $request
     */
    public function disable(Request $request)
    {
        $user = $request->user();
        $user->twofa_secret = null;
        $user->save();

        return view('TFA.disable');
    }

    /**
     * @return string
     */
    public function generateSecret()
    {
        $randomBytes = random_bytes(10);

        return Base32::encode($randomBytes);
    }
}

<?php

namespace eien\Http\Controllers;

use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;

class TFAController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function enable(Request $request)
    {
        $secret = $this->generateSecret();
        $user = $request->user();

        $user->twofa_secret = $secret;
        $user->save();

        $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret);

        return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function disable(Request $request)
    {
        $user = $request->user();
        $user->twofa_secret = null;
        $user->save();

        return view('TFA.disable');
    }

    /**
     * Generate a secure secret with the constant time library.
     *
     * @return string
     */
    public function generateSecret()
    {
        $randomBytes = random_bytes(10);

        return Base32::encode($randomBytes);
    }
}

Docblocks: Update return values, explain what generateSecret() does


<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class WriteNoteRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return false;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			//
		];
	}

}

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class WriteNoteRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return false;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			'title' => 'required|min:4',
            'body'  => 'requried|min:10',
            'public' => 'boolean'
		];
	}

}

Add the rules to ensure the notes params conform to some custom rules.


<?php

/**
 * Class definition for DTS_Instance.
 *
 * @package     DTS
 * @author      Eric Bollens
 * @copyright   Copyright (c) 2012 UC Regents
 * @license     BSD
 * @version     20120131
 */

/**
 * A class that encapsulates the instance of DTS in js.php and passthru.php.
 *
 * @package     DTS
 * @see         /www/js.php
 * @see         /www/passthru.php
 */
class DTS_Instance
{
    public static function render()
    {
        $dts = new DTS();

        $dts->add('capability.js');
        $dts->add('browser.js');
        $dts->add('useragent.js');
        $dts->add('screen.js');
        $dts->add('server.js');
        $dts->add('server/screen.js');
        $dts->add('server/useragent.js');

        return $dts->render();
    }
}

<?php

/**
 * Class definition for DTS_Instance.
 *
 * @package     DTS
 * @author      Eric Bollens
 * @copyright   Copyright (c) 2012 UC Regents
 * @license     BSD
 * @version     20120131
 */

/**
 * A class that encapsulates the instance of DTS in js.php and passthru.php.
 *
 * @package     DTS
 * @see         /www/js.php
 * @see         /www/passthru.php
 */
class DTS_Instance
{
    public static function render()
    {
        $dts = new DTS();

        $dts->add('capability.js');
        $dts->add('classification.js');
        $dts->add('browser.js');
        $dts->add('useragent.js');
        $dts->add('screen.js');
        $dts->add('server.js');
        $dts->add('server/screen.js');
        $dts->add('server/useragent.js');

        return $dts->render();
    }
}

Add classification to base instance object


<?php

namespace Common\Form;

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TitleType extends TextType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(
            [
                'label' => 'lbl.Title',
                'required' => true,
                'attr' => [
                    'class' => 'form-control title',
                ]
            ]
        );
    }

    public function getBlockPrefix(): string
    {
        return 'title';
    }
}

<?php

namespace Common\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TitleType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(
            [
                'label' => 'lbl.Title',
                'required' => true,
                'attr' => [
                    'class' => 'form-control title',
                ]
            ]
        );
    }

    public function getParent(): string
    {
        return TextType::class;
    }

    public function getBlockPrefix(): string
    {
        return 'title';
    }
}

Use the normal way of extending a form type from symfony


<?php

namespace Pantheon\Terminus\Friends;

use Pantheon\Terminus\Models\User;

/**
 * Class UserJoinTrait
 * @package Pantheon\Terminus\Friends
 */
trait UserJoinTrait
{
    /**
     * @var User
     */
    private $user;

    /**
     * @inheritdoc
     */
    public function getReferences()
    {
        return array_merge(parent::getReferences(), $this->getUser()->getReferences());
    }

    /**
     * @inheritdoc
     */
    public function getUser()
    {
        if (empty($this->user)) {
            $nickname = \uniqid(__FUNCTION__ . '-');
            $this->getContainer()
                ->add($nickname, User::class)
                ->addArgument([$this->get('user')]);
            $user = $this->getContainer()->get($nickname);
            $user->memberships = [$this];
            $this->setUser($user);
        }
        return $this->user;
    }

    /**
     * @inheritdoc
     */
    public function setUser(User $user)
    {
        $this->user = $user;
    }
}

<?php

namespace Pantheon\Terminus\Friends;

use Pantheon\Terminus\Models\User;

/**
 * Class UserJoinTrait
 * @package Pantheon\Terminus\Friends
 */
trait UserJoinTrait
{
    /**
     * @var User
     */
    private $user;

    /**
     * @inheritdoc
     */
    public function getReferences()
    {
        return array_merge(parent::getReferences(), $this->getUser()->getReferences());
    }

    /**
     * @inheritdoc
     */
    public function getUser()
    {
        if (empty($this->user)) {
            $nickname = \uniqid(__FUNCTION__ . '-');
            $this->getContainer()
                ->add($nickname, User::class)
                ->addArgument($this->get('user'));
            $user = $this->getContainer()->get($nickname);
            $user->memberships = [$this];
            $this->setUser($user);
        }
        return $this->user;
    }

    /**
     * @inheritdoc
     */
    public function setUser(User $user)
    {
        $this->user = $user;
    }
}

Fix empty ID and EMAIL attributes of org:people:list result


<?php
use Migrations\AbstractMigration;

class ReorganizeTranslationTable 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()
    {
        $table = $this->table('language_translations');
        if ($table->hasColumn('is_active')) {
            $table->removeColumn('is_active');
        }
        if ($table->hasColumn('code')) {
            $table->removeColumn('code');
        }
        $table->addColumn('language_id', 'string', [
            'limit' => 36,
            'null' => false,
        ]);
        $table->save();
    }
}

<?php
use Migrations\AbstractMigration;

class ReorganizeTranslationTable 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()
    {
        $table = $this->table('language_translations');
        if ($table->hasColumn('is_active')) {
            $table->removeColumn('is_active');
        }
        if ($table->hasColumn('code')) {
            $table->removeColumn('code');
        }
        if ($table->hasColumn('language_id')) {
            $table->changeColumn('language_id', 'string', [
                'limit' => 36,
                'null' => false,
            ]);
        } else {
            $table->addColumn('language_id', 'string', [
                'limit' => 36,
                'null' => false,
            ]);
        }
        $table->save();
    }
}

Update column if it exists, create new column if not


	<meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=9" />
	<meta name="description" content="<?php print Settings::get('metaDescription'); ?>" />
	<meta name="keywords" content="<?php print Settings::get('metaTags'); ?>" />
	<link rel="shortcut icon" type="image/x-icon" href="<?php print $layout_favicon;?>" />
	<link rel="stylesheet" type="text/css" href="<?php print resourceLink("css/common.css");?>" />
	<link rel="stylesheet" type="text/css" id="theme_css" href="<?php print resourceLink($layout_themefile); ?>" />

	<script type="text/javascript" src="<?php print resourceLink("js/jquery.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/tricks.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/jquery.tablednd_0_5.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/jquery.scrollTo-1.4.2-min.js");?>"></script>

	<?php
		$bucket = "pageHeader"; include("./lib/pluginloader.php");
	?>

	<meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=10" />
	<meta name="description" content="<?php print Settings::get('metaDescription'); ?>" />
	<meta name="keywords" content="<?php print Settings::get('metaTags'); ?>" />
	<link rel="shortcut icon" type="image/x-icon" href="<?php print $layout_favicon;?>" />
	<link rel="stylesheet" type="text/css" href="<?php print resourceLink("css/common.css");?>" />
	<link rel="stylesheet" type="text/css" id="theme_css" href="<?php print resourceLink($layout_themefile); ?>" />

	<script type="text/javascript" src="<?php print resourceLink("js/jquery.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/tricks.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/jquery.tablednd_0_5.js");?>"></script>
	<script type="text/javascript" src="<?php print resourceLink("js/jquery.scrollTo-1.4.2-min.js");?>"></script>

	<?php
		$bucket = "pageHeader"; include("./lib/pluginloader.php");
	?>

Set mode for IE to IE10

Set mode for IE to IE10


<!DOCTYPE html>

<title>Layout Test</title>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<?php
	wp_head();
	comments_popup_script(400, 400);
?>

A

Bla blah blah bleh blee!

Home

About

<!DOCTYPE html>

<title>Layout Test</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<?php
	wp_head();
	comments_popup_script(400, 400);
?>

A

Bla blah blah bleh blee!

Home

About

Add character encoding meta tag

Add character encoding meta tag

Signed-off-by: Eddie Ringle <bacc1c505cb1756c59242c0a8ee25cd990a210e9@eringle.net>


<?php

namespace Chromabits\Illuminated\Auth;

use Chromabits\Illuminated\Auth\Models\KeyPair;
use Chromabits\Illuminated\Support\ServiceProvider;

/**
 * Class KeyPairServiceProvider
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Auth
 */
class KeyPairServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Boot the provider
     */
    public function boot()
    {
        KeyPair::registerEvents();
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        //
    }
}

<?php

namespace Chromabits\Illuminated\Auth;

use Chromabits\Illuminated\Auth\Interfaces\KeyPairFinderInterface;
use Chromabits\Illuminated\Auth\Interfaces\KeyPairGeneratorInterface;
use Chromabits\Illuminated\Auth\Models\KeyPair;
use Chromabits\Illuminated\Support\ServiceMapProvider;

/**
 * Class KeyPairServiceProvider
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Auth
 */
class KeyPairServiceProvider extends ServiceMapProvider
{
    protected $defer = false;

    protected $map = [
        KeyPairFinderInterface::class => KeyPairFinder::class,
        KeyPairGeneratorInterface::class => KeyPairGenerator::class,
    ];

    /**
     * Boot the provider
     */
    public function boot()
    {
        KeyPair::registerEvents();
    }
}

Add keypair services to provider

Add keypair services to provider


<?php

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

class CreatePostTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();

            $table->primary(['post_id', 'tag_id']);
            $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
        });

        $now = Carbon\Carbon::now();
        collect(DB::table('post_tag_pivot')->get())->each(function ($item) {
           DB::table('post_tag')->insert([
                'post_id' => $item->post_id,
                'tag_id' => $item->tag_id,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        });
    }

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

<?php

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

class CreatePostTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();

            $table->primary(['post_id', 'tag_id']);
            $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
        });

        $now = Carbon\Carbon::now();

        // This is here to migrate any data someone might have into the new post-tag table.
        collect(DB::table('post_tag_pivot')->get())->each(function ($item) {
           DB::table('post_tag')->insert([
                'post_id' => $item->post_id,
                'tag_id' => $item->tag_id,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        });
    }

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

Add comment to explain query/insert in migration


<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Transaction\Transaction;
use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface;

/**
 * TransactionRepository
 */
class TransactionRepository extends EntityRepository
    implements TransactionRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function add(Transaction $transaction)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getAll() : array
    {
        return [];
    }
}

<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Transaction\Transaction;
use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface;
use PerFi\PerFiBundle\Entity\Transaction as DtoTransaction;

/**
 * TransactionRepository
 */
class TransactionRepository extends EntityRepository
    implements TransactionRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function add(Transaction $transaction)
    {
        $entity = new DtoTransaction();
        $entity->setTransactionId((string) $transaction->id());
        $entity->setType((string) $transaction->type());
        $entity->setSourceAccount((string) $transaction->sourceAccount()->id());
        $entity->setDestinationAccount((string) $transaction->destinationAccount()->id());
        $entity->setDate($transaction->date());
        $entity->setDescription($transaction->description());

        $amount = $transaction->amount();
        $entity->setAmount($amount->getAmount());
        $entity->setCurrency((string) $amount->getCurrency());

        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getAll() : array
    {
        return [];
    }
}

Save a transaction entity to the database


<?php

namespace SymfonyDay\Bundle\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    public function getPublishedPost($id)
    {
        return $this
            ->createQueryBuilder('p')
            ->where('p.id = :id')
            ->andWhere('p.publishedAt IS NULL')
            ->orWhere('p.publishedAt <= :date')
            ->setParameter('id', $id)
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->createQueryBuilder('p')
            ->where('p.publishedAt IS NULL')
            ->orWhere('p.publishedAt <= :date')
            ->orderBy('p.publishedAt', 'DESC')
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->execute()
        ;
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    public function getPublishedPost($id)
    {
        return $this
            ->createQueryBuilder('p')
            ->where('p.id = :id')
            ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date')
            ->setParameter('id', $id)
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->createQueryBuilder('p')
            ->where('p.publishedAt IS NULL')
            ->orWhere('p.publishedAt <= :date')
            ->orderBy('p.publishedAt', 'DESC')
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->execute()
        ;
    }
}

Fix where clause in getPublishedPost

Fix where clause in getPublishedPost


<?php
/**
 * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
 */

namespace Catalog;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
    public function registerAutoloaders()
    {
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'Catalog\Controller' => APPLICATION_PATH . '/modules/catalog/controllers/',
            'Catalog\Model' => APPLICATION_PATH . '/modules/catalog/models/',
        ));
        $loader->register();
    }

    public function registerServices($di)
    {
        $dispatcher = $di->get('dispatcher');
        $dispatcher->setDefaultNamespace('Catalog\Controller');

        /**
         * @var $view \Phalcon\Mvc\View
         */
        $view = $di->get('view');
        $view->setLayout('index');
        $view->setViewsDir(APPLICATION_PATH . '/modules/catalog/views/');
        $view->setLayoutsDir('../../common/layouts/');
        $view->setPartialsDir('../../common/partials/');

        $di->set('view', $view);
    }
}

<?php
/**
 * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
 */

namespace Catalog;

use Phalcon\DiInterface;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
    public function registerAutoloaders(DiInterface $dependencyInjector = null)
    {
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'Catalog\Controller' => APPLICATION_PATH . '/modules/catalog/controllers/',
            'Catalog\Model' => APPLICATION_PATH . '/modules/catalog/models/',
        ));
        $loader->register();
    }

    public function registerServices(DiInterface $dependencyInjector)
    {
        $dispatcher = $dependencyInjector->get('dispatcher');
        $dispatcher->setDefaultNamespace('Catalog\Controller');

        /**
         * @var $view \Phalcon\Mvc\View
         */
        $view = $dependencyInjector->get('view');
        $view->setLayout('index');
        $view->setViewsDir(APPLICATION_PATH . '/modules/catalog/views/');
        $view->setLayoutsDir('../../common/layouts/');
        $view->setPartialsDir('../../common/partials/');

        $dependencyInjector->set('view', $view);
    }
}

Fix compatibility with Phalcon 2 in Catalog module


<?php
define('DB_HOST', 'db-server');
define('DB_NAME', 'db-name');
define('DB_USER', 'db-user');
define('DB_PASSWORD', 'db-password');

define( 'APP_PATH', realpath('..') . '/app' );

//AuthSession params
//define('AUTH_USER_MODEL', 'YOUR MODEL CLASS');
//define('AUTH_CRYPTO_COST', 10);

<?php
define('DB_CONNECTOR', 'mysql'); // Possible values: mysq, sqlite
define('DB_HOST', 'db-server');
define('DB_NAME', 'db-name'); // sqlite: used as file path
define('DB_USER', 'db-user');
define('DB_PASSWORD', 'db-password');

define( 'APP_PATH', realpath('..') . '/app' );

//AuthSession params
//define('AUTH_USER_MODEL', 'YOUR MODEL CLASS');
//define('AUTH_CRYPTO_COST', 10);

Add DB_CONNECTOR constant & comments

Add DB_CONNECTOR constant & comments


<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Froiden\RestAPI\Tests\TestCase;

class PaginationTest extends TestCase
{

    /**
     * Test User Index Page.
     *
     * @return void
     **/
    public function testPagination()
    {
        //Use "Limit" to get required number of result
        $response = $this->call('GET', '/dummyUser',
            [
                'order' => 'id asc',
                'offset' => '5',
                'limit' => '2'
            ]);

        dd($response->getContent());
        $this->assertEquals(200, $response->status());
    }
}

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Froiden\RestAPI\Tests\TestCase;

class PaginationTest extends TestCase
{

    /**
     * Test User Index Page.
     *
     * @return void
     **/
    public function testPagination()
    {
        //Pagination set offset = "5" or limit ="3"
        $response = $this->call('GET', '/dummyUser',
            [
                'order' => 'id asc',
                'offset' => '5',
                'limit' => '2'
            ]);
        $this->assertEquals(200, $response->status());

        //Pagination set offset = "1" or limit ="1"
        $response = $this->call('GET', '/dummyUser',
            [
                'order' => 'id asc',
                'offset' => '1',
                'limit' => '1'
            ]);
        $this->assertEquals(200, $response->status());

        //Pagination set offset = "5" or limit ="3"
        $response = $this->call('GET', '/dummyUser',
            [
                'order' => 'id asc',
                'offset' => '5',
                'limit' => '-2'
            ]);

        $this->assertNotEquals(200, $response->status());
    }
}

Test: Write TestCase for pagination with parameter 'offset' or 'limit'4


<?php

namespace Blablacar\MemcachedBundle\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Blablacar\MemcachedBundle\Memcached\ClientLogger;

class MemcachedDataCollector extends DataCollector
{
    protected $clients = array();

    public function addClient($name, ClientLogger $client)
    {
        $this->clients[$name] = $client;
    }

    /**
     * {@inheritDoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        foreach ($this->clients as $name => $client) {
            foreach ($client->getCommands() as $command) {
                $this->data[] = array(
                    'command'    => $command['name'],
                    'arguments'  => implode(', ', $command['arguments']),
                    'duration'   => $command['duration'],
                    'connection' => $name,
                    'return'     => implode(', ', $command['return'])
                );
            }

            $client->reset();
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'memcached';
    }

    /**
     * getCommands
     *
     * @return array
     */
    public function getCommands()
    {
        return $this->data;
    }

    /**
     * getDuration
     *
     * @return int
     */
    public function getDuration()
    {
        $time = 0;
        foreach ($this->data as $data) {
            $time += $data['duration'];
        }

        return $time;
    }
}

<?php

namespace Blablacar\MemcachedBundle\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Blablacar\MemcachedBundle\Memcached\ClientLogger;

class MemcachedDataCollector extends DataCollector
{
    protected $clients = array();

    public function addClient($name, ClientLogger $client)
    {
        $this->clients[$name] = $client;
    }

    /**
     * {@inheritDoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        foreach ($this->clients as $name => $client) {
            foreach ($client->getCommands() as $command) {
                $this->data[] = array(
                    'command'    => $command['name'],
                    'arguments'  => implode(', ', $command['arguments']),
                    'duration'   => $command['duration'],
                    'connection' => $name,
                    'return'     => implode(', ', $command['return'])
                );
            }

            $client->reset();
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'memcached';
    }

    /**
     * getCommands
     *
     * @return array
     */
    public function getCommands()
    {
        return $this->data;
    }

    /**
     * getDuration
     *
     * @return int
     */
    public function getDuration()
    {
        if (null === $this->data) {
            return 0;
        }

        $time = 0;
        foreach ($this->data as $data) {
            $time += $data['duration'];
        }

        return $time;
    }
}

Correct duration when no commands is logged


<?php

namespace Clastic\TaxonomyBundle\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 ClasticTaxonomyExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

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

<?php

namespace Clastic\TaxonomyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
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 ClasticTaxonomyExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

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

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (true === isset($bundles['StofDoctrineExtensionsBundle'])) {
            $this->configureStofDoctrineExtensionsBundle($container);
        }
    }

    /**
     * @param ContainerBuilder $container The service container
     *
     * @return void
     */
    protected function configureStofDoctrineExtensionsBundle(ContainerBuilder $container)
    {
        foreach (array_keys($container->getExtensions()) as $name) {
            switch ($name) {
                case 'stof_doctrine_extensions':
                    $container->prependExtensionConfig(
                        $name,
                        array('orm' => array('default' => array('tree' => true)))
                    );
                    break;
            }
        }
    }
}

Move configuration to Bundle Extension.

[Taxonomy] Move configuration to Bundle Extension.


<?php namespace GeneaLabs\LaravelCaffeine\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class LaravelCaffeineDripMiddleware implements Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $content = null;
        $response = $next($request);

        if (! method_exists($response, 'getOriginalContent')) {
            return $response;
        }

        $content = $response->getOriginalContent();

        if (method_exists($content, 'render')) {
            $content = $content->render();
        }

        if (is_string($content) && strpos($content, '_token')) {
            $content = str_replace('', "", $content);
            $response->setContent($content);
        }

        return $response;
    }
}

Fix drip interval from 5e3 to 3e5

Fix drip interval from 5e3 to 3e5


<?php

namespace Mockery\Generator\StringManipulation\Pass;

use Mockery\Generator\MockConfiguration;

class ClassPass implements Pass
{
    public function apply($code, MockConfiguration $config)
    {
        $target = $config->getTargetClass();

        if (!$target) {
            return $code;
        }

        if ($target->isFinal()) {
            return $code;
        }

        $className = ltrim($target->getName(), "\\");
        if (!class_exists($className)) {

            $targetCode = '<?php ';

            if ($target->inNamespace()) {
                $targetCode.= 'namespace ' . $target->getNamespaceName(). '; ';
            }

            $targetCode.= 'class ' . $target->getShortName() . ' {} ';

            eval('?>' . $targetCode);
        }

        $code = str_replace(
            "implements MockInterface",
            "extends \\" . $className . " implements MockInterface",
            $code
        );

        return $code;
    }
}

<?php

namespace Mockery\Generator\StringManipulation\Pass;

use Mockery\Generator\MockConfiguration;

class ClassPass implements Pass
{
    public function apply($code, MockConfiguration $config)
    {
        $target = $config->getTargetClass();

        if (!$target) {
            return $code;
        }

        if ($target->isFinal()) {
            return $code;
        }

        $className = ltrim($target->getName(), "\\");
        if (!class_exists($className)) {

            $targetCode = '<?php ';

            if ($target->inNamespace()) {
                $targetCode.= 'namespace ' . $target->getNamespaceName(). '; ';
            }

            $targetCode.= 'class ' . $target->getShortName() . ' {} ';

            /*
             * We could eval here, but it doesn't play well with the way
             * PHPUnit tries to backup global state and the require definition
             * loader
             */
            $tmpfname = tempnam(sys_get_temp_dir(), "Mockery");
            file_put_contents($tmpfname, $targetCode);
            require $tmpfname;
        }

        $code = str_replace(
            "implements MockInterface",
            "extends \\" . $className . " implements MockInterface",
            $code
        );

        return $code;
    }
}

Create unknown targets with require

Create unknown targets with require


<?php

namespace Dafiti\Log;

use Monolog\Logger;
use Monolog\Handler\NewRelicHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Processor\TagProcessor;

class Factory
{
    /**
     * @param string $applicationName
     * @param string $stream
     *
     * @return \Monolog\Logger $logger
     */
    public function createInstance($applicationName, $stream)
    {
        if (!isset($applicationName, $stream)) {
            throw new \InvalidArgumentException('The $applicationName and $stream
             parameters are required');
        }

        $logger = new Logger($applicationName);
        $logger->pushHandler(new NewRelicHandler());

        $requestId = getenv('MESSAGE_ID');
        if ($requestId != '') {
            $tag = new TagProcessor(['request-id' => $requestId]);
            $logger->pushProcessor($tag);
        }

        $streamHandler = new StreamHandler($stream);
        $formatter = new Formatter\LogstashFormatter($applicationName);
        $streamHandler->setFormatter($formatter);
        $logger->pushHandler($streamHandler);

        return $logger;
    }
}

<?php

namespace Dafiti\Log;

use Monolog\Logger;
use Monolog\Handler\NewRelicHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Processor\TagProcessor;

class Factory
{
    /**
     * @param string $applicationName
     * @param string $stream
     *
     * @return \Monolog\Logger $logger
     */
    public function createInstance($applicationName, $stream)
    {
        if (!isset($applicationName, $stream)) {
            throw new \InvalidArgumentException('The $applicationName and $stream
             parameters are required');
        }

        $logger = new Logger($applicationName);

        if (extension_loaded('newrelic')) {
            $logger->pushHandler(new NewRelicHandler());
        }

        $requestId = getenv('MESSAGE_ID');
        if ($requestId != '') {
            $tag = new TagProcessor(['request-id' => $requestId]);
            $logger->pushProcessor($tag);
        }

        $streamHandler = new StreamHandler($stream);
        $formatter = new Formatter\LogstashFormatter($applicationName);
        $streamHandler->setFormatter($formatter);
        $logger->pushHandler($streamHandler);

        return $logger;
    }
}

Revert "removed unnecessary code, tks @fabiorphp"

This reverts commit c85ca25a06f6b3073e2e7cfaecb42f9d81a2d774.


<?php

namespace Michaeljennings\Carpenter\Tests\Components;

use Michaeljennings\Carpenter\Components\Cell as CellComponent;
use Michaeljennings\Carpenter\Contracts\Cell as CellContract;
use Michaeljennings\Carpenter\Tests\TestCase;

class CellTest extends TestCase
{
    public function testCellImplementsContract()
    {
        $cell = $this->makeCell();

        $this->assertInstanceOf(CellContract::Class, $cell);
    }

    public function testValueCanBeRetrieved()
    {
        $cell = $this->makeCell();

        $this->assertEquals('Test', $cell->value);
        $this->assertEquals('Test', $cell->getValue());
        $this->assertEquals('Test', $cell->value());
        $this->assertEquals('Test', $cell);
    }

    public function testColumnPresenterIsRunOnCellValue()
    {
        $table = $this->makeTableWithData();

        $table->column('foo')->setPresenter(function($value) {
            return 'Value is: ' . $value;
        });

        $cell = new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);

        $this->assertEquals('Value is: Test', $cell->value);
    }

    protected function makeCell()
    {
        $table = $this->makeTableWithData();

        return new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
    }
}

<?php

namespace Michaeljennings\Carpenter\Tests\Components;

use Michaeljennings\Carpenter\Components\Cell as CellComponent;
use Michaeljennings\Carpenter\Tests\TestCase;

class CellTest extends TestCase
{
    public function testCellImplementsContract()
    {
        $cell = $this->makeCell();

        $this->assertInstanceOf('Michaeljennings\Carpenter\Contracts\Cell', $cell);
    }

    public function testValueCanBeRetrieved()
    {
        $cell = $this->makeCell();

        $this->assertEquals('Test', $cell->value);
        $this->assertEquals('Test', $cell->getValue());
        $this->assertEquals('Test', $cell->value());
        $this->assertEquals('Test', $cell);
    }

    public function testColumnPresenterIsRunOnCellValue()
    {
        $table = $this->makeTableWithData();

        $table->column('foo')->setPresenter(function($value) {
            return 'Value is: ' . $value;
        });

        $cell = new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);

        $this->assertEquals('Value is: Test', $cell->value);
    }

    protected function makeCell()
    {
        $table = $this->makeTableWithData();

        return new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
    }
}

Fix 5.4 error in cell test

Fix 5.4 error in cell test


<?php

namespace Kunstmaan\PagePartBundle\Tests\Form;

use Kunstmaan\NodeBundle\Form\Type\URLChooserType;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Forms;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * PagePartAdminTypeTestCase
 */
class PagePartAdminTypeTestCase extends WebTestCase
{
    /**
     * @var FormBuilder
     */
    protected $builder;

    /**
     * @var EventDispatcher
     */
    protected $dispatcher;

    /**
     * @var \Symfony\Component\Form\FormFactoryInterface
     */
    protected $factory;

    /**
     * @var OptionsResolver
     */
    protected $resolver;

    protected function setUp(): void
    {
        $formFactoryBuilderInterface = Forms::createFormFactoryBuilder();
        $formFactoryBuilderInterface->addType(new URLChooserType());
        $formFactoryBuilderInterface->addTypeGuesser(new DoctrineOrmTypeGuesser($this->createMock('Doctrine\Common\Persistence\ManagerRegistry')));
        $this->factory = $formFactoryBuilderInterface->getFormFactory();
        $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory);
        $this->resolver = new OptionsResolver();
    }
}

<?php

namespace Kunstmaan\PagePartBundle\Tests\Form;

use Kunstmaan\NodeBundle\Form\Type\URLChooserType;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Forms;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * PagePartAdminTypeTestCase
 */
class PagePartAdminTypeTestCase extends WebTestCase
{
    /**
     * @var FormBuilder
     */
    protected $builder;

    /**
     * @var EventDispatcher
     */
    protected $dispatcher;

    /**
     * @var \Symfony\Component\Form\FormFactoryInterface
     */
    protected $factory;

    /**
     * @var OptionsResolver
     */
    protected $resolver;

    protected function setUp(): void
    {
        $formFactoryBuilderInterface = Forms::createFormFactoryBuilder();
        $formFactoryBuilderInterface->addType(new URLChooserType());
        $formFactoryBuilderInterface->addTypeGuesser(new DoctrineOrmTypeGuesser($this->createMock('Doctrine\Persistence\ManagerRegistry')));
        $this->factory = $formFactoryBuilderInterface->getFormFactory();
        $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory);
        $this->resolver = new OptionsResolver();
    }
}

[AllBundles] Fix doctrine common deprecations and resolve doctrine bundle v2 incompatibility


<?php

$repo_clone_url = '{ user: "%1$s", team: "%2$s", project: "%3$s" }';
$user = 'bees';
$team = 'ABC';
$project = 'wasps';
$expected_url = "{ user: \"$user\", team: \"$team\", project: \"$project\" }";

$config = Configuration::getInstance();
$config->override('repo_clone_url', $repo_clone_url);
$config->override('modules', array('proj'));

$config->override("user.default", "death");
$config->override("user.default.teams", array(1, 2, $team));
$config->override("auth_module", "single");

// do a quick authentication
$auth = AuthBackend::getInstance();
test_true($auth->authUser($user,'face'), "authentication failed");

// setup the required input keys
$input = Input::getInstance();
$input->setInput("team", $team);
$input->setInput("project", $project);

$mm = ModuleManager::getInstance();
$mm->importModules();
$proj = $mm->getModule('proj');

$proj->dispatchCommand('info');

$output = Output::getInstance();
$repoUrl = $output->getOutput('repoUrl');
test_nonnull($repoUrl, 'Failed to get repoUrl from output');

test_equal($repoUrl, $expected_url, "Wrong repo url data output");

<?php

$repo_clone_url = '{ user: "%1$s", team: "%2$s", project: "%3$s" }';
$user = 'bees';
$team = 'ABC';
$project = 'wasps';

$config = Configuration::getInstance();
$config->override('repo_clone_url', $repo_clone_url);
$config->override('modules', array('proj'));

$config->override("user.default", "death");
$config->override("user.default.teams", array(1, 2, $team));
$config->override("auth_module", "single");

// do a quick authentication
$auth = AuthBackend::getInstance();
test_true($auth->authUser($user,'face'), "authentication failed");

// setup the required input keys
$input = Input::getInstance();
$input->setInput("team", $team);

function check_project($project, $expected_url) {
    $input = Input::getInstance();
    $input->setInput("project", $project);

    $mm = ModuleManager::getInstance();
    $mm->importModules();
    $proj = $mm->getModule('proj');
    $proj->dispatchCommand('info');

    $output = Output::getInstance();
    $repoUrl = $output->getOutput('repoUrl');
    test_nonnull($repoUrl, 'Failed to get repoUrl from output');

    test_equal($repoUrl, $expected_url, "Wrong repo url data output");
}

check_project('wasps', "{ user: \"$user\", team: \"$team\", project: \"wasps\" }");

Move test logic into a function for re-use.

Change-Id: I29ad81ee0f15a969a3d7d89b644b8044af4fd1da


<?php

namespace BuzzwordCompliant\FAQs\Controllers;

use Backend\Facades\BackendMenu;
use Illuminate\Http\Request;

class FAQs extends Controller
{
    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('BuzzwordCompliant.FAQs', 'faqs');
    }

    public $implement = [
        'Backend.Behaviors.ListController',
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.RelationController',
        'Backend.Behaviors.ReorderController',
    ];
    public $listConfig = 'config_list.yaml';
    public $formConfig = 'config_form.yaml';
    public $relationConfig = 'config_relation.yaml';
    public $reorderConfig = 'config_reorder.yaml';

    public function reorderExtendQuery($query)
    {
        $query->where('faq_id', $this->params[0]);
    }
}

<?php

namespace BuzzwordCompliant\FAQs\Controllers;

use Backend\Classes\Controller;
use Backend\Facades\BackendMenu;
use Illuminate\Http\Request;

class FAQs extends Controller
{
    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('BuzzwordCompliant.FAQs', 'faqs');
    }

    public $implement = [
        'Backend.Behaviors.ListController',
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.RelationController',
        'Backend.Behaviors.ReorderController',
    ];
    public $listConfig = 'config_list.yaml';
    public $formConfig = 'config_form.yaml';
    public $relationConfig = 'config_relation.yaml';
    public $reorderConfig = 'config_reorder.yaml';

    public function reorderExtendQuery($query)
    {
        $query->where('faq_id', $this->params[0]);
    }
}

Fix Controller class not found

Fix Controller class not found


<?php

namespace Remp\MailerModule\Mailer;

use Nette\Mail\IMailer;
use Nette\Mail\Message;
use Remp\MailerModule\Config\Config;
use Remp\MailerModule\Repository\ConfigsRepository;

class SmtpMailer extends Mailer implements IMailer
{
    private $mailer;

    protected $alias = 'remp-smtp';

    protected $options = [
        'host' => [
            'required' => true,
            'label' => 'SMTP host',
        ],
        'port' => [
            'required' => true,
            'label' => 'SMTP Port',
        ],
        'username' => [
            'required' => false,
            'label' => 'SMTP Username',
        ],
        'password' => [
            'required' => false,
            'label' => 'SMTP Password',
        ],
        'secure' => [
            'required' => false,
            'label' => 'SMTP Secure',
        ],
    ];

    public function __construct(
        Config $config,
        ConfigsRepository $configsRepository
    ) {

        parent::__construct($config, $configsRepository);
        $this->mailer = new \Nette\Mail\SmtpMailer($this->options);
    }

    public function send(Message $message)
    {
        $this->mailer->send($message);
    }
}

<?php

namespace Remp\MailerModule\Mailer;

use Nette\Mail\IMailer;
use Nette\Mail\Message;
use Remp\MailerModule\Config\Config;
use Remp\MailerModule\Repository\ConfigsRepository;

class SmtpMailer extends Mailer implements IMailer
{
    private $mailer;

    protected $alias = 'remp-smtp';

    protected $options = [
        'host' => [
            'required' => true,
            'label' => 'SMTP host',
        ],
        'port' => [
            'required' => true,
            'label' => 'SMTP Port',
        ],
        'username' => [
            'required' => false,
            'label' => 'SMTP Username',
        ],
        'password' => [
            'required' => false,
            'label' => 'SMTP Password',
        ],
        'secure' => [
            'required' => false,
            'label' => 'SMTP Secure',
        ],
    ];

    public function __construct(
        Config $config,
        ConfigsRepository $configsRepository
    ) {
        parent::__construct($config, $configsRepository);

        // SMTP Mailer expects plain options
        $options = [];
        foreach ($this->options as $name => $option) {
            if (isset($option['value'])) {
                $options[$name] = $option['value'];
            }
        }

        $this->mailer = new \Nette\Mail\SmtpMailer($options);
    }

    public function send(Message $message)
    {
        $this->mailer->send($message);
    }
}

Fix initialization of Smtp Mailer

Fix initialization of Smtp Mailer


<?php

/**
 * Fetches the name of the current module folder name.
 *
 * @return string
**/
define('BLOGGER_DIR', dirname(__FILE__));

<?php

/**
 * Fetches the name of the current module folder name.
 *
 * @return string
**/
define('BLOGGER_DIR', basename(dirname(__FILE__)));

FIX Base pase constant BLOGGER_DIR

FIX Base pase constant BLOGGER_DIR


<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
$stmt->bindParam(1, $row["election"]);
$stmt->execute();
$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];

?>

        Edit Election
        <?php echo $election_name; ?>

 Elections

<?php echo $election_name; ?>

<?php

require_once('page_template_dash_foot.php');

?>

<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
$stmt->bindParam(1, $_GET['id']);
$stmt->execute();
$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];

?>

        Edit Election
        <?php echo $election_name; ?>

 Elections

<?php echo $election_name; ?>

<?php

require_once('page_template_dash_foot.php');

?>

Change how we get election ID

Change how we get election ID


<?php

namespace Bauhaus;

use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class Application
{
    private $stack = [];

    public function stackUp($middleware): void
    {
        if (false === $this->canStackUp($middleware)) {
            throw new InvalidArgumentException('Can only stack up PSR-15 middlewares');
        }

        $this->stack[] = $middleware;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $headDelegator = $this->buildDelegatorChain();

        return $headDelegator->process($request);
    }

    private function canStackUp($middleware): bool
    {
        if (is_object($middleware)) {
            return $middleware instanceof MiddlewareInterface;
        }

        if (false === is_string($middleware)) {
            return false;
        }

        if (false === class_exists($middleware)) {
            return false;
        }

        $implementedInterfaces = class_implements($middleware);

        return in_array(MiddlewareInterface::class, $implementedInterfaces);
    }

    private function buildDelegatorChain(): DelegateInterface
    {
        $currentDelegator = new GroundDelegator();

        foreach($this->stack as $middleware) {
            $currentDelegator = new Delegator($middleware, $currentDelegator);
        }

        return $currentDelegator;
    }
}

<?php

namespace Bauhaus;

use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class Application
{
    private $middlewareStack = [];

    public function stackUp($middleware): void
    {
        if (false === $this->canStackUp($middleware)) {
            throw new InvalidArgumentException('Can only stack up PSR-15 middlewares');
        }

        $this->middlewareStack[] = $middleware;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $firstHandler = $this->buildChain();

        return $firstHandler->process($request);
    }

    private function canStackUp($middleware): bool
    {
        if (is_object($middleware)) {
            return $middleware instanceof MiddlewareInterface;
        }

        if (false === is_string($middleware)) {
            return false;
        }

        if (false === class_exists($middleware)) {
            return false;
        }

        $implementedInterfaces = class_implements($middleware);

        return in_array(MiddlewareInterface::class, $implementedInterfaces);
    }

    private function buildChain(): DelegateInterface
    {
        $currentDelegator = new GroundDelegator();

        foreach($this->middlewareStack as $middleware) {
            $currentDelegator = new Delegator($middleware, $currentDelegator);
        }

        return $currentDelegator;
    }
}

Rename class attribute, method and variable


<?php
namespace Lio\Forum\Replies;

use App;
use Input;
use McCool\LaravelAutoPresenter\BasePresenter;
use Request;

class ReplyPresenter extends BasePresenter
{
    public function url()
    {
        $slug = $this->thread->slug;
        $threadUrl = action('Forum\ForumThreadsController@getShowThread', [$slug]);
        return $threadUrl . \App::make('Lio\Forum\Replies\ReplyQueryStringGenerator')->generate($this->getWrappedObject());
    }

    public function created_ago()
    {
        return $this->getWrappedObject()->created_at->diffForHumans();
    }

    public function updated_ago()
    {
        return $this->getWrappedObject()->updated_at->diffForHumans();
    }

    public function body()
    {
        $body = $this->getWrappedObject()->body;
        $body = $this->convertMarkdown($body);
        $body = $this->formatGists($body);
        $body = $this->linkify($body);

        return $body;
    }

    // ------------------- //

    private function convertMarkdown($content)
    {
        return App::make('Lio\Markdown\HtmlMarkdownConvertor')->convertMarkdownToHtml($content);
    }

    private function formatGists($content)
    {
        return App::make('Lio\Github\GistEmbedFormatter')->format($content);
    }

    private function linkify($content)
    {
        $linkify = new \Misd\Linkify\Linkify();
        return $linkify->process($content);
    }
}

<?php
namespace Lio\Forum\Replies;

use Input;
use McCool\LaravelAutoPresenter\BasePresenter;
use Misd\Linkify\Linkify;
use Request;

class ReplyPresenter extends BasePresenter
{
    public function url()
    {
        $slug = $this->getWrappedObject()->thread->slug;
        $threadUrl = action('Forum\ForumThreadsController@getShowThread', $slug);

        return $threadUrl . app(ReplyQueryStringGenerator::class)->generate($this->getWrappedObject());
    }

    public function created_ago()
    {
        return $this->getWrappedObject()->created_at->diffForHumans();
    }

    public function updated_ago()
    {
        return $this->getWrappedObject()->updated_at->diffForHumans();
    }

    public function body()
    {
        $body = $this->getWrappedObject()->body;
        $body = $this->convertMarkdown($body);
        $body = $this->formatGists($body);
        $body = $this->linkify($body);

        return $body;
    }

    private function convertMarkdown($content)
    {
        return app('Lio\Markdown\HtmlMarkdownConvertor')->convertMarkdownToHtml($content);
    }

    private function formatGists($content)
    {
        return app('Lio\Github\GistEmbedFormatter')->format($content);
    }

    private function linkify($content)
    {
        $linkify = new Linkify();

        return $linkify->process($content);
    }
}

Use wrapped object for presenter

Use wrapped object for presenter


<?php

include '../d-bug.php';

class A {

}

class B extends A {
	public $a = 'test';
	public $b = [[1, 2, 3, 4], 2, 3, 4];

	const C = 42;

	public static function test($a, $b = true) {
		return true;
	}
}

$test = [];
$test[] = fopen(__FILE__, 'r');
$test[] = 'test';
$test[] = 1;
$test[] = 2.3;
$test[] = true;
$test[] = null;
$test[] = [[1, 2, 3, 4], 2, 3, 4];
$test[] = new A();
$test[] = new B();

foreach($test as $k => $t) {
	echo "Test #", $k, "\n\n";
	D::bugType($t, false);
	echo "----------------------------------------\n\n";
}

fclose($test[0]);

<?php

chdir(__DIR__);

include '../d-bug.php';

class A {

}

class B extends A {
	public $a = 'test';
	public $b = [[1, 2, 3, 4], 2, 3, 4];

	const C = 42;

	public static function test($a, $b = true) {
		return true;
	}
}

$test = [];
$test[] = fopen(__FILE__, 'r');
$test[] = 'test';
$test[] = 1;
$test[] = 2.3;
$test[] = true;
$test[] = null;
$test[] = [[1, 2, 3, 4], 2, 3, 4];
$test[] = new A();
$test[] = new B();

foreach($test as $k => $t) {
	echo "Test #", $k, "\n\n";
	D::bugType($t, false);
	echo "----------------------------------------\n\n";
}

fclose($test[0]);

Test script can be run from outside of its own directory


<?php

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

namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection;

use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase;
use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SwiftmailerExtensionTest extends TestCase
{
    public function testConfigLoad()
    {
        $container = new ContainerBuilder();
        $loader = new SwiftmailerExtension();

        $loader->load(array(array()), $container);
        $this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded');

        $loader->load(array(array('transport' => 'sendmail')), $container);
        $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');
        $loader->load(array(array()), $container);
        $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');
    }
}

<?php

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

namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection;

use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase;
use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SwiftmailerExtensionTest extends TestCase
{
    public function testConfigLoad()
    {
        $container = new ContainerBuilder();
        $loader = new SwiftmailerExtension();

        $loader->load(array(array()), $container);
        $this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded');

        $loader->load(array(array('transport' => 'sendmail')), $container);
        $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');

        $loader->load(array(array()), $container);
        $this->assertEquals('smtp', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() provides default values for configuration options');
    }
}

[SwiftmailerBundle] Fix expected default value in SwiftmailerExtension unit test


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

namespace BrZend;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

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

    public function onBootstrap(MvcEvent $e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }
}

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

namespace BrZend;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

/**
 * @codeCoverageIgnore
 * @author igor
 *
 */
class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

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

    public function onBootstrap(MvcEvent $e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }
}

Add ignore block of code coverage

Add ignore block of code coverage


<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package _s
 */

get_header(); ?>

		<?php if ( have_posts() ) : ?>

<?php printf( __( 'Search Results for: %s', '_s' ), '' . get_search_query() . '' ); ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', 'search' ); ?>

			<?php endwhile; ?>

			<?php _s_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<?php get_template_part( 'no-results', 'search' ); ?>

		<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package _s
 */

get_header(); ?>

		<?php if ( have_posts() ) : ?>

<?php printf( __( 'Search Results for: %s', '_s' ), '' . get_search_query() . '' ); ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', 'search' ); ?>

			<?php endwhile; ?>

			<?php _s_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<?php get_template_part( 'content', 'none' ); ?>

		<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Use content-none.php instead of no-results.php

Renamed no-results.php to content-none.php for consistency (as done in core: https://core.trac.wordpress.org/ticket/25181); so let's make sure it's used.


<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

use Flarum\Extend;
use Flarum\Frontend\Document;
use Psr\Http\Message\ServerRequestInterface as Request;

return [
    (new Extend\Frontend('forum'))
        ->route(
            '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]',
            'embed.discussion',
            function (Document $document, Request $request) {
                // Add the discussion content to the document so that the
                // payload will be included on the page and the JS app will be
                // able to render the discussion immediately.
                app(Flarum\Forum\Content\Discussion::class)($document, $request);

                app(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request);
            }
        ),

    (new Extend\Frontend('embed'))
        ->js(__DIR__.'/js/dist/forum.js')
        ->css(__DIR__.'/less/forum.less')
];

<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

use Flarum\Extend;
use Flarum\Frontend\Document;
use Psr\Http\Message\ServerRequestInterface as Request;

return [
    (new Extend\Frontend('forum'))
        ->route(
            '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]',
            'embed.discussion',
            function (Document $document, Request $request) {
                // Add the discussion content to the document so that the
                // payload will be included on the page and the JS app will be
                // able to render the discussion immediately.
                resolve(Flarum\Forum\Content\Discussion::class)($document, $request);

                resolve(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request);
            }
        ),

    (new Extend\Frontend('embed'))
        ->js(__DIR__.'/js/dist/forum.js')
        ->css(__DIR__.'/less/forum.less')
];

Use resolve helper instead of app

Use resolve helper instead of app


<?php

namespace Kevinrob\GuzzleCache\Storage;

use Kevinrob\GuzzleCache\CacheEntry;

/**
 * This cache class is backed by a PHP Array.
 */
class VolatileRuntimeStorage implements CacheStorageInterface
{

    /**
     * @var CacheEntry[]
     */
    protected $cache = [];

    /**
     * @param string $key
     *
     * @return CacheEntry|null the data or false
     */
    public function fetch($key)
    {
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }

        return;
    }

    /**
     * @param string $key
     * @param CacheEntry $data
     *
     * @return bool
     */
    public function save($key, CacheEntry $data)
    {
        $this->cache[$key] = $data;

        return true;
    }

}

Add newline at end of file

Add newline at end of file


<?hh // strict

class MailgunEmailClient extends EmailClient {
  private Mailgun\Mailgun $client;
  public string $domain;
  public string $email;

  public function __construct(string $api_key, string $domain, string $from_email): void {
    $this->client = new Mailgun\Mailgun($api_key);
    $this->domain = $domain;
    $this->email = $from_email;
  }

  public function send(string $to, string $subject, string $body): void {
    $this->client->sendMessage($this->domain, Map {
      'from' => $this->email,
      'to' => $to,
      'subject' => $subject,
      'text' => $body
    });
  }
}

<?hh // strict

use Mailgun\Mailgun;

class MailgunEmailClient extends EmailClient {
  private Mailgun $client;
  public string $domain;
  public string $email;

  public function __construct(string $api_key, string $domain, string $from_email): void {
    $this->client = new Mailgun($api_key);
    $this->domain = $domain;
    $this->email = $from_email;
  }

  public function send(string $to, string $subject, string $body): void {
    $this->client->sendMessage($this->domain, Map {
      'from' => $this->email,
      'to' => $to,
      'subject' => $subject,
      'text' => $body
    });
  }
}

Use 'use' keyword for Mailgun

Use 'use' keyword for Mailgun


<?php

namespace Silktide\Syringe;

use Silktide\Syringe\Loader\JsonLoader;
use Silktide\Syringe\Loader\YamlLoader;

/**
 * Create Containers from DI configuration
 *
 * Uses static methods in order to be accessible from
 */
class Syringe
{

    /**
     * @var ContainerBuilder
     */
    protected static $builder;

    /**
     * Initialise the DI container builder
     *
     * @param string $appDir - the root directory of the application
     * @param array $configFiles - the syringe config files to load into the container
     */
    public static function init($appDir, array $configFiles)
    {
        $resolver = new ReferenceResolver();
        $loaders = [
            new JsonLoader(),
            new YamlLoader()
        ];

        $configPaths = [
            $appDir
        ];

        self::$builder = new ContainerBuilder($resolver, $configPaths);

        foreach ($loaders as $loader) {
            self::$builder->addLoader($loader);
        }
        self::$builder->setApplicationRootDirectory($appDir);

        self::$builder->addConfigFiles($configFiles);
    }

    /**
     * Build a new DI container
     *
     * @return \Pimple\Container
     */
    public static function createContainer()
    {
        return self::$builder->createContainer();
    }

}

<?php

namespace Silktide\Syringe;

use Silktide\Syringe\Loader\JsonLoader;
use Silktide\Syringe\Loader\YamlLoader;

/**
 * Create Containers from DI configuration
 *
 * Uses static methods in order to be accessible from
 */
class Syringe
{

    protected static $loaders;

    protected static $appDir;

    protected static $configFiles;

    /**
     * Initialise the DI container builder
     *
     * @param string $appDir - the root directory of the application
     * @param array $configFiles - the syringe config files to load into the container
     */
    public static function init($appDir, array $configFiles)
    {
        self::$loaders = [
            new JsonLoader(),
            new YamlLoader()
        ];

        self::$appDir = $appDir;
        self::$configFiles = $configFiles;
    }

    /**
     * Build a new DI container
     *
     * @return \Pimple\Container
     */
    public static function createContainer()
    {
        $resolver = new ReferenceResolver();

        $builder = new ContainerBuilder($resolver, [self::$appDir]);

        foreach (self::$loaders as $loader) {
            $builder->addLoader($loader);
        }
        $builder->setApplicationRootDirectory(self::$appDir);

        $builder->addConfigFiles(self::$configFiles);

        return $builder->createContainer();
    }

}

Rebuild the entire ContainerBuilder when getting a new container - Getting more than one container from the same ContainerBuilder caused some services to be linked and private services didn't match the registered private names


<?php

/*
 * This file is part of the Collections library.
 *
 * (c) University of Cambridge
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Misd\Collections;

/**
 * Abstract set.
 *
 * This provides a skeletal implementation of {@link SetInterface}, to
 * minimize the effort required to implement this interface.
 *
 * This is an immutable collection: you must overwrite methods such as `add()`
 * to allow modification.
 *
 * @author Chris Wilkinson <chris.wilkinson@admin.cam.ac.uk>
 */
abstract class AbstractSet extends AbstractCollection implements SetInterface
{
    /**
     * {@inheritdoc}
     */
    public function __construct($elements = array())
    {
        if ($elements instanceof CollectionInterface) {
            $elements = $elements->toArray();
        }

        $this->elements = array_values(array_unique($elements, SORT_REGULAR));
    }
}

<?php

/*
 * This file is part of the Collections library.
 *
 * (c) University of Cambridge
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Misd\Collections;

/**
 * Abstract set.
 *
 * This provides a skeletal implementation of {@link SetInterface}, to
 * minimize the effort required to implement this interface.
 *
 * This is an immutable collection: you must overwrite methods such as `add()`
 * to allow modification.
 *
 * @author Chris Wilkinson <chris.wilkinson@admin.cam.ac.uk>
 */
abstract class AbstractSet extends AbstractCollection implements SetInterface
{
    /**
     * {@inheritdoc}
     */
    protected $elements;

    /**
     * {@inheritdoc}
     */
    public function __construct($elements = array())
    {
        if ($elements instanceof CollectionInterface) {
            $elements = $elements->toArray();
        }

        $this->elements = array_values(array_unique($elements, SORT_REGULAR));
    }
}

Stop incorrect inspection in PhpStorm (WI-12377)


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 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);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
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);
}

echo "Code coverage was 100%\n";

Use phpcs as a library.

Use phpcs as a library.


<?php
/**
 *  ocs-webserver
 *
 *  Copyright 2016 by pling GmbH.
 *
 *    This file is part of ocs-webserver.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
class Default_Model_DbTable_StatPageViews extends Zend_Db_Table_Abstract
{

    protected $_name = "stat_page_views";

    public function savePageView($project_id, $clientIp, $member_id)
    {

        $newData = array(
            'project_id' => $project_id,
            'ip' => $clientIp,
            'member_id' => $member_id
        );
        $this->insert($newData);

    }

}

<?php
/**
 *  ocs-webserver
 *
 *  Copyright 2016 by pling GmbH.
 *
 *    This file is part of ocs-webserver.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
class Default_Model_DbTable_StatPageViews extends Zend_Db_Table_Abstract
{

    protected $_name = "stat_page_views";

    public function savePageView($project_id, $clientIp, $member_id)
    {

        $this->_db->query("INSERT LOW_PRIORITY INTO {$this->_name} (`project_id`, `ip`, `member_id`) VALUES (:param1, :param2, :param3);",
            array(
                'param1' => $project_id,
                'param2' => $clientIp,
                'param3' => $member_id
            ));
        $this->_db->commit();

    }

}

Insert into stat_page_views with LOW_PRIORITY


<?php

/*
Copyright (C) 2010-2016 by the FusionInventory Development Team
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Armadito Plugin for GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include("../../../inc/includes.php");

if (PluginArmaditoMenu::canView()) {
    Html::header(__('Armadito', 'armadito'), $_SERVER["PHP_SELF"], "plugins", "pluginarmaditomenu", "stateboard");

    PluginArmaditoMenu::displayHeader();
    PluginArmaditoMenu::displayMenu("mini");
    $board = new PluginArmaditoStateBoard();
    $board->displayBoard();
} else {
    Html::displayRightError();
}

Html::footer();

?>

<?php

/*
Copyright (C) 2010-2016 by the FusionInventory Development Team
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Armadito Plugin for GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include("../../../inc/includes.php");

if (PluginArmaditoMenu::canView())
{
    Html::header(__('Armadito', 'armadito'), $_SERVER["PHP_SELF"], "plugins", "pluginarmaditomenu", "stateboard");

    PluginArmaditoMenu::displayHeader();
    PluginArmaditoMenu::displayMenu("mini");

    try {
        $board = new PluginArmaditoStateBoard();
        $board->displayBoard();
    }
    catch(Exception $e) {
        PluginArmaditoLog::Error($e->getMessage(), 500);
    }

} else {
    Html::displayRightError();
}

Html::footer();

?>

Add try/catch for state board display

Add try/catch for state board display


<?php

/**
 * Package Routes
 */

Route::group(['namespace' => 'Taskforcedev\CrudAPI\Http\Controllers'], function () {
    Route::group(['prefix' => 'api'], function () {
        Route::get('{model}/{id}', 'ApiController@show');
        Route::get('{model}', 'ApiController@index');
        Route::post('{model}', 'ApiController@store');
        Route::delete('{model}/{id}', 'ApiController@destroy');
    });

    Route::group(['prefix' => 'admin/crud'], function () {
        Route::get('{model}/{id}', 'AdminController@show');
        Route::get('{model}', 'AdminController@index');
        Route::post('{model}', 'AdminController@store');
    });
});

<?php

/**
 * Package Routes
 */

Route::group(['namespace' => 'Taskforcedev\CrudAPI\Http\Controllers'], function () {
    Route::group(['middleware' => 'web', 'prefix' => 'api'], function () {
        Route::get('{model}/{id}', 'ApiController@show');
        Route::get('{model}', 'ApiController@index');
        Route::post('{model}', 'ApiController@store');
        Route::delete('{model}/{id}', 'ApiController@destroy');
    });

    Route::group(['middleware' => 'web', 'prefix' => 'admin/crud'], function () {
        Route::get('{model}/{id}', 'AdminController@show');
        Route::get('{model}', 'AdminController@index');
        Route::post('{model}', 'AdminController@store');
    });
});

Add route middleware (requires 5.2 laravel+ now to work).