<?php

namespace Cs278\BankModulus\Spec;

/**
 * Default factory implementation.
 *
 * Uses the correct specification based on the current date.
 */
final class DefaultSpecFactory implements SpecFactoryInterface
{
    /** @var \DateTimeZone */
    private $tz;

    /** @var \DateTime|null */
    private $now;

    public function __construct()
    {
        // This is hard coded, but modulus checking is intrinsically related
        // to banking in the UK which happens on London time.
        $this->tz = new \DateTimeZone('Europe/London');
    }

    /** {@inheritdoc} */
    public function create()
    {
        $this->now = \DateTime('today', $this->tz);

        if ($this->dateOnOrAfter('2017-01-09')) {
            return new VocaLinkV400();
        }

        return new VocaLink390();
    }

    private function dateOnOrAfter($when)
    {
        Assert::string($when);
        Assert::regex($when, '{^[0-9]{4}-[0-9]{2}-[0-9]{2}$}');

        $when = \DateTime::createFromFormat('!Y-m-d', $when);

        assert($when instanceof \DateTime);

        return $this->now >= $when;
    }
}

<?php

namespace Cs278\BankModulus\Spec;

use Cs278\BankModulus\Exception\Util as E;
use Webmozart\Assert\Assert;

/**
 * Default factory implementation.
 *
 * Uses the correct specification based on the current date.
 */
final class DefaultSpecFactory implements SpecFactoryInterface
{
    /** @var \DateTimeZone */
    private $tz;

    /** @var \DateTime|null */
    private $now;

    public function __construct()
    {
        // This is hard coded, but modulus checking is intrinsically related
        // to banking in the UK which happens on London time.
        $this->tz = new \DateTimeZone('Europe/London');
    }

    /** {@inheritdoc} */
    public function create()
    {
        $this->now = \DateTime('today', $this->tz);

        if ($this->dateOnOrAfter('2017-01-09')) {
            return new VocaLinkV400();
        }

        return new VocaLink390();
    }

    private function dateOnOrAfter($when)
    {
        try {
            Assert::string($when);
            Assert::regex($when, '{^[0-9]{4}-[0-9]{2}-[0-9]{2}$}');
        } catch (\InvalidArgumentException $e) {
            throw E::wrap($e);
        }

        $when = \DateTime::createFromFormat('!Y-m-d', $when);

        assert($when instanceof \DateTime);

        return $this->now >= $when;
    }
}

Fix assertions in default spec factory

Fix assertions in default spec factory


<?php
namespace GuzzleHttp\Subscriber\Log\Support;

use DebugBar\DataCollector\ExceptionsCollector;
use DebugBar\DebugBar;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Log\LogSubscriber;
use GuzzleHttp\Subscriber\Log\DebugbarSubscriber;
use Psr\Log\LoggerInterface;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use DebugBar\DataCollector\TimeDataCollector;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Register method
     */
    public function register()
    {
        $this->registerGuzzleSubscriber();
    }

    /**
     * Register a log subscriber on every Guzzle client.
     */
    private function registerGuzzleSubscriber()
    {
        // Register a log subscriber with every Guzzle client.
        $this->app->bind('GuzzleHttp\Client', function () {
            // Create new client.
            $client = new Client;

            /** @var DebugBar $debugBar */
            $debugBar = $this->app->make('debugbar');

            /** @var LoggerInterface $logger */
            $logger = $debugBar->getCollector('messages');

            /** @var TimeDataCollector $timeline */
            $timeline = $debugBar->getCollector('time');

            /** @var ExceptionsCollector $exceptions */
            $exceptions = $debugBar->getCollector('exceptions');

            // Attach event subscribers.
            $client->getEmitter()->attach(new LogSubscriber($logger));
            $client->getEmitter()->attach(new DebugbarSubscriber($timeline, $exceptions));

            // Return configured client.
            return $client;
        });
    }
}

<?php
namespace GuzzleHttp\Subscriber\Log\Support;

use DebugBar\DataCollector\ExceptionsCollector;
use DebugBar\DebugBar;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Log\LogSubscriber;
use GuzzleHttp\Subscriber\Log\DebugbarSubscriber;
use Psr\Log\LoggerInterface;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use DebugBar\DataCollector\TimeDataCollector;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Register method
     */
    public function register()
    {
        $this->registerGuzzleSubscriber();
    }

    /**
     * Register a log subscriber on every Guzzle client.
     */
    private function registerGuzzleSubscriber()
    {
        // Register a log subscriber with every Guzzle client.
        $this->app->bind('GuzzleHttp\Client', function ($app, $params) {
            // Create new client.
            $client = new Client(array_shift($params) ?: []);

            /** @var DebugBar $debugBar */
            $debugBar = $this->app->make('debugbar');

            /** @var LoggerInterface $logger */
            $logger = $debugBar->getCollector('messages');

            /** @var TimeDataCollector $timeline */
            $timeline = $debugBar->getCollector('time');

            /** @var ExceptionsCollector $exceptions */
            $exceptions = $debugBar->getCollector('exceptions');

            // Attach event subscribers.
            $client->getEmitter()->attach(new LogSubscriber($logger));
            $client->getEmitter()->attach(new DebugbarSubscriber($timeline, $exceptions));

            // Return configured client.
            return $client;
        });
    }
}

Allow to do app->make with parameters to pass to the constructor of guzzle client


<?php

namespace Padawan\Framework\Generator;

use Padawan\Framework\Utils\PathResolver;
use Padawan\Domain\Project;
use Padawan\Domain\Generator\FilesFinder as FilesFinderInterface;

class FilesFinder implements FilesFinderInterface
{
    public function __construct(PathResolver $path)
    {
        $this->path = $path;
    }

    public function findProjectFiles(Project $project)
    {
        return $this->filterFiles(
            $project,
            $this->path->getDirFilesRecursive(
                $project->getRootDir()
            )
        );
    }

    public function findChangedProjectFiles(Project $project)
    {
        throw new \Exception("Not implemented yet");
    }

    protected function filterFiles(Project $project, $files)
    {
        $projectFiles = [];
        foreach ($files as $file) {
            if (!preg_match('/\.php$/', $file)) {
                continue;
            }
            $projectFiles[] = $this->path->relative($project->getRootDir(), $file);
        }
        return $projectFiles;
    }
    /** @var PathResolver */
    private $path;
}

<?php

namespace Padawan\Framework\Generator;

use Padawan\Framework\Utils\PathResolver;
use Padawan\Domain\Project;
use Padawan\Domain\Generator\FilesFinder as FilesFinderInterface;

class FilesFinder implements FilesFinderInterface
{
    public function __construct(PathResolver $path)
    {
        $this->path = $path;
    }

    public function findProjectFiles(Project $project)
    {
        return $this->filterFiles(
            $project,
            $this->path->getDirFilesRecursive(
                $project->getRootDir()
            )
        );
    }

    public function findChangedProjectFiles(Project $project)
    {
        throw new \Exception("Not implemented yet");
    }

    protected function filterFiles(Project $project, $files)
    {
        $projectFiles = [];
        foreach ($files as $file) {
            if (!preg_match('/\.php$/', $file)) {
                continue;
            }
            if (preg_match('#/[tT]ests?/#', $file)) {
                // exclude test files
                continue;
            }
            $projectFiles[] = $this->path->relative($project->getRootDir(), $file);
        }
        return $projectFiles;
    }
    /** @var PathResolver */
    private $path;
}

Exclude test files from indexing.

Exclude test files from indexing.

May put this into command line argument, but now just use a default one.


<!DOCTYPE html>

		Course
		Student ID
		Student Name
		Student E-mail
		Enrollment Date

	@foreach($enrollments as $enrollment)

		{{ $enrollment->course->name }}
		{{ $enrollment->student->student_number }}
		{{ $enrollment->student->user->name }}
		{{ $enrollment->student->user->email }}
		{{ $enrollment->student->created_at }}

	@endforeach

<!DOCTYPE html>

        Course
        Student ID
        Student Name
        Student E-mail
        Enrollment Date

    @foreach($enrollments as $enrollment)

        {{ $enrollment->course->id }}
        {{ $enrollment->course->name }}
        {{ $enrollment->student->student_number }}
        {{ $enrollment->student->user->name }}
        {{ $enrollment->student->user->email }}
        {{ $enrollment->student->created_at }}

    @endforeach

Add course ID to the enrollments export list


<?php

declare(strict_types=1);

namespace NewTwitchApi;

use GuzzleHttp\Client;

class HelixGuzzleClient extends Client
{
    private const BASE_URI = 'https://ad5211862b1bcde69e96954213b8859a.m.pipedream.net/';

    public function __construct(string $clientId, array $config = [])
    {
        parent::__construct($config + [
            'base_uri' => self::BASE_URI,
            'timeout' => 30,
            'headers' => ['Client-ID' => $clientId, 'Content-Type' => 'application/json'],
        ]);
    }
}

<?php

declare(strict_types=1);

namespace NewTwitchApi;

use GuzzleHttp\Client;

class HelixGuzzleClient extends Client
{
    private const BASE_URI = 'https://api.twitch.tv/helix/';

    public function __construct(string $clientId, array $config = [])
    {
        parent::__construct($config + [
            'base_uri' => self::BASE_URI,
            'timeout' => 30,
            'headers' => ['Client-ID' => $clientId, 'Content-Type' => 'application/json'],
        ]);
    }
}

Rollback change to BASE_URI (mistake)

Rollback change to BASE_URI (mistake)


<?php
namespace Dropbox;

/**
 * @internal
 */
final class SdkVersion {
    // When doing a release:
    // 1. Set VERSION to the version you're about to release, tag the relase, then commit+push.
    // 2. Immediately afterwards, append "-dev", then commit+push.
    const VERSION = "1.1.6-dev";
}

<?php
namespace Dropbox;

/**
 * @internal
 */
final class SdkVersion {
    // When doing a release:
    // 1. Set VERSION to the version you're about to release, tag the relase, then commit+push.
    // 2. Immediately afterwards, append "-dev", then commit+push.
    const VERSION = "1.1.6";
}

