<?php
/**
 * @author @fabfuel <fabian@fabfuel.de>
 * @created 14.11.14, 08:39
 */
namespace Fabfuel\Prophiler\Plugin\Phalcon\Db;

use Fabfuel\Prophiler\Benchmark\BenchmarkInterface;
use Fabfuel\Prophiler\Plugin\PluginAbstract;
use Phalcon\Events\Event;
use Phalcon\Db\Adapter;

/**
 * Class Dispatcher
 * @package Rocket\Toolbar\Plugin
 */
class AdapterPlugin extends PluginAbstract
{
    /**
     * @var BenchmarkInterface
     */
    private $benchmark;

    /**
     * Start the query benchmark
     *
     * @param Event $event
     * @param Adapter $database
     */
    public function beforeQuery(Event $event, Adapter $database)
    {
        $metadata = [
            'query' => $database->getSQLStatement()
        ];

        $this->benchmark = $this->getProfiler()->start(get_class($event->getSource()) . '::query', $metadata, 'Database');
    }

    /**
     * Stop the query benchmark
     */
    public function afterQuery()
    {
        $this->getProfiler()->stop($this->benchmark);
    }
}

<?php
/**
 * @author @fabfuel <fabian@fabfuel.de>
 * @created 14.11.14, 08:39
 */
namespace Fabfuel\Prophiler\Plugin\Phalcon\Db;

use Fabfuel\Prophiler\Benchmark\BenchmarkInterface;
use Fabfuel\Prophiler\Plugin\PluginAbstract;
use Phalcon\Events\Event;
use Phalcon\Db\Adapter;

/**
 * Class AdapterPlugin
 */
class AdapterPlugin extends PluginAbstract
{
    /**
     * @var BenchmarkInterface
     */
    private $benchmark;

    /**
     * Start the query benchmark
     *
     * @param Event $event
     * @param Adapter $database
     */
    public function beforeQuery(Event $event, Adapter $database)
    {
        $metadata = [
            'query' => $database->getSQLStatement(),
            'params' => $database->getSQLVariables(),
            'bindtypes' => $database->getSQLBindTypes()
        ];
        $desc = $database->getDescriptor();
        if (isset($desc['dbname'])) {
            $metadata['database'] = $desc['dbname'];
        }

        $this->benchmark = $this->getProfiler()->start(get_class($event->getSource()) . '::query', $metadata, 'Database');
    }

    /**
     * Stop the query benchmark
     */
    public function afterQuery()
    {
        $this->getProfiler()->stop($this->benchmark);
    }
}

Add database, params and bindings in query


<?php

$context                = Timber::get_context();
$post                   = new TimberPost();
$context['post']        = $post;
$context['cancel_link'] = get_cancel_comment_reply_link(__('Cancel reply', 'base-camp'));

if (post_password_required($post->ID)) {
    Timber::render('single-password.twig', $context);
} else {
    Timber::render(['single-' . $post->ID . '.twig', 'single-' . $post->post_type . '.twig', 'single.twig'], $context);
}

<?php

$context                = Timber::get_context();
$post                   = new TimberPost();
$context['post']        = $post;
$context['cancel_link'] = get_cancel_comment_reply_link(__('Cancel reply', 'base-camp'));

if (post_password_required($post->ID)) {
    Timber::render('single-password.twig', $context);
} else {
    $post_type = $post->post_type === 'revision' ? get_post_type($post->post_parent)  : $post->post_type;
    Timber::render(['single-' . $post->ID . '.twig', 'single-' . $post_type . '.twig', 'single.twig'], $context);
}

Fix custom post type preview

Fix custom post type preview


<?php

namespace Tests\Feature;

use App\User;
use App\Space;
use App\Tag;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase {
    public function testUnauthorizedUserCantEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(403);
    }
}

<?php

namespace Tests\Feature;

use App\User;
use App\Space;
use App\Tag;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase {
    public function testAuthorizedUserCanEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $user->spaces()->sync([$space->id]);

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(200);
    }

    public function testUnauthorizedUserCantEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(403);
    }
}

Test authorized user's access to editing of tags


<?php
/**
 * Created by PhpStorm.
 * User: Bram
 * Date: 1-9-2017
 * Time: 06:59
 */

namespace Stormyy\B3\Helper;

use q3tool;
use Stormyy\B3\Models\B3Server;

abstract  class Cod4Server
{
    public static function getRcon(B3Server $server){

    }

    public static function screenshotAll(B3Server $server){
        $tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
        $response = $tool->send_rcon('getss all');
        return $response;
    }

    public static function screenshot(B3Server $server, $guid, $user=null){
        try {
            $filename = '';
            if ($user != null) {
                $filename = ' user-' . $user->id . '-';
            }

            $tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
            $response = $tool->send_rcon('getss ' . $guid . $filename);
            return $response;
        } catch (\Exception $exception){
            return response()->json([
                'code' => 'InvalidRcon',
                'message' => 'Invalid rcon try reloading the nehoscreenshotuploader plugin'
            ], 500);
        }
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Bram
 * Date: 1-9-2017
 * Time: 06:59
 */

namespace Stormyy\B3\Helper;

use q3tool;
use Stormyy\B3\Models\B3Server;

abstract  class Cod4Server
{
    public static function getRcon(B3Server $server){

    }

    public static function screenshotAll(B3Server $server){
        $tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
        $response = $tool->send_rcon('getss all');
        return $response;
    }

    public static function screenshot(B3Server $server, $guid, $user=null){
        try {
            $filename = '';
            if ($user != null) {
                $filename = ' user-' . $user->id . '-';
            }

            $tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
            $response = $tool->send_rcon('getss ' . $guid . $filename);

            if(str_contains($response, 'Bad rcon')){
                throw new \Exception('Bad rcon');
            }

            return $response;
        } catch (\Exception $exception){
            return response()->json([
                'code' => 'InvalidRcon',
                'message' => 'Invalid rcon try reloading the nehoscreenshotuploader plugin'
            ], 500);
        }
    }
}

Throw exception when bad rcon

Throw exception when bad rcon


<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use InvalidArgumentException;

/**
 * Logistic
 *
 * Linking implementation that transforms data into out and out of logistic
 * form.
 */
final class Logistic extends Linking
{
    public function delinearize(float $value): float
    {
        return 1.0 / (1.0 + exp(-$value));
    }

    public function linearize(float $value): float
    {
        if ($value <= 0 || $value >= 1) {
            throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
        }

        return -log(1.0 / $value - 1.0);
    }
}

<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use InvalidArgumentException;
use mcordingley\Regression\Gradient;
use mcordingley\Regression\Helpers;

/**
 * Logistic
 *
 * Linking implementation that transforms data into out and out of logistic
 * form.
 */
final class Logistic extends Linking implements Gradient
{
    public function delinearize(float $value): float
    {
        return 1.0 / (1.0 + exp(-$value));
    }

    public function linearize(float $value): float
    {
        if ($value <= 0 || $value >= 1) {
            throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
        }

        return -log(1.0 / $value - 1.0);
    }

    public function loss(CoefficientSet $coefficients, array $observations, float $outcome, int $index): float
    {
        $sumProduct = Helpers::sumProduct($coefficients->toArray(), $observations);
        $hypothesis = $this->delinearize($sumProduct);

        return ($outcome - $hypothesis) * $hypothesis * (1.0 - $hypothesis) * $observations[$i];
    }
}

Implement the L2 loss function for the logistic function.


<?php

namespace Korobi\WebBundle\Repository;

use Doctrine\ODM\MongoDB\DocumentRepository;

class ChannelRepository extends DocumentRepository {

    /**
     * @param $network
     * @return mixed
     */
    public function findAllByNetwork($network) {
        return $this->createQueryBuilder()
            ->sort('channel', 'ASC')
            ->field('network')
                ->equals($network)
            ->getQuery()
            ->execute();
    }

    /**
     * @param $network
     * @param $channel
     * @return mixed
     */
    public function findByChannel($network, $channel) {
        return $this->createQueryBuilder()
            ->sort('channel', 'ASC')
            ->field('network')
                ->equals($network)
            ->field('channel')
                ->equals(new \MongoRegex('/^' . $channel . '/i'))
            ->getQuery()
            ->execute();
    }
}

<?php

namespace Korobi\WebBundle\Repository;

use Doctrine\ODM\MongoDB\DocumentRepository;

class ChannelRepository extends DocumentRepository {

    /**
     * @param $network
     * @return mixed
     */
    public function findAllByNetwork($network) {
        return $this->createQueryBuilder()
            ->sort('channel', 'ASC')
            ->field('network')
                ->equals($network)
            ->getQuery()
            ->execute();
    }

    /**
     * @param $network
     * @param $channel
     * @return mixed
     */
    public function findByChannel($network, $channel) {
        return $this->createQueryBuilder()
            ->sort('channel', 'ASC')
            ->field('network')
                ->equals($network)
            ->field('channel')
                ->equals(new \MongoRegex('/^' . $channel . '/i'))
            ->getQuery()
            ->execute();
    }

    /**
     * @param int $limit Number of channels to grab.
     * @return array The public n last channels.
     */
    public function getRecentlyActiveChannels($limit) {
        return $this->createQueryBuilder()
            ->sort('last_activity', 'DESC')
            ->field('key')
            ->equals(null)
            ->limit($limit)
            ->getQuery()
            ->execute();
    }
}

Add function for getting last active channels


<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        $project_id = $querydata['id'];
        if (!isset($_SESSION)) {
            session_start();
        }
        $query_get_project_details = <<<EOF
SELECT project FROM full_webuser_data
    WHERE webuser_data_id = :project_id AND provider = :provider AND oauth_id = :oauth_id
EOF;
        $stm_get_project_details = $db->prepare($query_get_project_details);
        $stm_get_project_details->bindValue('project_id', $project_id);
        $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']);
        $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']);
        $stm_get_project_details->execute();

        while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) {
            $result[$project_id] = $row['project'];
        }
        return $result;
    }
}

