<?php

namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;

use Core;
use UserInfo;
use Concrete\Core\Page\Page;

class UserCorePageProperty extends CorePageProperty
{
    public function __construct()
    {
        $this->setCorePagePropertyHandle('user');
        $this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User'));
        $this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png');
    }

    public function publishToPage(Page $c, $data, $controls)
    {
        if (Core::make('helper/validation/numbers')->integer($data['user'])) {
            $this->addPageTypeComposerControlRequestValue('uID', $data['user']);
        }
        parent::publishToPage($c, $data, $controls);
    }

    public function validate()
    {
        $uID = $this->getPageTypeComposerControlDraftValue();
        $ux = UserInfo::getByID($uID);
        $e = Core::make('helper/validation/error');
        if (!is_object($ux)) {
            $control = $this->getPageTypeComposerFormLayoutSetControlObject();
            $e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel()));

            return $e;
        }
    }

    public function getPageTypeComposerControlDraftValue()
    {
        if (is_object($this->page)) {
            $c = $this->page;

            return $c->getCollectionUserID();
        }
    }
}

<?php

namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;

use Core;
use UserInfo;
use Page;

class UserCorePageProperty extends CorePageProperty
{
    public function __construct()
    {
        $this->setCorePagePropertyHandle('user');
        $this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User'));
        $this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png');
    }

    public function publishToPage(Page $c, $data, $controls)
    {
        if (Core::make('helper/validation/numbers')->integer($data['user'])) {
            $this->addPageTypeComposerControlRequestValue('uID', $data['user']);
        }
        parent::publishToPage($c, $data, $controls);
    }

    public function validate()
    {
        $uID = $this->getPageTypeComposerControlDraftValue();
        $ux = UserInfo::getByID($uID);
        $e = Core::make('helper/validation/error');
        if (!is_object($ux)) {
            $control = $this->getPageTypeComposerFormLayoutSetControlObject();
            $e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel()));

            return $e;
        }
    }

    public function getPageTypeComposerControlDraftValue()
    {
        if (is_object($this->page)) {
            $c = $this->page;

            return $c->getCollectionUserID();
        }
    }
}

Use \Page instead of Concrete\Core\Page\Page


<?php

namespace Api\Model\Languageforge\Lexicon;

use Api\Model\Shared\Mapper\ObjectForEncoding;

class LexCommentReply extends ObjectForEncoding
{
    public function __construct($content = '')
    {
        $this->content = $content;
        $this->id = uniqid();
        $this->authorInfo = new LexAuthorInfo();
        $this->isDeleted = false;
    }

    /** @var LexAuthorInfo */
    public $authorInfo;

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

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

    /** @var boolean */
    public $isDeleted;
}

<?php

namespace Api\Model\Languageforge\Lexicon;

use Api\Model\Shared\Mapper\ObjectForEncoding;

class LexCommentReply extends ObjectForEncoding
{
    public function __construct($content = '')
    {
        $this->content = $content;
        $this->id = uniqid();
        $this->authorInfo = new LexAuthorInfo();
        $this->isDeleted = false;
    }

    /** @var LexAuthorInfo */
    public $authorInfo;

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

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

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

    /** @var boolean */
    public $isDeleted;
}

Fix comment replies being duplicated during S/R

Turns out it was quite simple: the reply GUIDs weren't being tracked by
PHP and sent to the Javascript frontend, so when the frontend created a
new reply and updated the entire list of replies, it sent a list with no
GUIDs in it. Simply keeping track of the reply GUIDs in PHP is enough to
get rid of this bug.


<?php

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

class AddSignatureToWorkflowActivityLogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('workflow_activity_log', function (Blueprint $table) {
            $table->text('signature')->after('data');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('workflow_activity_log', function (Blueprint $table) {
            $table->dropColumn('signature');
        });
    }
}

<?php

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

class AddSignatureToWorkflowActivityLogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('workflow_activity_log', function (Blueprint $table) {
            $table->text('signature')->nullable()->after('data');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('workflow_activity_log', function (Blueprint $table) {
            $table->dropColumn('signature');
        });
    }
}

Add nullable to signature column in DB

Add nullable to signature column in DB


<!DOCTYPE html>

        <meta charset="utf-8" />

        <title>Joutes - Schedule</title>

        <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />

        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

        <title>Laravel</title>

                    @yield('content')

<!DOCTYPE html>

        <meta charset="utf-8" />

        <title>Joutes - Schedule</title>

        <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
        <link href="{{ asset('css/schedule.css') }}" rel="stylesheet" type="text/css" />

        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

        <title>Laravel</title>

                    @yield('content')

Include schdule css into barebone template


<?php

/**
 * Class CacheIncludeSiteTreeExtension
 */
class CacheIncludeSiteTreeExtension extends DataExtension
{
    /**
     * @return array
     */
    public function extraStatics()
    {
        return array(
            'db' => array(
                'FullLink' => 'Varchar(255)'
            )
        );
    }
    /**
     *
     */
    public function onBeforeWrite()
    {
        parent::onBeforeWrite();

        // Ensure that the method exists
        if (method_exists($this->owner, 'RelativeLink')) {
            $this->owner->FullLink = $this->owner->RelativeLink();
        }
    }
}

<?php

/**
 * Class CacheIncludeSiteTreeExtension
 */
class CacheIncludeSiteTreeExtension extends DataExtension
{
    /**
     * @param null $class
     * @param null $extension
     * @return array
     */
    public function extraStatics($class = null, $extension = null)
    {
        return array(
            'db' => array(
                'FullLink' => 'Varchar(255)'
            )
        );
    }
    /**
     *
     */
    public function onBeforeWrite()
    {
        parent::onBeforeWrite();

        // Ensure that the method exists
        if (method_exists($this->owner, 'RelativeLink')) {
            $this->owner->FullLink = $this->owner->RelativeLink();
        }
    }
}

UPDATE: Make cache include extension consistent with SS api


<?php

/**
 * Class DataObjectAnnotatorTask
 *
 * Task to add or remove annotations from a module or dataobject.
 *
 * @package IDEAnnotator/Tasks
 */
class DataObjectAnnotatorTask extends BuildTask
{
    /**
     * @param $request SS_HTTPRequest
     *
     * @return null
     */
    public function run($request)
    {
        if (!Config::inst()->get('DataObjectAnnotator', 'enabled')) {
            return false;
        }

        $permissionChecker = Injector::inst()->get('AnnotatePermissionChecker');
        $className = $request->getVar('dataobject');
        $moduleName = $request->getVar('module');

        /* @var $annotator DataObjectAnnotator */
        $annotator = DataObjectAnnotator::create();
        if ($className && $permissionChecker->classNameIsAllowed($className)) {
            $annotator->annotateDataObject($className);
        } elseif ($moduleName && $permissionChecker->moduleIsAllowed($moduleName)) {
            $annotator->annotateModule($moduleName);
        }

        $result = "Annotated module $moduleName/class $className\n";

        echo $result;
    }

}

<?php

/**
 * Class DataObjectAnnotatorTask
 *
 * Task to add or remove annotations from a module or dataobject.
 *
 * @package IDEAnnotator/Tasks
 */
class DataObjectAnnotatorTask extends BuildTask
{

    /**
     * DataObjectAnnotatorTask constructor.
     * Setup default values. In this case title and description.
     */
    public function __construct()
    {
        parent::__construct();
        $this->title = 'DataObject annotations for specific DataObjects';
        $this->description = "DataObject Annotator annotates your DO's if possible, helping you write better code.
"
            . 'Usage: add the module or DataObject as parameter to the URL, e.g. ?module=ideannotator
'
            . 'To undo annotations, add undo=true to the URL.';

    }

    /**
     * @param $request SS_HTTPRequest
     *
     * @return null
     */
    public function run($request)
    {
        if (!Config::inst()->get('DataObjectAnnotator', 'enabled')) {
            return false;
        }

        $permissionChecker = Injector::inst()->get('AnnotatePermissionChecker');
        $className = $request->getVar('dataobject');
        $moduleName = $request->getVar('module');

        /* @var $annotator DataObjectAnnotator */
        $annotator = DataObjectAnnotator::create();
        if ($className && $permissionChecker->classNameIsAllowed($className)) {
            $annotator->annotateDataObject($className);
        } elseif ($moduleName && $permissionChecker->moduleIsAllowed($moduleName)) {
            $annotator->annotateModule($moduleName);
        }

        $result = "Annotated module $moduleName/class $className\n";

        echo $result;
    }

}

Add title and description to the task.

Add title and description to the task.


<?php

declare(strict_types=1);

namespace Codeception\Subscriber;

use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FailFast implements EventSubscriberInterface
{
    use Shared\StaticEventsTrait;

    /**
     * @var array<string, array<string, int>>
     */
    protected static array $events = [
        Events::TEST_FAIL => ['stopOnFail', 128],
        Events::TEST_ERROR => ['stopOnFail', 128],
    ];

    private int $failureCount = 0;

    public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
    {
    }

    public function stopOnFail(TestEvent $e): void
    {
        $this->failureCount++;

        if ($this->failureCount >= $this->stopFailureCount) {
            $this->resultAggregator->stop();
        }
    }
}

<?php

declare(strict_types=1);

namespace Codeception\Subscriber;

use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FailFast implements EventSubscriberInterface
{
    use Shared\StaticEventsTrait;

    /**
     * @var array<string, array<string|int>>
     */
    protected static array $events = [
        Events::TEST_FAIL => ['stopOnFail', 128],
        Events::TEST_ERROR => ['stopOnFail', 128],
    ];

    private int $failureCount = 0;

    public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
    {
    }

    public function stopOnFail(TestEvent $e): void
    {
        $this->failureCount++;

        if ($this->failureCount >= $this->stopFailureCount) {
            $this->resultAggregator->stop();
        }
    }
}

Fix array structure in @var annotation

Fix array structure in @var annotation


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