Make sure to use Dropbox SDK v1.1.6

Make sure to use Dropbox SDK v1.1.6


<?php
class MainController extends RedeAppController
{

	var $name = 'Main';
	var $uses = array();

	function index()
	{
		// GET HIGHLIGHTED CONTENT (3 FIRST COLUMNS)
		$this->loadModel('MexcHighlights.MexcHighlightedContent');
		$highlighted = $this->MexcHighlightedContent->getHightlightedsFrom('museu');

		// GET NEWS
		$this->loadModel('MexcNews.MexcNew');
		$this->MexcNew->setActiveStatuses(array('display_level' => array('general')));
		$news = $this->MexcNew->find('all', array('limit' => 10, 'contain' => false));
		$three_news = array_slice($news, 0, 3);
		$seven_news = array_slice($news, 3);

		// GET PROGRAMS
		$this->loadModel('SiteFactory.FactSite');
		$fact_sites = $this->FactSite->find('all', array('contain' => false));

		// GET EVENTS
		$this->loadModel('MexcEvents.MexcEvent');
		$this->MexcEvent->setActiveStatuses(array('display_level' => array('general')));
		$events = $this->MexcEvent->find('all', array(
			'limit' => 9,
			'contain' => false,
			'conditions' => array('MexcEvent.end >=' => date('Y-m-d')),
			'order' => array('MexcEvent.start' => 'asc')
		));
		if (empty($events))
		{
			$events = $this->MexcEvent->find('all', array('limit' => 9, 'contain' => false));
		}
		$two_events = array_slice($events, 0, 2);
		$seven_events = array_slice($events, 2);

		// GET GALLERY
		$this->loadModel('MexcGalleries.MexcGallery');
		$this->MexcGallery->setActiveStatuses(array('display_level' => array('general')));
		$gallery = $this->MexcGallery->find('first', array('contain' => array('MexcImage' => array('limit' => 1))));

		// SET THEM ALL
		$this->set(compact('highlighted', 'three_news', 'seven_news', 'two_events', 'seven_events', 'gallery', 'fact_sites'));
	}
}

<?php
class MainController extends RedeAppController
{

	var $name = 'Main';
	var $uses = array();

	function index()
	{
		// GET GALLERY
		$this->loadModel('UnifiedSearch.SblSearchItem');
		$paging = array();
		$items = $this->SblSearchItem->getSearchResults("", array(), $paging);

		// GET PROGRAMS
		$this->loadModel('SiteFactory.FactSite');
		$fact_sites = $this->FactSite->find('all', array('contain' => false));

		// SET THEM ALL
		$this->set(compact('items', 'fact_sites'));
	}
}

Remove old finds from main

Remove old finds from main


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

namespace Zend\Db\Adapter\Driver\Sqlsrv;

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Adapter
 */
class ErrorException extends \Exception
{

    /**
     * Errors
     *
     * @var array
     */
    protected $errors = array();

    /**
     * Construct
     *
     * @param boolean $errors
     */
    public function __construct($errors = false)
    {
        $this->errors = ($errors === false) ? sqlsrv_errors() : $errors;
    }

}

Convert files from dos format to unix format


<?php
	require_once('IP2Country.php');

	define('DB_SERVER', 'localhost');
	define('DB_PORT', 3306);
	define('DB_NAME', 'dnscheckng');
	define('DB_USER', 'dnscheckng');
	define('DB_PASS', 'dnscheckng');

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());
?>

<?php
	require_once('IP2Country.php');

	define('DB_SERVER', 'localhost');
	define('DB_PORT', 3306);
	define('DB_NAME', 'dnscheckng');
	define('DB_USER', 'dnscheckng');
	define('DB_PASS', 'dnscheckng');

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());

    /* Provide a place where settings can be overridden, to make Debian packaging easier. */
    if (is_readable('/etc/dnscheck.php')) {
        require_once('/etc/dnscheck.php');
    }

?>

Make configuration overrideable from /etc


    @if (isset($post))

{{{ $post->title }}}

        {{-- Escape html entities, format with paragraph tags --}}
        {{-- Leading and trailing paragraph tags are required for leading and trailing paragraphs respectively --}}

{{ str_replace(array("\n","\r\n"), "

", e($post->content)) }}

            {{{ $post->tags }}}
            {{ $post->created_at }}

    @else

Sorry! That post doesn't exist!

Unfortunately the post you were looking for isn't in the database. Maybe try looking in the archive for the post you were seeking.

    @endif

Add column width to posts for larger displays


<?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
            ->getActivePostsQueryBuilder('p')
            ->andWhere('p.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->getQuery()
            ->execute()
        ;
    }

    private function getActivePostsQueryBuilder($alias)
    {
        return $this
            ->createQueryBuilder($alias)
            ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date')
            ->setParameter('date', date('Y-m-d H:i'))
        ;
    }
}

<?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
            ->getActivePostsQueryBuilder('p')
            ->select('p, c')
            ->leftJoin('p.comments', 'c')
            ->andWhere('p.id = :id')
            ->andWhere('c.isPublished = :published')
            ->setParameter('id', $id)
            ->setParameter('published', true)
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->getQuery()
            ->execute()
        ;
    }

    private function getActivePostsQueryBuilder($alias)
    {
        return $this
            ->createQueryBuilder($alias)
            ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date')
            ->setParameter('date', date('Y-m-d H:i'))
        ;
    }
}

Decrease the query count when loading a blog post


<?php
	// Require functions file
	require_once("./inc/functions.php");

	// URI and explode
	$uri = $_SERVER["REQUEST_URI"];
	$uri = explode("/",$uri);

	// Redirect to the right url with right parameter
	switch($uri[1])
	{
		// Redirect to userpage
		case 'u': redirect("../index.php?u=".$uri[2]); break;
		// Redirect to bloodcat map download
		case 'd': redirect("http://bloodcat.com/osu/s/".explode('?', $uri[2])[0]); break;
		// No matches, redirect to index
		default: redirect("../index.php"); break;
	}
?>

<?php
	// Require functions file
	require_once("./inc/functions.php");

	// URI and explode
	$uri = $_SERVER["REQUEST_URI"];
	$uri = explode("/",$uri);

	// Redirect to the right url with right parameter
	switch($uri[1])
	{
		// Redirect to userpage
		case 'u': redirect("../index.php?u=".$uri[2]); break;
		// Redirect to bloodcat map download
		case 'd': redirect(file_get_contents("http://bcache.zxq.co/download.php?s=" . explode('?', $uri[2])[0])); break;
		// No matches, redirect to index
		default: redirect("../index.php"); break;
	}
?>

Use bcache.zxq.co for serving files via bloodcat


<?php

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

class CreateVehiclesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('vehicles', function (Blueprint $table) {
            $table->string('code')->primary();
            $table->foreign('code')->references('code')->on('items');

            $table->integer('year')->nullable();
            $table->integer('engine_displacement')->nullable();
            $table->string('reg_plate_code')->nullable();
            $table->boolean('is_good_condition')->nullable();

            $table->integer('make_id')->unsigned()->nullable();
            $table->foreign('make_id')->references('id')->on('vehicles_makes');

            $table->integer('model_id')->unsigned()->nullable();
            $table->foreign('model_id')->references('id')->on('vehicles_models');

            $table->integer('color_id')->unsigned()->nullable();
            $table->foreign('color_id')->references('id')->on('vehicles_colors');

            $table->integer('fuel_id')->unsigned()->nullable();
            $table->foreign('fuel_id')->references('id')->on('vehicles_fuels');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('vehicles');
    }
}

<?php

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

class CreateVehiclesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('vehicles', function (Blueprint $table) {
            $table->string('code')->primary();
            $table->foreign('code')->references('code')->on('items');

            $table->integer('year')->nullable();
            $table->integer('engine_displacement')->nullable();
            $table->string('reg_plate_code')->nullable();
            $table->boolean('is_good_condition')->nullable();

            $table->integer('make_id')->unsigned()->nullable();
            $table->foreign('make_id')->references('id')->on('vehicles_makes');

            $table->integer('model_id')->unsigned()->nullable();
            $table->foreign('model_id')->references('id')->on('vehicles_models');

            $table->integer('color_id')->unsigned()->nullable();
            $table->foreign('color_id')->references('id')->on('vehicles_colors');

            $table->integer('fuel_id')->unsigned()->nullable();
            $table->foreign('fuel_id')->references('id')->on('vehicles_fuels');

            $table->integer('type_id')->unsigned()->nullable();
            $table->foreign('type_id')->references('id')->on('vehicles_types');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('vehicles');
    }
}

Add a new foreign key for the vehicle type


<?php

namespace Palmtree\CanonicalUrlBundle\DependencyInjection\Compiler;

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

class CompilerPass implements CompilerPassInterface
{

    /**
     * @inheritDoc
     */
    public function process(ContainerBuilder $container)
    {
        $bundleConfig = $container->getParameter('palmtree_canonical_url.config');

        $definition = $container->getDefinition('palmtree_canonical_url.url_generator');
        $definition->addArgument($bundleConfig);

        $definition = $container->getDefinition('palmtree_canonical_url.kernel_event_listener');
        $definition->addArgument($bundleConfig);
    }
}

<?php

namespace Palmtree\CanonicalUrlBundle\DependencyInjection\Compiler;

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

class CompilerPass implements CompilerPassInterface
{

    /**
     * @inheritDoc
     */
    public function process(ContainerBuilder $container)
    {
        $bundleConfig = $container->getParameter('palmtree_canonical_url.config');

        $definition = $container->getDefinition('palmtree_canonical_url.url_generator');
        $definition->addArgument($bundleConfig);

        $definition = $container->getDefinition('palmtree_canonical_url.request_listener');
        $definition->addArgument($bundleConfig);

        $definition = $container->getDefinition('palmtree_canonical_url.exception_listener');
        $definition->addArgument($bundleConfig);
    }
}

Fix incorrect service name in compiler pass


<?php