<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        $ids = $querydata['ids'];
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        if (!isset($_SESSION)) {
            session_start();
        }
        $query_get_project_details = <<<EOF
SELECT webuser_data_id, project FROM full_webuser_data
    WHERE provider = ? AND oauth_id = ? AND webuser_data_id IN ($placeholders)
EOF;
        $stm_get_project_details = $db->prepare($query_get_project_details);
        $stm_get_project_details->execute(
            array_merge(array($_SESSION['user']['provider'], $_SESSION['user']['id']), $ids)
        );

        while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) {
            $result[$row['webuser_data_id']] = $row['project'];
        }
        return $result;
    }
}

Update webservice to use array of ids

Update webservice to use array of ids


<?php

declare(strict_types=1);

use Illuminate\Database\Seeder;

class CortexFoundationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $abilities = [
            ['name' => 'access-adminarea', 'title' => 'Access adminarea'],
            ['name' => 'access-managerarea', 'title' => 'Access managerarea'],

            ['name' => 'list', 'title' => 'List media', 'entity_type' => 'media'],
            ['name' => 'create', 'title' => 'Create media', 'entity_type' => 'media'],
            ['name' => 'update', 'title' => 'Update media', 'entity_type' => 'media'],
            ['name' => 'delete', 'title' => 'Delete media', 'entity_type' => 'media'],
        ];

        collect($abilities)->each(function (array $ability) {
            app('cortex.auth.ability')->create($ability);
        });
    }
}

<?php

declare(strict_types=1);

use Illuminate\Database\Seeder;

class CortexFoundationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $abilities = [
            ['name' => 'access-adminarea', 'title' => 'Access adminarea'],
            ['name' => 'access-managerarea', 'title' => 'Access managerarea'],

            ['name' => 'list', 'title' => 'List media', 'entity_type' => 'media'],
            ['name' => 'create', 'title' => 'Create media', 'entity_type' => 'media'],
            ['name' => 'update', 'title' => 'Update media', 'entity_type' => 'media'],
            ['name' => 'delete', 'title' => 'Delete media', 'entity_type' => 'media'],
        ];

        collect($abilities)->each(function (array $ability) {
            app('cortex.auth.ability')->firstOrCreate([
                'name' => $ability['name'],
                'entity_type' => $ability['entity_type'],
            ], $ability);
        });
    }
}

Check if ability exists before seeding

Check if ability exists before seeding


<?php
/**
 * @title          User API Ajax Class
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2013-2017, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / User / Asset / Ajax
 */
namespace PH7;
defined('PH7') or exit('Restricted access');

use PH7\Framework\Mvc\Request\Http;

class ApiAjax
{
    private $_oUser, $_mOutput;

    public function __construct()
    {
        $this->_oUser = new UserCore;
        $this->_init();
    }

    public function display()
    {
        return $this->_mOutput;
    }

    private function _init()
    {
        $oHttpRequest = new Http;
        $sParam = $oHttpRequest->post('param');
        $sType = $oHttpRequest->post('type');
        unset($oHttpRequest);

        switch($sType)
        {
            case 'profile_link':
                $this->_mOutput = $this->_oUser->getProfileLink($sParam);
            break;

            // If we receive another invalid value, we display a message with a HTTP header.
            default:
                Framework\Http\Http::setHeadersByCode(400);
            exit('Bad Request Error!');
        }
    }
}

echo (new ApiAjax)->display();

<?php
/**
 * @title          User API Ajax Class
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2013-2017, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / User / Asset / Ajax
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Mvc\Request\Http;

class ApiAjax
{
    /** @var UserCore */
    private $_oUser;

    /** @var mixed */
    private $mOutput;

    public function __construct()
    {
        $this->_oUser = new UserCore;
        $this->_init();
    }

    public function display()
    {
        return $this->mOutput;
    }

    private function _init()
    {
        $oHttpRequest = new Http;
        $sParam = $oHttpRequest->post('param');
        $sType = $oHttpRequest->post('type');
        unset($oHttpRequest);

        switch($sType) {
            case 'profile_link':
                $this->mOutput = $this->_oUser->getProfileLink($sParam);
                break;

            // If we receive another invalid value, we display a message with a HTTP header.
            default:
                Framework\Http\Http::setHeadersByCode(400);
                exit('Bad Request Error!');
        }
    }
}

echo (new ApiAjax)->display();

Fix indentation + remove underscore to private member


<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\VersionInfo;
use \BNETDocs\Models\Legal as LegalModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Controller;
use \CarlBennett\MVC\Libraries\Router;
use \CarlBennett\MVC\Libraries\View;
use \DateTime;
use \DateTimeZone;

class Legal extends Controller {

  public function &run(Router &$router, View &$view, array &$args) {

    $model                  = new LegalModel();
    $model->license         = file_get_contents("../LICENSE.txt");
    $model->license_version = VersionInfo::$version->bnetdocs[3];
    $model->license_version = explode(' ', $model->license_version);

    $model->license_version[1] = new DateTime(
      $model->license_version[1], new DateTimeZone('Etc/UTC')
    );

    $view->render($model);

    $model->_responseCode = 200;
    $model->_responseHeaders["Content-Type"] = $view->getMimeType();
    $model->_responseTTL = 0;

    return $model;

  }

}

<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\VersionInfo;
use \BNETDocs\Models\Legal as LegalModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Controller;
use \CarlBennett\MVC\Libraries\Router;
use \CarlBennett\MVC\Libraries\View;
use \DateTime;
use \DateTimeZone;

class Legal extends Controller {

  public function &run( Router &$router, View &$view, array &$args ) {

    $model                  = new LegalModel();
    $model->license         = file_get_contents( '../LICENSE.txt' );
    $model->license_version = VersionInfo::$version->bnetdocs[3];
    $model->license_version = explode( ' ', $model->license_version );

    $model->license_version[1] = new DateTime(
      $model->license_version[1], new DateTimeZone( 'Etc/UTC' )
    );

    $view->render( $model );

    $model->_responseCode = 200;
    $model->_responseHeaders[ 'Content-Type' ] = $view->getMimeType();
    $model->_responseTTL = 0;

    return $model;

  }

}

Improve readability of source file

Improve readability of source file


@extends('clearboard.main.template')

@section('title', '404 Not Found')

@section('content')

404 Not Found

The page you requested doesn't exist.

Goto the homepage

@endsection

@extends('clearboard.main.template')

@section('title', '404 Not Found')

@section('content')

404 Not Found

The page you requested doesn't exist.

Goto the homepage

Go back

@endsection

Add go back link to 404 page

Add go back link to 404 page


<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP shortcode
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */
abstract class WPshortcode implements WPhook
{

  protected $slug;

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

  public function register()
  {
    add_shortcode( $this->slug, array($this,'callback') );
  }

  public function remove()
  {
    remove_shortcode($this->slug);
  }

  abstract public function callback();

}

<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP shortcode
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */
class WPshortcode extends WPaction
{
  protected $slug;
  protected $view;

  public function __construct($shortcode, View $view)
  {
    $this->slug = $shortcode;
    $this->view = $view;

    parent::__construct('init');
  }

  public function action()
  {
    add_shortcode( $this->slug, array($this,'callback') );
  }

  public function callback()
  {
    return $this->view->getContent();
  }
}

Improve shortcode support using view and WPaction


<?php

class Category extends Elegant
{
    protected $table = 'categories';
    protected $softDelete = true;

    /**
    * Category validation rules
    */
    public $rules = array(
        'user_id' => 'numeric',
        'name'   => 'required|alpha_dash|min:3|max:255|unique:categories,name,{id}',
    );

    public function has_models()
    {
        return $this->hasMany('Model', 'category_id')->count();
    }

    public function models()
    {
        return $this->hasMany('Model', 'category_id');

    }

}

<?php

class Category extends Elegant
{
    protected $table = 'categories';
    protected $softDelete = true;

    /**
    * Category validation rules
    */
    public $rules = array(
        'user_id' => 'numeric',
        'name'   => 'required|alpha_space|min:3|max:255|unique:categories,name,{id}',
    );

    public function has_models()
    {
        return $this->hasMany('Model', 'category_id')->count();
    }

    public function models()
    {
        return $this->hasMany('Model', 'category_id');

    }

}

Allow spaces in category name

Allow spaces in category name


<?php
class Af_SomethingPositive extends Plugin {

    function about() {
        return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik");

    }
    function init($host) {
        $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
    }

    function hook_article_filter($article) {
        $owner_uid = $article["owner_uid"];
        if (strpos($article["link"], "somethingpositive.net") !== FALSE) {
            if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) {
                $image_url = preg_replace("/shtml/", "png", $article['link']);
                $article["content"] = '<img src="' . $image_url . '"/>';
                $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"];
            }
            else if (isset($article["stored"]["content"])) {
                $article["content"] = $article["stored"]["content"];
            }
        }
        return $article;
    }
}
?>

<?php
class Af_SomethingPositive extends Plugin {

    function about() {
        return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik");

    }
    function init($host) {
        $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
    }