namespace Zend\Db\Adapter;

use Zend\Db\ResultSet;

/**
 *
 * @property Driver\DriverInterface $driver
 * @property Platform\PlatformInterface $platform
 */
interface AdapterInterface
{
    /**
     * @return Driver\DriverInterface
     */
    public function getDriver();

    /**
     * @return Platform\PlatformInterface
     */
    public function getPlatform();

    /**
     * query() is a convenience function
     *
     * @param string $sql
     * @param string|array|ParameterContainer $parametersOrQueryMode
     * @param \Zend\Db\ResultSet\ResultSetInterface $resultPrototype
     * @throws Exception\InvalidArgumentException
     * @return Driver\StatementInterface|ResultSet\ResultSet
     */
    public function query($sql, $parametersOrQueryMode = self::QUERY_MODE_PREPARE, ResultSet\ResultSetInterface $resultPrototype = null);
}

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

namespace Zend\Db\Adapter;

use Zend\Db\ResultSet;

/**
 *
 * @property Driver\DriverInterface $driver
 * @property Platform\PlatformInterface $platform
 */
interface AdapterInterface
{
    /**
     * @return Driver\DriverInterface
     */
    public function getDriver();

    /**
     * @return Platform\PlatformInterface
     */
    public function getPlatform();

    /**
     * query() is a convenience function
     *
     * @param string $sql
     * @param string|array|ParameterContainer $parametersOrQueryMode
     * @param \Zend\Db\ResultSet\ResultSetInterface $resultPrototype
     * @throws Exception\InvalidArgumentException
     * @return Driver\StatementInterface|ResultSet\ResultSet
     */
    public function query($sql, $parametersOrQueryMode, ResultSet\ResultSetInterface $resultPrototype = null);
}

Fix interface that cannot reference to self


<?php

namespace WP_CLI_Login;

if (! class_exists('WP_CLI')) {
    return;
}

LoginCommand::setPackage(new Package(__DIR__));

\WP_CLI::add_command('login', LoginCommand::class);

<?php

namespace WP_CLI_Login;

if (! class_exists('WP_CLI')) {
    return;
}

if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

LoginCommand::setPackage(new Package(__DIR__));

\WP_CLI::add_command('login', LoginCommand::class);

Load local autoloader, if present

Load local autoloader, if present


<?php namespace TightenCo\Jigsaw\Console;

use Symfony\Component\Console\Input\InputArgument;
use TightenCo\Jigsaw\File\Filesystem;

class InitCommand extends Command
{
    private $files;
    private $base;

    public function __construct(Filesystem $files)
    {
        $this->files = $files;
        $this->base = getcwd();
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('init')
            ->setDescription('Scaffold a new Jigsaw project.')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Where should we initialize this project?'
            );
    }

    protected function fire()
    {
        if ($base = $this->input->getArgument('name')) {
            $this->base .= '/' . $base;
        }

        $this->scaffoldSite();
        $this->scaffoldMix();
        $this->info('Site initialized successfully!');
    }

    private function scaffoldSite()
    {
        $this->files->copyDirectory(__DIR__ . '/../../stubs/site', $this->base);
    }

    private function scaffoldMix()
    {
        $this->files->copyDirectory(__DIR__ . '/../../stubs/mix', $this->base);
    }
}

<?php namespace TightenCo\Jigsaw\Console;

use Symfony\Component\Console\Input\InputArgument;
use TightenCo\Jigsaw\File\Filesystem;

class InitCommand extends Command
{
    private $files;
    private $base;

    public function __construct(Filesystem $files)
    {
        $this->files = $files;
        $this->base = getcwd();
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('init')
            ->setDescription('Scaffold a new Jigsaw project.')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Where should we initialize this project?'
            );
    }

    protected function fire()
    {
        if ($base = $this->input->getArgument('name')) {
            $this->base .= '/' . $base;
        }

        $this->ifAlreadyScaffoldedWarnBeforeDoingTheFollowing(function () {
            $this->scaffoldSite();
            $this->scaffoldMix();
            $this->info('Site initialized successfully!');
        });
    }

    private function ifAlreadyScaffoldedWarnBeforeDoingTheFollowing($callback)
    {
        if ($this->files->exists($this->base . '/config.php')) {
            $this->info('It looks like you\'ve already run "jigsaw init" on this project.');
            $this->info('Running it again may overwrite important files.');
            $this->info('');

            if (! $this->confirm('Do you wish to continue?')) {
                return;
            }
        }

        $callback();
    }

    private function scaffoldSite()
    {
        $this->files->copyDirectory(__DIR__ . '/../../stubs/site', $this->base);
    }

    private function scaffoldMix()
    {
        $this->files->copyDirectory(__DIR__ . '/../../stubs/mix', $this->base);
    }
}

Add confirmation before running init command in existing project

ugh, another useless commit

Undo temp file


<?php

namespace engine\controllers;

use Walrus\core\WalrusFrontController as WalrusFrontController;

class HelloController extends WalrusFrontController
{

    public function helloHome ()
    {
        $this->register('test', 'global work !');

        $this->setView('home', 'coucou');
        $this->register('beta', 'template 2 specified variable work', 'home', 'coucou');

        $this->setView('home', 'alias');
        $this->register('beta', 'template 1 specified variable work', 'home', 'alias');

        $this->setView('test/test');
        $this->register('gamma', $this, 'test/test');
    }

    public function doHelloWorld ($id = false)
    {
        echo 'Hello World ! ' . $id;
    }

    public function doHelloWorldNew()
    {
        echo 'new Hello World !';
    }
}

<?php

namespace engine\controllers;

use Walrus\core\WalrusFrontController as WalrusFrontController;

class HelloController extends WalrusFrontController
{

    public function helloHome ()
    {
        $this->register('test', 'global work !');

        $this->setView('home', 'coucou');
        $this->register('beta', 'template 2 specified variable work', 'home', 'coucou');

        $this->setView('home', 'alias');
        $this->register('beta', 'template 1 specified variable work', 'home', 'alias');

        $this->setView('test/test');
        $this->register('gamma', $this, 'test/test');
    }

    public function doHelloWorld ($id = false)
    {
        echo 'Hello World ! ' . $id;
    }

    public function doHelloWorldNew()
    {
        $this->skeleton('_skeleton_main');
        $this->register('beta', 'coucou', 'home');
    }
}

Test Controller: add skeleton test

Test Controller: add skeleton test


<?php

namespace Egzaminer\Exam;

use Egzaminer\Admin\Dashboard as Controller;

class ExamAdd extends Controller
{
    public function addAction()
    {
        if (isset($_POST['add'])) {
            $model = new ExamAddModel();
            if ($id = $model->add($_POST)) {
                $this->data['valid'] = true;
                header('Location: '.$this->dir().'/admin/test/edit/'.$id);
                exit;
            } else {
                $this->data['valid'] = false;
            }
        }
        $this->render('admin-exam-add', 'Dodawanie testu');
    }
}

<?php

namespace Egzaminer\Exam;

use Egzaminer\Admin\Dashboard as Controller;

class ExamAdd extends Controller
{
    public function addAction()
    {
        if (isset($_POST['add'])) {
            $model = new ExamAddModel();
            if ($id = $model->add($_POST)) {
                $_SESSION['valid'] = true;
                header('Location: '.$this->dir().'/admin/test/edit/'.$id);
                exit;
            } else {
                $this->data['valid'] = false;
            }
        }
        $this->render('admin-exam-add', 'Dodawanie testu');
    }
}

Fix flash message on test add

Fix flash message on test add


<?php

namespace MirMigration\Lib;

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;

class Doctrine
{
    private static $instance = null;

    /**
     * @param \MirMigration\Lib\AppFactory $factory
     * @param \MirMigration\Lib\Yaml $parser
     * @return Connection
     */
    public static function getInstance(AppFactory $factory, Yaml $parser){
        if( self::$instance !== null ) return self::$instance;

        $dotenv = new \Dotenv\Dotenv(__DIR__.'/../../');
        $dotenv->load();

        $config = new Configuration();
        $connectionParams = [
            'dbname' => getenv('DB_NAME'),
            'user' => getenv('DB_USER'),
            'host' => getenv('DB_HOST'),
            'driver' => 'pdo_mysql',
        ];
        if(getenv('DB_PASSWORD')){
            $connectionParams['password'] = getenv('DB_PASSWORD'),
        }
        self::$instance = DriverManager::getConnection($connectionParams, $config);
        return self::getInstance($factory, $parser);
    }

}

<?php

namespace MirMigration\Lib;

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Dotenv\Dotenv;

class Doctrine
{
    private static $instance = null;

    /**
     * @param \MirMigration\Lib\AppFactory $factory
     * @param \MirMigration\Lib\Yaml $parser
     * @return Connection
     */
    public static function getInstance(AppFactory $factory, Yaml $parser){
        if( self::$instance !== null ) return self::$instance;

        $dotenv = new Dotenv(__DIR__.'/../../');
        $dotenv->load();

        $config = new Configuration();
        $connectionParams = [
            'dbname' => getenv('DB_NAME'),
            'user' => getenv('DB_USER'),
            'host' => getenv('DB_HOST'),
            'driver' => 'pdo_mysql',
        ];
        if(getenv('DB_PASSWORD')){
            $connectionParams['password'] = getenv('DB_PASSWORD');
        }
        self::$instance = DriverManager::getConnection($connectionParams, $config);
        return self::getInstance($factory, $parser);
    }

}

Attach doctrine to variables environement


<?hh //strict
enum HTTP: string as string {
  GET = 'GET';
  POST = 'POST';
  PUT = 'PUT';
  DELETE = 'DELETE';
  PATCH = 'PATCH';
}
enum AppEnv: string as string {
  API = 'API';
  UNIT_TESTS = 'UNIT_TESTS';
  MAIN = 'MAIN';
  PRODUCTION = 'production';
  DEVELOPMENT = 'development';
}
const string ASSETS_PREFIX = 'res.app.com/';
const string HOSTNAME = 'app.com';