if( is_dir(__DIR__ . '/../../public_html/') ) {
    define('BOLT_WEB_DIR', __DIR__ . '/../../public_html/');
} else {
    define('BOLT_WEB_DIR', __DIR__ . '/../../web/');
}

require_once( __DIR__ . '/../../vendor/bolt/bolt/app/bootstrap.php' );

$app['season'] = '2014-2015';

<?php

if( is_dir(__DIR__ . '/../../public_html/') ) {
    define('BOLT_WEB_DIR', __DIR__ . '/../../public_html/');
} else {
    define('BOLT_WEB_DIR', __DIR__ . '/../../web/');
}

set_include_path(implode(PATH_SEPARATOR, array(
    realpath(__DIR__ . '/../../vendor/zend/gdata/library'),
    get_include_path(),
)));

require_once( __DIR__ . '/../../vendor/bolt/bolt/app/bootstrap.php' );

$app['season'] = '2014-2015';

Fix include path for zend

Fix include path for zend


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends Application
{

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * Homepage for our app
	 */
	public function index()
	{
		// this is the view we want shown
		$this->data['pagebody'] = 'homepage';

		// build the list of authors, to pass on to our view
		$source = $this->quotes->all();
		$authors = array ();
		foreach ($source as $record)
		{
			$authors[] = array ('who' => $record['who'], 'mug' => $record['mug'], 'href' => $record['where']);
		}
		$this->data['authors'] = $authors;

		$this->render();
	}

}

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends Application
{

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * Homepage for our app
	 */
	public function index()
	{
		// this is the view we want shown
		$this->data['pagebody'] = 'homepage';

		// build the list of authors, to pass on to our view
		$source = $this->quotes->all();
		$authors = array ();
		foreach ($source as $record)
		{
			$authors[] = array ('who' => $record['who'], 'mug' => $record['mug'], 'href' => $record['where'],'what'=>$record['what']);
		}
		$this->data['authors'] = $authors;

		$this->render();
	}

}

Add an additional field, what

Add an additional field, what

Adding a what field to the array


<?php

$pdo = new PDO('mysql:host=127.0.0.1;dbname=marjo21mlo', 'root', 'root');

?>

<?php
header('Content-Type: text/html; charset=UTF-8');
$pdo = new PDO('mysql:host=127.0.0.1;dbname=marjo21mlo', 'root', 'root');
$pdo->exec("SET CHARACTER SET utf8");
?>

Add some lines to encode all in UTF8

Add some lines to encode all in UTF8


<?

if( !$shutup ) :

$tags = db::fetch('select tag, count(*) as c from categories_tags inner join categories using(categories_id) where `status` and `list` group by tag order by tag');
//print_r( $tags );
echo '
';
foreach( $tags as $tag ) {
	echo '' . $tag['tag'] . ' ';
}
echo '
';

endif;

<?

if( !$shutup ) :

$tags = db::fetch('select *
from
	(
		select
			(@counter :=@counter + 1)& 1 as x,
			w.*
		FROM
			(SELECT @counter := 0)v,
			(
				select
					tag,
					count(*)as c
				from
					categories_tags
				inner join categories using(categories_id)
				where
					`status`
				and `list`
				group by
					tag
				order by
					c
			)w
	)x
order by
	x, if(x, - c, c), if(x, -CHAR_LENGTH(tag), CHAR_LENGTH(tag))');

//print_r( $tags );
echo '
';
foreach( $tags as $tag ) {
	echo '' . $tag['tag'] . ' ';
}
echo '
';

endif;

Tag cloud improvements from Donat Studios


@extends('layouts.master')

@section('content')

Dashboard

         $user->id, 'secret' => $user->secret()))) }}">Subscribe with iTunes
         $user->id, 'secret' => $user->secret())) }}">Subscribe with RSS

Articles are automatically fetched, convert to podcast episodes and added to your feed every hour.

Once you've listened to them, you'll need to manually mark them as read in Pocket.

    @if (count($items) > 0)

Articles

These articles are currently in your feed.

        @include('partials.items', array('items' => $items))

Update

    @else

Get pocket articles

    @endif

@endsection

@extends('layouts.master')

@section('content')

Dashboard

         $user->id, 'secret' => $user->secret()))) }}">Subscribe with iTunes
         $user->id, 'secret' => $user->secret())) }}">Subscribe with RSS

Most recent 20 unread articles are automatically fetched, convert to podcast episodes and added to your feed every hour.

Once you've listened to them, you'll need to manually mark them as read in Pocket.

    @if (count($items) > 0)

Articles

These articles are currently in your feed.

        @include('partials.items', array('items' => $items))

Update

    @else

Get pocket articles

    @endif

@endsection

Update dashboard description to show that only the most recent articles are synced.


<?php

/**
* ownCloud - bookmarks plugin
*
* @author Arthur Schiwon
* @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library 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 Lesser General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

//no apps or filesystem
$RUNTIME_NOSETUPFS=true;

// Check if we are a user
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('bookmarks');

require_once(OC::$APPSROOT . '/apps/bookmarks/bookmarksHelper.php');
$id = addBookmark($_GET['url'], $_GET['title'], $_GET['tags']);
OCP\JSON::success(array('data' => $id));

<?php

/**
* ownCloud - bookmarks plugin
*
* @author Arthur Schiwon
* @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library 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 Lesser General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

//no apps or filesystem
$RUNTIME_NOSETUPFS=true;

// Check if we are a user
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('bookmarks');

require_once(OC_App::getAppPath('bookmarks').'/bookmarksHelper.php');
$id = addBookmark($_GET['url'], $_GET['title'], $_GET['tags']);
OCP\JSON::success(array('data' => $id));

Correct remote and public, and last occurence of OC::


<?php
/**
 * Class made by pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Validation;

use PFBC\Validation;

class Name extends Validation
{
    public function __construct()
    {
        parent::__construct();

        $this->message = t("Error: %element% must be a valid name. The name doesn't seem to be correct.");
    }

    public function isValid($sValue)
    {
        return $this->isNotApplicable($sValue) || $this->oValidate->name($sValue);
    }
}

<?php
/**
 * Class made by pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Validation;

use PFBC\Validation;

class Name extends Validation
{
    public function __construct()
    {
        parent::__construct();

        $this->message = t("%element% must be a valid name.");
    }

    public function isValid($sValue): bool
    {
        return $this->isNotApplicable($sValue) || $this->oValidate->name($sValue);
    }
}

Update error message (make it shorter)

Update error message (make it shorter)

* Update the error message (to make it shorter)
* Specify `bool` return type for `isValid` method's signature


<?php

/*
 * Core functions.
 *
 * Don't forget to add own ones.
 */

// `encrypt`
//
// Encrypts `$str` in rot13.
function encrypt($str) {
  echo str_rot13($str);
}

// `decrypt`
//
// Decrypts `$str` from rot13.
function decrypt($str) {
  echo str_rot13(str_rot13($str));
}

// `cfile`
//
// Checks for current file.
function cfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `fcount`
//
// Counts number of files in a directory.
function fcount($dir) {
  $i = 0;
  if ($handle = opendir($dir)) {
    while (($file = readdir($handle)) !== false) {
      if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
        $i++;
      }
    }
  }
}

// `feedparse`
//
// Parses RSS feed easily.
function feedparse($url) {
  $feed = @fopen("$url", 'r');
  if ($feed) {
    $data = '';
    while (!feof($feed)) {
      $data .= fread($feed, 8192);
    }
  }
  fclose($feed);
  echo $data;
}

?>

<?php

/*
 * Core functions.
 *
 * Don't forget to add own ones.
 */

// `encrypt`
//
// Encrypts `$str` in rot13.
function encrypt($str) {
  echo str_rot13($str);
}

// `decrypt`
//
// Decrypts `$str` from rot13.
function decrypt($str) {
  echo str_rot13(str_rot13($str));
}

// `cfile`
//
// Checks for current file. Change the class name if necessary.
function cfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `fcount`
//
// Counts number of files in a directory.
function fcount($dir) {
  $i = 0;
  if ($handle = opendir($dir)) {
    while (($file = readdir($handle)) !== false) {
      if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
        $i++;
      }
    }
  }
}

// `feedparse`
//
// Parses RSS feed easily.
function feedparse($url) {
  $feed = @fopen("$url", 'r');
  if ($feed) {
    $data = '';
    while (!feof($feed)) {
      $data .= fread($feed, 8192);
    }
  }
  fclose($feed);
  echo $data;
}

?>

Add the class name note

Add the class name note


<?php

/*
 * Core functions.
 *
 * Don't forget to add own ones.
 */

// `encrypt`
//
// Encrypts `$str` in rot13.
function encrypt($str) {
  echo str_rot13($str);
}

// `decrypt`
//
// Decrypts `$str` in rot13. Gives `$str` as output.
function decrypt($str) {
  echo str_rot13(str_rot13($str));
}

// `cfile`
//
// Checks for current file. Change the target class name if necessary.
function cfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `fcount`
//
// Counts number of files in a directory.
function fcount($dir) {
  $i = 0;
  if ($handle = opendir($dir)) {
    while (($file = readdir($handle)) !== false) {
      if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
        $i++;
      }
    }
  }
}

// `feedparse`
//
// Parses RSS or Atom feeds.
function feedparse($url) {
  $feed = @fopen("$url", 'r');
  if ($feed) {
    $data = '';
    while (!feof($feed)) {
      $data .= fread($feed, 8192);
    }
  }
  fclose($feed);
  echo $data;
}

?>

<?php

/*
 * Core functions.
 *
 * Don't forget to add own ones.
 */

// `encrypt`
//
// Encrypts `$str` in rot13.
function encrypt($str) {
  echo str_rot13($str);
}

// `decrypt`
//
// Decrypts `$str` in rot13. Gives `$str` as output.
function decrypt($str) {
  echo str_rot13(str_rot13($str));
}

// `cfile`
//
// Checks for current file. Change the target class name if necessary.
function cfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `fcount`
//
// Counts number of files in a directory.
function fcount($dir) {
  $i = 0;
  if ($handle = opendir($dir)) {
    while (($file = readdir($handle)) !== false) {
      if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
        $i++;
      }
    }
  }
}