    function hook_article_filter($article) {
        $owner_uid = $article["owner_uid"];
        if (strpos($article["link"], "somethingpositive.net") !== FALSE) {
            if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) {
                $image_url = preg_replace("/shtml/", "png", $article['link']);
                $article["content"] = '<img src="' . $image_url . '"/>';
                $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"];
            }
            else if (isset($article["stored"]["content"])) {
                $article["content"] = $article["stored"]["content"];
            }
        }
        return $article;
    }

    function api_version() {
        return 2;
    }
}
?>

Update Something Positive plugin for 1.7.9 compatibility


<?php

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

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

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

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

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

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

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

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

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

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

<?php

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

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

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

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

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

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

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

            $table->integer('category_id')->unsigned()->nullable();
            $table->foreign('category_id')->references('id')->on('vehicles_categories');

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

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

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

Add a new foreign key for the vehicle category


<?php
namespace Config;
class Environment {
    private $name;
    private $isRemoteServer;
    private $debug;

    public function __construct(\Utils\Request $request, $name) {
        $this->name = $name;
        // If the document root is not windows then it must be remote
        $this->isRemoteServer = strpos($request->server('DOCUMENT_ROOT'), 'C:') !== 0;
        // If it is local or a test site then debug
        $this->debug = (strpos($request->server('SERVER_NAME'), 'test') === 0 || !$this->isRemoteServer);
    }

    public function getName() {
        return $this->name;
    }

    public function getIsOnline() {
        return $this->isRemoteServer;
    }

    public function getDebug() {
        return $this->debug;
    }

    public function getRoot() {
        if (!$this->isRemoteServer) return '/' . $this->name . '/';
        else return DIRECTORY_SEPARATOR;
    }
}

<?php
namespace Config;
class Environment {
    private $localRootPath;
    private $isRemoteServer;
    private $debug;

    public function __construct(\Utils\Request $request, $localRootPath) {
        $this->localRootPath = $localRootPath;
        // If the document root is not windows then it must be remote
        $this->isRemoteServer = strpos($request->server('DOCUMENT_ROOT'), 'C:') !== 0;
        // If it is local or a test site then debug
        $this->debug = (strpos($request->server('SERVER_NAME'), 'test') === 0 || !$this->isRemoteServer);
    }

    public function getLocalRootPath() {
        return $this->localRootPath;
    }

    public function getIsOnline() {
        return $this->isRemoteServer;
    }

    public function getDebug() {
        return $this->debug;
    }

    public function getRoot() {
        if (!$this->isRemoteServer) return '/' . $this->localRootPath . '/';
        else return DIRECTORY_SEPARATOR;
    }
}

Rename variable to suit what it does

Rename variable to suit what it does

The name variable was used only as the path for the local root


<?php

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;

foreach (array(__DIR__.'/../../autoload.php', __DIR__.'/../vendor/autoload.php', __DIR__.'/vendor/autoload.php') as $autoload) {
    if (file_exists($autoload)) {
        require_once $autoload;

        break;
    }
}

if (PHP_MAJOR_VERSION < 7) {
    $io = new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
    $io->error('☠ PHP 7 is required in order to run manalize.');
    exit(1);
}

define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));

/**
 * Creates a unique tmp dir.
 *
 * @param string $prefix
 *
 * @return string The path to the tmp dir created
 */
function manala_get_tmp_dir($prefix = '')
{
    if (!is_dir(MANALIZE_TMP_ROOT_DIR)) {
        @mkdir(MANALIZE_TMP_ROOT_DIR);
    }

    $tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
    unlink($tmp);
    mkdir($tmp, 0777, true);

    return $tmp;
}

<?php

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;

foreach (array(__DIR__.'/../../autoload.php', __DIR__.'/../vendor/autoload.php', __DIR__.'/vendor/autoload.php') as $autoload) {
    if (file_exists($autoload)) {
        require_once $autoload;

        break;
    }
}

if (version_compare(PHP_VERSION, '7.1.3') < 0) {
    $io = new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
    $io->error('☠ PHP >= 7.1.3 is required in order to run manalize.');
    exit(1);
}

define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));

/**
 * Creates a unique tmp dir.
 *
 * @param string $prefix
 *
 * @return string The path to the tmp dir created
 */
function manala_get_tmp_dir($prefix = '')
{
    if (!is_dir(MANALIZE_TMP_ROOT_DIR)) {
        @mkdir(MANALIZE_TMP_ROOT_DIR);
    }

    $tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
    unlink($tmp);
    mkdir($tmp, 0777, true);

    return $tmp;
}

Update PHP check to 7.1

Update PHP check to 7.1


<?php
/*
 * This file is part of Console package.
 *
 * (c) Martí Adrogué <marti.adrogue@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace MartiAdrogue\Console;

class Output
{
    public function turnOnBuffering()
    {
        ob_start();
    }

    public function print($data)
    {
        ob_end_clean();
        echo $data.PHP_EOL;
    }
}

<?php
/*
 * This file is part of Console package.
 *
 * (c) Martí Adrogué <marti.adrogue@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace MartiAdrogue\Console;

class Output
{
    public function turnOnBuffering()
    {
        ob_start();
    }

    public function print($data)
    {
        if (ob_get_length()) {
            ob_end_clean();
        }
        echo $data.PHP_EOL;
    }
}

Check if there is buffer

Check if there is buffer


<?php
namespace Atarashii\APIBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Atarashii\APIBundle\Parser\AnimeParser;

class AnimeController extends FOSRestController
{
    /**
     * Anime get action
     * @var integer $id Id of the anime
     * @return array
     *
     * @Rest\View()
     */
	public function getAction($id)
	{
		#http://myanimelist.net/anime/#{id}

		$downloader = $this->get('atarashii_api.communicator');
		$animedetails = $downloader->fetch('/anime/' . $id);

 		$anime = AnimeParser::parse($animedetails);

 		return $anime;
	}
}

<?php
namespace Atarashii\APIBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\Request;
use Atarashii\APIBundle\Parser\AnimeParser;

class AnimeController extends FOSRestController
{
    /**
     * Anime get action
     * @var integer $id Id of the anime
     * @return array
     *
     * @Rest\View()
     */
	public function getAction($id, Request $request)
	{
		#http://myanimelist.net/anime/#{id}

		$usepersonal = (int) $request->query->get('mine');

		$downloader = $this->get('atarashii_api.communicator');

		if($usepersonal) {
			//get the credentials we received
			$username = $this->getRequest()->server->get('PHP_AUTH_USER');
			$password = $this->getRequest()->server->get('PHP_AUTH_PW');

			//Don't bother making a request if the user didn't send any authentication
			if($username == null) {
				$view = $this->view(Array('error' => 'unauthorized'), 401);
				$view->setHeader('WWW-Authenticate', 'Basic realm="myanimelist.net"');
				return $view;
			}

			$downloader->cookieLogin($username, $password);
		}

		$animedetails = $downloader->fetch('/anime/' . $id);

 		$anime = AnimeParser::parse($animedetails);

 		return $anime;
	}
}

Add Personal Details in Anime Details If Requested

Support for the mine=1 request on anime is complete. If mine=1 is added
on the API request URL, it’ll try to grab the login info and then have
the communicator do a cookie login to MAL before fetching the anime
details.


<?php
/**
 * This file is part of the CronSymfonyBundle package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cron\CronBundle\Cron;

use Symfony\Component\Process\PhpExecutableFinder;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class CommandBuilder
{
    /**
     * @var string
     */
    private $environment;

    /**
     * @var string
     */
    private $phpExecutable;

    /**
     * @param string $environment
     */
    public function __construct($environment)
    {
        $this->environment = $environment;

        $finder = new PhpExecutableFinder();
        $this->phpExecutable = $finder->find();
    }

    /**
     * @param string $command
     *
     * @return string
     */
    public function build($command)
    {
        return sprintf('%s %s %s --env=%s', $this->phpExecutable, 'app/console', $command, $this->environment);
    }
}

<?php
/**
 * This file is part of the CronSymfonyBundle package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cron\CronBundle\Cron;

use Symfony\Component\Process\PhpExecutableFinder;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class CommandBuilder
{
    /**
     * @var string
     */
    private $environment;

    /**
     * @var string
     */
    private $phpExecutable;

    /**
     * @param string $environment
     */
    public function __construct($environment)
    {
        $this->environment = $environment;

        $finder = new PhpExecutableFinder();
        $this->phpExecutable = $finder->find();
    }

    /**
     * @param string $command
     *
     * @return string
     */
    public function build($command)
    {
        return sprintf('%s %s %s --env=%s', $this->phpExecutable, $_SERVER['SCRIPT_NAME'], $command, $this->environment);
    }
}

Use the relative path to the executable.


<?php

namespace OCA\OJSXC\Db;

use Sabre\Xml\Reader;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlDeserializable;
use Sabre\Xml\XmlSerializable;

/**
 * This is an entity used by the IqHandler, but not stored/mapped in the database.
 * Class IQRoster
 *
 * @package OCA\OJSXC\Db
 */
class IQRoster extends Stanza implements XmlSerializable{

	public $type;
	public $qid;
	public $items;

	public function xmlSerialize(Writer $writer) {
		$writer->write([
			[
				'name' => 'iq',
				'attributes' => [
					'to' => $this->to,
					'type' => $this->type,
					'id' => $this->qid
				],
				'value' => [[
					'name' => 'query',
					'attributes' => [
						'xmlns' => 'jabber:iq:roster',
					],
					'value' => $this->items
				]]
			]
		]);
	}

	public function addItem($jid, $name){
		$this->items[] = [
			"name" => "item",
			"attributes" => [
				"jid" => $jid,
				"name" => $name
			],
			"value" => ''
		];
	}

}