<?hh //strict
enum HTTP: string as string {
  GET = 'GET';
  POST = 'POST';
  PUT = 'PUT';
  DELETE = 'DELETE';
  PATCH = 'PATCH';
}
enum AppEnv: string as string {
  API = 'API';
  UNIT_TESTS = 'UNIT_TESTS';
  MAIN = 'MAIN';
  PRODUCTION = 'production';
  DEVELOPMENT = 'development';
}
enum ExceptionCode:int as int {
	GENERIC = 1;
	NOT_FOUND = 2;
	NETWORK_ERROR = 3;
	DELETED = 4;
}
const string ASSETS_PREFIX = 'res.app.com/';
const string HOSTNAME = 'app.com';

Create a standard enum for Exception Codes


<?php
/**
 * Created by PhpStorm.
 * User: rahman
 * Date: 11/5/14
 * Time: 8:47 AM
 */

Event::listen('auth.login', function($user)
{
    Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});

Event::listen('auth.logout', function($user)
{
    Event::fire('logger', array(array('logout',array('username'=>$user->username),3)));
});

Event::listen('logger', function($log)
{
    $log = array(
        'event_name'=> $log[0],
        'custom_parameter'=> json_encode($log[1]),
        'verbose_level' => $log[2],
        'ip_address' => Request::getClientIp(),
        'request_uri' => Request::url(),
    );

    $logger = Logger::create($log);

    $freshTimestamp = new \Carbon\Carbon();
    $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;

    File::append(Config::get('settings.log_file'),$log_string);

});

<?php
/**
 * Created by PhpStorm.
 * User: rahman
 * Date: 11/5/14
 * Time: 8:47 AM
 */

Event::listen('auth.login', function($user)
{
    Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});

Event::listen('auth.logout', function($user)
{
    $username = $user ? $user->username : '-';
    Event::fire('logger', array(array('logout',array('username'=>$user->username),3)));
});

Event::listen('logger', function($log)
{
    $log = array(
        'event_name'=> $log[0],
        'custom_parameter'=> json_encode($log[1]),
        'verbose_level' => $log[2],
        'ip_address' => Request::getClientIp(),
        'request_uri' => Request::url(),
    );

    $logger = Logger::create($log);

    $freshTimestamp = new \Carbon\Carbon();
    $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;

    File::append(Config::get('settings.log_file'),$log_string);

});

Fix logout logger no username

Fix logout logger no username


<?php

/*
 * This file is part of the qandidate/symfony-json-request-transformer package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Qandidate\Common\Symfony\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Transforms the body of a json request to POST parameters.
 */
class JsonRequestTransformerListener
{
    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        $content = $request->getContent();

        if (empty($content)) {
            return;
        }

        if (! $this->isJsonRequest($request)) {
            return;
        }

        if (! $this->transformJsonBody($request)) {
            $response = Response::create('Unable to parse request.', 400);
            $event->setResponse($response);
        }
    }

    private function isJsonRequest(Request $request)
    {
        return 'json' === $request->getContentType();
    }

    private function transformJsonBody(Request $request)
    {
        $data = json_decode($request->getContent(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return false;
        }

        if ($data === null) {
            return true;
        }

        $request->request->replace($data);

        return true;
    }
}

<?php

/*
 * This file is part of the qandidate/symfony-json-request-transformer package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Qandidate\Common\Symfony\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Transforms the body of a json request to POST parameters.
 */
class JsonRequestTransformerListener
{
    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        if (! $this->isJsonRequest($request)) {
            return;
        }

        $content = $request->getContent();

        if (empty($content)) {
            return;
        }

        if (! $this->transformJsonBody($request)) {
            $response = Response::create('Unable to parse request.', 400);
            $event->setResponse($response);
        }
    }

    private function isJsonRequest(Request $request)
    {
        return 'json' === $request->getContentType();
    }

    private function transformJsonBody(Request $request)
    {
        $data = json_decode($request->getContent(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return false;
        }

        if ($data === null) {
            return true;
        }

        $request->request->replace($data);

        return true;
    }
}

Return immediately if request is not json

Fetching the contents before this check may result in OutOfMemory excpetion if the request is multipart with files.


<?php

namespace InfinityBase\Mapper;

use Doctrine\ORM\EntityRepository;
use InfinityBase\ServiceManager\AbstractServiceLocatorAware;

abstract class AbstractMapper extends AbstractServiceLocatorAware
{

    use EntityManagerAwareTrait;

    /**
     * @var EntityRepository
     */
    private $repository;

    /**
     * Get the accounts repository
     *
     * @return EntityRepository
     */
    private function getRepository()
    {
        if (null === $this->repository) {
            $this->repository = $this->getEntityManager()
                    ->getRepository($this->getModuleNamespace() . '\Entity\\' . $this->getEntityName());
        }
        return $this->repository;
    }

}

<?php

namespace InfinityBase\Mapper;

use Doctrine\ORM\EntityRepository;
use InfinityBase\ServiceManager\AbstractServiceLocatorAware;

abstract class AbstractMapper extends AbstractServiceLocatorAware
{

    /**
     * @var EntityRepository
     */
    private $repository;

    /**
     * Get the accounts repository
     *
     * @return EntityRepository
     */
    private function getRepository()
    {
        if (null === $this->repository) {
            $this->repository = $this->getEntityManager()
                    ->getRepository($this->getModuleNamespace() . '\Entity\\' . $this->getEntityName());
        }
        return $this->repository;
    }

}

Remove entitymanagerawaretrait as it's extending abstractservicelocatoraware


<?php

namespace app\packages\services\widgets;

use yii\base\Widget;
use yii\helpers\ArrayHelper;
use app\packages\services\models\ServicesForm;
use Yii;

class Services extends Widget{

    public $_params = [];

    public function init(){
        parent::init();
    }

    public function run(){
    	$view = ArrayHelper::getValue($this->_params, 'view', 'services');
    	$slug = ArrayHelper::getValue($this->_params, 'slug', null);

    	$model = new ServicesForm;
        return $this->render($view, ['model' => $model, 'slug' => $slug]);
    }

}

<?php

namespace app\packages\services\widgets;

use yii\base\Widget;
use yii\helpers\ArrayHelper;
use app\packages\services\models\ServicesForm;
use Yii;

class Services extends Widget{

    public $_params = [];

    public function init(){
        parent::init();
    }

    public function run(){
    	$view = ArrayHelper::getValue($this->_params, 'view', 'services');
    	$slug = ArrayHelper::getValue($this->_params, 'slug', null);

    	$model = new ServicesForm;
        $model->scenario = 'borrow';
        return $this->render($view, ['model' => $model, 'slug' => $slug]);
    }

}

Add widget search, change form check bank, remove index.php for url


<?php
namespace GoRemote\Model;

class CompanyModel
{
	public $id = 0;
	public $name;
	public $url = '';
	public $twitter;
	public $logo;

	public function insert(\Doctrine\DBAL\Connection $db)
	{
		$duplicateId = $db->fetchAssoc(
			'select companyid, url, logo from companies where name=?',
			[
				(string) $this->name
			]);

		if ($duplicateId) {
            if (empty($duplicateId['logo']) && !empty($this->logo)) {
                $db->createQueryBuilder()
                    ->update('companies')
                    ->set('logo', '?')
                    ->where('companyid = ?')
                    ->setParameter(0, $this->logo)
                    ->setParameter(1, $duplicateId['companyid']);
            }
			$this->id = $duplicateId;
			return $duplicateId;
		}

		$company = [
			'name' => $this->name,
			'dateadded' => date('Y-m-d H:i:s'),
			'logo' => $this->logo,
			'twitter' => $this->twitter,
			'url' => $this->url
		];

		$db->insert('companies', $company);
		$this->id = $db->lastInsertId();
		return $this->id;
	}
}

<?php
namespace GoRemote\Model;

class CompanyModel
{
	public $id = 0;
	public $name;
	public $url = '';
	public $twitter;
	public $logo;

	public function insert(\Doctrine\DBAL\Connection $db)
	{
		$duplicateId = $db->fetchAssoc(
			'select companyid, url, logo from companies where name=?',
			[
				(string) $this->name
			]);

		if ($duplicateId) {
            if (empty($duplicateId['logo']) && !empty($this->logo)) {
                $db->createQueryBuilder()
                    ->update('companies')
                    ->set('logo', '?')
                    ->where('companyid = ?')
                    ->setParameter(0, $this->logo)
                    ->setParameter(1, $duplicateId['companyid'])
                    ->execute();
            }
			$this->id = $duplicateId;
			return $duplicateId;
		}

		$company = [
			'name' => $this->name,
			'dateadded' => date('Y-m-d H:i:s'),
			'logo' => $this->logo,
			'twitter' => $this->twitter,
			'url' => $this->url
		];

		$db->insert('companies', $company);
		$this->id = $db->lastInsertId();
		return $this->id;
	}
}

Update company logos if they didn't previously have one but they do now


<?php
namespace CodeDay\Clear\Controllers\Manage\Event;

use \CodeDay\Clear\Models;

class SubscriptionsController extends \Controller {
  public function getIndex()
  {
    return \View::make('event/subscriptions');
  }

  public function postDelete()
  {
    $event = \Route::input('event');
    $subscription = Models\Batch\Event\Notify::where('id', '=', \Input::get('id'))->firstOrFail();

    if ($subscription->batches_event_id !== $event->id) {
        \App::abort(401);
    }

    \Session::flash('status_message', 'Subscription removed');
    $subscription->delete();
    return \Redirect::to('/event/'.$event->id.'/subscriptions');
  }
}

<?php
namespace CodeDay\Clear\Controllers\Manage\Event;

use \CodeDay\Clear\Models;

class SubscriptionsController extends \Controller {
  public function getIndex()
  {
    return \View::make('event/subscriptions');
  }