// `feedparse`
//
// Parses RSS or Atom feeds.
function feedparse($url) {
  $feed = fopen("$url", 'r');
  $data = stream_get_contents($feed);
  fclose($feed);
  echo $data;
}

?>

Update feedparse() for PHP 5

Update feedparse() for PHP 5


<?php
namespace common\commands;

use Yii;
use common\models\Company;
use yii\helpers\Url;

class CompanyDropdown
{
    public function get(){
        $companyAccess = new CompanyAccess();

        $companies = Company::find()
            ->select(['id','name'])
            ->where( $companyAccess->getQueryConditions() )
            ->all();

        $companyDropdown = [];

        foreach($companies as $company){

            $url_parts = explode("?", Url::canonical());
            $url_params = "";
            foreach($_GET as $key => $param){
                if($key=="id") continue;

                $url_params .= "$key=$param&";
            }
            $url = $url_parts[0]."?".$url_params."id={$company->id}";

            $companyDropdown[] = [
                'label'=>$company->name,
                'url'=> $url,
            ];
        }

        return $companyDropdown;
    }
}

<?php
namespace common\commands;

use Yii;
use common\models\Company;
use yii\helpers\Url;

class CompanyDropdown
{
    public function get(){
        $companyAccess = new CompanyAccess();

        $companies = Company::find()
            ->select(['id','name'])
            ->where( $companyAccess->getQueryConditions() )
            ->all();

        $companyDropdown = [];

        foreach($companies as $company){

            $url_parts = explode("?", Url::canonical());
            $url_params = "";
            foreach($_GET as $key => $param){
                if($key=="company") continue;

                $url_params .= "$key=$param&";
            }
            $url = $url_parts[0]."?".$url_params."company={$company->id}";

            $companyDropdown[] = [
                'label'=>$company->name,
                'url'=> $url,
            ];
        }

        return $companyDropdown;
    }
}

Modify the stripped key name

Modify the stripped key name


<?php

namespace Yeah\Fw\Application;

/**
 * Use for storing runtime configuration
 *
 * @author David Cavar
 */
class Config {

    private $config = array();

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

    public function __get($name) {
        if(!isset($this->config[$name])) {
            return false;
        }
        return $this->config[$name];
    }

    public function __set($name, $value) {
        if(is_array($value)) {
            $config = new Config($value);
            $this->config[$name] = $config;
            return;
        }
        $this->config[$name] = $value;
    }

    public function importArray($array) {
        foreach($array as $key => $value) {
            $this->$key = $value;
        }
    }

    public function toArray() {
        return $this->config;
    }

}

<?php

namespace Yeah\Fw\Application;

/**
 * Use for storing runtime configuration
 *
 * @author David Cavar
 */
class Config {

    private $config = array();

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

    public function __get($name) {
        if(!isset($this->config[$name])) {
            return false;
        }
        return $this->config[$name];
    }

    public function __set($name, $value) {
        if(is_array($value)) {
            $config = new Config($value);
            $this->config[$name] = $config;
            return;
        }
        $this->config[$name] = $value;
    }

    public function importArray($array) {
        if($array == null) {
            return;
        }
        foreach($array as $key => $value) {
            $this->$key = $value;
        }
    }

    public function toArray() {
        return $this->config;
    }

}

Check for validity of config array

Check for validity of config array


Add FRSS 1.2-dev in the version list

Add FRSS 1.2-dev in the version list

See https://github.com/FreshRSS/FreshRSS/issues/738#issuecomment-74739891


<?php

namespace App\Providers;

use App\Tag;
use App\Note;
use Validator;
use Illuminate\Http\Request;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Validate photos for a maximum filesize
        Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
            if ($value[0] !== null) {
                foreach ($value as $file) {
                    if ($file->getSize() > 5000000) {
                        return false;
                    }
                }
            }

            return true;
        });

        //Add tags for notes
        Note::created(function ($note) {
            $tagsToAdd = [];
            preg_match_all('/#([^\s<>]+)\b/', $note->note, $tags);
            foreach ($tags[1] as $tag) {
                $tag = Tag::normalizeTag($tag);
            }
            $tags = array_unique($tags[1]);
            foreach ($tags as $tag) {
                $tag = Tag::firstOrCreate(['tag' => $tag]);
                $tagsToAdd[] = $tag->id;
            }
            if (count($tagsToAdd) > 0) {
                $note->tags()->attach($tagsToAdd);
            }
        });

        // Request AS macro
        Request::macro('wantsActivityStream', function () {
            return str_contains(mb_strtolower($this->header('Accept')), 'application/activity+json');
        });

        // configure Intervention/Image
        $this->app->bind('Intervention\Image\ImageManager', function () {
            return new \Intervention\Image\ImageManager(['driver' => config('image.driver')]);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

<?php

namespace App\Providers;

use App\Note;
use Illuminate\Http\Request;
use App\Observers\NoteObserver;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Note::observe(NoteObserver::class);

        // Request AS macro
        Request::macro('wantsActivityStream', function () {
            return str_contains(mb_strtolower($this->header('Accept')), 'application/activity+json');
        });

        // configure Intervention/Image
        $this->app->bind('Intervention\Image\ImageManager', function () {
            return new \Intervention\Image\ImageManager(['driver' => config('image.driver')]);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

Remove unused validation rule, and remove note tagging code, its now in the references observer


<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Bootstrap;

use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;

/**
 * @internal
 */
final class LoadConfiguration implements BoostrapperContract
{
    /**
     * {@inheritdoc}
     */
    public function bootstrap(Application $app): void
    {
        $app->make(BaseLoadConfiguration::class)
            ->bootstrap($app);

        $app->detectEnvironment(
            function () use ($app) {
                return $app['config']->get('app.production', true) ? 'production' : 'development';
            }
        );

        /*
         * When artisan starts, sets the application name and the application version.
         */
        Artisan::starting(
            function ($artisan) use ($app) {
                $artisan->setName($app['config']->get('app.name', 'Laravel Zero'));
                $artisan->setVersion($app->version());
            }
        );
    }
}

<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Bootstrap;

use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;

/**
 * @internal
 */
final class LoadConfiguration implements BoostrapperContract
{
    /**
     * {@inheritdoc}
     */
    public function bootstrap(Application $app): void
    {
        $app->make(BaseLoadConfiguration::class)
            ->bootstrap($app);

        $app->detectEnvironment(
            function () use ($app) {
                return $app['config']->get('app.env', 'production');
            }
        );

        /*
         * When artisan starts, sets the application name and the application version.
         */
        Artisan::starting(
            function ($artisan) use ($app) {
                $artisan->setName($app['config']->get('app.name', 'Laravel Zero'));
                $artisan->setVersion($app->version());
            }
        );
    }
}

Update to use 'app.env' for environment

Update to use 'app.env' for environment


<?php

namespace Bap\Bundle\IssueBundle\Entity\Repository;

use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityRepository;

/**
 * Class IssueRepository
 * @package Bap\Bundle\IssueBundle\Entity\Repository
 */
class IssueRepository extends EntityRepository
{
    public function getIssuesByStatus()
    {
        $result = $this->getFullEntityList();

    }

    public function getFullEntityList()
    {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();

        $qb->select(['COUNT(issue.id) as cnt', 'workflowStep.label'])
            ->from('OroWorkflowBundle:WorkflowStep', 'workflowStep')
            ->leftJoin('workflowStep.definition', 'definition')
            ->leftJoin(
                'BapIssueBundle:Issue',
                'issue',
                'WITH',
                'issue.workflowStep = workflowStep AND definition.name = :d_name'
            )
            ->andWhere('')
            ->groupBy('workflowStep.label')
            ->orderBy('cnt')
            ->setParameter('d_name', 'issue_flow');

        return $qb
            ->getQuery()
            ->getResult(
                AbstractQuery::HYDRATE_SIMPLEOBJECT
            );
    }
}

<?php

namespace Bap\Bundle\IssueBundle\Entity\Repository;

use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityRepository;

/**
 * Class IssueRepository
 * @package Bap\Bundle\IssueBundle\Entity\Repository
 */
class IssueRepository extends EntityRepository
{
    public function getIssuesByStatus()
    {
        $items  = $this->getCountIssuesByLabel();
        $result = [];

        while($item = array_pop($items)) {
            $key   = $item['label'];
            $count = $item['count_issues'];

            $result[$key] = [
                'count' => $count
            ];
        }

        return $result;
    }

    public function getCountIssuesByLabel()
    {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();

        $qb->select(['COUNT(issue.id) as count_issues', 'workflowStep.label'])
            ->from('OroWorkflowBundle:WorkflowStep', 'workflowStep')
            ->leftJoin('workflowStep.definition', 'definition')
            ->leftJoin(
                'BapIssueBundle:Issue',
                'issue',
                'WITH',
                'issue.workflowStep = workflowStep AND definition.name = :d_name'
            )
            ->andWhere('')
            ->groupBy('workflowStep.label')
            ->orderBy('cnt')
            ->setParameter('d_name', 'issue_flow');

        return $qb
            ->getQuery()
            ->getResult(
                AbstractQuery::HYDRATE_SIMPLEOBJECT
            );
    }
}

Add method to calculate count issues by label


<?php

namespace Nwidart\Modules\Traits;

trait CanClearModulesCache
{
    /**
     * Clear the modules cache if it is enabled
     */
    public function clearCache()
    {
        if (config('modules.cache.enabled') === true) {
            app('cache')->forget('laravel-modules');
        }
    }
}

<?php

namespace Nwidart\Modules\Traits;

trait CanClearModulesCache
{
    /**
     * Clear the modules cache if it is enabled
     */
    public function clearCache()
    {
        if (config('modules.cache.enabled') === true) {
            app('cache')->forget(config('modules.cache.key'));
        }
    }
}

Use the key configured to clear

Use the key configured to clear


<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class PdoAuthenticator implements AuthenticatorInterface
{
    private $options;

    public function __construct(array $options = array())
    {

        /* Default options. */
        $this->options = array(
            "table" => "users",
            "user" => "user",
            "hash" => "hash"
        );

        if ($options) {
            $this->options = array_merge($this->options, $options);
        }
    }

    public function authenticate($user, $pass)
    {
        $statement = $this->options["pdo"]->prepare(
            "SELECT *
             FROM {$this->options['table']}
             WHERE {$this->options['user']} = ?
             LIMIT 1"
        );

        $statement->execute(array($user));

        if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
            return password_verify($pass, $user[$this->options["hash"]]);
        }

        return false;
    }
}

<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class PdoAuthenticator implements AuthenticatorInterface
{
    private $options;

    public function __construct(array $options = array())
    {

        /* Default options. */
        $this->options = array(
            "table" => "users",
            "user" => "user",
            "hash" => "hash"
        );

        if ($options) {
            $this->options = array_merge($this->options, $options);
        }
    }

    public function authenticate($user, $pass)
    {
         if($this->options["pdo"]->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlsrv"){

         $statement = $this->options["pdo"]->prepare(
                "SELECT top 1 *
                 FROM {$this->options['table']}
                 WHERE {$this->options['user']} = ?"
             );

        }else{
            $statement = $this->options["pdo"]->prepare(
                 "SELECT *
                  FROM {$this->options['table']}
                  WHERE {$this->options['user']} = ?
                  LIMIT 1"
        );

    }

        $statement->execute(array($user));

        if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
            return password_verify($pass, $user[$this->options["hash"]]);
        }

        return false;
    }
}

Add conditional PDO statement for sqlsrv

Add conditional check for PDO driver and added an edited PDO statement to address limit issue with sqlsrv PDO driver .


@extends('layouts.default')

@section('title')
@parent
Edit {{ $page->title }}
@stop

@section('content')

<div class="well">
    <?php
    $form = array('url' => URL::route('pages.update', array('pages' => $page->slug)),
        'method' => 'PUT',
        'button' => 'Save Page',
        'defaults' => array(
            'title' => $page->title,
            'icon' => $page->icon,
            'body' => $page->body,
            'show_title' => ($page->show_title == true),
            'show_nav' => ($page->show_nav == true),
            ));
    ?>
    @include('pages.form')
</div>

@stop

@section('css')

{{ Basset::show('switches.css') }}
{{ Basset::show('editor.css') }}

@stop

@section('js')

{{ Basset::show('switches.js') }}
{{ Basset::show('editor.js') }}

@stop

@extends('layouts.default')

@section('title')
@parent
Edit {{ $page->title }}
@stop

@section('content')

<div class="well">
    <?php
    $form = array('url' => URL::route('pages.update', array('pages' => $page->slug)),
        'method' => 'PATCH',
        'button' => 'Save Page',
        'defaults' => array(
            'title' => $page->title,
            'icon' => $page->icon,
            'body' => $page->body,
            'show_title' => ($page->show_title == true),
            'show_nav' => ($page->show_nav == true),
            ));
    ?>
    @include('pages.form')
</div>

@stop

@section('css')

{{ Basset::show('switches.css') }}
{{ Basset::show('editor.css') }}

@stop

@section('js')

{{ Basset::show('switches.js') }}
{{ Basset::show('editor.js') }}

@stop

Use PATCH to update a page

Use PATCH to update a page


<?php
/**
 * Interface Google\Site_Kit\Core\Modules\Module_With_Settings
 *
 * @package   Google\Site_Kit\Core\Modules
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Modules;

use Google\Site_Kit\Core\Storage\Setting;

interface Module_With_Setting {

	/**
	 * Gets the module's setting instance.
	 *
	 * @since n.e.x.t
	 *
	 * @return Setting The Setting instance for the current module.
	 */
	public function get_setting();
}

<?php
/**
 * Interface Google\Site_Kit\Core\Modules\Module_With_Settings
 *
 * @package   Google\Site_Kit\Core\Modules
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Modules;

use Google\Site_Kit\Core\Storage\Setting;

interface Module_With_Setting {

	/**
	 * Gets the module's Setting instance.
	 *
	 * @since n.e.x.t
	 *
	 * @return Setting The Setting instance for the current module.
	 */
	public function get_setting();
}