<?php

namespace OCA\OJSXC\Db;

use Sabre\Xml\Reader;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlDeserializable;
use Sabre\Xml\XmlSerializable;

/**
 * This is an entity used by the IqHandler, but not stored/mapped in the database.
 * Class IQRoster
 *
 * @package OCA\OJSXC\Db
 */
class IQRoster extends Stanza implements XmlSerializable{

	public $type;
	public $qid;
	public $items;

	public function xmlSerialize(Writer $writer) {
		$writer->write([
			[
				'name' => 'iq',
				'attributes' => [
					'to' => $this->to,
					'type' => $this->type,
					'id' => $this->qid
				],
				'value' => [[
					'name' => 'query',
					'attributes' => [
						'xmlns' => 'jabber:iq:roster',
					],
					'value' => $this->items
				]]
			]
		]);
	}

	public function addItem($jid, $name){
		$this->items[] = [
			"name" => "item",
			"attributes" => [
				"jid" => $jid,
				"name" => $name,
				"subscription" => "both"
			],
			"value" => ''
		];
	}

}

Set subscription to both for colorful avatars


<?php

namespace Statamic\Addons\LinkOgData;

use Statamic\Extend\Fieldtype;

class LinkOgDataFieldtype extends Fieldtype
{
    protected function init()
    {
        $this->linkogdata = new LinkOgData;
    }

    /**
     * The blank/default value
     *
     * @return array
     */
    public function blank()
    {
        return [
            'url' => null
        ];
    }

    /**
     * Pre-process the data before it gets sent to the publish page
     *
     * @param mixed $data
     * @return array|mixed
     */
    public function preProcess($data)
    {
        return $data;
    }

    /**
     * Process the data before it gets saved
     *
     * @param mixed $data
     * @return array|mixed
     */
    public function process($data)
    {
        $url = $data['url'];

	$data = [
            'url' => $data['url'],
        ];

        $result = $this->linkogdata->getOgData($url);

        return array_merge($data, $result);
    }
}

<?php

namespace Statamic\Addons\LinkOgData;

use Statamic\Extend\Fieldtype;

class LinkOgDataFieldtype extends Fieldtype
{
    /**
     * The blank/default value
     *
     * @return array
     */
    public function blank()
    {
        return [
            'url' => null
        ];
    }

    /**
     * Pre-process the data before it gets sent to the publish page
     *
     * @param mixed $data
     * @return array|mixed
     */
    public function preProcess($data)
    {
        return $data;
    }

    /**
     * Process the data before it gets saved
     *
     * @param mixed $data
     * @return array|mixed
     */
    public function process($data)
    {
        return $data;
    }
}

Remove redundant lookup from field type process


<?php
    // Parse the json payload from github
    $json = file_get_contents('php://input');
    $obj = json_decode($json);

    // If there is a playload, deploy the website
    if ( $obj ) {
        // Log the payload
        file_put_contents('log/payload.txt', date("\n[d M Y H:i:s]\n").print_r($obj, true), FILE_APPEND);

        // perform the deploy
        utenv('PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:');
        $exec_string = 'cd /var/customers/webs/jmm/weltengeschichte.de.repo/ && git reset --hard HEAD && git pull && && npm install && grunt deploy';
        exec ( $exec_string, $output);

        // Log the output
        file_put_contents('log/output.txt', date("\n[d M Y H:i:s]\n").print_r($output, true), FILE_APPEND);
    }
?>

<?php
    // Parse the json payload from github
    $json = file_get_contents('php://input');
    $obj = json_decode($json);

    // If there is a playload, deploy the website
    if ( $obj ) {
        // Log the payload
        file_put_contents('log/payload.txt', date("\n[d M Y H:i:s]\n").print_r($obj, true), FILE_APPEND);

        // perform the deploy
        putenv('PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:');
        $exec_string = 'cd /var/customers/webs/jmm/weltengeschichte.de.repo/ && git reset --hard HEAD && git pull && && npm install && grunt deploy';
        exec ( $exec_string, $output);

        // Log the output
        file_put_contents('log/output.txt', date("\n[d M Y H:i:s]\n").print_r($output, true), FILE_APPEND);
    }
?>

Deploy on push, test 9

Deploy on push, test 9


<?php defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController {

	public function view() {
		$this->set('tracking_code', Config::get('SITE_TRACKING_CODE'));
		$tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION');
		if (!$tracking_code_position) {
			$tracking_code_position = 'bottom';
		}
		$this->set('tracking_code_position', $tracking_code_position);

		if ($this->isPost()) {
			if ($this->token->validate('update_tracking_code')) {
					Config::save('SITE_TRACKING_CODE', $this->post('tracking_code'));
					Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position'));
					$this->redirect('/dashboard/system/seo/tracking_codes', 'saved');
			} else {
				$this->error->add($this->token->getErrorMessage());
			}
		}
	}

	public function saved() {
		$this->set('message', t('Tracking code settings updated successfully.'));
		$this->view();
	}
}

<?php defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController {

	public function view() {
		$this->set('tracking_code', Config::get('SITE_TRACKING_CODE'));
		$tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION');
		if (!$tracking_code_position) {
			$tracking_code_position = 'bottom';
		}
		$this->set('tracking_code_position', $tracking_code_position);

		if ($this->isPost()) {
			if ($this->token->validate('update_tracking_code')) {
					Config::save('SITE_TRACKING_CODE', $this->post('tracking_code'));
					Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position'));
					Cache::flush();
					$this->redirect('/dashboard/system/seo/tracking_codes', 'saved');
			} else {
				$this->error->add($this->token->getErrorMessage());
			}
		}
	}

	public function saved() {
		$this->set('message', implode(PHP_EOL, array(
			t('Tracking code settings updated successfully.'),
			t('Cached files removed.')
		)));
		$this->view();
	}
}

Fix outdated cache after saving tracking codes

Former-commit-id: 45ef9d25124db43847f9f163be12b73c18411239


<?php

/**
* REST API
*/
class Controller_Api_V0_Todo extends Controller_Rest
{
    public function get_todo($id)
    {
        return;
    }

    public function get_todo_list()
    {
        return;
    }

    public function delete_todo($id)
    {
        return;
    }

    public function post_todo()
    {
        return;
    }

    public function put_todo($id)
    {
        return;
    }

    public function patch_todo($id)
    {
        return;
    }
}

<?php

/**
* REST API
*/
class Controller_Api_V0_Todo extends Controller_Rest
{
    public function before()
    {
        parent::before();
        Domain_Todo::before();
    }

    public function get_todo($id)
    {
        return;
    }

    public function get_todo_list()
    {
        return;
    }

    public function delete_todo($id)
    {
        return;
    }

    public function post_todo()
    {
        return;
    }

    public function put_todo($id)
    {
        return;
    }

    public function patch_todo($id)
    {
        return;
    }
}

Add set up = before

Add set up = before


<?php namespace Nathanmac\InstantMessenger\Contracts;

interface MessengerQueue {

    /**
     * Queue a new instance message for sending.
     *
     * @param  array   $data
     * @param  \Closure|string  $callback
     * @return mixed
     */
    public function queue(array $data, $callback);

    /**
     * Queue a new instance message for sending after (n) seconds.
     *
     * @param  int  $delay
     * @param  array  $data
     * @param  \Closure|string  $callback
     * @return mixed
     */
    public function later($delay, array $data, $callback);

}

<?php namespace Nathanmac\InstantMessenger\Contracts;

interface MessengerQueue {

    /**
     * Queue a new instance message for sending.
     *
     * @param  \Closure|string  $callback
     * @param  string  $queue
     * @return mixed
     */
    public function queue($callback, $queue = null);

    /**
     * Queue a new instance message for sending after (n) seconds.
     *
     * @param  int  $delay
     * @param  \Closure|string  $callback
     * @param  string  $queue
     * @return mixed
     */
    public function later($delay, $callback, $queue = null);
}

Update queue interface for Messenger, missing queue name setting


<?php
/**
 * @author gareth.evans
 */

namespace Qubes\Defero\Applications\Defero\Forms;

use Cubex\Data\Validator\Validator;
use Cubex\Form\Form;

class CampaignForm extends DeferoForm
{
  protected function _postBind()
  {
    $this->getElement("active")->setLabelPosition(Form::LABEL_NONE);

    if($this->_mapper->id())
    {
      $this->getElement("reference")->addAttribute("disabled", "disabled");
    }

    $this->getElement("submit")
      ->addAttribute("data-loading-text", "Submitting Campaign");

    return parent::_postBind();
  }
}

<?php
/**
 * @author gareth.evans
 */

namespace Qubes\Defero\Applications\Defero\Forms;

use Cubex\Data\Validator\Validator;
use Cubex\Form\Form;

class CampaignForm extends DeferoForm
{
  protected function _postBind()
  {
    $this->getElement("active")->setLabelPosition(Form::LABEL_NONE);

    if($this->_mapper->id())
    {
      $this->getElement("reference")->addAttribute("disabled", "disabled");
    }

    $return = parent::_postBind();

    $this->getElement("submit")
      ->addAttribute("data-loading-text", "Submitting Campaign");

    return $return;
  }
}

Set submit attribute after parent postBind is called


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

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->boolean('is_locked')->default(0);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropColumn('is_locked');
        });
    }
];

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

use Flarum\Database\Migration;

return Migration::addColumns('discussions', [
    'is_locked' => ['boolean', 'default' => 0]
]);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php echo sprintf(lang('snippets.edit_snippet'), $snippet->name);?>