  public function postDelete()
  {
    $event = \Route::input('event');
    $subscription = Models\Notify::where('id', '=', \Input::get('id'))->firstOrFail();

    if ($subscription->batches_event_id !== $event->id) {
        \App::abort(401);
    }

    \Session::flash('status_message', 'Subscription removed');
    $subscription->delete();
    return \Redirect::to('/event/'.$event->id.'/subscriptions');
  }
}

Fix model name in subscriptions/postDelete


<?php

namespace Rad\Logging\Adapter;

use Rad\Logging\AbstractAdapter;

/**
 * File Adapter
 *
 * @package Rad\Logging\Adapter
 */
class FileAdapter extends AbstractAdapter
{
    protected $handle;

    /**
     * Rad\Logging\Adapter\FileAdapter constructor
     *
     * @param string $filePath Log file path
     */
    public function __construct($filePath)
    {
        $this->handle = fopen($filePath, 'ab+');
    }

    /**
     * Rad\Logging\Adapter\FileAdapter destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Closes an open file pointer
     *
     * @return bool
     */
    public function close()
    {
        return fclose($this->handle);
    }

    /**
     * {@inheritdoc}
     */
    public function log($level, $message, $time, array $context = [])
    {
        fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context));
    }
}

<?php

namespace Rad\Logging\Adapter;

use Rad\Logging\AbstractAdapter;

/**
 * File Adapter
 *
 * @package Rad\Logging\Adapter
 */
class FileAdapter extends AbstractAdapter
{
    protected $handle;

    /**
     * Rad\Logging\Adapter\FileAdapter constructor
     *
     * @param string $filePath Log file path
     */
    public function __construct($filePath)
    {
        $dirPath = dirname($filePath);
        if (false === is_dir($dirPath)) {
            mkdir($dirPath, 0775, true);
        }

        if (substr($filePath, -4) !== '.log') {
            $filePath .= '.log';
        }

        $this->handle = fopen($filePath, 'ab+');
    }

    /**
     * Rad\Logging\Adapter\FileAdapter destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Closes an open file pointer
     *
     * @return bool
     */
    public function close()
    {
        return fclose($this->handle);
    }

    /**
     * {@inheritdoc}
     */
    public function log($level, $message, $time, array $context = [])
    {
        fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context));
    }
}

Create log directory if does'nt exist.

Create log directory if does'nt exist.


<?php

class Log {

  public static function emergency($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_EMERGENCY);
  }

  public static function alert($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_ALERT);
  }

  public static function critical($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_CRITICAL);
  }

  public static function error($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_ERROR);
  }

  public static function warning($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_WARNING);
  }

  public static function notice($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_NOTICE);
  }

  public static function info($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_INFO);
  }

  public static function debug($message, $tag = "") {
    self::invoke_watchdog($message, $tag, WATCHDOG_DEBUG);
  }

  private static function invoke_watchdog($message, $tag, $severity) {
    watchdog($tag, $message, [], $severity);
  }
}

<?php

class Log {

  public static function emergency($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_EMERGENCY);
  }

  public static function alert($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_ALERT);
  }

  public static function critical($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_CRITICAL);
  }

  public static function error($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_ERROR);
  }

  public static function warning($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_WARNING);
  }

  public static function notice($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_NOTICE);
  }

  public static function info($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_INFO);
  }

  public static function debug($tag, $message = "") {
    self::invoke_watchdog($tag, $message, WATCHDOG_DEBUG);
  }

  private static function invoke_watchdog($tag, $message, $severity) {
    if (!$message) { // Only message with no tags
      watchdog("", $tag, [], $severity);
    } else if (is_array($tag)) { // Tags specified as an array
      watchdog(implode($tag, ' '), $message, [], $severity);
    } else { // Tags specified as a string
      watchdog($tag, $message, [], $severity);
    }
  }
}

Improve tag usage in logging helper

Improve tag usage in logging helper

Tags can be now specified before the message. Nice logger automatically
recognices tags specified as a string or as an array.

Closes #2


<?php
namespace Laranix\AntiSpam\Middleware;

use Closure;
use Laranix\AntiSpam\Sequence\Sequence;
use Laranix\AntiSpam\Recaptcha\Recaptcha;
use Laranix\Support\Request\Middleware;

class Verify extends Middleware
{
    /**
     * Process middleware.
     * Write this as you would a normal handle method for laravel middleware
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    protected function before($request, Closure $next)
    {
        $sequence   = $this->app->make(Sequence::class);

        if (!$sequence->verify()) {
            return $sequence->redirect();
        }

        $recaptcha  = $this->app->make(Recaptcha::class);

        if (!$recaptcha->verify()) {
            return $recaptcha->redirect();
        }

        return $next($request);
    }
}

<?php
namespace Laranix\AntiSpam\Middleware;

use Closure;
use Laranix\AntiSpam\Sequence\Sequence;
use Laranix\AntiSpam\Recaptcha\Recaptcha;
use Laranix\Support\Request\Middleware;

class Verify extends Middleware
{
    /**
     * Handle request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param bool                     $recaptcha
     * @return mixed
     */
    public function handle($request, Closure $next, bool $recaptcha = true)
    {
        if ($this->shouldExecute($request)) {
            return $this->before($request, $next, $recaptcha);
        }

        return $next($request);
    }

    /**
     * Process middleware.
     * Write this as you would a normal handle method for laravel middleware
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param bool                     $recaptcha
     * @return mixed
     */
    protected function before($request, Closure $next, bool $recaptcha = true)
    {
        $sequence   = $this->app->make(Sequence::class);

        if (!$sequence->verify()) {
            return $sequence->redirect();
        }

        if ($recaptcha) {
            $recaptcha = $this->app->make(Recaptcha::class);

            if (!$recaptcha->verify()) {
                return $recaptcha->redirect();
            }
        }

        return $next($request);
    }
}

Add check/override for ignoring recaptcha


<?php
namespace PhpBrew\Command;

use PhpBrew\Config;
use PhpBrew\VariantParser;

class ListCommand extends \CLIFramework\Command
{
    public function brief()
    {
        return 'list installed PHP versions';
    }

    public function execute()
    {
        $versions = Config::getInstalledPhpVersions();
        $currentVersion = Config::getCurrentPhpName();

        // var_dump( $versions );
        echo "Installed versions:\n";

        if ($currentVersion === false or in_array($currentVersion, $versions) === false) {
            echo "* (system)\n";
        }

        foreach ($versions as $version) {
            $versionPrefix = Config::getVersionBuildPrefix($version);

            printf('  %-15s  (%-10s)', $version, $versionPrefix);

            if (file_exists($versionPrefix . DIRECTORY_SEPARATOR . 'phpbrew.variants')) {
                $info = unserialize(file_get_contents($versionPrefix . DIRECTORY_SEPARATOR . 'phpbrew.variants'));

                echo "\n";
                echo str_repeat(' ', 19);
                echo VariantParser::revealCommandArguments($info);
            }

            echo "\n";
        }
    }
}

<?php
namespace PhpBrew\Command;

use PhpBrew\Config;
use PhpBrew\VariantParser;

class ListCommand extends \CLIFramework\Command
{
    public function brief()
    {
        return 'List installed PHP versions';
    }

    public function options($opts)
    {
        $opts->add('d|dir','Show php directories.');
        $opts->add('v|variants','Show used variants.');
    }

    public function execute()
    {
        $versions = Config::getInstalledPhpVersions();
        $currentVersion = Config::getCurrentPhpName();

        // var_dump( $versions );
        echo "Installed versions:\n";

        if ($currentVersion === false or in_array($currentVersion, $versions) === false) {
            echo "* (system)\n";
        }

        foreach ($versions as $version) {
            $versionPrefix = Config::getVersionBuildPrefix($version);

            printf('* %-15s', $version);

            if ($this->options->dir) {
                printf("\n    %s", $versionPrefix);
            }

            if ($this->options->variants && file_exists($versionPrefix . DIRECTORY_SEPARATOR . 'phpbrew.variants')) {
                $info = unserialize(file_get_contents($versionPrefix . DIRECTORY_SEPARATOR . 'phpbrew.variants'));
                echo "\n    ";
                echo wordwrap(VariantParser::revealCommandArguments($info), 75, " \\\n    ");
            }

            echo "\n";
        }
    }
}

Introduce -d, -v options to list command

-d, --dir, show directories
-v, --variants, show variants


<?php
/**
*Application settings
*/

define("db_user", "root");
define("db_pass", "");
define("db_host", "localhost");
define("db_name", "qdi");
define("db_table", "contacts");

<?php
/**
*Application settings
*/

define("db_user", "");
define("db_pass", "");
define("db_host", "");
define("db_name", "");
define("db_table", "");

Set DB conn data to blank for publication.


<?php

return [
    // Basic author information
    'site_name' => 'Site Name',
    'user' => 'John Doe',
    'email' => 'email@provider.com',
    'theme' => 'default',
    'status' => 'live', // live, maintenance, unavailable, landing, prelaunch
    'debug' => False, // echo DEBUG pages + debug info on failure
    'backend' => 'db',
    'cache-age' => 24, // max cache age in hours
    // Blog sidebar
    'about' => "",
    // Meta description
    'description' => "",
    // Social media accounts (usernames for links)
    'github' => '',
    'twitter' => '',
    'facebook' => ''
];

<?php

return [
    // Basic author information
    'site_name' => 'Site Name',
    'user' => 'John Doe',
    'email' => 'email@provider.com',
    'theme' => 'default',
    'status' => 'live', // live, maintenance, unavailable, landing, prelaunch
    'debug' => False, // echo DEBUG pages + debug info on failure
    'backend' => 'db',
    'cache-age' => 24, // max cache age in hours
    // Blog sidebar
    'about' => "This appears in the blog sidebar.",
    // Meta description
    'description' => "A site built using B3",
    // Social media accounts (usernames for links)
    'github' => '',
    'twitter' => '',
    'facebook' => ''
];