Update casing in docblock in reference to class name.


<?php

namespace Bauhaus;

use Bauhaus\Container\ItemNotFoundException;

class Container implements ContainerInterface
{
    private $items = [];

    public function __construct(array $items = [])
    {
        $this->items = $items;
    }

    final public function has($label)
    {
        return array_key_exists($label, $this->items);
    }

    public function get($label)
    {
        if (false === $this->has($label)) {
            throw new ItemNotFoundException($label);
        }

        return $this->items[$label];
    }

    final public function __get($label)
    {
        return $this->get($label);
    }

    public function all(): array
    {
        return $this->items;
    }

    final public function getIterator()
    {
        return new \ArrayIterator($this->items);
    }
}

<?php

namespace Bauhaus;

use Bauhaus\Container\ItemNotFoundException;

class Container implements ContainerInterface
{
    private $items = [];

    public function __construct(array $items = [])
    {
        $this->items = $items;
    }

    final public function has($label)
    {
        return array_key_exists($label, $this->items);
    }

    public function get($label)
    {
        if (false === $this->has($label)) {
            throw new ItemNotFoundException($label);
        }

        return $this->items[$label];
    }

    final public function __get($label)
    {
        return $this->get($label);
    }

    public function all(): array
    {
        return $this->items;
    }

    final public function getIterator()
    {
        return new \ArrayIterator($this->all());
    }
}

Fix potencial bug to behavior of child classes


<?php
/**
 * Helper functions to work with the Twig template engine.
 */

namespace Siler\Twig;

use Siler\Container;

/**
 * Initialze the Twig environment.
 *
 * @param string $templatesPath      Path to templates
 * @param string $templatesCachePath Path to templates cache
 * @param bool   $debug              Should TwigEnv allow debugging
 *
 * @return \Twig_Environment
 */
function init($templatesPath, $templatesCachePath = null, $debug = null)
{
    if (is_null($templatesCachePath)) {
        $templatesCachePath = false;
    }

    if (is_null($debug)) {
        $debug = false;
    }

    $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [
        'debug' => $debug,
        'cache' => $templatesCachePath,
    ]);

    Container\set('twig', $twig);

    return $twig;
}

/**
 * Renders the given template within the given data.
 *
 * @param string $name The template name in the templates path
 * @param array  $data The array of data to used within the template
 *
 * @throws RuntimeException if Twig isn't initialized
 *
 * @return string
 */
function render($name, $data = [])
{
    $twig = Container\get('twig');

    if (is_null($twig)) {
        throw new \RuntimeException('Twig should be initialized first');
    }

    return $twig->render($name, $data);
}

<?php
/**
 * Helper functions to work with the Twig template engine.
 */

namespace Siler\Twig;

use Siler\Container;

/**
 * Initialize the Twig environment.
 *
 * @param string $templatesPath      Path to templates
 * @param string $templatesCachePath Path to templates cache
 * @param bool   $debug              Should TwigEnv allow debugging
 *
 * @return \Twig_Environment
 */
function init($templatesPath, $templatesCachePath = null, $debug = null)
{
    if (is_null($templatesCachePath)) {
        $templatesCachePath = false;
    }

    if (is_null($debug)) {
        $debug = false;
    }

    $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [
        'debug' => $debug,
        'cache' => $templatesCachePath,
    ]);

    Container\set('twig', $twig);

    return $twig;
}

/**
 * Renders the given template within the given data.
 *
 * @param string $name The template name in the templates path
 * @param array  $data The array of data to used within the template
 *
 * @throws \RuntimeException if Twig isn't initialized
 *
 * @return string
 */
function render($name, $data = [])
{
    $twig = Container\get('twig');

    if (is_null($twig)) {
        throw new \RuntimeException('Twig should be initialized first');
    }

    return $twig->render($name, $data);
}

Fix typo and namespace root

Fix typo and namespace root


<?php

return [
    'es_AR.utf8' => 'Español',
    # 'en_US.utf8' => 'English',
];

<?php

return [
    'es_ES.utf8' => 'Español',
    'es_AR.utf8' => 'Español Argentina',
    # 'en_US.utf8' => 'English',
];

Add es_ES support to lang switcher menu

Add es_ES support to lang switcher menu


<?php

namespace Ibericode\Vat\Clients;

use Ibericode\Vat\Exceptions\Exception;

interface Client
{

    /**
     * This method should return an associative array in the following format:
     *
     * [
     *  'NL' => [
     *      new Period(DateTime $effectiveFrom, array $rates)
     *    ]
     * ]
     *
     * @see https://github.com/ibericode/vat-rates*
     * @return array
     * @throws ClientException
     */
    public function fetch() : array;
}

<?php

namespace Ibericode\Vat\Clients;

interface Client
{

    /**
     * This method should return an associative array in the following format:
     *
     * [
     *  'NL' => [
     *      new Period(DateTime $effectiveFrom, array $rates)
     *    ]
     * ]
     *
     * @see https://github.com/ibericode/vat-rates*
     * @return array
     * @throws ClientException
     */
    public function fetch() : array;
}

Remove unused and wrong namespace Exception import

The Ibericode\Vat\Exceptions\Exception is an unused class in this interface. In addition, it is also referencing the class in the wrong namespace, as its FQCN is Ibericode\Vat\Exception.


<?php

namespace Outlandish\Wpackagist\Package;

class Plugin extends AbstractPackage
{
    public function getVendorName()
    {
        return 'wpackagist-plugin';
    }

    public function getComposerType()
    {
        return 'wordpress-plugin';
    }

    public static function getSvnBaseUrl()
    {
        return 'https://plugins.svn.wordpress.org/';
    }

    public function getHomepageUrl()
    {
        return "https://wordpress.org/plugins/".$this->getName().'/';
    }

    public function getDownloadUrl($version)
    {
        $filename = $this->versions[$version] == 'trunk' ? $this->getName() : $this->getName().'.'.$version;

        return "https://downloads.wordpress.org/plugin/$filename.zip";
    }
}