<?php echo form_open_multipart($this->uri->uri_string(), 'class="crud"'); ?>

			<?php echo lang('snippets.snippet_content');?> *
			<?php echo $this->snippets_m->snippets->{$snippet->type}->form_output($snippet->content); ?>

	<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel') )); ?>

<?php echo form_close(); ?>

<?php echo sprintf(lang('snippets.edit_snippet'), $snippet->name);?>

<?php echo form_open_multipart($this->uri->uri_string(), 'class="crud"'); ?>

			<?php echo lang('snippets.snippet_content');?> *
			<?php echo $this->snippets_m->snippets->{$snippet->type}->form_output($snippet->content, $snippet->params); ?>

	<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel') )); ?>

<?php echo form_close(); ?>

Make snippet parameters to form_output tag.


<?php

namespace AppBundle\API;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class Webservice
{
    const ERROR_NOT_LOGGED_IN = "Error. Not logged in.";

    private $DB;

    public function __construct(\AppBundle\DB $DB)
    {
        $this->DB = $DB;
    }

    /**
     * @param ParameterBag $query
     * @param SessionInterface $session
     * @return array result
     */
    public function execute(ParameterBag $query, SessionInterface $session = null){
        return array();
    }

    /**
     * @param $namespace string
     * @param $classname string
     * @return Webservice|null
     */
    public function factory($namespace, $classname)
    {
        $serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace);
        $class = $serviceNamespace . '\\' . ucfirst($classname);
        if (!class_exists($class)) {
            return null;
        }

        return new $class($this->DB);
    }

    /**
     * @param $query ParameterBag
     * @return \PDO db connection
     */
    protected function getDbFromQuery($query){
        if (! $query->has('dbversion')){
            throw new Exception('No valid dbversion provided');
        }
        return $this->DB->getDbForVersion($query->get('dbversion'));
    }
}

<?php

namespace AppBundle\API;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class Webservice
{
    const ERROR_NOT_LOGGED_IN = "Error. Not logged in.";

    private $DB;

    public function __construct(\AppBundle\DB $DB)
    {
        $this->DB = $DB;
    }

    /**
     * @param ParameterBag $query
     * @param SessionInterface $session
     * @return array result
     */
    public function execute(ParameterBag $query, SessionInterface $session = null){
        return array();
    }

    /**
     * @param $namespace string
     * @param $classname string
     * @throws Exception
     * @return Webservice
     */
    public function factory($namespace, $classname)
    {
        $serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace);
        $class = $serviceNamespace . '\\' . ucfirst($classname);
        if (!class_exists($class)) {
            throw new Exception("Could not find class: ".$namespace."\\".$class);
        }

        return new $class($this->DB);
    }

    /**
     * @param $query ParameterBag
     * @return \PDO db connection
     */
    protected function getDbFromQuery($query){
        if (! $query->has('dbversion')){
            throw new Exception('No valid dbversion provided');
        }
        return $this->DB->getDbForVersion($query->get('dbversion'));
    }
}

Throw exception if class is not found rather than returning null


<?php

/**
 * Wrapper for PHP's pgsql extension providing conversion of complex DB types
 *
 * LICENSE
 *
 * This source file is subject to BSD 2-Clause License that is bundled
 * with this package in the file LICENSE and available at the URL
 * https://raw.githubusercontent.com/sad-spirit/pg-wrapper/master/LICENSE
 *
 * @package   sad_spirit\pg_wrapper
 * @copyright 2014-2020 Alexey Borzov
 * @author    Alexey Borzov <avb@php.net>
 * @license   http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause license
 * @link      https://github.com/sad-spirit/pg-wrapper
 */

declare(strict_types=1);

namespace sad_spirit\pg_wrapper\converters;

use sad_spirit\pg_wrapper\TypeConverter;

/**
 * Implementation of TypeConverter that performs no conversion
 *
 * Always returned by StubTypeConverterFactory, returned by DefaultTypeConverterFactory in case proper converter
 * could not be determined.
 */
class StubConverter implements TypeConverter
{
    /**
     * {@inheritdoc}
     */
    public function output($value): ?string
    {
        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function input(?string $native)
    {
        return $native;
    }

    /**
     * {@inheritdoc}
     */
    public function dimensions(): int
    {
        return 0;
    }
}

<?php

/**
 * Wrapper for PHP's pgsql extension providing conversion of complex DB types
 *
 * LICENSE
 *
 * This source file is subject to BSD 2-Clause License that is bundled
 * with this package in the file LICENSE and available at the URL
 * https://raw.githubusercontent.com/sad-spirit/pg-wrapper/master/LICENSE
 *
 * @package   sad_spirit\pg_wrapper
 * @copyright 2014-2020 Alexey Borzov
 * @author    Alexey Borzov <avb@php.net>
 * @license   http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause license
 * @link      https://github.com/sad-spirit/pg-wrapper
 */

declare(strict_types=1);

namespace sad_spirit\pg_wrapper\converters;

use sad_spirit\pg_wrapper\TypeConverter;

/**
 * Implementation of TypeConverter that performs no conversion
 *
 * Always returned by StubTypeConverterFactory, returned by DefaultTypeConverterFactory in case proper converter
 * could not be determined.
 */
class StubConverter implements TypeConverter
{
    /**
     * {@inheritdoc}
     */
    public function output($value): ?string
    {
        return null === $value ? null : (string)$value;
    }

    /**
     * {@inheritdoc}
     */
    public function input(?string $native)
    {
        return $native;
    }

    /**
     * {@inheritdoc}
     */
    public function dimensions(): int
    {
        return 0;
    }
}

Convert $value to string to prevent strict_types errors


<?php

namespace duncan3dc\SwiftMailer;

class Mailer extends Email
{

    public function __construct(array $options = null)
    {
        if (!is_array($options)) {
            $options = [];
        }

        if (empty($options["hostname"])) {
            $hostname = "localhost";
        } else {
            $hostname = $options["hostname"];
        }

        if ($hostname === "localhost") {
            $port = isset($options["local-port"]) ? $options["local-port"] : 25;
        } else {
            $port = isset($options["port"]) ? $options["port"] : 465;
        }

        $server = new Server($hostname, $port);

        if (!empty($options["username"]) || !empty($options["password"])) {
            $server->setCredentials($options["username"], $options["password"]);
        }

        if (!empty($options["fromAddress"])) {
            $server->setFromAddress($options["fromAddress"], $options["fromName"]);
        }

        if (!empty($options["encryption"])) {
            $server->setEncryptionMethod($options["encryption"]);
        }

        if (!empty($options["returnPath"])) {
            $server->setReturnPath($options["returnPath"]);
        }

        parent::__construct($server);
    }
}

<?php

namespace duncan3dc\SwiftMailer;

class Mailer extends Email
{

    public function __construct(array $options = null)
    {
        if (!is_array($options)) {
            $options = [];
        }

        if (empty($options["smtpServer"])) {
            $hostname = "localhost";
        } else {
            $hostname = $options["smtpServer"];
        }

        if ($hostname === "localhost") {
            $port = isset($options["local-port"]) ? $options["local-port"] : 25;
        } else {
            $port = isset($options["port"]) ? $options["port"] : 465;
        }

        $server = new Server($hostname, $port);

        if (!empty($options["username"]) || !empty($options["password"])) {
            $server->setCredentials($options["username"], $options["password"]);
        }

        if (!empty($options["fromAddress"])) {
            $server->setFromAddress($options["fromAddress"], $options["fromName"]);
        }

        if (!empty($options["encryption"])) {
            $server->setEncryptionMethod($options["encryption"]);
        }

        if (!empty($options["returnPath"])) {
            $server->setReturnPath($options["returnPath"]);
        }

        parent::__construct($server);
    }
}

Correct the hostname option (smtpServer)


<?php

namespace APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;

class InjectTypeController extends Controller
{
    public static $INJECT_TYPE_MANUAL = 'openex_manual';

    /**
     * @ApiDoc(
     *    description="List inject types"
     * )
     * @Rest\Get("/inject_types")
     */
    public function getInjectTypesAction(Request $request)
    {
        $logger = $this->get('logger');

        $contracts = array();
        try {
            $url = $this->getParameter('worker_url') . '/cxf/contracts';
            $contracts = json_decode(file_get_contents($url), true);
        } catch (\Exception $e) {
            $logger->error('Contracts can not be retrieved from worker');
        }

        $other = array();
        $other['type'] = self::$INJECT_TYPE_MANUAL;
        $other['fields'] = array();
        $other['fields'][] = array(
            'name' => 'content',
            'type' => 'textarea',
            'cardinality' => '1',
            'mandatory' => true,
        );

        $contracts[] = $other;

        $output = json_encode($contracts);
        return new Response($output);
    }
}

<?php

namespace APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;

class InjectTypeController extends Controller
{
    public static $INJECT_TYPE_MANUAL = 'openex_manual';

    /**
     * @ApiDoc(
     *    description="List inject types"
     * )
     * @Rest\Get("/inject_types")
     */
    public function getInjectTypesAction(Request $request)
    {
        $logger = $this->get('logger');

        $contracts = array();
        try {
            $url = $this->getParameter('worker_url') . '/cxf/contracts';
            $contracts = json_decode(file_get_contents($url), true);
        } catch (\Exception $e) {
            $logger->error('Contracts can not be retrieved from worker: ' . $e->getMessage());
        }

        $other = array();
        $other['type'] = self::$INJECT_TYPE_MANUAL;
        $other['fields'] = array();
        $other['fields'][] = array(
            'name' => 'content',
            'type' => 'textarea',
            'cardinality' => '1',
            'mandatory' => true,
        );

        $contracts[] = $other;

        $output = json_encode($contracts);
        return new Response($output);
    }
}

Fix the token request and log level

Fix the token request and log level


<?php

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class StartpageControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');