Add dummmy default values in config

Add dummmy default values in config


<?php

	$headers = array(
		array(
			'img' => 'images/headers/header_sign.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4485964682/',
			'width' => 950,
			'height' => 250,
		),
		array(
			'img' => 'images/headers/header_duckies.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4710923546/',
			'width' => 950,
			'height' => 250,
		),
		array(
			'img' => 'images/headers/header_pier.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4485317853/',
			'width' => 950,
			'height' => 250,
		),
	/*	array(
			'img' => 'images/headers/header_lake.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/3576628927/',
			'width' => 950,
			'height' => 250,
		), */
	);

	// pick a header
	$header = $headers[ mt_rand( 0, count( $headers ) - 1 ) ];

	echo json_encode( $header );

?>

<?php

	$headers = array(
		array(
			'img' => 'images/headers/header_sign.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4485964682/',
			'width' => 950,
			'height' => 250,
		),
		array(
			'img' => 'images/headers/header_duckies.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4710923546/',
			'width' => 950,
			'height' => 250,
		),
		array(
			'img' => 'images/headers/header_pier.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/4485317853/',
			'width' => 950,
			'height' => 250,
		),
		array(
			'img' => 'images/headers/header_lake.jpg',
			'flickr' => 'http://www.flickr.com/photos/mellertime/3576628927/',
			'width' => 950,
			'height' => 250,
		),
	);

	// pick a header
	$header = $headers[ mt_rand( 0, count( $headers ) - 1 ) ];

	echo json_encode( $header );

?>

Add the lake header back into the rotation, it looks fine.

git-svn-id: 71ac0145df79e26b076d62e50011532b62ebd840@97 9841916d-1f77-4d57-ab71-7f08b6dd89e2


<?php

namespace Dingo\Api\Http;

use Illuminate\Http\Request as IlluminateRequest;

class Validator
{
    protected $domain;

    protected $prefix;

    /**
     * Create a new request validator instance.
     *
     * @param string $domain
     * @param string $prefix
     *
     * @return void
     */
    public function __construct($domain = null, $prefix = null)
    {
        $this->domain = $domain;
        $this->prefix = $prefix;
    }

    /**
     * Validate a request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function validateRequest(IlluminateRequest $request)
    {
        return $this->validateDomain($request) || $this->validatePrefix($request);
    }

    /**
     * Validates domain in the request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function validateDomain(IlluminateRequest $request)
    {
        return ! is_null($this->domain) && $request->header('host') == $this->domain;
    }

    /**
     * Validates prefix in the request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function validatePrefix(IlluminateRequest $request)
    {
        $prefix = $this->filterAndExplode($this->prefix);

        $path = $this->filterAndExplode($request->getPathInfo());

        return ! is_null($this->prefix) && $prefix == array_slice($path, 0, count($prefix));
    }

    /**
     * Explode array on slash and remove empty values.
     *
     * @param array $array
     *
     * @return array
     */
    protected function filterAndExplode($array)
    {
        return array_filter(explode('/', $array));
    }
}

<?php

namespace Dingo\Api\Http;

use Illuminate\Container\Container;
use Illuminate\Http\Request as IlluminateRequest;

class Validator
{
    /**
     * Container instance.
     *
     * @var \Illuminate\Container\Container
     */
    protected $container;

    /**
     * Array of request validators.
     *
     * @var array
     */
    protected $validators = [
        'Dingo\Api\Http\Matching\DomainValidator',
        'Dingo\Api\Http\Matching\PrefixValidator',
        'Dingo\Api\Http\Matching\AcceptValidator'
    ];

    /**
     * Create a new request validator instance.
     *
     * @param \Illuminate\Container\Container $container
     *
     * @return void
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Validate a request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function validateRequest(IlluminateRequest $request)
    {
        foreach ($this->validators as $validator) {
            $validator = $this->container->make($validator);

            if (! $validator->matches($request)) {
                return false;
            }
        }

        return true;
    }
}

Implement a better way of validating incoming requests.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<?php

header('Location: Sauna.php');
?>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sauna</title>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script>
	$(document).ready(function(e) {
       $.ajax({
			url:"Sauna.php",
			dataType:"html",
			success: function(html) {
				$('body').html(html);
			}
		});
    });
</script>
</head>

<body>
</body>
</html>

Revert "Revert "Index aangepast zodat deze via ajax Sauna.php ophaalt""

This reverts commit e3bd68e4342ff3e9a14c193ccf5e1801d17f39e4.


#!/opt/local/bin/php56
<?php
	$input = stream_get_contents(STDIN);

	$data = yaml_parse($input);

	if($data !== FALSE) {
		print_r($data);
		echo "\n";
	}
	else {
		echo "invalid YAML document\n";
	}
?>

#!/opt/local/bin/php56
<?php
	$input = stream_get_contents(STDIN);
	$line = explode("\n", $input);

	$i = 0;
	foreach($line as $l) {
		printf("%4d: %s\n", $i, $l);
		$i++;
	}

	$data = yaml_parse($input);

	if($data !== FALSE) {
		print_r($data);
		echo "\n";
	}
	else {
		echo "invalid YAML document\n";
	}
?>

Add line numbers to yams output

Add line numbers to yams output

The error message shows the line number that contains the error


<?php
/**
 * Plugin Name: E2E Tests Site Verification Plugin
 * Plugin URI:  https://github.com/google/site-kit-wp
 * Description: Utility plugin for bypassing site verification during E2E tests.
 * Author:      Google
 * Author URI:  https://opensource.google.com
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

/**
 * Fake a verified site state.
 */
add_filter(
	'get_user_option_googlesitekit_site_verified_meta',
	function () {
		return 'verified';
	}
);

<?php
/**
 * Plugin Name: E2E Tests Site Verification Plugin
 * Plugin URI:  https://github.com/google/site-kit-wp
 * Description: Utility plugin for bypassing site verification during E2E tests.
 * Author:      Google
 * Author URI:  https://opensource.google.com
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

/**
 * Fake a verified site state.
 * Verification checks for metadata existence so must filter get metadata instead of user option.
 * @see \metadata_exists
 */
add_filter(
	'get_user_metadata',
	function ( $null, $object_id, $meta_key ) {
		if (
			preg_match( '/googlesitekit_site_verified_meta$/', $meta_key )
			&& get_current_user_id() === $object_id
		) {
			return '1';
		}
		return $null;
	},
	10,
	3
);

Update e2e site verification plugin.

Update e2e site verification plugin.


<?php

use mageekguy\atoum\reports;

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

$travis = getenv('TRAVIS');

if ($travis)
{
	$script->addDefaultReport();

	$coverallsToken = getenv('COVERALLS_REPO_TOKEN');

	if ($coverallsToken)
	{
		$coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken);

		$defaultFinder = $coverallsReport->getBranchFinder();

		$coverallsReport
			->setBranchFinder(function() use ($defaultFinder) {
					if (($branch = getenv('TRAVIS_BRANCH')) === false)
					{
						$branch = $defaultFinder();
					}

					return $branch;
				}
			)
			->setServiceName('travis-ci')
			->setServiceJobId(getenv('TRAVIS_JOB_ID'))
			->addDefaultWriter()
		;

		$runner->addReport($coverallsReport);
	}
}

<?php

use mageekguy\atoum\reports;

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

$travis = getenv('TRAVIS');

if ($travis)
{
	$script->addDefaultReport();

	$coverallsToken = getenv('COVERALLS_REPO_TOKEN');

	if ($coverallsToken)
	{
		$coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken);

		$defaultFinder = $coverallsReport->getBranchFinder();

		$coverallsReport
			->setBranchFinder(function() use ($defaultFinder) {
					if (($branch = getenv('TRAVIS_BRANCH')) === false)
					{
						$branch = $defaultFinder();
					}

					return $branch;
				}
			)
			->setServiceName('travis-ci')
			->setServiceJobId(getenv('TRAVIS_JOB_ID'))
			->addDefaultWriter()
		;

		$runner->addReport($coverallsReport);
	}
}

Update source directory in coveralls configuration.


<?php namespace VotingApp\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

class Setting extends Model
{

    public static function boot()
    {
        parent::boot();

        static::updating(function ($setting) {
            if (Cache::has('settings.' . $setting->key)) {
                Cache::forget('settings.' . $setting->key);
            }
        });
    }

    /**
     * Primary key used to reference this model in the DB.
     */
    protected $primaryKey = 'key';

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = ['key', 'value'];

    /**
     * Save a file, and store the path.
     * @param \Symfony\Component\HttpFoundation\File\File $file
     */
    public function saveFile($file)
    {
        $path = public_path('images/settings');

        // Create directory if it doesn't exist
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $filename = $this->key . '.' . $file->getExtension();
        $file->move($path, $filename);

        $this->value = 'images/settings/' . $filename;
    }

}

<?php namespace VotingApp\Models;

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Cache;

class Setting extends Model
{

    public static function boot()
    {
        parent::boot();

        static::updating(function ($setting) {
            if (Cache::has('settings.' . $setting->key)) {
                Cache::forget('settings.' . $setting->key);
            }
        });
    }

    /**
     * Primary key used to reference this model in the DB.
     */
    protected $primaryKey = 'key';

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = ['key', 'value'];

    /**
     * Save a file, and store the path.
     * @param File|UploadedFile $file
     */
    public function saveFile($file)
    {
        $path = public_path('images/settings');

        // Create directory if it doesn't exist
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        // Get extension
        if ($file instanceof UploadedFile) {
            $extension = $file->getClientOriginalExtension();
        } else {
            $extension = $file->getExtension();
        }

        $filename = $this->key . '.' . $extension;
        $file->move($path, $filename);

        $this->value = 'images/settings/' . $filename;
    }

}

Handle difference between File and UploadedFile APIs.


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace AppBundle\Service;

/**
 * Description of Extrait
 *
 * @author Human Booster
 */