<?php

namespace Outlandish\Wpackagist\Package;

class Plugin extends AbstractPackage
{
    public function getVendorName()
    {
        return 'wpackagist-plugin';
    }

    public function getComposerType()
    {
        return 'wordpress-plugin';
    }

    public static function getSvnBaseUrl()
    {
        return 'https://plugins.svn.wordpress.org/';
    }

    public function getHomepageUrl()
    {
        return "https://wordpress.org/plugins/".$this->getName().'/';
    }

    public function getDownloadUrl($version)
    {
        $isTrunk = $this->versions[$version] === 'trunk';

        //Assemble file name and append ?timestamp= variable to the trunk version to avoid Composer cache when plugin/theme author only updates the trunk
        $filename = ($isTrunk ? $this->getName() : $this->getName().'.'.$version) . '.zip' . ($isTrunk ? '?timestamp=' . urlencode($this->last_committed->format('U')) : '');

        return "https://downloads.wordpress.org/plugin/{$filename}";
    }
}

Append timestamp to dev-trunk url

Append timestamp to dev-trunk url


<?php

/**
 * This class represents objects dispensed by the Email model
 *
 * @package  Nails\Email\Resource
 * @category resource
 */

namespace Nails\Email\Resource;

use Nails\Common\Resource;

/**
 * Class Email
 *
 * @package Nails\Email\Resource
 */
class Email extends Resource
{
    /** @var int */
    public $id;

    /** @var string */
    public $ref;

    /** @var int|null */
    public $user_id;

    /** @var string|null */
    public $user_email;

    /** @var \Nails\Common\Resource\DateTime */
    public $sent;

    /** @var string */
    public $status;

    /** @var string */
    public $type;

    /** @var string|null */
    public $email_vars;

    /** @var string|null */
    public $internal_ref;

    /** @var int */
    public $read_count;

    /** @var int */
    public $link_click_count;

    /** @var string|null */
    public $fail_reason;
}

<?php

/**
 * This class represents objects dispensed by the Email model
 *
 * @package  Nails\Email\Resource
 * @category resource
 */

namespace Nails\Email\Resource;

use Nails\Common\Resource;

/**
 * Class Email
 *
 * @package Nails\Email\Resource
 */
class Email extends Resource
{
    /** @var int */
    public $id;

    /** @var string */
    public $ref;

    /** @var int|null */
    public $user_id;

    /** @var string|null */
    public $user_email;

    /** @var \Nails\Common\Resource\DateTime */
    public $queued;

    /** @var int|null */
    public $queue_priority;

    /** @var \Nails\Common\Resource\DateTime */
    public $sent;

    /** @var string */
    public $status;

    /** @var string */
    public $type;

    /** @var string|null */
    public $email_vars;

    /** @var string|null */
    public $internal_ref;

    /** @var int */
    public $read_count;

    /** @var int */
    public $link_click_count;

    /** @var string|null */
    public $fail_reason;
}

Add missing properties to email resource


<?php namespace Adviser\Utilities;

class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase
{

    /**
     * @test
     */
    public function it_runs_a_terminal_command()
    {
        $output = (new CommandRunnerUtility())->run(getcwd()."/testing/utility-command.sh");

        $this->assertInternalType("array", $output);

        $this->assertEquals($output["stdout"], "from stdout".PHP_EOL);
        $this->assertEquals($output["stderr"], "from stderr".PHP_EOL);
    }

    /**
     * @test
     */
    public function it_throws_an_exception_if_something_goes_wrong()
    {
        $this->setExpectedException("RuntimeException");

        // Redefine "proc_open" in the current namespace for the purpose of testing.
        function proc_open()
        {
            return false;
        }

        (new CommandRunnerUtility())->run("some command");
    }
}

<?php namespace Adviser\Utilities;

class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase
{

    /**
     * @test
     */
    public function it_runs_a_terminal_command()
    {
        $output = (new CommandRunnerUtility())->run(ADVISER_DIR."/testing/utility-command.sh");

        $this->assertInternalType("array", $output);

        $this->assertEquals($output["stdout"], "from stdout".PHP_EOL);
        $this->assertEquals($output["stderr"], "from stderr".PHP_EOL);
    }

    /**
     * @test
     */
    public function it_throws_an_exception_if_something_goes_wrong()
    {
        $this->setExpectedException("RuntimeException");

        // Redefine "proc_open" in the current namespace for the purpose of testing.
        function proc_open()
        {
            return false;
        }

        (new CommandRunnerUtility())->run("some command");
    }
}

Use ADVISER_DIR instead of getcwd().

Use ADVISER_DIR instead of getcwd().


<?php

/*
 * This file is part of the XiideaEasyAuditBundle package.
 *
 * (c) Xiidea <http://www.xiidea.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Xiidea\EasyAuditBundle\Traits;

trait EntityHydrationMethod
{
    public function fromArray($data = array())
    {
        foreach ($data as $property => $value) {
            $method = sprintf('set%s', ucwords($property));
            $this->$method($value);
        }

        return $this;
    }
}

<?php

/*
 * This file is part of the XiideaEasyAuditBundle package.
 *
 * (c) Xiidea <http://www.xiidea.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Xiidea\EasyAuditBundle\Traits;

use Symfony\Component\PropertyAccess\PropertyAccess;

trait EntityHydrationMethod
{
    final public function fromArray($data = array())
    {
        $accessor = PropertyAccess::createPropertyAccessor();

        foreach ($data as $property => $value) {
            $accessor->setValue($this, $property, $value);
        }

        return $this;
    }
}

Refactor fromArray method to use property accessor


<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Support;

class ExtensionsServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('flarum.extensions', 'Flarum\Support\ExtensionManager');

        $config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled');
        $extensions = json_decode($config, true);

        $events = $this->app->make('events');

        foreach ($extensions as $extension) {
            if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php')) {
                $provider = require $file;

                if (is_string($provider)) {
                    $this->app->register($provider)->listen($events);
                } elseif (is_callable($provider)) {
                    $provider($events);
                }
            }
        }
    }
}

<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Support;

class ExtensionsServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('flarum.extensions', 'Flarum\Support\ExtensionManager');

        $config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled');
        $extensions = json_decode($config, true);

        foreach ($extensions as $extension) {
            if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php')) {
                $bootstrapper = require $file;

                $bootstrapper($this->app);
            }
        }
    }
}

Remove ability for extensions to register a service provider

The concept of returning a bootstrapper function is simpler and the use of service providers had no advantage over it.


<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width" />
	<title>@lang('gorilla.app_name')</title>

	{{ HTML::style('static/css/normalize.css') }}
	{{ HTML::style('static/css/foundation.min.css') }}
	{{ HTML::style('static/css/admin.css') }}

	{{ HTML::script('static/js/modernizr.min.js') }}

@lang('gorilla.app_name')

			@yield('content')

	{{ HTML::script('static/js/jquery.min.js') }}
	{{ HTML::script('static/js/plugins/foundation/foundation.min.js') }}
	{{ HTML::script('static/js/plugins/placeholder/jquery.placeholder.min.js') }}
	{{ HTML::script('static/js/admin.js') }}

	@yield('bottom_scripts')

<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width" />
	<title>@lang('gorilla.app_name')</title>

	{{ HTML::style('static/css/normalize.css') }}
	{{ HTML::style('static/css/plugins/foundation/foundation.min.css') }}
	{{ HTML::style('static/css/admin.css') }}

	{{ HTML::script('static/js/modernizr.min.js') }}

@lang('gorilla.app_name')

			@yield('content')

	{{ HTML::script('static/js/jquery.min.js') }}
	{{ HTML::script('static/js/plugins/foundation/foundation.min.js') }}
	{{ HTML::script('static/js/plugins/placeholder/jquery.placeholder.min.js') }}
	{{ HTML::script('static/js/admin.js') }}

	@yield('bottom_scripts')

Fix inclusione css foundation dopo lo spostamento


<?php
namespace Omnipay\Skrill\Message;

use Omnipay\Tests\TestCase;

class AuthorizeTransferRequestTest extends TestCase
{
    /**
     * @var AuthorizeTransferRequest
     */
    private $request;

    public function setUp()
    {
        parent::setUp();

        $this->request = new AuthorizeTransferRequest($this->getHttpClient(), $this->getHttpRequest());
    }

    public function testGetData()
    {
        $expectedData = array(
            'email'         => 'test@php.unit',
            'password'      => 'password',
            'amount'        => '12.34',
            'currency'      => 'EUR',
            'subject'       => 'subject',
            'note'          => 'note',
            'customerEmail' => 'customer@php.unit',
            'transactionId' => 'transaction_id',
        );
        $this->request->initialize($expectedData);

        $data = $this->request->getData();

        $this->assertSame($expectedData['amount'], $data['amount']);
        $this->assertSame($expectedData['currency'], $data['currency']);
        $this->assertSame($expectedData['subject'], $data['subject']);
        $this->assertSame($expectedData['note'], $data['note']);
        $this->assertSame($expectedData['customerEmail'], $data['bnf_email']);
        $this->assertSame($expectedData['transactionId'], $data['frn_trn_id']);
    }
}

<?php
namespace Omnipay\Skrill\Message;

use Omnipay\Tests\TestCase;

class AuthorizeTransferRequestTest extends TestCase
{
    /**
     * @var AuthorizeTransferRequest
     */
    private $request;

    public function setUp()
    {
        parent::setUp();

        $this->request = new AuthorizeTransferRequest($this->getHttpClient(), $this->getHttpRequest());
    }