        $this->assertTrue(
            $client->getResponse()->isRedirect('/test/startpage'),
            'response is a redirect to /test/startpage'
        );

        $crawler = $client->followRedirect();

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('Projects', $crawler->filter('div')->text());
        $this->assertContains('Organisms', $crawler->filter('div')->text());
        $this->assertContains('Traits', $crawler->filter('div')->text());
    }
}

<?php

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class StartpageControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $client->request('GET', '/');

        $this->assertTrue(
            $client->getResponse()->isRedirect('/test/startpage'),
            'response is a redirect to /test/startpage'
        );

        $crawler = $client->followRedirect();

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('Projects', $crawler->filter('#wrapper')->text());
        $this->assertContains('Organisms', $crawler->filter('#wrapper')->text());
        $this->assertContains('Traits', $crawler->filter('#wrapper')->text());
    }
}

Fix selector for startpage controller test


<?php

return [
    'cache' => [
        'doctrine_dev_mode' => true,
        'enabled' => false,
        'overrides' => false,
        'pages' => false,
        'blocks' => false,
    ],
    'user' => [
        'password' => [
            'hash_cost_log2' => 1,
        ],
    ],
    'misc' => [
        // Let's lower the PNG compression, so that tests run faster
        'default_png_image_compression' => 5,
    ],
];

<?php

return [
    'cache' => [
        'doctrine_dev_mode' => true,
        'enabled' => false,
        'overrides' => false,
        'pages' => false,
        'blocks' => false,
    ],
    'user' => [
        'password' => [
            'hash_cost_log2' => 1,
        ],
        'email' => [
            // Needed because of a bug in 1.1.x versions of Egulias\EmailValidator which throws a "Undefined variable: dns" warning if this isn't set
            'test_mx_record' => true,
        ],
    ],
    'misc' => [
        // Let's lower the PNG compression, so that tests run faster
        'default_png_image_compression' => 5,
    ],
];

Fix test problem caused by an old versions of Egulias\EmailValidator


<?php
namespace Crud\Action;

use Crud\Traits\SerializeTrait;
use Crud\Traits\ViewTrait;
use Crud\Traits\ViewVarTrait;

/**
 * Handles 'Index' Crud actions
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 */
class IndexAction extends BaseAction
{

    use SerializeTrait;
    use ViewTrait;
    use ViewVarTrait;

    /**
     * Default settings for 'index' actions
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => true,
        'scope' => 'table',
        'view' => null,
        'viewVar' => null,
        'serialize' => [],
        'api' => [
            'success' => [
                'code' => 200
            ],
            'error' => [
                'code' => 400
            ]
        ]
    ];

    /**
     * Generic handler for all HTTP verbs
     *
     * @return void
     */
    protected function _handle()
    {
        $subject = $this->_subject(['success' => true, 'object' => null]);

        $this->_trigger('beforePaginate', $subject);
        $items = $this->_controller()->paginate($subject->object);
        $subject->set(['entities' => $items]);

        $this->_trigger('afterPaginate', $subject);
        $this->_trigger('beforeRender', $subject);
    }
}

<?php
namespace Crud\Action;

use Crud\Traits\SerializeTrait;
use Crud\Traits\ViewTrait;
use Crud\Traits\ViewVarTrait;

/**
 * Handles 'Index' Crud actions
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 */
class IndexAction extends BaseAction
{

    use SerializeTrait;
    use ViewTrait;
    use ViewVarTrait;

    /**
     * Default settings for 'index' actions
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => true,
        'scope' => 'table',
        'view' => null,
        'viewVar' => null,
        'serialize' => [],
        'api' => [
            'success' => [
                'code' => 200
            ],
            'error' => [
                'code' => 400
            ]
        ]
    ];

    /**
     * Generic handler for all HTTP verbs
     *
     * @return void
     */
    protected function _handle()
    {
        $subject = $this->_subject(['success' => true, 'query' => null]);

        $this->_trigger('beforePaginate', $subject);
        $items = $this->_controller()->paginate($subject->query);
        $subject->set(['entities' => $items]);

        $this->_trigger('afterPaginate', $subject);
        $this->_trigger('beforeRender', $subject);
    }
}

Standardize on 'query' instead of 'object' for query object


<header class="banner">
  <a class="brand" href="{{ home_url('/') }}">
    {{ $siteName }}
  </a>

  @if (has_nav_menu('primary_navigation'))
    <nav class="nav-primary">
      {!! wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav', 'echo' => false]) !!}
    </nav>
  @endif
</header>

<header class="banner">
  <a class="brand" href="{{ home_url('/') }}">
    {{ $siteName }}
  </a>

  @if (has_nav_menu('primary_navigation'))
    <nav class="nav-primary" aria-label="{{wp_get_nav_menu_name('primary_navigation')}}">
      {!! wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav', 'echo' => false]) !!}
    </nav>
  @endif
</header>

Use menu name as accessible name of `<nav>`


<?php

namespace MiniSuite;

/*
	Expectation abstract class
*/
abstract class AbstractExpectation implements ExpectationInterface {

	/*
		Format a value to a string

		Parameters
			mixed $value

		Return
			String
	*/
	static protected function format($value) {
		if(is_object($value)) {
			return get_class($value);
		}
		if(is_array($value)) {
			return 'Array['.count($value).']';
		}
		else if(is_resource($value)) {
			$type=get_resource_type($value);
			if($type=='Unknown') {
				return 'unknown resource';
			}
			else {
				return $type;
			}
		}
		else{
			return (string)$value;
		}
	}

}

<?php

namespace MiniSuite;

/*
	Expectation abstract class
*/
abstract class AbstractExpectation implements ExpectationInterface {

	/*
		Format a value to a string

		Parameters
			mixed $value

		Return
			String
	*/
	static protected function format($value) {
		if(is_object($value)) {
			return get_class($value);
		}
		else if(is_array($value)) {
			return '['.implode(', ', array_map(
				function ($v, $k) { return sprintf("%s => %s", $k, $v); },
				$value,
				array_keys($value)
			)).']';
		}
		else if(is_bool($value)) {
			return $value ? 'true' : 'false';
		}
		else if(is_resource($value)) {
			$type=get_resource_type($value);
			if($type=='Unknown') {
				return 'unknown resource';
			}
			else {
				return $type;
			}
		}
		else{
			return (string)$value;
		}
	}

}

Add better support for array and boolean values printing


<?php

use Illuminate\Routing\Router;

/** @var Router $router */
if (! App::runningInConsole()) {
    $router->get('{uri}', ['uses' => 'PublicController@uri', 'as' => 'page']);
    $router->get('/', ['uses' => 'PublicController@homepage', 'as' => 'homepage']);
}

<?php

use Illuminate\Routing\Router;

/** @var Router $router */
if (! App::runningInConsole()) {
    $router->get('/', ['uses' => 'PublicController@homepage', 'as' => 'homepage']);
    $router->any('{uri}', ['uses' => 'PublicController@uri', 'as' => 'page'])->where('uri', '.*');
}

Allow to have slugs with multiple parts.


<?php
/*
 * This file is part of the PHP To 7 Aid project.
 *
 * (c) Giso Stallenberg <gisostallenberg@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace GisoStallenberg\phpTo7aid\Console;

use Symfony\Component\Console\Application as BaseApplication;
/**
 * @author Giso Stallenberg <gisostallenberg@gmail.com>
 */
class Application extends BaseApplication
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        error_reporting(-1);
        parent::__construct('PHP To 7 Aid', '0.0.0');
    }

    public function getLongVersion()
    {
        $version = parent::getLongVersion().' by <comment>Giso Stallenberg</comment>';
        $commit = '@git-commit@';
        if ('@'.'git-commit@' !== $commit) {
            $version .= ' ('.substr($commit, 0, 7).')';
        }
        return $version;
    }
}

<?php
/*
 * This file is part of the PHP To 7 Aid project.
 *
 * (c) Giso Stallenberg <gisostallenberg@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace GisoStallenberg\phpTo7aid\Console;

use GisoStallenberg\phpTo7aid\Console\Command\RunCommand;
use Symfony\Component\Console\Application as BaseApplication;

/**
 * @author Giso Stallenberg <gisostallenberg@gmail.com>
 */
class Application extends BaseApplication
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        error_reporting(-1);
        parent::__construct('PHP To 7 Aid', '0.0.0');
        $this->add(new RunCommand() );
    }

    public function getLongVersion()
    {
        $version = parent::getLongVersion().' by <comment>Giso Stallenberg</comment>';
        $commit = '@git-commit@';
        if ('@'.'git-commit@' !== $commit) {
            $version .= ' ('.substr($commit, 0, 7).')';
        }
        return $version;
    }
}

Add run command to application

Add run command to application


<?php

namespace BasilFX\JobQueue\Contrib;

use Phalcon\CLI\Task;

use BasilFX\JobQueue\Job;
use BasilFX\JobQueue\Exception;

/**
 * @description("Job queue tasks runner")
 */