class ExtraitWithLink {

    private $router, $max;

    public function __construct(\Symfony\Component\Routing\RouterInterface $router, $max) {
        $this->router = $router;
        $this->max = $max;
    }

    function get(\AppBundle\Entity\Article $article) {
        $texte = strip_tags($article->getContenu());

        if (strlen($texte) > $this->max) {
            $texte = substr($texte, 0, $this->max);
            $texte = substr($texte, 0, strrpos($texte, ' '));

            $url = $this->router->generate('blog_detail', ['id' => $article->getId()]);
            $texte .= 'Lire la suite';
        }
        return $texte;
    }

}

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace AppBundle\Service;

/**
 * Description of Extrait
 *
 * @author Human Booster
 */
class ExtraitWithLink {

    private $router, $max;

    public function __construct(\Symfony\Component\Routing\Router $router, $max) {
        $this->router = $router;
        $this->max = $max;
    }

    function get(\AppBundle\Entity\Article $article) {
        $texte = strip_tags($article->getContenu());

        if (strlen($texte) > $this->max) {
            $texte = substr($texte, 0, $this->max);
            $texte = substr($texte, 0, strrpos($texte, ' '));

            $url = $this->router->generate('blog_detail', ['id' => $article->getId()]);
            $texte .= 'Lire la suite';
        }
        return $texte;
    }

}

Revert "Mardi 4 Juillet, Matin 1: Correction depreciation"

This reverts commit 3f4f94057631c9cbea5f3a0fe4acbe996c1bf409.


<?php

namespace Neves\Events;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;

class EventServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../../config/transactional-events.php',
            'transactional-events'
        );

        if (! $this->app['config']->get('transactional-events.enable')) {
            return;
        }

        $connectionResolver = $this->app->make('db');
        $eventDispatcher = $this->app->make(EventDispatcher::class);
        $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
            $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
            $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
            $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));

            return $dispatcher;
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = app()->basePath().'/config';

        $this->publishes([
            __DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php',
        ]);
    }
}

<?php

namespace Neves\Events;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;

class EventServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../../config/transactional-events.php',
            'transactional-events'
        );

        if (! $this->app['config']->get('transactional-events.enable')) {
            return;
        }

        $connectionResolver = $this->app->make('db');
        $eventDispatcher = $this->app->make(EventDispatcher::class);
        $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
            $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
            $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
            $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));

            return $dispatcher;
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = $this->app->basePath().'/config';

        $this->publishes([
            __DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php',
        ]);
    }
}

Replace app() helper with the instance

Replace app() helper with the instance


<?php

namespace CachetHQ\Segment;

use Illuminate\Support\ServiceProvider;

class SegmentServiceProvider extends ServiceProvider
{
    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

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

<?php

namespace CachetHQ\Segment;

use Illuminate\Support\ServiceProvider;
use Segment;

class SegmentServiceProvider extends ServiceProvider
{
    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('cachethq/segment');

        /**
         * Load the Segment.io configuration.
         */
        $writeKey = $this->app->config->get('segment::config.write_key');
        Segment::init($writeKey);
    }

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

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array();
    }
}

Call Segment::init from the service provider


<?php

namespace Brick\Form\Element\Input;

use Brick\Form\Attribute\CheckedAttribute;
use Brick\Form\Attribute\RequiredAttribute;
use Brick\Form\Attribute\ValueAttribute;
use Brick\Form\Element\Input;

/**
 * Represents a checkbox input element.
 */
class Checkbox extends Input
{
    use CheckedAttribute;
    use RequiredAttribute;
    use ValueAttribute;

    /**
     * {@inheritdoc}
     */
    protected function getType()
    {
        return 'checkbox';
    }

    /**
     * {@inheritdoc}
     */
    protected function doPopulate($value)
    {
        $this->setChecked($value === $this->getValue());
    }
}

<?php

namespace Brick\Form\Element\Input;

use Brick\Form\Attribute\CheckedAttribute;
use Brick\Form\Attribute\RequiredAttribute;
use Brick\Form\Attribute\ValueAttribute;
use Brick\Form\Element\Input;

/**
 * Represents a checkbox input element.
 */
class Checkbox extends Input
{
    use CheckedAttribute;
    use RequiredAttribute;
    use ValueAttribute;

    /**
     * {@inheritdoc}
     */
    protected function getType()
    {
        return 'checkbox';
    }

    /**
     * {@inheritdoc}
     */
    protected function doPopulate($value)
    {
        $thisValue = $this->getValueOrNull();

        if ($thisValue === null) {
            $thisValue = 'on';
        }

        $this->setChecked($value === $thisValue);
    }
}

Support checkboxes with no value specified


<?php namespace ProcessWire\GraphQL\Type;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Cache;

class UserType
{
  public static $name = 'User';

  public static $description = 'ProcessWire User.';

  public static function type()
  {
    return Cache::type(self::$name, function () {
      return new ObjectType([
        'name' => self::$name,
        'description' => self::$description,
        'fields' => [
          'name' => [
            'type' => Type::nonNull(Type::string()),
            'description' => "The user's login name.",
          ],
          'email' => [
            'type' => Type::nonNull(Type::string()),
            'description' => "The user's email address.",
          ],
          'id' => [
            'type' => Type::nonNull(Type::id()),
            'description' => "The user's id.",
          ],
        ]
      ]);
    });
  }
}

<?php namespace ProcessWire\GraphQL\Type;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Cache;
use ProcessWire\GraphQL\Type\Fieldtype\FieldtypeEmail;

class UserType
{
  public static $name = 'User';

  public static $description = 'ProcessWire User.';

  public static function type()
  {
    return Cache::type(self::$name, function () {
      return new ObjectType([
        'name' => self::$name,
        'description' => self::$description,
        'fields' => [
          'name' => [
            'type' => Type::nonNull(Type::string()),
            'description' => "The user's login name.",
          ],
          'email' => [
            'type' => FieldtypeEmail::type(),
            'description' => "The user's email address.",
          ],
          'id' => [
            'type' => Type::nonNull(Type::id()),
            'description' => "The user's id.",
          ],
        ]
      ]);
    });
  }
}

Use Email type for `$user->email` field.


<?php

declare(strict_types = 1);

namespace LotGD\Core\Console\Command;

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

use LotGD\Core\Console\Main;

class ConsoleCommand extends Command
{
    protected function configure()
    {
        $this->setName('console')
             ->setDescription('Start a shell to interact with the game.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $g = Main::createGame();

        $boris = new \Boris\Boris('🐲> ');
        $boris->setLocal(array(
            'g' => $g
        ));
        $boris->start();
    }
}

<?php

declare(strict_types = 1);

namespace LotGD\Core\Console\Command;

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

use LotGD\Core\Console\Main;

class ConsoleCommand extends Command
{
    protected function configure()
    {
        $this->setName('console')
             ->setDescription('Start a shell to interact with the game.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $g = Main::createGame();

        print("Daenerys console, the dragon prompt. lotgd/core " . \LotGD\Core\Game::getVersion() . ".\n");
        print("Enter some PHP, but be careful, this is live and attached to your currently configured setup:\n\n");
        print($g->getConfiguration());

        print("\n");
        print("Try things like `\$g::getVersion()`. To quit, ^D or `exit();`.\n");
        print("\n");

        $boris = new \Boris\Boris('🐲  > '); // For some reason we need the extra spaces.
        $boris->setLocal(array(
            'g' => $g
        ));
        $boris->start();
    }
}

Add some help to the daenerys console command.


<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter;

/**
 * Handle the dialog with an Adapter
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
interface AdapterInterface
{
    /**
     * Get the Calendar API to use for this adapter
     *
     * @return CalendarApiInterface
     */
    public function getCalendarApi();

    /**
     * Get the Event API to use for this adapter (scoped to a particular calendar)
     *
     * @param Calendar $calendar Calendar to scope this api to
     *
     * @return EventApiInterface
     */
    public function getEventApi(Calendar $calendar);
}

<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter;

use CalendArt\Calendar;

/**
 * Handle the dialog with an Adapter
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
interface AdapterInterface
{
    /**
     * Get the Calendar API to use for this adapter
     *
     * @return CalendarApiInterface
     */
    public function getCalendarApi();

    /**
     * Get the Event API to use for this adapter (scoped to a particular calendar)
     *
     * @param Calendar $calendar Calendar to scope this api to
     *
     * @return EventApiInterface
     */
    public function getEventApi(Calendar $calendar);
}

Connect the GoogleAdapter with the EventApi


<?php

class SyntaxErrorTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException FluxBB\CommonMark\Exception\SyntaxError
     * @expectedExceptionMessage [link] Unable to find id "id" in Reference-style link at line 3
     */
    public function testSyntaxErrorPointsRightLineNumber()
    {
        $md = new \FluxBB\CommonMark\Parser();
        $md->render(<<< EOL
This is a paragraph

This is a [paragraph][id].

<pre>
preformatted text
</pre>
EOL
, array('strict' => true)
);
    }

}

<?php

class SyntaxErrorTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException FluxBB\CommonMark\Exception\SyntaxError
     * @expectedExceptionMessage [link] Unable to find id "id" in Reference-style link at line 3
     */
    public function testSyntaxErrorPointsRightLineNumber()
    {
        $parser = new \FluxBB\CommonMark\DocumentParser();

        $markdown = <<< EOL
This is a paragraph

This is a [paragraph][id].

<pre>
preformatted text
</pre>
EOL;

        $parser->convert($markdown);
    }

}

Update test to work with latest classes.


Set to false for now.

Set to false for now.


<?php
namespace tpl;

require_once('centerContent.tpl.php');

function passwordSuccessfullyChangedMessage() {
    $title = 'Password Changed';

    $centerContent = <<<ENDTPL

Your password has been successfully changed.

ENDTPL;

    return centerContent($title, $centerContent);
}

<?php
namespace tpl;