    public function testGetData()
    {
        $expectedData = array(
            'email'         => 'test@php.unit',
            'password'      => 'password',
            'amount'        => '12.34',
            'currency'      => 'EUR',
            'subject'       => 'subject',
            'note'          => 'note',
            'customerEmail' => 'customer@php.unit',
            'transactionId' => 'transaction_id',
        );
        $this->request->initialize($expectedData);

        $data = $this->request->getData();

        $this->assertSame('prepare', $data['action']);
        $this->assertSame($expectedData['email'], $data['email']);
        $this->assertSame($expectedData['password'], $data['password']);
        $this->assertSame($expectedData['amount'], $data['amount']);
        $this->assertSame($expectedData['currency'], $data['currency']);
        $this->assertSame($expectedData['subject'], $data['subject']);
        $this->assertSame($expectedData['note'], $data['note']);
        $this->assertSame($expectedData['customerEmail'], $data['bnf_email']);
        $this->assertSame($expectedData['transactionId'], $data['frn_trn_id']);
    }
}

Add missing assertions on authorizeTransfer test


<?php
use CodeGen\Expr\CallExpr;
use CodeGen\Testing\CodeGenTestCase;
use CodeGen\Statement\Statement;

class CallExprTest extends CodeGenTestCase
{
    public function testSimpleMethodCall()
    {
        $call = new CallExpr('$foo','->','bar');
        $statement = new Statement($call);
        $this->assertCodeEquals('$foo->bar();', $statement);
    }

    public function testFunctionCall()
    {
        $call = new CallExpr(null,null,'spl_autoload_register');
        $statement = new Statement($call);
        $this->assertCodeEquals('spl_autoload_register();', $statement);
    }
}

<?php
use CodeGen\Expr\CallExpr;
use CodeGen\Testing\CodeGenTestCase;
use CodeGen\Statement\Statement;

class CallExprTest extends CodeGenTestCase
{
    public function testSimpleMethodCall()
    {
        $call = new CallExpr('$foo','->','bar');
        $statement = new Statement($call);
        $this->assertCodeEquals('$foo->bar();', $statement);
    }

    public function testStaticMethodCall()
    {
        $call = new CallExpr('Some','::','bar');
        $statement = new Statement($call);
        $this->assertCodeEquals('Some::bar();', $statement);
    }

    public function testFunctionCall()
    {
        $call = new CallExpr(null,null,'spl_autoload_register');
        $statement = new Statement($call);
        $this->assertCodeEquals('spl_autoload_register();', $statement);
    }
}

Add static method call generator test

Add static method call generator test


<?php

namespace Weidner\Goutte;

use Goutte\Client as GoutteClient;
use GuzzleHttp\Client as GuzzleClient;

class GoutteServiceProviderTest extends TestCase
{
    /**
     * @test
     */
    public function has_registered_services()
    {
        $this->assertTrue($this->app->bound('goutte'));
        $this->assertTrue($this->app->bound('goutte.client'));
    }

    /**
     * @test
     */
    public function has_registered_aliases()
    {
        $this->assertTrue($this->app->isAlias(GoutteClient::class));
        $this->assertEquals('goutte', $this->app->getAlias(GoutteClient::class));

        $this->assertTrue($this->app->isAlias(GuzzleClient::class));
        $this->assertEquals('goutte.client', $this->app->getAlias(GuzzleClient::class));
    }

    /**
     * @test
     */
    public function has_registered_package_config()
    {
        $config = $this->app->make('config');

        $this->assertEquals($config->get('goutte.client'), [
            'allow_redirects' => false,
            'cookies' => true,
        ]);
    }
}

<?php

namespace Weidner\Goutte;

use Goutte\Client as GoutteClient;
use GuzzleHttp\Client as GuzzleClient;

class GoutteServiceProviderTest extends TestCase
{
    /**
     * @test
     */
    public function has_registered_services()
    {
        $this->assertTrue($this->app->bound('goutte'));
        $this->assertTrue($this->app->bound('goutte.client'));

        $this->assertInstanceOf(GoutteClient::class, $this->app->make('goutte'));
        $this->assertInstanceOf(GuzzleClient::class, $this->app->make('goutte.client'));
    }

    /**
     * @test
     */
    public function has_registered_aliases()
    {
        $this->assertTrue($this->app->isAlias(GoutteClient::class));
        $this->assertEquals('goutte', $this->app->getAlias(GoutteClient::class));
    }

    /**
     * @test
     */
    public function has_registered_package_config()
    {
        $config = $this->app->make('config');

        $this->assertEquals($config->get('goutte.client'), [
            'allow_redirects' => false,
            'cookies' => true,
        ]);
    }

    /**
     * @test
     */
    public function does_provide_singleton_instance ()
    {
        $this->assertSame($this->app->make('goutte'), $this->app->make('goutte'));
        $this->assertSame($this->app->make('goutte.client'), $this->app->make('goutte.client'));
    }

    /**
     * @test
     */
    public function does_not_remap_guzzle_client_to_custom_singleton()
    {
        $a = $this->app->make(GuzzleClient::class);
        $b = $this->app->make(GuzzleClient::class);

        $this->assertNotSame($a, $b);
    }
}

Add test cases for the service provider

test: Add test cases for the service provider


<?php namespace Nord\Lumen\Core\App\Exception;

use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ApiExceptionHandler
{

    /**
     * @var bool
     */
    private $debug;

    /**
     * ApiExceptionHandler constructor.
     *
     * @param bool $debug
     */
    public function __construct($debug)
    {
        $this->debug = $debug;
    }

    /**
     * @param \Exception $exception
     *
     * @return JsonResponse
     */
    public function createResponse(\Exception $exception)
    {
        if ($this->debug) {
            $data = [
                'exception' => get_class($exception),
                'message' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => $exception->getTrace(),
            ];
        } else {
            $data = ['message' => trans('errors.something_went_wrong')];
        }

        $status = $exception instanceof HttpResponseException ? $exception->getStatusCode() : 500;

        return new JsonResponse($data, $status);
    }
}

<?php namespace Nord\Lumen\Core\App\Exception;

use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ApiExceptionHandler
{

    /**
     * @var bool
     */
    private $debug;

    /**
     * ApiExceptionHandler constructor.
     *
     * @param bool $debug
     */
    public function __construct($debug)
    {
        $this->debug = $debug;
    }

    /**
     * @param \Exception $exception
     *
     * @return JsonResponse
     */
    public function createResponse(\Exception $exception)
    {
        if ($this->debug) {
            $data = [
                'exception' => get_class($exception),
                'message' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => $exception->getTrace(),
            ];
        } else {
            $data = ['message' => trans('errors.something_went_wrong')];
        }

        $status = $exception instanceof HttpResponseException ? $exception->getStatusCode() : 500;

        return new JsonResponse($data, $status, array(), JSON_PARTIAL_OUTPUT_ON_ERROR);
    }
}

Add `JSON_PARTIAL_OUTPUT_ON_ERROR` flag when encoding JSON responses in the exception handler

This fixes the scenario when json_encode() would fail and the default PHP exception handler takes over and returns something else than JSON


<?php namespace Aedart\Scaffold\Contracts\Tasks;

use Aedart\Scaffold\Exceptions\CannotExecuteTaskException;
use Illuminate\Contracts\Config\Repository;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Console Task Runner
 *
 * Executes a set of console tasks
 *
 * @see \Aedart\Scaffold\Contracts\Tasks\ConsoleTask
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Contracts\Tasks
 */
interface ConsoleTaskRunner
{
    /**
     * Execute the given console tasks
     *
     * @param string[] $tasks Class paths to the tasks that must be executed
     * @param InputInterface $input Console input
     * @param OutputInterface $output Console output
     * @param Repository $config Configuration to be passed to each task
     *
     * @return void
     *
     * @throws CannotExecuteTaskException
     */
    public function execute(array $tasks, InputInterface $input, OutputInterface $output, Repository $config);
}

<?php namespace Aedart\Scaffold\Contracts\Tasks;

use Aedart\Scaffold\Exceptions\CannotExecuteTaskException;
use Illuminate\Contracts\Config\Repository;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Console Task Runner
 *
 * Executes a set of console tasks
 *
 * @see \Aedart\Scaffold\Contracts\Tasks\ConsoleTask
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Contracts\Tasks
 */
interface ConsoleTaskRunner
{
    /**
     * Execute the given console tasks
     *
     * @param string[]|ConsoleTask[] $tasks Class paths to the tasks that must be executed
     * @param InputInterface $input Console input
     * @param OutputInterface $output Console output
     * @param Repository $config Configuration to be passed to each task
     *
     * @return void
     *
     * @throws CannotExecuteTaskException
     */
    public function execute(array $tasks, InputInterface $input, OutputInterface $output, Repository $config);
}

Allow also array of console task instances

There might be a scenario where instances are provided, rather than
just class paths


<?php

namespace Paraunit\Bin;

use Paraunit\Command\CoverageCommand;
use Paraunit\Command\ParallelCommand;
use Paraunit\Configuration\ParallelConfiguration;
use Paraunit\Configuration\CoverageConfiguration;
use Symfony\Component\Console\Application;

/**
 * Class Paraunit
 * @package Paraunit\Bin
 */
class Paraunit
{
    const VERSION = '0.7.4';

    public static function createApplication()
    {
        $application = new Application('Paraunit', self::VERSION);

        $parallelCommand = new ParallelCommand(new ParallelConfiguration());
        $application->add($parallelCommand);

        $CoverageCommand = new CoverageCommand(new CoverageConfiguration());
        $application->add($CoverageCommand);

        return $application;
    }
}

<?php

namespace Paraunit\Bin;

use Paraunit\Command\CoverageCommand;
use Paraunit\Command\ParallelCommand;
use Paraunit\Configuration\ParallelConfiguration;
use Paraunit\Configuration\CoverageConfiguration;
use Symfony\Component\Console\Application;

/**
 * Class Paraunit
 * @package Paraunit\Bin
 */
class Paraunit
{
    const VERSION = '0.8-BETA1';

    public static function createApplication()
    {
        $application = new Application('Paraunit', self::VERSION);

        $parallelCommand = new ParallelCommand(new ParallelConfiguration());
        $application->add($parallelCommand);

        $CoverageCommand = new CoverageCommand(new CoverageConfiguration());
        $application->add($CoverageCommand);

        return $application;
    }
}

Tag first beta to attempt release

Tag first beta to attempt release


<?php

namespace $$NAMESPACE$$;