class JobQueueTask extends Task
{
    /**
     * Start the job broker loop.
     *
     * @description("Spawn a new worker process to handle queued jobs")
     */
    public function mainAction()
    {
        $running = true;
        echo "Starting worker task until. To interrupt, press CTRL + C.\n";

        // This is the main loop that will poll for tasks and process them.
        while ($running) {
            // Fetch the next job from the queue.
            $job = $this->jobQueue->getNext();

            if (!$job) {
                usleep(500000);
                continue;
            }

            // Process a job.
            try {
                echo "Processing job with ID {$job->getId()}.\n";

                $start = microtime(true);
                $this->jobQueue->process($job);
                $time = (microtime(true) - $start) * 1000;

                echo "Job with ID {$job->getId()} finished in $time ms.\n";
            } catch (\Exception $e) {
                echo "Job with ID {$job->getId()} failed: {$e->getMessage()}.\n";
            }
        }

        echo "Worker task stopped.\n";
    }
}

<?php

namespace BasilFX\JobQueue\Contrib;

use Phalcon\CLI\Task;

use BasilFX\JobQueue\Job;
use BasilFX\JobQueue\Exception;

/**
 * Phalcon JobQueue related tasks.
 */
class PhalconTask extends Task
{
    /**
     * Start the job broker loop.
     */
    public function mainAction()
    {
        $running = true;
        $success = 0;
        $failed = 0;

        echo "Starting worker task. To interrupt, press CTRL + C.\n";

        // This is the main loop that will poll for tasks and process them.
        while ($running) {
            // Fetch the next job from the queue.
            $job = $this->jobQueue->getNext();

            if (!$job) {
                usleep(500000);
                continue;
            }

            // Process a job.
            try {
                echo "Processing job with ID {$job->getId()}.\n";

                $start = microtime(true);
                $this->jobQueue->process($job);
                $time = (microtime(true) - $start) * 1000;

                echo "Job with ID {$job->getId()} finished in $time ms.\n";
                $success++;
            } catch (\Exception $e) {
                echo "Job with ID {$job->getId()} failed: {$e->getMessage()}.\n";
                $failed++;
            }
        }

        echo "Worker task stopped, $success successful and $failed failed tasks processed.\n";
    }
}

Fix for the jobqueue task.

Fix for the jobqueue task.


<?php

namespace Kunstmaan\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * The Abstract ORM entity
 */
abstract class AbstractEntity implements EntityInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set id
     *
     * @param int $id The unique identifier
     *
     * @return AbstractEntity
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Return string representation of entity
     *
     * @return string
     */
    public function __toString()
    {
        return "" . $this->getId();
    }

}

<?php

namespace Kunstmaan\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * The Abstract ORM entity
 */
abstract class AbstractEntity implements EntityInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set id
     *
     * @param int $id The unique identifier
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Return string representation of entity
     *
     * @return string
     */
    public function __toString()
    {
        return "" . $this->getId();
    }

}

Fix docblock so child entities fluent setters wont break


@foreach ($discussions as $discussion)

				{!! avatar($discussion->author)->link() !!}

				{!! $discussion->present()->titleAsLink !!}

						{!! $discussion->present()->topic !!}

					@if ($discussion->replies_count > 0)

							@icon('chat')
							{{ $discussion->replies_count }} {{ str_plural('reply', $discussion->replies_count) }}

					@endif

						@icon('clock')

							{!! $discussion->present()->updatedAtRelative !!}
							by {!! $discussion->present()->updatedBy !!}

					@if ($discussion->answer_count > 0)

							@icon('check')
							answered

					@endif

@endforeach

@forelse ($discussions as $discussion)

				{!! avatar($discussion->author)->link() !!}

				{!! $discussion->present()->titleAsLink !!}

						{!! $discussion->present()->topic !!}

					@if ($discussion->replies_count > 0)

							@icon('chat')
							{{ $discussion->replies_count }} {{ str_plural('reply', $discussion->replies_count) }}

					@endif

						@icon('clock')

							{!! $discussion->present()->updatedAtRelative !!}
							by {!! $discussion->present()->updatedBy !!}

					@if ($discussion->answer_count > 0)

							@icon('check')
							answered

					@endif

@empty
	{!! alert('warning', 'No discussions found.') !!}
@endforelse

Handle situations with no discussions

Handle situations with no discussions


<?php
declare(strict_types = 1);
/**
 * /tests/Integration/Controller/VersionControllerTest.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Tests\Integration\Controller;

use App\Controller\VersionController;
use App\Service\Version;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * Class VersionControllerTest
 *
 * @package App\Tests\Integration\Controller
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class VersionControllerTest extends KernelTestCase
{
    /**
     * @testdox Test that `__invoke` method calls expected service methods
     */
    public function testThatInvokeMethodIsCallingExpectedMethods(): void
    {
        $version = $this->getMockBuilder(Version::class)
            ->disableOriginalConstructor()
            ->getMock();

        $version
            ->expects(self::once())
            ->method('get')
            ->willReturn('1.0.0');

        $response = (new VersionController($version))();
        $content = $response->getContent();

        self::assertSame(200, $response->getStatusCode());
        self::assertNotFalse($content);
        self::assertJson($content);
    }
}

<?php
declare(strict_types = 1);
/**
 * /tests/Integration/Controller/VersionControllerTest.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Tests\Integration\Controller;

use App\Controller\VersionController;
use App\Service\Version;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * Class VersionControllerTest
 *
 * @package App\Tests\Integration\Controller
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class VersionControllerTest extends KernelTestCase
{
    /**
     * @testdox Test that `__invoke` method calls expected service methods
     */
    public function testThatInvokeMethodIsCallingExpectedMethods(): void
    {
        $version = $this->getMockBuilder(Version::class)
            ->disableOriginalConstructor()
            ->getMock();

        $version
            ->expects(self::once())
            ->method('get')
            ->willReturn('1.0.0');

        $response = (new VersionController($version))();
        $content = $response->getContent();

        self::assertSame(200, $response->getStatusCode());
        self::assertNotFalse($content);
        self::assertJson($content);
        self::assertJsonStringEqualsJsonString('{"version": "1.0.0"}', $content);
    }
}

Check that output is expected JSON

Check that output is expected JSON


<?php
namespace App\Test\TestCase\Controller;

use App\Controller\ActivitiesController;
use Cake\Core\Configure;
use Cake\TestSuite\IntegrationTestCase;

class ActivitiesControllerTest extends IntegrationTestCase {

    public $fixtures = array(
        'app.sentences',
        'app.users',
        'app.users_languages'
    );

    public function testPaginateRedirectsPageOutOfBoundsToLastPage() {
        $user = 'kazuki';
        $userId = 7;
        $lastPage = 2;

        $this->get("/eng/activities/translate_sentences_of/$user?page=9999999");

        $this->assertRedirect("/eng/activities/translate_sentences_of/$user?page=$lastPage");
    }
}

<?php
namespace App\Test\TestCase\Controller;

use App\Controller\ActivitiesController;
use Cake\Core\Configure;
use Cake\TestSuite\IntegrationTestCase;
use App\Test\TestCase\Controller\TatoebaControllerTestTrait;

class ActivitiesControllerTest extends IntegrationTestCase {
    use TatoebaControllerTestTrait;

    public $fixtures = array(
        'app.aros',
        'app.acos',
        'app.aros_acos',
        'app.audios',
        'app.favorites_users',
        'app.links',
        'app.private_messages',
        'app.sentences',
        'app.sentences_lists',
        'app.sentences_sentences_lists',
        'app.transcriptions',
        'app.users',
        'app.users_languages'
    );

    public function setUp() {
        parent::setUp();
        Configure::write('Acl.database', 'test');
    }

    public function accessesProvider() {
        return [
            // url; user; is accessible or redirection url
            [ '/eng/activities/adopt_sentences', null, true ],
            [ '/eng/activities/adopt_sentences', 'contributor', true ],
            [ '/eng/activities/adopt_sentences/jav', null, true ],
            [ '/eng/activities/adopt_sentences/jav', 'contributor', true ],
            [ '/eng/activities/translate_sentences', null, true ],
            [ '/eng/activities/translate_sentences', 'contributor', true ],
            [ '/eng/activities/translate_sentences_of/admin', null, true ],
            [ '/eng/activities/translate_sentences_of/admin', 'contributor', true ],
            [ '/eng/activities/translate_sentences_of/admin/fra', null, true ],
            [ '/eng/activities/translate_sentences_of/admin/fra', 'contributor', true ],
        ];
    }

    /**
     * @dataProvider accessesProvider
     */
    public function testActivitiesControllerAccess($url, $user, $response) {
        $this->assertAccessUrlAs($url, $user, $response);
    }

    public function testPaginateRedirectsPageOutOfBoundsToLastPage() {
        $user = 'kazuki';
        $userId = 7;
        $lastPage = 2;

        $this->get("/eng/activities/translate_sentences_of/$user?page=9999999");

        $this->assertRedirect("/eng/activities/translate_sentences_of/$user?page=$lastPage");
    }
}

Add tests for the Activities controller actions


<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class RegistrationController extends Controller
{
    /**
     * @Route("/inscription", name="registration")
     * @Method({"GET","POST"})
     */
    public function registrationAction(Request $request)
    {
        return $this->render('registration.html.twig');
    }
}

Fix (controller): Text files should end with a newline character


<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

class EditTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }
}

<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

class EditTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testWeCanGoToEditFromTheIndexPage(): void
    {
        $client = static::createClient();
        $this->login($client);

        $crawler = $client->request('GET', '/private/en/tags/index');
        $this->assertContains(
            'most used',
            $client->getResponse()->getContent()
        );

        $link = $crawler->selectLink('most used')->link();
        $client->click($link);

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains(
            '&id=2',
            $client->getHistory()->current()->getUri()
        );
    }
}