require_once('centerContent.tpl.php');

function passwordSuccessfullyChangedMessage() {
    $title = 'Password Changed';

    $centerContent = <<<ENDTPL

Your password has been successfully changed.

You may now return to the site and log in with your new password.

ENDTPL;

    return centerContent($title, $centerContent);
}

Add extra line to password changed message.


<?php

namespace Frontend\Modules\Tags\Actions;

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

use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Modules\Tags\Engine\Model as FrontendTagsModel;

/**
 * This is the index-action
 */
class Index extends FrontendBaseBlock
{
    /**
     * List of tags
     *
     * @var array
     */
    private $tags = [];

    public function execute(): void
    {
        $this->loadTemplate();
        $this->getData();
        $this->parse();
    }

    private function getData(): void
    {
        $this->tags = FrontendTagsModel::getAll();
    }

    private function parse(): void
    {
        // make tags available
        $this->template->assign('tags', $this->tags);

        // tag-pages don't have any SEO-value, so don't index them
        $this->header->addMetaData(['name' => 'robots', 'content' => 'noindex, follow'], true);
    }
}

<?php

namespace Frontend\Modules\Tags\Actions;

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

use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Modules\Tags\Engine\Model as FrontendTagsModel;

class Index extends FrontendBaseBlock
{
    /**
     * List of tags
     *
     * @var array
     */
    private $tags = [];

    public function execute(): void
    {
        $this->loadTemplate();
        $this->getData();
        $this->parse();
    }

    private function getData(): void
    {
        $this->tags = FrontendTagsModel::getAll();
    }

    private function parse(): void
    {
        $this->template->assign('tags', $this->tags);

        // tag-pages don't have any SEO-value, so don't index them
        $this->header->addMetaData(['name' => 'robots', 'content' => 'noindex, follow'], true);
    }
}

Clean up the tags index action

Clean up the tags index action


<?php

namespace KeenIO\Http\Adaptor;

use Buzz\Browser;

/**
 * Class Buzz
 * @package KeenIO\Http\Adaptor
 */
final class Buzz implements AdaptorInterface
{

    private $apiKey;
    private $browser;

    /**
     * @param $apiKey
     * @param null $client
     */
    public function __construct($apiKey, $client = null)
    {
        $this->apiKey = $apiKey;

        if (!$client) {
            $client = new Browser();
        }

        $this->browser = $client;
    }

    /**
     * post to the KeenIO API
     *
     * @param $url
     * @param array $parameters
     * @return mixed
     */
    public function doPost($url, array $parameters)
    {
        $headers = array(
            'Authorization' => $this->apiKey,
            'Content-Type' => 'application/json'
        );

        $content = json_encode($parameters);

        $response = $this->browser->post($url, $headers, $content);

        return $response->getContent();
    }
}

<?php

namespace KeenIO\Http\Adaptor;

use Buzz\Browser;
use Buzz\Client\Curl;

/**
 * Class Buzz
 * @package KeenIO\Http\Adaptor
 */
final class Buzz implements AdaptorInterface
{

    private $apiKey;
    private $browser;

    /**
     * @param $apiKey
     * @param null $client
     */
    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
        $this->browser = new Browser(new Curl());
    }

    /**
     * post to the KeenIO API
     *
     * @param $url
     * @param array $parameters
     * @return mixed
     */
    public function doPost($url, array $parameters)
    {
        $headers = array(
            'Authorization' => $this->apiKey,
            'Content-Type' => 'application/json'
        );

        $content = json_encode($parameters);

        $response = $this->browser->post($url, $headers, $content);

        return $response->getContent();
    }
}

Use curl instead of file_get_contents

Use curl instead of file_get_contents


<?php namespace Modules\Setting\Providers;

use Modules\Core\Providers\RoutingServiceProvider as CoreRoutingServiceProvider;

class RouteServiceProvider extends CoreRoutingServiceProvider
{
    /**
     * The root namespace to assume when generating URLs to actions.
     * @var string
     */
    protected $namespace = 'Modules\Setting\Http\Controllers';

    /**
     * @return string
     */
    protected function getFrontendRoute()
    {
        return false;
    }

    /**
     * @return string
     */
    protected function getBackendRoute()
    {
        return __DIR__ . '/../Http/backendRoutes.php';
    }
}

<?php namespace Modules\Setting\Providers;

use Modules\Core\Providers\RoutingServiceProvider as CoreRoutingServiceProvider;

class RouteServiceProvider extends CoreRoutingServiceProvider
{
    /**
     * The root namespace to assume when generating URLs to actions.
     * @var string
     */
    protected $namespace = 'Modules\Setting\Http\Controllers';

    /**
     * @return string
     */
    protected function getFrontendRoute()
    {
        return false;
    }

    /**
     * @return string
     */
    protected function getBackendRoute()
    {
        return __DIR__ . '/../Http/backendRoutes.php';
    }

    /**
     * @return string
     */
    protected function getApiRoute()
    {
        return false;
    }
}

Add the net ApiRoutes method

Add the net ApiRoutes method


<?php
/**
 * Copyright (c) 2016 RhubarbPHP.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Rhubarb\Crown\Tests\unit\String;

use Rhubarb\Crown\String\Template;
use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase;

class TemplateTest extends RhubarbTestCase
{
    public function testTemplateParsing()
    {
        $plainTextTemplate = "Nothing in here to parse";

        $this->assertEquals($plainTextTemplate, Template::parseTemplate($plainTextTemplate, []));

        $template = "Ah something to process! {Forename}";

        $this->assertEquals(
            "Ah something to process! Andrew",
            Template::parseTemplate($template, ["Forename" => "Andrew"])
        );

        $template = "Something to parse, but that you can't parse, because there is no data";

        $this->assertEquals(
            $template, Template::parseTemplate($template, [])
        );
    }
}

<?php
/**
 * Copyright (c) 2016 RhubarbPHP.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Rhubarb\Crown\Tests\unit\String;

use Rhubarb\Crown\String\Template;
use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase;

class TemplateTest extends RhubarbTestCase
{
    public function testTemplateParsing()
    {
        $plainTextTemplate = "Nothing in here to parse";

        $this->assertEquals($plainTextTemplate, Template::parseTemplate($plainTextTemplate, []));

        $template = "Ah something to process! {Forename}";

        $this->assertEquals(
            "Ah something to process! Andrew",
            Template::parseTemplate($template, ["Forename" => "Andrew"])
        );

        $template = "Something to parse, but that you can't parse, because there is no {data}";

        $this->assertEquals(
            $template, Template::parseTemplate($template, [])
        );
    }
}

Make sure that we're testing properly

Make sure that we're testing properly


<?php

namespace Zizaco\FactoryMuff\Kind;

use Zizaco\FactoryMuff\Kind;

class Integer extends Kind
{
  public function generate()
  {
    $length = substr($this->kind, 8);
    $faker = \Faker\Factory::create();
    return $faker->randomNumber($length);
  }
}

<?php

namespace Zizaco\FactoryMuff\Kind;

use Zizaco\FactoryMuff\Kind;

class Integer extends Kind
{
  public function generate()
  {
    $length = (int) $this->getOption(0, 5);
    $faker = \Faker\Factory::create();
    return $faker->randomNumber($length);
  }
}

Use getOption to get length for integer (with default)


<?php
//paths
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');

require_once(INC_PATH.'environment_setup.php');

if(ENV_CURRENT === ENV_DEV){
	define('BASE_URL','/folder_name/public_html/');
}

define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

<?php
//paths
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');

require_once(INC_PATH.'environment_setup.php');

//urls
define('BASE_URL','/');

define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

Edit base url to use root relative urls

Edit base url to use root relative urls


<?php

/*
 * Copyright (c) 2016 Refinery29, Inc.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Refinery29\Test\Util\DataProvider;

trait DataProviderTrait
{
    /**
     * @param array $values
     *
     * @return \Generator
     */
    public function provideData(array $values)
    {
        foreach ($values as $value) {
            yield [
                $value,
            ];
        }
    }
}

<?php

/*
 * Copyright (c) 2016 Refinery29, Inc.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Refinery29\Test\Util\DataProvider;

trait DataProviderTrait
{
    /**
     * @param array $values
     *
     * @return \Generator
     */
    protected function provideData(array $values)
    {
        foreach ($values as $value) {
            yield [
                $value,
            ];
        }
    }
}

Fix: Reduce visibility of provideData from public to protected


<?php

namespace CachetHQ\Cachet\Http\Controllers;

use CachetHQ\Cachet\Models\Component;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\View;

class DashboardController extends Controller
{
    /**
     * Shows the dashboard view.
     *
     * @return \Illuminate\View\View
     */
    public function showDashboard()
    {
        // TODO: Find steps needed to complete setup.
        $components = Component::all();

        return View::make('dashboard.index')->with([
            'components' => $components,
        ]);
    }

    /**
     * Shows the metrics view.
     *
     * @return \Illuminate\View\View
     */
    public function showMetrics()
    {
        return View::make('dashboard.metrics.index')->with([
            'pageTitle' => trans('dashboard.metrics.metrics').' - '.trans('dashboard.dashboard'),
        ]);
    }

    /**
     * Shows the notifications view.
     *
     * @return \Illuminate\View\View
     */
    public function showNotifications()
    {
        return View::make('dashboard.notifications.index')->with([
            'pageTitle' => trans('dashboard.notifications.notifications').' - '.trans('dashboard.dashboard'),
        ]);
    }
}

<?php

namespace CachetHQ\Cachet\Http\Controllers;

use CachetHQ\Cachet\Models\Component;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\View;

class DashboardController extends Controller
{
    /**
     * Shows the dashboard view.
     *
     * @return \Illuminate\View\View
     */
    public function showDashboard()
    {
        $components = Component::all();

        return View::make('dashboard.index')->with([
            'components' => $components,
        ]);
    }