use Radvance\Framework\BaseWebApplication;
use Radvance\Framework\FrameworkApplicationInterface;
// use $$NAMESPACE$$\Repository\PdoExampleRepository;
use RuntimeException;

class Application extends BaseWebApplication implements FrameworkApplicationInterface
{
    public function getRootPath()
    {
        return realpath(__DIR__ . '/../');
    }

    protected function configureRepositories()
    {
        // Add repositories here
        // $this->addRepository(new PdoExampleRepository($this->pdo));
    }
}

<?php

namespace $$NAMESPACE$$;

use Radvance\Framework\BaseWebApplication;
use Radvance\Framework\FrameworkApplicationInterface;
// use $$NAMESPACE$$\Repository\PdoExampleRepository;
use RuntimeException;

class Application extends BaseWebApplication implements FrameworkApplicationInterface
{
    public function getRootPath()
    {
        return realpath(__DIR__ . '/../');
    }
}

Use automatic repository configuration in generated application


<?php
/**
 * This file controls a day view output for iCalendar information.
 */
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:UNL_UCBCN//UNL Event Publisher
X-WR-CALNAME:<?php echo $this->calendar->name; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:<?php echo date('Ymd\THis\Z'); ?>
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
	UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR

<?php
/**
 * This file controls a day view output for iCalendar information.
 */
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:UNL_UCBCN//UNL Event Publisher
X-WR-CALNAME:<?php echo $this->calendar->name."\n"; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:<?php echo date('Ymd\THis\Z')."\n"; ?>
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
	UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR

Add newlines after calendar name and date modified echos


<?php
/**
 *@file
 * Contains \Drupal\AppConsole\Generator\CommandGenerator.
 */

namespace Drupal\AppConsole\Generator;

class CommandGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  string $module     Module name
   * @param  string $command    Command name
   * @param  string $class_name class name for plugin block
   * @param  array  $container  Access to container class
   */
  public function generate($module, $command, $class_name, $container)
  {
    $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module);
    $path_plugin = $path . '/src/Command';

    $parameters = [
      'module_name' => $module,
      'command'     => $command,
      'name'        => [
        'class'     => $class_name,
      ],
      'container'   => $container,
    ];

    $this->renderFile(
      'module/command.php.twig',
      $path_plugin . '/'. $class_name .'.php',
      $parameters
    );
  }
}

<?php
/**
 *@file
 * Contains \Drupal\AppConsole\Generator\CommandGenerator.
 */

namespace Drupal\AppConsole\Generator;

class CommandGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  string $module     Module name
   * @param  string $command    Command name
   * @param  string $class_name class name for plugin block
   * @param  array  $container  Access to container class
   */
  public function generate($module, $command, $class_name, $container)
  {

    $parameters = [
      'module_name' => $module,
      'command'     => $command,
      'name'        => [
        'class'     => $class_name,
      ],
      'container'   => $container,
    ];

    $this->renderFile(
      'module/command.php.twig',
      $path_plugin . '/'. $class_name .'.php',
      $parameters
    );
  }
}

Remove local vars path & path_plugin

Remove local vars path & path_plugin


<?php

class ArrTest extends PHPUnit_Framework_TestCase {
  function testFlatten() {
    $this->assertEquals(
      array('a', 'b', 'c', 'd'),
      Missing\Arr::flatten(array(
        array('a','b'),
        'c',
        array(array(array('d'))),
      ))
    );
  }

  function testSortByInt() {
    $this->assertEquals(
      array('a', 'a', 'ab', 'abc', 'abcd'),
      Missing\Arr::sort_by(
        array('abcd', 'ab', 'a', 'abc', 'a'),
        function ($a) { return strlen($a); }
      )
    );
  }

  function testSortByString() {
    $this->assertEquals(
      array('a333', 'b22', 'c1', 'd55555'),
      Missing\Arr::sort_by(
        array('d55555', 'b22', 'a333', 'c1'),
        function ($a) { return $a; }
      )
    );
  }

  function testSortByArray() {
    $this->assertEquals(
      array(array(1, 'b'), array(1, 'c'), array(2, 'a')),
      Missing\Arr::sort_by(
        array(array(2, 'a'), array(1, 'c'), array(1, 'b')),
        function ($a) { return $a; }
      )
    );
  }

  function testSortByTriggersError() {
    $this->setExpectedException('PHPUnit_Framework_Error');
    Missing\Arr::sort_by(function(){}, array());
  }
}

<?php

class ArrTest extends PHPUnit_Framework_TestCase {
  function testFlatten() {
    $this->assertEquals(
      array('a', 'b', 'c', 'd'),
      Missing\Arr::flatten(array(
        array('a','b'),
        'c',
        array(array(array('d'))),
      ))
    );
  }

  function testSortByInt() {
    $this->assertEquals(
      array('a', 'a', 'ab', 'abc', 'abcd'),
      Missing\Arr::sort_by(
        array('abcd', 'ab', 'a', 'abc', 'a'),
        function ($a) { return strlen($a); }
      )
    );
  }

  function testSortByString() {
    $this->assertEquals(
      array('a333', 'b22', 'c1', 'd55555'),
      Missing\Arr::sort_by(
        array('d55555', 'b22', 'a333', 'c1'),
        function ($a) { return $a; }
      )
    );
  }

  function testSortByArray() {
    $this->assertEquals(
      array(array(2, 'b'), array(2, 'c'), array(19, 'a')),
      Missing\Arr::sort_by(
        array(array(19, 'a'), array(2, 'c'), array(2, 'b')),
        function ($a) { return $a; }
      )
    );
  }

  function testSortByTriggersError() {
    $this->setExpectedException('PHPUnit_Framework_Error');
    Missing\Arr::sort_by(function(){}, array());
  }
}

Use two digit numbers to ensure PHP isn't converting the array to a string


<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" <?php language_attributes(); ?>> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" <?php language_attributes(); ?>> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" <?php language_attributes(); ?>> <!--<![endif]-->
<head>

  <meta charset="utf-8">
  <title><?php wp_title('|', true, 'right'); bloginfo('name'); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/x-icon" href="/favicon.ico" />

  <?php wp_head(); ?>

  <?php if (wp_count_posts()->publish > 0) : ?>
  <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
  <?php endif; ?>
</head>

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" <?php language_attributes(); ?>><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" <?php language_attributes(); ?>> <!--<![endif]-->
<head>

  <meta charset="utf-8">
  <title><?php wp_title(''); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/x-icon" href="/favicon.ico" />

  <?php wp_head(); ?>

  <?php if (wp_count_posts()->publish > 0) : ?>
  <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
  <?php endif; ?>
</head>

Drop Boilerplate <IE8 classes; wp_title cleanup


<?php

add_action('init', 'create_post_type');

function create_post_type()
{
    add_post_type_support('page', 'excerpt');
    register_post_type('event',
        array(
            'labels' => array(
                'name' => __('Událost'),
            ),
            'public' => true,
            'has_archive' => true,
        )
    );
    register_post_type('krizovatka',
        array(
            'labels' => array(
                'name' => __('Křižovatka'),
            ),
            'public' => true,
            'has_archive' => true,
        )
    );
}

<?php

add_action('init', 'create_post_type');

function create_post_type()
{
    add_post_type_support('page', 'excerpt');
    register_post_type('event',
        array(
            'labels' => array(
                'name' => __('Událost'),
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array(
	            'title',
	            'author',
	            'excerpt',
	            'editor',
	            'thumbnail',
            )
        )
    );
    register_post_type('krizovatka',
        array(
            'labels' => array(
                'name' => __('Křižovatka'),
            ),
            'public' => true,
            'has_archive' => true,
        )
    );
}

Add thumbnail support to event post type.


<?php
    namespace Core;

    /**
     * Manage vendor and can automatically detect vendor.
     *
     * @package Core
     */
    class Vendor
    {
        /**
         * Cache vendor list
         *
         * @var array
         */
        private $vendors = array();

        public function __construct()
        {
            if (ENVIRONMENT == 'development')
            {
                $dirs = scandir(BASE_PATH);
                $length = count($dirs);
                $arr = array();
                for ($i = 0 ; $i < count($dirs) ; $i++)
                {
                    if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
                        is_dir($dirs[$i]))
                    {
                        $arr[] = $dirs[$i];
                    }
                }

                $config =& loadClass('Config', 'Core');
                $config->save('Vendor', $arr);
                $this->vendors = $arr;
            }
            else
            {
                $config =& loadClass('Config', 'Core');
                $arr = $config->load('Vendor');

                if ($arr !== false)
                {
                    $this->vendors = $arr;
                }
            }
        }

        /**
         * Get vendor list
         *
         * @return array Vendor list as an array
         */
        public function lists()
        {
            return $this->vendors;
        }
    }

?>

<?php
    namespace Core;

    /**
     * Manage vendor and can automatically detect vendor.
     *
     * @package Core
     */
    class Vendor
    {
        /**
         * Cache vendor list
         *
         * @var array
         */
        private $vendors = array();

        public function __construct()
        {
            if (ENVIRONMENT == 'development')
            {
                $this->generateConfig();
            }
            else
            {
                $this->loadConfig();
            }
        }

        /**
         * Generate Config that contain vendor list
         */
        private function generateConfig()
        {
            $dirs = scandir(BASE_PATH);
            $length = count($dirs);
            $arr = array();
            for ($i = 0 ; $i < count($dirs) ; $i++)
            {
                if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
                    is_dir($dirs[$i]))
                {
                    $arr[] = $dirs[$i];
                }
            }

            $config =& loadClass('Config', 'Core');
            $config->save('Vendor', $arr);
            $this->vendors = $arr;
        }

        /**
         * Load vendor list from config
         */
        private function loadConfig()
        {
            $config =& loadClass('Config', 'Core');
            $arr = $config->load('Vendor');

            if ($arr !== false)
            {
                $this->vendors = $arr;
            }
        }

        /**
         * Get vendor list
         *
         * @return array Vendor list as an array
         */
        public function lists()
        {
            return $this->vendors;
        }
    }

?>

Add method to generate config and load config on vendor class