Test that we can go to the edit page of a tag from the index


<?php defined('SYSPATH') or die('No direct access allowed.');

return array(
	'topbar'	=>	array(
		'home'		=> array(
			'title'		=>	'Home',
			'url'		=>	'/',
			'priority'	=>	1,
		),
		'assets'	=> array(
			'title'		=>	'Assets',
			'url'		=>	'/cms/assets',
			'action'	=>	'manage_assets',
			'priority'	=>	2,
		),
		'people'	=>	array(
			'title'		=>	'People',
			'url'		=>	'/cms/people',
			'action'	=>	'manage_people',
			'priority'	=>	3,
		),
		'templates'	=>	array(
			'title'		=>	'Templates',
			'url'		=>	'/cms/templates',
			'action'	=>	'manage_templates',
			'priority'	=>	4,
		),
	),
);

<?php defined('SYSPATH') or die('No direct access allowed.');

return array(
	'topbar'	=>	array(
		'home'		=> array(
			'title'		=>	'Home',
			'url'		=>	'/',
			'priority'	=>	1,
		),
		'assets'	=> array(
			'title'		=>	'Assets',
			'url'		=>	'/cms/assets',
			'action'	=>	'manage_assets',
			'priority'	=>	3,
		),
		'people'	=>	array(
			'title'		=>	'People',
			'url'		=>	'/cms/people',
			'action'	=>	'manage_people',
			'priority'	=>	4,
		),
		'pages'	=>	array(
			'title'		=>	'Pages',
			'url'		=>	'/cms/pages',
			'priority'	=>	2,
		),
		'templates'	=>	array(
			'title'		=>	'Templates',
			'url'		=>	'/cms/templates',
			'action'	=>	'manage_templates',
			'priority'	=>	5,
		),
	),
);

Put pages link back into topnav

Put pages link back into topnav


<?php

class Controller_Tag extends Controller_Abstract
{
    public function get($tagId, $slug = null)
    {

        $tag = $this->_getContainer()->Tag()->load($tagId);

        // While we only need post ID, ensure that we use post slug for SEO
        if ($slug != $tag->getSlug()) {
            header("Location: " . $tag->getUrl(), true, 301);
        }

        $posts = $this->_getContainer()->Post()->fetchByTagId($tagId);

        echo $this->_getTwig()->render('tag.html.twig', array(
            'session'       => $this->_getSession(),
            'tag'           => $tag,
            'posts'         => $posts,
            'local_config'  => $this->_getContainer()->LocalConfig(),
        ));
    }

}

<?php

class Controller_Tag extends Controller_Abstract
{
    public function get($tagId, $slug = null)
    {

        $tag = $this->_getContainer()->Tag()->load($tagId);

        // While we only need tag ID, ensure that we use tag slug for SEO
        if ($slug != $tag->getSlug()) {
            header("Location: " . $tag->getUrl(), true, 301);
        }

        $posts = $this->_getContainer()->Post()->fetchByTagId($tagId);

        echo $this->_getTwig()->render('tag.html.twig', array(
            'session'       => $this->_getSession(),
            'tag'           => $tag,
            'posts'         => $posts,
            'local_config'  => $this->_getContainer()->LocalConfig(),
        ));
    }

}

Copy and paste tidy up.

Copy and paste tidy up.


<?php

namespace Laravel\Dusk;

use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class DuskServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any package services.
     *
     * @return void
     */
    public function boot()
    {
        Route::get('/_dusk/login/{userId}/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@login',
        ]);

        Route::get('/_dusk/logout/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@logout',
        ]);

        Route::get('/_dusk/user/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@user',
        ]);
    }

    /**
     * Register any package services.
     *
     * @return void
     * @throws Exception
     */
    public function register()
    {
        if ($this->app->environment('production')) {
            throw new Exception('Do not register Dusk in production!');
        }

        if ($this->app->runningInConsole()) {
            $this->commands([
                Console\InstallCommand::class,
                Console\DuskCommand::class,
                Console\MakeCommand::class,
                Console\PageCommand::class,
            ]);
        }
    }
}

<?php

namespace Laravel\Dusk;

use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class DuskServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any package services.
     *
     * @return void
     */
    public function boot()
    {
        Route::get('/_dusk/login/{userId}/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@login',
        ]);

        Route::get('/_dusk/logout/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@logout',
        ]);

        Route::get('/_dusk/user/{guard?}', [
            'middleware' => 'web',
            'uses' => 'Laravel\Dusk\Http\Controllers\UserController@user',
        ]);
    }

    /**
     * Register any package services.
     *
     * @return void
     * @throws Exception
     */
    public function register()
    {
        if ($this->app->environment('production')) {
            throw new Exception('Do not register Dusk in production! Read more on https://github.com/laravel/dusk/issues/57');
        }

        if ($this->app->runningInConsole()) {
            $this->commands([
                Console\InstallCommand::class,
                Console\DuskCommand::class,
                Console\MakeCommand::class,
                Console\PageCommand::class,
            ]);
        }
    }
}

Add more information to exception

Add more information to exception


<?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 spec\Refinery29\Piston\Stub;

use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Request;
use Zend\Diactoros\Response\HtmlResponse;

class FooController
{
    public function fooAction(Request $req, ApiResponse $resp)
    {
        return $resp;
    }

    public function test(Request $req, ApiResponse $response)
    {
        $response->setResult(ResourceFactory::result(['something' => 'yolo']));

        return $response;
    }

    public function testHTMLResponse()
    {
        return new HTMLResponse('
Hello World
');
    }
}

<?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 spec\Refinery29\Piston\Stub;

use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Request;
use Zend\Diactoros\Response\HtmlResponse;

class FooController
{
    public function fooAction(Request $req, ApiResponse $resp)
    {
        return $resp;
    }

    public function test(Request $req, ApiResponse $response, array $vars)
    {
        $response->setResult(ResourceFactory::result(['something' => 'yolo']));

        return $response;
    }

    public function testHTMLResponse()
    {
        return new HTMLResponse('
Hello World
');
    }
}

Fix: Add missing parameter to method signature


<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        $json = json_decode($this->response, true);

        return is_array($json) ? $json : $this->response;
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        return is_array($this->response) ? $this->response : json_decode($this->response, true);
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

Change order of json_decode within Response


<?php

namespace OrgManager\ApiClient\Test;

use GuzzleHttp\Client;
use OrgManager\ApiClient\OrgManager;

class OrgManagerTest extends \PHPUnit_Framework_TestCase
{
    /** @var \OrgManager\ApiClient\OrgManager */
    protected $orgmanager;

    public function setUp()
    {
        $client = new Client();

        $this->orgmanager = new OrgManager($client);

        parent::setUp();
    }

    /** @test */
    public function it_does_not_have_token()
    {
        $this->assertNull($this->orgmanager->apiToken);
    }

    /** @test */
    public function you_can_set_api_token()
    {
        $this->orgmanager->connect('API_TOKEN');
        $this->assertEquals('API_TOKEN', $this->orgmanager->apiToken);
    }
}

<?php

namespace OrgManager\ApiClient\Test;

use GuzzleHttp\Client;
use OrgManager\ApiClient\OrgManager;

class OrgManagerTest extends \PHPUnit_Framework_TestCase
{
    /** @var \OrgManager\ApiClient\OrgManager */
    protected $orgmanager;

    public function setUp()
    {
        $this->orgmanager = new OrgManager();

        parent::setUp();
    }

    /** @test */
    public function it_does_not_have_token()
    {
        $this->assertNull($this->orgmanager->apiToken);
    }

    /** @test */
    public function you_can_set_api_token()
    {
        $this->orgmanager->connect('API_TOKEN');
        $this->assertEquals('API_TOKEN', $this->orgmanager->apiToken);
    }

    /** @test */
    public function you_can_get_client()
    {
        $this->assertEquals($this->orgmanager->getClient(), $this->orgmanager->client);
        $this->assertInstanceOf(Client::class, $this->orgmanager->getClient());
    }

    /** @test */
    public function you_can_set_client()
    {
        $newClient = new Client;
        $this->assertInstanceOf(Client::class, $newClient);
        $this->assertNotEquals($this->orgmanager->client, $newClient)
        $this->orgmanager->setClient($newClient);
        $this->assertEquals($newClient, $this->orgmanager->client);
    }
}

Fix tests & add client tests

Fix tests & add client tests


<?php

class Denkmal_Usertext_Filter_LinksTest extends CMTest_TestCase {

    public function testLinkChange() {
        $render = new CM_Render();
        $link = Denkmal_Model_Link::create('foo', 'http://foo.com', true);

        $filter = new Denkmal_Usertext_Filter_Links();
        $this->assertSame('hello foo bar', $filter->transform('hello foo bar', $render));

        $link->setLabel('bar');
        $filter = new Denkmal_Usertext_Filter_Links();
        $this->assertSame('hello foo bar', $filter->transform('hello foo bar', $render));
    }
}

<?php

class Denkmal_Usertext_Filter_LinksTest extends CMTest_TestCase {

    public function testLinkChange() {
        $render = new CM_Frontend_Render();
        $link = Denkmal_Model_Link::create('foo', 'http://foo.com', true);

        $filter = new Denkmal_Usertext_Filter_Links();
        $this->assertSame('hello foo bar', $filter->transform('hello foo bar', $render));

        $link->setLabel('bar');
        $filter = new Denkmal_Usertext_Filter_Links();
        $this->assertSame('hello foo bar', $filter->transform('hello foo bar', $render));
    }
}

Adjust CM_Render -> CM_Frontend_Render in tests