    /**
     * Shows the metrics view.
     *
     * @return \Illuminate\View\View
     */
    public function showMetrics()
    {
        return View::make('dashboard.metrics.index')->with([
            'pageTitle' => trans('dashboard.metrics.metrics').' - '.trans('dashboard.dashboard'),
        ]);
    }

    /**
     * Shows the notifications view.
     *
     * @return \Illuminate\View\View
     */
    public function showNotifications()
    {
        return View::make('dashboard.notifications.index')->with([
            'pageTitle' => trans('dashboard.notifications.notifications').' - '.trans('dashboard.dashboard'),
        ]);
    }
}

Remove TODO about steps, coming soon!

Remove TODO about steps, coming soon!


<?php

/**
 * @project: Intern Portal.
 * @author: nkmathew
 * @date: 20/06/2016
 * @time: 17:09
 */

/* @var $this yii\web\View */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

?>

        Update your profile below

            <?php $form = ActiveForm::begin(['action' => '/site/profile', 'id' => 'profile-form']); ?>
            <?= $form->field($model, 'firstName')->textInput(['autofocus' => true]) ?>
            <?= $form->field($model, 'surname') ?>
            <?= $form->field($model, 'email') ?>
            <?= $form->field($model, 'sex')->dropDownList(['Male', 'Female', 'Other']); ?>

                <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

            <?php ActiveForm::end(); ?>

<?php

/**
 * @project: Intern Portal.
 * @author: nkmathew
 * @date: 20/06/2016
 * @time: 17:09
 */

/* @var $this yii\web\View */
/* @var $model app\models\Profile */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

?>

        Update your profile below

            <?= var_dump($profile); ?>
            <?php $form = ActiveForm::begin(['action' => '/site/profile', 'id' => 'profile-form']); ?>
            <?= $form->field($model, 'firstName')->textInput(['autofocus' => true, 'value' => $model->firstName]) ?>
            <?= $form->field($model, 'surname')->textInput(['value' => $model->surname]) ?>
            <?= $form->field($model, 'email')->textInput(['readonly' => true, 'value' => $model->email])  ?>
            <?= $form->field($model, 'sex')->dropDownList(['Male', 'Female', 'Other']); ?>

                <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

            <?php ActiveForm::end(); ?>

Add default values for form fields

Add default values for form fields


<?php

/**
 * These are the test for the core files.
 *
 * @package Open Source Evangelist Agnostic Package
 * @author Surajudeen AKANDE <surajudeen.akande@andela.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 * @link http://www.github.com/andela-sakande
 */
namespace Sirolad\Evangelist\Test;

use Sirolad\Evangelist\EvangelistStatus;

/*
* EvangelistStatusTest is the test for the EvangelistStatus Class.
 */
class EvangelistStatusTest extends \PHPUnit_Framework_TestCase
{
    //class property
    protected $statustest;

    //instantiate the EvangelistStatus Class with argument
    public function setUp()
    {
        $this->statustest = new EvangelistStatus(2345678);
    }

    //destroy the EvangelistStatus Class
    public function tearDown()
    {
        unset($this->statustest);
    }

    /*
    * Test for less string output.
     */
    public function testStatusOutput()
    {
        $this->assertTrue(is_string($this->statustest->getStatus()));
    }
}

<?php

/**
 * These are the test for the core files.
 *
 * @package Open Source Evangelist Agnostic Package
 * @author Surajudeen AKANDE <surajudeen.akande@andela.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 * @link http://www.github.com/andela-sakande
 */
namespace Sirolad\Evangelist\Test;

use Sirolad\Evangelist\EvangelistStatus;

/*
* EvangelistStatusTest is the test for the EvangelistStatus Class.
 */
class EvangelistStatusTest extends \PHPUnit_Framework_TestCase
{
    //class property
    protected $statustest;

    //instantiate the EvangelistStatus Class with argument
    public function setUp()
    {
        $this->statustest = new EvangelistStatus(2345678);
    }

    //destroy the EvangelistStatus Class
    public function tearDown()
    {
        unset($this->statustest);
    }

    /*
    * Test for less string output.
     */
    public function testStatusOutput()
    {
        $this->assertInternalType('string', $this->statustest->getStatus());
    }
}

Use assertInternalType instead of assertTrue


<?php namespace Illuminate\Contracts\Validation;

interface Factory {

	/**
	 * Create a new Validator instance.
	 *
	 * @param  array  $data
	 * @param  array  $rules
	 * @param  array  $messages
	 * @param  array  $customAttributes
	 * @return \Illuminate\Contracts\Validation\Validator
	 */
	public function make(array $data, array $rules, array $messages = array(), array $customAttributes = array());

}

<?php namespace Illuminate\Contracts\Validation;

interface Factory {

	/**
	 * Create a new Validator instance.
	 *
	 * @param  array  $data
	 * @param  array  $rules
	 * @param  array  $messages
	 * @param  array  $customAttributes
	 * @return \Illuminate\Contracts\Validation\Validator
	 */
	public function make(array $data, array $rules, array $messages = array(), array $customAttributes = array());

	/**
	 * Register a custom validator extension.
	 *
	 * @param  string  $rule
	 * @param  \Closure|string  $extension
	 * @param  string  $message
	 * @return void
	 */
	public function extend($rule, $extension, $message = null);

	/**
	 * Register a custom implicit validator extension.
	 *
	 * @param  string   $rule
	 * @param  \Closure|string  $extension
	 * @param  string  $message
	 * @return void
	 */
	public function extendImplicit($rule, $extension, $message = null);

	/**
	 * Register a custom implicit validator message replacer.
	 *
	 * @param  string   $rule
	 * @param  \Closure|string  $replacer
	 * @return void
	 */
	public function replacer($rule, $replacer);

}

Add methods to the validation factory contract.


<?php

namespace Illuminate\Database\Schema;

class MySqlBuilder extends Builder
{
    /**
     * Determine if the given table exists.
     *
     * @param  string  $table
     * @return bool
     */
    public function hasTable($table)
    {
        $sql = $this->grammar->compileTableExists();

        $database = $this->connection->getDatabaseName();

        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select($sql, [$database, $table])) > 0;
    }

    /**
     * Get the column listing for a given table.
     *
     * @param  string  $table
     * @return array
     */
    public function getColumnListing($table)
    {
        $sql = $this->grammar->compileColumnListing();

        $database = $this->connection->getDatabaseName();

        $table = $this->connection->getTablePrefix().$table;

        $results = $this->connection->select($sql, [$database, $table]);

        return $this->connection->getPostProcessor()->processColumnListing($results);
    }
}

<?php

namespace Illuminate\Database\Schema;

class MySqlBuilder extends Builder
{
    /**
     * Determine if the given table exists.
     *
     * @param  string  $table
     * @return bool
     */
    public function hasTable($table)
    {
        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select(
            $this->grammar->compileTableExists(), [$this->connection->getDatabaseName(), $table]
        )) > 0;
    }

    /**
     * Get the column listing for a given table.
     *
     * @param  string  $table
     * @return array
     */
    public function getColumnListing($table)
    {
        $table = $this->connection->getTablePrefix().$table;

        $results = $this->connection->select(
            $this->grammar->compileColumnListing(), [$this->connection->getDatabaseName(), $table]
        );

        return $this->connection->getPostProcessor()->processColumnListing($results);
    }
}

Work on MySQL schema builder.

Work on MySQL schema builder.


<?php
/**
 * @author Jean Silva <me@jeancsil.com>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Validator;

use Jeancsil\FlightSpy\Command\Entity\Parameter;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Input\InputInterface;

class CommandLineParameterValidator implements ValidatorInterface
{
    /**
     * @var InputInterface
     */
    private $input;

    /**
     * @param $instance
     * @return $this
     */
    public function setTarget($instance)
    {
        if (!$instance instanceof InputInterface) {
            throw new \LogicException(
                sprintf('$instance must be instance of InputInterface. %s given', $instance)
            );
        }

        $this->input = $instance;

        return $this;
    }

    /**
     * TODO validate all fields
     * @throw ValidationException
     */
    public function validate()
    {
        $configFile = $this->input->getOption(Parameter::FILE);
        $from = $this->input->getOption(Parameter::FROM);
        $to = $this->input->getOption(Parameter::TO);
        $departureDate = $this->input->getOption(Parameter::DEPARTURE_DATE);
        $returnDate = $this->input->getOption(Parameter::RETURN_DATE);
        $maxPrice = $this->input->getOption(Parameter::MAX_PRICE);

        if ($configFile && file_exists($configFile)) {
            return; // TODO validate file content
            //throw new \InvalidArgumentException(sprintf('File not found: %s', $configFile));
        }

        $options = [
            '--from' => $from,
            '--to' => $to,
            '--departure' => $departureDate,
            '--arrival' => $returnDate,
            '--max-price' => $maxPrice
        ];

        foreach ($options as $longForm => $option) {
            if (!$option) {
                throw new InvalidOptionException("Option $longForm not defined");
            }
        }
    }
}

<?php
/**
 * @author Jean Silva <me@jeancsil.com>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Validator;

use Jeancsil\FlightSpy\Command\Entity\Parameter;
use Symfony\Component\Console\Input\InputInterface;

class CommandLineParameterValidator implements ValidatorInterface
{
    /**
     * @var InputInterface
     */
    private $input;

    /**
     * @param $instance
     * @return $this
     */
    public function setTarget($instance)
    {
        if (!$instance instanceof InputInterface) {
            throw new \LogicException(
                sprintf('$instance must be instance of InputInterface. %s given', $instance)
            );
        }

        $this->input = $instance;

        return $this;
    }

    /**
     * @throw ValidationException
     */
    public function validate()
    {
        $configFile = $this->input->getOption(Parameter::FILE);

        if (!$configFile || !file_exists($configFile)) {
            throw new \InvalidArgumentException(sprintf('File not found: %s', $configFile));
        }
    }
}

Remove old parameters. Only supporting now --file.