<?php

namespace wcf\system\template\plugin;

use wcf\system\template\TemplateEngine;
use wcf\system\WCF;
use wcf\util\DateUtil;

/**
 * Template modifier plugin which formats a unix timestamp.
 * Default date format contains year, month, day, hour and minute.
 *
 * Usage:
 *  {$timestamp|time}
 *  {"132845333"|time}
 *
 * @author Alexander Ebert, Marcel Werk
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Template\Plugin
 */
class TimeModifierTemplatePlugin implements IModifierTemplatePlugin
{
    /**
     * @inheritDoc
     */
    public function execute($tagArgs, TemplateEngine $tplObj)
    {
        $timestamp = \intval($tagArgs[0]);
        $dateTimeObject = DateUtil::getDateTimeByTimestamp($timestamp);
        $isFutureDate = ($timestamp > TIME_NOW);
        $dateAndTime = \IntlDateFormatter::create(
            WCF::getLanguage()->getLocale(),
            \IntlDateFormatter::LONG,
            \IntlDateFormatter::SHORT,
            WCF::getUser()->getTimeZone()
        )->format($dateTimeObject);

        return \sprintf(
            '<woltlab-core-date-time date="%s"%s>%s</woltlab-core-date-time>',
            DateUtil::format($dateTimeObject, 'c'),
            $isFutureDate ? ' static' : '',
            $dateAndTime
        );
    }
}

<?php

namespace wcf\system\template\plugin;

use wcf\system\template\TemplateEngine;
use wcf\system\WCF;

/**
 * Template modifier plugin which formats a unix timestamp.
 * Default date format contains year, month, day, hour and minute.
 *
 * Usage:
 *  {$timestamp|time}
 *  {"132845333"|time}
 *
 * @author Alexander Ebert, Marcel Werk
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Template\Plugin
 */
class TimeModifierTemplatePlugin implements IModifierTemplatePlugin
{
    /**
     * @inheritDoc
     */
    public function execute($tagArgs, TemplateEngine $tplObj)
    {
        $timestamp = \intval($tagArgs[0]);
        $dateTime = new \DateTimeImmutable('@' . $timestamp);

        $isFutureDate = $dateTime->getTimestamp() > TIME_NOW;

        $dateAndTime = \IntlDateFormatter::create(
            WCF::getLanguage()->getLocale(),
            \IntlDateFormatter::LONG,
            \IntlDateFormatter::SHORT,
            WCF::getUser()->getTimeZone()
        )->format($dateTime);

        return \sprintf(
            '<woltlab-core-date-time date="%s"%s>%s</woltlab-core-date-time>',
            $dateTime->format('c'),
            $isFutureDate ? ' static' : '',
            $dateAndTime
        );
    }
}

Clean up implementation of TimeModifierTemplatePlugin

No need to use the DateUtil here. `getDateTimeByTimestamp()` is trivial,
localization already happens via `IntlDateFormatter` and the `c` format is
meant for technical consumption, thus no need to run this via `DateUtil`’s
localization and TZ logic.


<?php

namespace Tests\Stub;

use Symfony\Component\Console\Output\BufferedOutput;

/**
 * Class UnformattedOutputStub
 * @package Tests\Stub
 */
class UnformattedOutputStub extends BufferedOutput
{
    /** @var string */
    protected $outputBuffer;

    public function __construct()
    {
        parent::__construct(null, false);
    }

    /**
     * @return string
     */
    public function getOutput()
    {
        if (is_null($this->outputBuffer)) {
            $this->outputBuffer = $this->fetch();
        }

        return $this->outputBuffer;
    }
}

<?php

namespace Tests\Stub;

use Symfony\Component\Console\Output\Output;

/**
 * Class UnformattedOutputStub
 * This class is inspired by Symfony\Component\Console\Output\BufferedOutput, which is not available in Symfony 2.3
 * @package Tests\Stub
 */
class UnformattedOutputStub extends Output
{
    /** @var string */
    protected $buffer;

    public function __construct()
    {
        parent::__construct(null, false);
    }

    /**
     * @return string
     */
    public function getOutput()
    {
        if ($this->buffer === null) {
            $this->buffer = $this->fetch();
        }

        return $this->buffer;
    }

    /**
     * {@inheritdoc}
     */
    protected function doWrite($message, $newline)
    {
        $this->buffer .= $message;

        if ($newline) {
            $this->buffer .= "\n";
        }
    }

    /**
     * Empties buffer and returns its content.
     *
     * @return string
     */
    public function fetch()
    {
        $content = $this->buffer;
        $this->buffer = '';

        return $content;
    }
}

Remove usage of BufferedOutput, since is not available in SF 2.3


<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
}

<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
    }
}

Load factories on startup of tests

Load factories on startup of tests


<?php

namespace Dardarlt\Bundle\TwitterTaskBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

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

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

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}

<?php

namespace Dardarlt\Bundle\TwitterTaskBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultControllerTest extends WebTestCase
{
    public function testServiceIsWorking()
    {
        $client = static::createClient();

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

        $this->assertTrue($crawler->filter('html:contains("Tweets")')->count() > 0);
    }

    public function testServiceNotFound()
    {
        $client = static::createClient();
        $client->request('GET', '/task2/tweets/random_user_not');
        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }
}

Update controller test , check if service is not found with incorect parameters


<?php
/**
 * @file src/Worker/RemoveContact.php
 * @brief Removes orphaned data from deleted contacts
 */
namespace Friendica\Worker;

use Friendica\Database\DBA;

require_once 'include/dba.php';

class RemoveContact {
	public static function execute($id) {

		// Only delete if the contact is archived
		$condition = ['archive' => true, 'network' => Protocol::PHANTOM, 'id' => $id];
		$r = DBA::exists('contact', $condition);
		if (!DBA::isResult($r)) {
			return;
		}

		// Now we delete the contact and all depending tables
		DBA::delete('contact', ['id' => $id]);
	}
}

<?php
/**
 * @file src/Worker/RemoveContact.php
 * @brief Removes orphaned data from deleted contacts
 */
namespace Friendica\Worker;

use Friendica\Database\DBA;
use Friendica\Core\Protocol;

require_once 'include/dba.php';

class RemoveContact {
	public static function execute($id) {

		// Only delete if the contact is archived
		$condition = ['archive' => true, 'network' => Protocol::PHANTOM, 'id' => $id];
		$r = DBA::exists('contact', $condition);
		if (!DBA::isResult($r)) {
			return;
		}

		// Now we delete the contact and all depending tables
		DBA::delete('contact', ['id' => $id]);
	}
}

Fix a fatal error when removing contacts


<?php

/**
 * @group conduit
 */
final class ConduitAPI_differential_createrevision_Method
  extends ConduitAPIMethod {

  public function getMethodDescription() {
    return "Create a new Differential revision.";
  }

  public function defineParamTypes() {
    return array(
      'diffid' => 'required diffid',
      'fields' => 'required dict',
    );
  }

  public function defineReturnType() {
    return 'nonempty dict';
  }

  public function defineErrorTypes() {
    return array(
      'ERR_BAD_DIFF' => 'Bad diff ID.',
    );
  }

  protected function execute(ConduitAPIRequest $request) {
    $fields = $request->getValue('fields');

    $diff = id(new DifferentialDiff())->load($request->getValue('diffid'));
    if (!$diff) {
      throw new ConduitException('ERR_BAD_DIFF');
    }

    $revision = DifferentialRevisionEditor::newRevisionFromConduitWithDiff(
      $fields,
      $diff,
      $request->getUser());

    return array(
      'revisionid'  => $revision->getID(),
      'uri'         => PhabricatorEnv::getURI('/D'.$revision->getID()),
    );
  }

}

<?php

/**
 * @group conduit
 */
final class ConduitAPI_differential_createrevision_Method
  extends ConduitAPIMethod {

  public function getMethodDescription() {
    return "Create a new Differential revision.";
  }

  public function defineParamTypes() {
    return array(
      // TODO: Arcanist passes this; prevent fatals after D4191 until Conduit
      // version 7 or newer.
      'user'   => 'ignored',
      'diffid' => 'required diffid',
      'fields' => 'required dict',
    );
  }

  public function defineReturnType() {
    return 'nonempty dict';
  }

  public function defineErrorTypes() {
    return array(
      'ERR_BAD_DIFF' => 'Bad diff ID.',
    );
  }

  protected function execute(ConduitAPIRequest $request) {
    $fields = $request->getValue('fields');

    $diff = id(new DifferentialDiff())->load($request->getValue('diffid'));
    if (!$diff) {
      throw new ConduitException('ERR_BAD_DIFF');
    }

    $revision = DifferentialRevisionEditor::newRevisionFromConduitWithDiff(
      $fields,
      $diff,
      $request->getUser());

    return array(
      'revisionid'  => $revision->getID(),
      'uri'         => PhabricatorEnv::getURI('/D'.$revision->getID()),
    );
  }

}

Add `user` parameter to differential.createrevision

Summary: arc incorrectly passes a "user" parameter to differential.createrevision (long ago, we respected it, I think). After D4191 this fatals. Provide a stub call until the next version bump.

Test Plan: inspection

Reviewers: vrana, btrahan

Reviewed By: btrahan

CC: aran

Differential Revision: https://secure.phabricator.com/D4220


<?php

namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;

use Symfony\Component\HttpFoundation\Request;

use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandler;
use Datatheke\Bundle\PagerBundle\Pager\PagerView;

class ViewHandler implements HttpHandlerInterface
{
    protected $pagerHandler;

    public function __construct($options = array())
    {
        if ($options instanceof PagerViewHandler) {
            $this->pagerHandler = $options;
        } elseif (is_array($options)) {
            $this->pagerHandler = new PagerViewHandler($options);
        } else {
            throw new \Exception('ViewHandler::__construct() first agrument should be an array or a Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler object');
        }
    }

    public function handleRequest(HttpDataGridInterface $datagrid, Request $request)
    {
        $pager = $datagrid->getPager();
        $this->pagerHandler->handleRequest($pager, $request);

        return $this->createView($datagrid, $request);
    }

    protected function createView(HttpDataGridInterface $datagrid, Request $request)
    {
        return new DataGridView($datagrid, new PagerView($datagrid->getPager(), $this->pagerHandler));
    }
}

<?php

namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;

use Symfony\Component\HttpFoundation\Request;

use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandler;
use Datatheke\Bundle\PagerBundle\Pager\PagerView;

class ViewHandler implements HttpHandlerInterface
{
    protected $pagerHandler;

    public function __construct($options = array())
    {
        if ($options instanceof PagerViewHandler) {
            $this->pagerHandler = $options;
        } elseif (is_array($options)) {
            $this->pagerHandler = new PagerViewHandler($options);
        } else {
            throw new \Exception('ViewHandler::__construct() first agrument should be an array or a Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler object');
        }
    }

    public function setOption($option, $value)
    {
        $this->pagerHandler->setOption($option, $value);

        return $this;
    }

    public function handleRequest(HttpDataGridInterface $datagrid, Request $request)
    {
        $pager = $datagrid->getPager();
        $this->pagerHandler->handleRequest($pager, $request);

        return $this->createView($datagrid, $request);
    }

    protected function createView(HttpDataGridInterface $datagrid, Request $request)
    {
        return new DataGridView($datagrid, new PagerView($datagrid->getPager(), $this->pagerHandler));
    }
}

Add setOption method to change default configuration


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('pages.dashboard');
})->name('page.dashboard');

Route::get('/list-guru', function () {
    return view('pages.list-guru');
})->name('page.list-guru');

Route::get('/list-siswa', function () {
    return view('pages.list-siswa');
})->name('page.list-siswa');

Route::get('/list-staf', function () {
    return view('pages.list-staf');
})->name('page.list-staf');

Route::get('/list-agenda', function () {
    return view('pages.list-activity');
})->name('page.list-agenda');

Route::get('/calendar', function () {
    return view('pages.calendar');
})->name('page.calendar');

Route::get('/user/create', function () {
    return view('pages.create-user');
})->name('page.create-user');

Route::get('/agenda/create', function () {
    return view('pages.create-activity');
})->name('page.create-agenda');

Route::get('/user/edit', function () {
    return view('pages.update-user');
})->name('page.edit-user');

Route::get('/agenda/edit', function () {
    return view('pages.update-activity');
})->name('page.edit-agenda');

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('pages.dashboard');
})->name('page.dashboard');

Route::get('/siswa','Pages\UserController@siswa')->name('page.list-siswa');
Route::get('/guru','Pages\UserController@guru')->name('page.list-guru');
Route::get('/staf','Pages\UserController@staf')->name('page.list-staf');
Route::get('/users/create','Pages\UserController@create')->name('page.create-user');
Route::get('/users/{id}/edit','Pages\UserController@edit')->name('page.edit-user');

Route::get('/activity','Pages\ActivityController@index')->name('page.list-activity');
Route::get('/activity/create','Pages\ActivityController@create')->name('page.create-activity');
Route::get('/activity/{id}/edit','Pages\ActivityController@edit')->name('page.edit-activity');

Route::get('/calendar', function () {
    return view('pages.calendar');
})->name('page.calendar');

Move return view to controller

Move return view to controller


<?php namespace Affinity
{
	use Dotink\Flourish;

	/**
	 *
	 */
	class Config implements ConfigInterface
	{
		/**
		 *
		 */
		static public function create($types, $data = NULL)
		{
			if (func_num_args() == 1) {
				$types    = [];
				$resource = func_get_arg(0);
			}

			return new static($types, $data);
		}

		/**
		 *
		 */
		public function __construct(Array $types, Array $data)
		{
			$this->types = array_unique($types);
			$this->data  = $data;
		}

		/**
		 *
		 */
		public function extend(ConfigInterface $config)
		{
			$this->types = array_unique(array_merge(
				$this->getTypes(),
				$config->getTypes()
			));

			$this->data = array_replace_recursive(
				$this->getData(),
				$config->getData()
			);
		}

		/**
		 *
		 */
		public function getData()
		{
			return $this->data;
		}

		/**
		 *
		 */
		public function getTypes()
		{
			return $this->types;
		}
	}
}

<?php namespace Affinity
{
	use Dotink\Flourish;

	/**
	 *
	 */
	class Config implements ConfigInterface
	{
		/**
		 *
		 */
		static public function create($types, $data = NULL)
		{
			if (func_num_args() == 1) {
				$types = [];
				$data  = func_get_arg(0);
			}

			return new static($types, $data);
		}

		/**
		 *
		 */
		public function __construct(Array $types, Array $data)
		{
			$this->types = array_unique($types);
			$this->data  = $data;
		}

		/**
		 *
		 */
		public function extend(ConfigInterface $config)
		{
			$this->types = array_unique(array_merge(
				$this->getTypes(),
				$config->getTypes()
			));

			$this->data = array_replace_recursive(
				$this->getData(),
				$config->getData()
			);
		}

		/**
		 *
		 */
		public function getData()
		{
			return $this->data;
		}

		/**
		 *
		 */
		public function getTypes()
		{
			return $this->types;
		}
	}
}

Fix factory with proper variable name

Fix factory with proper variable name


<?
include '../scat.php';

$criteria= array();

$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);

foreach ($terms as $term) {
  $term= $db->real_escape_string($term);
  $criteria[]= "(person.name LIKE '%$term%'
             OR person.company LIKE '%$term%')";
}

if (!$_REQUEST['all'])
  $criteria[]= 'active';

if (empty($criteria)) {
  $criteria= '1=1';
} else {
  $criteria= join(' AND ', $criteria);
}

$q= "SELECT id,
            CONCAT(IFNULL(name, ''),
                   IF(name != '' AND company != '', ' / ', ''),
                   IFNULL(company, ''))
                AS value
       FROM person
      WHERE $criteria
      ORDER BY value";

$r= $db->query($q)
  or die_query($db, $q);

$list= array();
while ($row= $r->fetch_assoc()) {
  /* force numeric values to numeric type */
  $list[]= $row;
}

echo jsonp($list);

<?
include '../scat.php';

$criteria= array();

$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);

foreach ($terms as $term) {
  $term= $db->real_escape_string($term);
  $criteria[]= "(person.name LIKE '%$term%'
             OR person.company LIKE '%$term%')";
}

if (!$_REQUEST['all'])
  $criteria[]= 'active';

if (($type= $_REQUEST['role'])) {
  $criteria[]= "person.role = '" . $db->escape($type) . "'";
}

if (empty($criteria)) {
  $criteria= '1=1';
} else {
  $criteria= join(' AND ', $criteria);
}

$q= "SELECT id,
            CONCAT(IFNULL(name, ''),
                   IF(name != '' AND company != '', ' / ', ''),
                   IFNULL(company, ''))
                AS value
       FROM person
      WHERE $criteria
      ORDER BY value";

$r= $db->query($q)
  or die_query($db, $q);

$list= array();
while ($row= $r->fetch_assoc()) {
  /* force numeric values to numeric type */
  $list[]= $row;
}

echo jsonp($list);

Allow limiting selection by role

Allow limiting selection by role


<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    protected $primaryKey = 'user_id';
    public $incrementing = false;

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_role');
    }
}

<?php

namespace App\Models;

use App\Models\Traits\HasRole;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, HasRole;

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    protected $primaryKey = 'user_id';

    public $incrementing = false;

}

Remove old roles relationship function

Remove old roles relationship function


<?php

	// TODO Set ALL the parameters

	$Page['Title'] = 'Puff Sys';
	$Page['Type']  = 'Article';
	$Page['Published'] = '2015-02-05';
	require_once __DIR__.'/_puff/sitewide.php';
	require_once $Sitewide['Templates']['Header'];
?>

Welcome to Puff.

<?php
	require_once $Sitewide['Templates']['Footer'];
?>

Remove closing PHP tag at end of file

Remove closing PHP tag at end of file


<?php

require_once(__DIR__ . "/core/init.php");

use \plugin\Plugin as Plugin;

Plugin::activate("doctrine1");
Plugin::activate("mvc", __DIR__ . "/vendor/makmonty/movac-mvc");
// Plugin::activate("mvc", __DIR__ . "/../movac-mvc");

Plugin::activate("jquery");
Plugin::activate("bootstrap_theme_yeti");

$dispatcher = new Dispatcher();
$dispatcher->run($_SERVER['REQUEST_URI']);

<?php

require_once(__DIR__ . "/core/init.php");

use \plugin\Plugin as Plugin;

Plugin::activate("doctrine1");
Plugin::activate("mvc", dirname($_SERVER["SCRIPT_FILENAME"]) . "/vendor/makmonty/movac-mvc");
// Plugin::activate("mvc", __DIR__ . "/../movac-mvc");

Plugin::activate("jquery");
Plugin::activate("bootstrap_theme_yeti");

$dispatcher = new Dispatcher();
$dispatcher->run($_SERVER['REQUEST_URI']);

Use path relative to project

Use path relative to project


<?php

namespace CHH\Test;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use CHH\UrlMap;
use Stack\CallableHttpKernel;

class UrlMapTest extends \PHPUnit_Framework_TestCase
{
    function test()
    {
        $app = new CallableHttpKernel(function(Request $req) {
            return new Response("Fallback!");
        });

        $urlMap = new UrlMap($app);
        $urlMap->setMap(array(
            '/foo' => new CallableHttpKernel(function(Request $req) {
                return new Response('foo');
            })
        ));

        $req = Request::create('/foo');
        $resp = $urlMap->handle($req);

        $this->assertEquals('foo', $resp->getContent());
    }

    function testOverridesPathInfo()
    {
        $test = $this;

        $app = new CallableHttpKernel(function(Request $req) {
            return new Response("Fallback!");
        });

        $urlMap = new UrlMap($app);
        $urlMap->setMap(array(
            '/foo' => new CallableHttpKernel(function(Request $req) use ($test) {
                $test->assertEquals('/', $req->getPathinfo());
                $test->assertEquals('/foo', $req->attributes->get(UrlMap::ATTR_PREFIX));

                return new Response("Hello World");
            })
        ));

        $resp = $urlMap->handle(Request::create('/foo?bar=baz'));

        $this->assertEquals('Hello World', $resp->getContent());
    }
}

<?php

namespace CHH\Test;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use CHH\UrlMap;
use Stack\CallableHttpKernel;

class UrlMapTest extends \PHPUnit_Framework_TestCase
{
    function test()
    {
        $app = new CallableHttpKernel(function(Request $req) {
            return new Response("Fallback!");
        });

        $urlMap = new UrlMap($app);
        $urlMap->setMap(array(
            '/foo' => new CallableHttpKernel(function(Request $req) {
                return new Response('foo');
            })
        ));

        $req = Request::create('/foo');
        $resp = $urlMap->handle($req);

        $this->assertEquals('foo', $resp->getContent());
    }

    function testOverridesPathInfo()
    {
        $test = $this;

        $app = new CallableHttpKernel(function(Request $req) {
            return new Response("Fallback!");
        });

        $urlMap = new UrlMap($app);
        $urlMap->setMap(array(
            '/foo' => new CallableHttpKernel(function(Request $req) use ($test) {
                $test->assertEquals('/', $req->getPathinfo());
                $test->assertEquals('/foo', $req->attributes->get(UrlMap::ATTR_PREFIX));
                $test->assertEquals('/foo', $req->getBaseUrl());

                return new Response("Hello World");
            })
        ));

        $resp = $urlMap->handle(Request::create('/foo?bar=baz'));

        $this->assertEquals('Hello World', $resp->getContent());
    }
}

Add assertion that request base URL is set to the prefix


<?php
	header('Content-type: application/javascript');
	$geturl = "http://www.typesafe.com/how/training.json";
        include "$geturl";
?>

<?php
	header('Content-type: application/javascript');
	$geturl = "http://typesafe.com/subscription/training.json";
        include "$geturl";
?>

Update URL to Typesafe training feed

Update URL to Typesafe training feed


<?php

global $project;
$project = 'mysite';

include_once dirname(__FILE__).'/local.conf.php';

// Sites running on the following servers will be
// run in development mode. See
// http://doc.silverstripe.com/doku.php?id=devmode
// for a description of what dev mode does.
Director::set_dev_servers(array(
	'localhost',
	'127.0.0.1',
));

if (!defined('SS_LOG_FILE')) {
	define('SS_LOG_FILE', '/var/log/silverstripe/'.basename(dirname(dirname(__FILE__))).'.log');
}

SS_Log::add_writer(new SS_LogFileWriter(SS_LOG_FILE), SS_Log::NOTICE, '<=');

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.com/themes/
SSViewer::set_theme('blackcandy');

// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();

MySQLDatabase::set_connection_charset('utf8');

// necessary for now
SQLite3Database::$vacuum = false;

<?php

global $project;
$project = 'mysite';

include_once dirname(__FILE__).'/local.conf.php';

// Sites running on the following servers will be
// run in development mode. See
// http://doc.silverstripe.com/doku.php?id=devmode
// for a description of what dev mode does.
Director::set_dev_servers(array(
	'127.0.0.1',
));

if (!defined('SS_LOG_FILE')) {
	define('SS_LOG_FILE', '/var/log/silverstripe/'.basename(dirname(dirname(__FILE__))).'.log');
}

SS_Log::add_writer(new SS_LogFileWriter(SS_LOG_FILE), SS_Log::NOTICE, '<=');

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.com/themes/
SSViewer::set_theme('blackcandy');

// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();

MySQLDatabase::set_connection_charset('utf8');

// necessary for now
SQLite3Database::$vacuum = false;

Remove localhost as an explicit dev server


<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load($pathAndFilename, $allowSplitSource = false): array
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load(string $pathAndFilename, bool $allowSplitSource = false): array
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

Adjust signature of test class fully

Adjust signature of test class fully


<?php
namespace Avh\Utility;

abstract class ShortcodesAbstract
{
    private $shortcode_map;

    /**
     * Method that's always called for the shortcode
     *
     * @param  array  $atts
     * @param  string $content
     * @param  string $tag
     *
     * @return string
     */
    public function bootstrap($atts, $content, $tag)
    {
        $method = $this->shortcode_map[$tag];
        ob_start();
        $html = '';
        if (is_callable(array($this, $method))) {
            $html = $this->$method($atts, $content, $tag);
            $html .= ob_get_clean();
        }

        return $html;
    }

    public function register($tag, $class)
    {
        $this->shortcode_map[$tag] = $class;
        add_shortcode($tag, array($this, 'bootstrap'));
    }
}

<?php
namespace Avh\Utility;

abstract class ShortcodesAbstract
{
    private $shortcode_map;
    private $shortcode_controller;

    /**
     * @param mixed $shortcode_controller
     */
    public function setShortcodeController($shortcode_controller)
    {
        $this->shortcode_controller = $shortcode_controller;
    }

    /**
     * Method that's always called for the shortcode
     *
     * @param  array  $atts
     * @param  string $content
     * @param  string $tag
     *
     * @return string
     */
    public function bootstrap($atts, $content, $tag)
    {
        $method = $this->shortcode_map[$tag];
        ob_start();
        $html = '';
        if (is_callable(array($this->shortcode_controller, $method))) {
            $html = $this->shortcode_controller->$method($atts, $content, $tag);
            $html .= ob_get_clean();
        }

        return $html;
    }

    public function register($tag, $class)
    {
        $this->shortcode_map[$tag] = $class;
        add_shortcode($tag, array($this, 'bootstrap'));
    }
}

Add more control for shortcode implementation


<?php

namespace Formwerdung\Square\Lib;

abstract class DashboardWidget extends Admin {
  protected static $widget_id;
  protected static $widget_name;

  /**
   * Init function
   */
  public static function widgetInit() {
    wp_add_dashboard_widget(
      static::$widget_id,
      static::$widget_name,
      get_called_class() . '::widgetTemplate'
    );
  }

  /**
   * Render template
   */
  public static function widgetTemplate() {
    throw new RuntimeException("Unimplemented");
  }

  /**
   * Register hook callbacks
   */
  public static function registerHookCallbacks() {
    add_action('wp_dashboard_setup', [get_called_class() , 'widgetInit']);
    add_action('admin_menu', [ get_called_class(), 'removeNavLabel'], 10);
    add_action('admin_bar_menu', [ get_called_class(), 'removeNode'], 999);
  }
}

<?php

namespace Formwerdung\Square\Lib;

abstract class DashboardWidget extends Admin {

  /**
   * @var   string ID of the widget we're gonna create
   * @access protected
   */
  protected static $widget_id;

  /**
   * @var    string name of the widget we're gonna create
   * @access protected
   */
  protected static $widget_name;

  /**
   * Wrapper function for wp_add_dashboard_widget
   *
   * @since  0.0.1
   * @access public
   * @uses   wp_add_dashboard_widget()
   */
  public static function widgetInit() {
    wp_add_dashboard_widget(
      static::$widget_id,
      static::$widget_name,
      get_called_class() . '::widgetTemplate'
    );
  }

  /**
   * Enforce implementation of widgetTemplate whose sole purpose is to pass data to the view
   *
   * @since  0.0.1
   * @access public
   */
  public static function widgetTemplate() {
    throw new RuntimeException("Unimplemented");
  }
}

Remove hook callback function since every child class implement individual version, inline documentation


<?php

namespace FluxBB\Controllers;

use FluxBB\Models\User,
	Illuminate\Routing\Controllers\Controller,
	Illuminate\Validation\Validator;

class BaseController extends Controller
{
	public $restful = true;

	public function __construct()
	{}

	public function user()
	{
		return User::current();
	}

	public function validator($attributes, $rules, $messages = array())
	{
		return \Validator::make($attributes, $rules, $messages);//->bundle('fluxbb');
	}

}

<?php

namespace FluxBB\Controllers;

use FluxBB\Models\User,
	Illuminate\Routing\Controller,
	Illuminate\Validation\Validator;

class BaseController extends Controller
{
	public $restful = true;

	public function __construct()
	{}

	public function user()
	{
		return User::current();
	}

	public function validator($attributes, $rules, $messages = array())
	{
		return \Validator::make($attributes, $rules, $messages);//->bundle('fluxbb');
	}

}

Use correct controller base class.

Use correct controller base class.


@extends('layouts.master')

@section('title', 'Do you know the way?')

@section('content')

{{ env('DOMAIN') }} is a private file hosting website.

Accounts are given with approval from {{ env('OWNER_NAME') }} <{{ env('OWNER_EMAIL') }}>.

Your request will NOT be accepted if I don't know you or I'm not expecting your request prior to you making
            it.

In other words, random requests are not welcome and will not be accepted.

        Login
        Request Account

@stop

Use container-sm on the index page also

Use container-sm on the index page also


<?php

namespace OpenSky\Bundle\RuntimeConfigBundle\Twig\Extension;

use OpenSky\Bundle\RuntimeConfigBundle\Service\RuntimeParameterBag;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;

class RuntimeConfigExtension extends \Twig_Extension
{
    protected $runtimeConfig;

    /**
     * Constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(RuntimeParameterBag $runtimeConfig)
    {
        $this->runtimeConfig = $runtimeConfig;
    }

    /**
     * Returns a list of global functions to add to the existing list.
     *
     * @return array An array of global functions
     */
    public function getFunctions()
    {
        return array(
            'runtime_config' => new \Twig_Function_Method($this, 'getRuntimeConfig'),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'runtime_config';
    }

    public function getRuntimeConfig($name)
    {
        try {
            return $this->runtimeConfig->get($name);
        } catch (ParameterNotFoundException $e) {
            return null;
        } catch (\InvalidArgumentException $e) {
            return null;
        }
    }
}

<?php

namespace OpenSky\Bundle\RuntimeConfigBundle\Twig\Extension;

use OpenSky\Bundle\RuntimeConfigBundle\Service\RuntimeParameterBag;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;

class RuntimeConfigExtension extends \Twig_Extension
{
    protected $runtimeConfig;

    /**
     * Constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(RuntimeParameterBag $runtimeConfig)
    {
        $this->runtimeConfig = $runtimeConfig;
    }

    /**
     * Returns a list of global functions to add to the existing list.
     *
     * @return array An array of global functions
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('runtime_config', array($this, 'getRuntimeConfig')),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'runtime_config';
    }

    public function getRuntimeConfig($name)
    {
        try {
            return $this->runtimeConfig->get($name);
        } catch (ParameterNotFoundException $e) {
            return null;
        } catch (\InvalidArgumentException $e) {
            return null;
        }
    }
}

Update RunTimeConfigExtension for Twig deprecations


<?php

namespace App\Http\Livewire;

use App\Models\SurveyScheduleView;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class SurveyScheduleTable extends DataTableComponent
{
    public string $defaultSortColumn = 'prevSurveyDate';
    public string $defaultSortDirection = 'asc';
    public bool $singleColumnSorting = false;
    public bool $paginationEnabled = false;

    public function columns(): array
    {
        return [
            Column::make('ID', 'id')
,
            Column::make('Description', 'description'),
            Column::make('Previous', 'prevSurveyDate')
                ->sortable(),
            Column::make('Prev Survey ID', 'prevSurveyID'),
            Column::make('Current', 'currSurveyDate')
                ->sortable(),
            Column::make('Current Survey ID', 'currSurveyID'),
        ];
    }

    public function rowView(): string
    {
        // Use a custom row view so that things like the manufacturer,
        // modality, description, location can be made clickable URLs
        return 'livewire-tables.survey-schedule-row';
    }

    public function query(): Builder
    {
        return SurveyScheduleView::query()
            ->with('machine', 'prevSurvey', 'currSurvey');
    }
}

<?php

namespace App\Http\Livewire;

use App\Models\SurveyScheduleView;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class SurveyScheduleTable extends DataTableComponent
{
    public string $defaultSortColumn = 'prevSurveyDate';
    public string $defaultSortDirection = 'asc';
    public bool $singleColumnSorting = false;
    public bool $paginationEnabled = false;

    public function columns(): array
    {
        return [
            Column::make('ID', 'id'),
            Column::make('Description', 'description')
                ->searchable(),
            Column::make('Previous', 'prevSurveyDate')
                ->sortable(),
            Column::make('Prev Survey ID', 'prevSurveyID'),
            Column::make('Current', 'currSurveyDate')
                ->sortable(),
            Column::make('Current Survey ID', 'currSurveyID'),
        ];
    }

    public function rowView(): string
    {
        // Use a custom row view so that things like the manufacturer,
        // modality, description, location can be made clickable URLs
        return 'livewire-tables.survey-schedule-row';
    }

    public function query(): Builder
    {
        return SurveyScheduleView::query()
            ->with('machine', 'prevSurvey', 'currSurvey');
    }
}

Make the description column searchable

Make the description column searchable

Works, but need to refresh the page to get rid of the "extra" results.
Could be related to https://github.com/rappasoft/laravel-livewire-tables/discussions/374


<?php

namespace App\Ship\Transporters;

use App\Ship\Parents\Transporters\Transporter;

/**
 * Class DataTransporter
 *
 * @author Johannes Schobel <johannes.schobel@googlemail.com>
 */
class DataTransporter extends Transporter
{
    /*
     * README FIRST and be sure to fully understand this concept!
     * This is the default transporter that is used, if no other one is specified in the REQUEST class itself. This Transporter,
     * in turn, makes no restrictions to the properties; i.e., it allows everything to be written. This may be ok for
     * some use-cases, however, you may also want to create your own, more specifically tailored Transporters.
     */

    /**
     * @var array
     */
    protected $schema = [
        'type' => 'object',
        'properties' => [
            //
        ],
        'additionalProperties' => true,
        'required' => [  // defined Transporter required fields ['first_name', 'last_name'],

        ],
        'default' => [
//            'foo' => 'bar',
        ]
    ];
}

<?php

namespace App\Ship\Transporters;

use App\Ship\Parents\Transporters\Transporter;

/**
 * Class DataTransporter
 *
 * @author Johannes Schobel <johannes.schobel@googlemail.com>
 */
class DataTransporter extends Transporter
{
    /*
     * README FIRST and be sure to fully understand this concept!
     * This is the default transporter that is used, if no other one is specified in the REQUEST class itself. This Transporter,
     * in turn, makes no restrictions to the properties; i.e., it allows everything to be written. This may be ok for
     * some use-cases, however, you may also want to create your own, more specifically tailored Transporters.
     */

    /**
     * @var array
     */
    protected $schema = [
        'type' => 'object',
        'properties' => [
            'additionalProperties' => true,
        ],
        'required' => [  // defined Transporter required fields ['first_name', 'last_name'],

        ],
        'default' => [
//            'foo' => 'bar',
        ]
    ];
}

Revert "Fix default transporter additional properties"


<?php

namespace Metrique\Building\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;

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

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'published_at' => 'published date',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => [
                'required',
                'string',
                new AbsoluteUrlPathRule,
                Rule::unique(
                    'pages',
                    'path'
                )->ignore(
                    optional($this->page)->id
                ),
            ],
            'title' => [
                'required',
                'string',
            ],
            'description' => [
                'required',
                'string',
            ],
            'image' => [
                'string',
                'url'
            ],
            'meta' => [
                'required',
                'json',
            ],
            'params' => [
                'required',
                'json',
            ],
            'published_at' => [
                'date',
            ],
        ];
    }
}

<?php

namespace Metrique\Building\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;

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

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'path' => 'Path',
            'published_at' => 'published date',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => [
                'required',
                'string',
                new AbsoluteUrlPathRule,
                Rule::unique(
                    'pages',
                    'path'
                )->ignore(
                    optional($this->page)->id
                ),
            ],
            'title' => [
                'required',
                'string',
            ],
            'description' => [
                'required',
                'string',
            ],
            'image' => [
                'string',
                'url'
            ],
            'meta' => [
                'required',
                'json',
            ],
            'params' => [
                'required',
                'json',
            ],
            'published_at' => [
                'nullable',
                'date',
            ],
        ];
    }
}

Allow null published_at, fix Validation message


<?php
namespace Alt3\Swagger\Controller;

use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Routing\Router;

/**
 * UiController class responsible for serving the swagger-ui template page.
 *
 * @package Alt3\Swagger\Controller
 */
class UiController extends AppController
{

    /**
     * Index action used for setting template variables.
     *
     * @return void
     */
    public function index()
    {
        $this->viewBuilder()->layout(false);

        $this->set('config', static::$config['ui']);

        // make the first document autoload inside the UI
        $defaultDocument = key(static::$config['library']);
        if (!$defaultDocument) {
            throw new \InvalidArgumentException("cakephp-swagger configuration file does not contain any documents");
        }

        $this->set('url', Router::url([
            'plugin' => 'Alt3/Swagger',
            'controller' => 'Docs',
            'action' => 'index',
            $defaultDocument
        ], true));
    }
}

<?php
namespace Alt3\Swagger\Controller;

use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Routing\Router;

/**
 * UiController class responsible for serving the swagger-ui template page.
 *
 * @package Alt3\Swagger\Controller
 */
class UiController extends AppController
{

    /**
     * Index action used for setting template variables.
     *
     * @return void
     */
    public function index()
    {
        $this->viewBuilder()->layout(false);

        $this->set('config', static::$config['ui']);

        // Load petstore document if library contains no entries
        if (empty(static::$config['library'])) {
            $this->set('url', 'http://petstore.swagger.io/v2/swagger.json');
            return;
        }

        // Otherwise load first document found in the library
        $defaultDocument = key(static::$config['library']);
        $this->set('url', Router::url([
            'plugin' => 'Alt3/Swagger',
            'controller' => 'Docs',
            'action' => 'index',
            $defaultDocument
        ], true));
    }
}

Load petstore if library contains no documents


<?php

namespace BrianFaust\Addressable\Interfaces;

interface HasAddresses
{
    /**
     * @return mixed
     */
    public function addresses();

    /**
     * @param $address
     *
     * @return mixed
     */
    public function primaryAddress($address);

    /**
     * @param $address
     *
     * @return mixed
     */
    public function billingAddress($address);

    /**
     * @param $address
     *
     * @return mixed
     */
    public function shippingAddress($address);

    /**
     * @param $data
     *
     * @return mixed
     */
    public function createAddress($data);

    /**
     * @param $address
     * @param $data
     *
     * @return mixed
     */
    public function updateAddress($address, $data);

    /**
     * @param $address
     *
     * @return mixed
     */
    public function deleteAddress($address);

    /**
     * @param $distance
     * @param $type
     * @param $lat
     * @param $lng
     *
     * @return mixed
     */
    public static function findByDistance($distance, $type, $lat, $lng);
}

<?php

namespace BrianFaust\Addressable\Interfaces;

interface HasAddresses
{
    /**
     * @return mixed
     */
    public function addresses();

    /**
     * @param $address
     *
     * @return mixed
     */
    public function primaryAddress($address);

    /**
     * @param $address
     *
     * @return mixed
     */
    public function billingAddress($address);

    /**
     * @param $address
     *
     * @return mixed
     */
    public function shippingAddress($address);

    /**
     * @param $distance
     * @param $type
     * @param $lat
     * @param $lng
     *
     * @return mixed
     */
    public static function findByDistance($distance, $type, $lat, $lng);
}

Remove CRUD methods from interface

Remove CRUD methods from interface


<?php
namespace wcf\system\page\handler;
use wcf\data\category\AbstractDecoratedCategory;
use wcf\data\IAccessibleObject;

/**
 * Implementation of the `IMenuPageHandler::isVisible()` methods for decorated category-bound pages.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Page\Handler
 * @since	3.0
 */
trait TDecoratedCategoryMenuPageHandler {
	/**
	 * Returns the name of the decorated class name.
	 *
	 * @return	string
	 */
	abstract protected function getDecoratedCategoryClass();

	/**
	 * @see	IMenuPageHandler::isVisible()
	 */
	public function isVisible($objectID = null) {
		$className = $this->getDecoratedCategoryClass();

		/** @var AbstractDecoratedCategory $category */
		$category = $className::getCategory($objectID);

		// check if category exists
		if ($category === null) {
			return false;
		}

		// check if access to category is restricted
		if ($category instanceof IAccessibleObject && !$className->isAccessible()) {
			return false;
		}

		// fallback to default value of AbstractMenuPageHandler::isVisible()
		return true;
	}
}

<?php
namespace wcf\system\page\handler;
use wcf\data\category\AbstractDecoratedCategory;
use wcf\data\IAccessibleObject;

/**
 * Implementation of the `IMenuPageHandler::isVisible()` methods for decorated category-bound pages.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Page\Handler
 * @since	3.0
 */
trait TDecoratedCategoryMenuPageHandler {
	/**
	 * Returns the name of the decorated class name.
	 *
	 * @return	string
	 */
	abstract protected function getDecoratedCategoryClass();

	/**
	 * @see	IMenuPageHandler::isVisible()
	 */
	public function isVisible($objectID = null) {
		$className = $this->getDecoratedCategoryClass();

		/** @var AbstractDecoratedCategory $category */
		$category = $className::getCategory($objectID);

		// check if category exists
		if ($category === null) {
			return false;
		}

		// check if access to category is restricted
		if ($category instanceof IAccessibleObject && !$category->isAccessible()) {
			return false;
		}

		// fallback to default value of AbstractMenuPageHandler::isVisible()
		return true;
	}
}

Fix variable name in `TDecoratedCategoryMenuPageHandler`


<?php
/**
 * This is a Tiramizo Webhook URL
 */

//oxid should execute oxtiramizoo_webhook view
$_POST['cl'] = 'oxtiramizoo_webhook';

// executing regular routines ...
require '../../index.php';

<?php
/**
 * This is a Tiramizo Webhook URL
 */

//oxid should execute oxtiramizoo_webhook view
$_POST['cl'] = 'oxtiramizoo_webhook';

// executing regular routines ...

if ( !defined( 'OXID_PHP_UNIT' ) ) {
	require '../../index.php';
}

Hide including index file from phpunit

Hide including index file from phpunit


<!doctype html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>

<!DOCTYPE html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>
</head><body></body>
</html>

Add charset to HTML5 doc (and make more XHTML friendly)


<?php
namespace common\widgets;

use app\modules\article\models\Tag;
use yii\base\Widget;
use yii\bootstrap\Html;

/**
 * Class TagsInputWidget
 * @package common\widgets
 * @property Tag[] $tags
 */
class TagsWidget extends Widget
{
    public function run()
    {
        $html = '';
        foreach ($this->tags as $tag) {
            $html .= $this->renderTagItem($tag);
        }

        return $html;
    }

    /**
     * @param Tag|Tag[] $tags
     */
    public function setTags($tags)
    {
        $this->tags = is_array($tags) ? $tags : [$tags];
    }

    /**
     * @param Tag $tag
     * @return string
     */
    private function renderTagItem(Tag $tag)
    {
        return Html::a($tag->name, $tag->getUrlView(), ['class' => 'label label-info']);
    }
}

<?php
namespace common\widgets;

use app\modules\article\models\Tag;
use yii\base\Widget;
use yii\bootstrap\Html;

/**
 * Class TagsInputWidget
 * @package common\widgets
 * @property Tag[] $tags
 */
class TagsWidget extends Widget
{
    public function run()
    {
        $html = '';
        foreach ($this->tags as $tag) {
            $html .= '
'.$this->renderTagItem($tag);
        }

        return $html;
    }

    /**
     * @param Tag|Tag[] $tags
     */
    public function setTags($tags)
    {
        $this->tags = is_array($tags) ? $tags : [$tags];
    }

    /**
     * @param Tag $tag
     * @return string
     */
    private function renderTagItem(Tag $tag)
    {
        return Html::a($tag->name, $tag->getUrlView(), ['class' => 'label label-info']);
    }
}

Write each tag from newline

Write each tag from newline


<?php
namespace MF\Email;

require_once('phpmailer/class.phpmailer.php');

class Mailer extends \PHPMailer {

}

<?php
namespace MF\Email;

require_once('phpmailer/class.phpmailer.php');

class Mailer extends \PHPMailer {
	public function __construct() {
		$this->CharSet = 'iso-8859-15';
	}
}

Add default Charset to iso-8859-15

Add default Charset to iso-8859-15


<?php

namespace Sle\TYPO3\Extbase\Domain\Utility;

use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Class EntityUtility
 *
 * @package Sle\TYPO3\Extbase\Domain\Utility
 * @author Steve Lenz <kontakt@steve-lenz.de>
 * @copyright (c) 2015, Steve Lenz
 */
class EntityUtility
{

    /**
     * @param mixed $value
     * @param string $fullQualifiedClassName - e.g. \\My\\App\\Entity
     * @return mixed
     */
    public static function getEntityByValueAdnClass($value, $fullQualifiedClassName)
    {
        if (is_a($value, $fullQualifiedClassName)) {
            return $value;
        } else {
            $om = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $repo = $om->get($fullQualifiedClassName . 'Repository');
            $entity = $repo->findByUid($value);
            return $entity;
        }
    }

}

<?php

namespace Sle\TYPO3\Extbase\Domain\Utility;

use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Class EntityUtility
 *
 * @package Sle\TYPO3\Extbase\Domain\Utility
 * @author Steve Lenz <kontakt@steve-lenz.de>
 * @copyright (c) 2015, Steve Lenz
 */
class EntityUtility
{

    /**
     * @param mixed $value
     * @param string $fullQualifiedClassName - e.g. \\My\\App\\Entity
     * @return mixed
     */
    public static function getEntityByValueAndClass($value, $fullQualifiedClassName)
    {
        if (is_a($value, $fullQualifiedClassName)) {
            return $value;
        } else {
            $om = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $repo = $om->get($fullQualifiedClassName . 'Repository');
            $entity = $repo->findByUid($value);
            return $entity;
        }
    }

}

[Bugfix] Remove typo in method name "getEntityByValueAndClass"


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

use \CodeDay\Clear\Models;

class DashboardController extends \Controller {

    public function getIndex()
    {
        return \View::make('dashboard');
    }

    public function getChangeBatch()
    {
        if (\Input::get('id')) {
            Models\Batch::find(\Input::get('id'))->manage();
            return \Redirect::to('/');
        } else {
            return \View::make('change_batch');
        }
    }

    public function getUpdates()
    {
        if (Models\User::me()->is_admin) {
            $events = Models\Batch::Managed()->events;
        } else {
            $events = Models\User::me()->current_managed_events;
        }

        $event_update = [];
        foreach ($events as $event) {
            $event_update[$event->id] = [
                'registrations' => $event->registrations->count(),
                'today' => count($event->registrations_today),
                'this_week' => count($event->registrations_this_week),
                'percent' => round(($event->registrations->count()/$event->registration_estimate)*100),
                'predicted' => '?',
                'notify' => $event->notify->count(),
                'allow_registrations' => $event->allow_registrations
            ];
        }

        return json_encode($event_update);
    }
}

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

use \CodeDay\Clear\Models;

class DashboardController extends \Controller {

    public function getIndex()
    {
        return \View::make('dashboard');
    }

    public function getChangeBatch()
    {
        if (\Input::get('id')) {
            Models\Batch::find(\Input::get('id'))->manage();
            return \Redirect::to('/');
        } else {
            return \View::make('change_batch');
        }
    }

    public function getUpdates()
    {
        if (Models\User::me()->is_admin) {
            $events = Models\Batch::Managed()->events;
        } else {
            $events = Models\User::me()->current_managed_events;
        }

        $event_update = [];
        foreach ($events as $event) {
            $event_update[$event->id] = [
                'registrations' => $event->registrations->count(),
                'today' => count($event->registrations_today),
                'this_week' => count($event->registrations_this_week),
                'percent' => $event->registration_estimate ? round(($event->registrations->count()/$event->registration_estimate)*100) : 0,
                'predicted' => '?',
                'notify' => $event->notify->count(),
                'allow_registrations' => $event->allow_registrations
            ];
        }

        return json_encode($event_update);
    }
}

Fix divide by zero when no reg estimate

Fix divide by zero when no reg estimate


<?php
declare(strict_types = 1);

namespace unreal4u\TelegramAPI\Telegram\Types\Custom;

use unreal4u\TelegramAPI\Abstracts\CustomType;
use Psr\Log\LoggerInterface;
use unreal4u\TelegramAPI\Interfaces\CustomArrayType;
use unreal4u\TelegramAPI\Telegram\Types\Message;

/**
 * Used for methods that will return an array of messages
 */
class MessageArray extends CustomType implements CustomArrayType
{
    public function __construct(array $data = null, LoggerInterface $logger = null)
    {
        if (count($data) !== 0) {
            foreach ($data as $telegramResponse) {
                // Create an actual Update object and fill the array
                $this->data[] = new Message($telegramResponse, $logger);
            }
        }
    }

    /**
     * Traverses through our $data, yielding the result set
     *
     * @return Update[]
     */
    public function traverseObject()
    {
        foreach ($this->data as $message) {
            yield $message;
        }
    }
}

<?php
declare(strict_types = 1);

namespace unreal4u\TelegramAPI\Telegram\Types\Custom;

use Psr\Log\LoggerInterface;
use unreal4u\TelegramAPI\Abstracts\TraversableCustomType;
use unreal4u\TelegramAPI\Telegram\Types\Message;

/**
 * Used for methods that will return an array of messages
 */
class MessageArray extends TraversableCustomType
{
    public function __construct(array $data = null, LoggerInterface $logger = null)
    {
        if (count($data) !== 0) {
            foreach ($data as $telegramResponse) {
                // Create an actual Update object and fill the array
                $this->data[] = new Message($telegramResponse, $logger);
            }
        }
    }

    /**
     * Traverses through our $data, yielding the result set
     *
     * @return Update[]
     */
    public function traverseObject()
    {
        foreach ($this->data as $message) {
            yield $message;
        }
    }
}

Fix some more BC between v2 and v3

Fix some more BC between v2 and v3


<?php
/**
 * Created by mcfedr on 7/28/16 14:24
 */
namespace Mcfedr\QueueManagerBundle\Manager;

use Mcfedr\QueueManagerBundle\Queue\Job;

class QueueManagerRegistry
{
    /**
     * @var QueueManager[]
     */
    private $queueManagers;

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

    /**
     * @param array $queueManagers
     * @param string $default
     */
    public function __construct(array $queueManagers, $default)
    {
        $this->queueManagers = $queueManagers;
        $this->default = $default;
    }

    /**
     * @param string $name
     * @param array $arguments
     * @param array $options
     * @param string $manager
     * @return Job
     */
    public function put($name, array $arguments = [], array $options = [], $manager = null)
    {
        return $this->queueManagers[$manager ?: $this->default]->put($name, $arguments, $options);
    }

    /**
     * @param Job $job
     * @param string $manager
     */
    public function delete(Job $job, $manager = null)
    {
        $this->queueManagers[$manager ?: $this->default]->delete($job);
    }
}

<?php
/**
 * Created by mcfedr on 7/28/16 14:24
 */
namespace Mcfedr\QueueManagerBundle\Manager;

use Mcfedr\QueueManagerBundle\Exception\NoSuchJobException;
use Mcfedr\QueueManagerBundle\Exception\WrongJobException;
use Mcfedr\QueueManagerBundle\Queue\Job;

class QueueManagerRegistry
{
    /**
     * @var QueueManager[]
     */
    private $queueManagers;

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

    /**
     * @param array $queueManagers
     * @param string $default
     */
    public function __construct(array $queueManagers, $default)
    {
        $this->queueManagers = $queueManagers;
        $this->default = $default;
    }

    /**
     * @param string $name
     * @param array $arguments
     * @param array $options
     * @param string $manager
     * @return Job
     */
    public function put($name, array $arguments = [], array $options = [], $manager = null)
    {
        return $this->queueManagers[$manager ?: $this->default]->put($name, $arguments, $options);
    }

    /**
     * @param Job $job
     * @param string $manager
     * @throws WrongJobException
     * @throws NoSuchJobException
     */
    public function delete(Job $job, $manager = null)
    {
        if ($manager) {
            $this->queueManagers[$manager]->delete($job);
            return;
        }

        foreach ($this->queueManagers as $queueManager) {
            try {
                $queueManager->delete($job);
                return;
            } catch (WrongJobException $e) {

            }
        }

        throw new WrongJobException('Cannot find a manager able to delete this job');
    }
}

Delete will try to delete from all the managers


<?php

$t = new Test\Ternary();

assert($t->testTernary1() === 101);
assert($t->testTernary2(true) === "foo");
assert($t->testTernary2(false) === "bar");
assert($t->testTernaryComplex1([], "") === 101);
assert($t->testTernaryComplex2([], "") === 106);
assert($t->testTernaryComplex3("") === "boolean");

<?php

$t = new Test\Ternary();

assert($t->testTernary1() === 101);
assert($t->testTernary2(true) === "foo");
assert($t->testTernary2(false) === "bar");
assert($t->testTernaryComplex1(array(), "") === 101);
assert($t->testTernaryComplex2(array(), "") === 106);
assert($t->testTernaryComplex3("") === "boolean");

Fix php 5.3 build failed on

Fix php 5.3 build failed on []


<?php

namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroImapBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addAccessTokenFieldToOroEmailOriginTable($schema);
    }

    /**
     * Adds Access Token field to the oro_email_origin table
     *
     * @param Schema $schema
     * @throws \Doctrine\DBAL\Schema\SchemaException
     */
    public static function addAccessTokenFieldToOroEmailOriginTable(Schema $schema)
    {
        $table = $schema->getTable('oro_email_origin');
        $table->addColumn('access_token', 'string', ['notnull' => false, 'length' => 255]);
    }
}

<?php

namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;

use Doctrine\DBAL\Schema\SchemaException;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroImapBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addAccessTokenFieldToOroEmailOriginTable($schema);
    }

    /**
     * Adds Access Token field to the oro_email_origin table
     *
     * @param Schema $schema
     * @throws SchemaException
     */
    public static function addAccessTokenFieldToOroEmailOriginTable(Schema $schema)
    {
        $table = $schema->getTable('oro_email_origin');
        $table->addColumn('access_token', 'string', ['notnull' => false, 'length' => 255]);
    }
}

Create new type Origin oauthOrigin

BAP-9558: Create new type Origin oauthOrigin


@extends('layouts.application.guest')

@section('content')
    <form action="{{ route('dashboard.user.login') }}" id="loginForm" method="post">
        {{ csrf_field() }}

        @php($isLoginSet = !empty(old('login')))

        {{-- Login --}}
        {!!
            Form::textInput()
                ->setIdAndName('login')
                ->setPlaceholder(__('Dashboard::views/user/login.login.placeholder'))
                ->setLeftAddonIcon('fa fa-user')
                ->setAutoValue(true)
                ->setAutofocus(!$isLoginSet)
         !!}

        {{-- Password --}}
        {!!
            Form::passwordInput()
                ->setIdAndName('password')
                ->setPlaceholder(__('Dashboard::views/user/login.password.placeholder'))
                ->setLeftAddonIcon('fa fa-key')
                ->setAutofocus($isLoginSet)
         !!}

                <input
                        type="checkbox"
                        id="remember-me"
                        name="remember-me"
                        value="1"
                        placeholder=""/>
                {{ __('Dashboard::views/user/login.remember-me.label') }}

            <button type="submit" class="btn btn-info">
                {{ __('Dashboard::views/user/login.submit') }}
            </button>

    </form>
@endsection

@extends('layouts.application.guest')

@section('content')
    <form action="{{ route('dashboard.user.login') }}" id="loginForm" method="post">
        {{ csrf_field() }}

        @php($isLoginSet = !empty(old('login')))

        {{-- Login --}}
        {!!
            Form::textInput()
                ->setIdAndName('login')
                ->setPlaceholder(__('Dashboard::views/user/login.login.placeholder'))
                ->setLeftAddonIcon('fa fa-user')
                ->setAutoValue(true)
                ->setAutofocus(!$isLoginSet)
         !!}

        {{-- Password --}}
        {!!
            Form::passwordInput()
                ->setIdAndName('password')
                ->setPlaceholder(__('Dashboard::views/user/login.password.placeholder'))
                ->setLeftAddonIcon('fa fa-key')
                ->setAutofocus($isLoginSet)
         !!}

        {{-- Remember me --}}
        {!!
            Form::checkbox()
                ->setIdAndName('remember-me')
                ->setLabel(__('Dashboard::views/user/login.remember-me.label'))
                ->setValue(1)
         !!}

            <button type="submit" class="btn btn-info">
                {{ __('Dashboard::views/user/login.submit') }}
            </button>

    </form>
@endsection

Use Form::checkbox() helper instead of raw HTML in login form.


<?php

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

class UpdateAssessmentsTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->char('score_comedy')->after('score_nuki')->nullable()->default('');
				$table->boolean('savable')->after('score_all')->nullable();
			});
		}
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->dropColumn(['score_comedy', 'savable']);
			});
		}
	}
}

<?php

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

class UpdateAssessmentsTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->char('score_comedy')->after('score_nuki')->nullable()->default('');
				$table->string('savable', 16)->after('score_all')->nullable()->default('unknown');
			});
		}
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->dropColumn(['score_comedy', 'savable']);
			});
		}
	}
}

Change data type of 'savable' column on 'assessments' table


<?php namespace Essence\Matchers;

class ContainMatcher extends AbstractMatcher
{

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        $configuration = essence()->getConfiguration("matcher_settings");

        if (array_key_exists(__CLASS__, $configuration)) {
            $this->value = $configuration[__CLASS__];
        }

        $element = end($this->arguments);

        $ofCorrectType = (is_array($this->value) or is_string($this->value));

        if ($this->configurationOnly or ! $ofCorrectType) {
            $this->throwUnintendedUsageException();
            // @codeCoverageIgnoreStart
        }
        // @codeCoverageIgnoreEnd

        $result = true;

        if (is_string($this->value)) {
            $result = strpos($this->value, $element) !== false;
        }

        if (is_array($this->value)) {
            $result = in_array($element, $this->value, true);
        }

        if ( ! $result) {
            $this->setMessage(sprintf(
                "ContainMatcher: the given %s does not contain the given %s value.",
                gettype($this->value),
                gettype($element)
            ));

            return false;
        }

        return true;
    }
}

<?php namespace Essence\Matchers;

class ContainMatcher extends AbstractMatcher
{

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        $configuration = essence()->getConfiguration("matcher_settings");

        if (array_key_exists(__CLASS__, $configuration)) {
            $this->value = $configuration[__CLASS__];

            unset($configuration[__CLASS__]);
            essence()->configure(function() use ($configuration) {
                return $configuration;
            });
        }

        $element = end($this->arguments);

        $ofCorrectType = (is_array($this->value) or is_string($this->value));

        if ($this->configurationOnly or ! $ofCorrectType) {
            $this->throwUnintendedUsageException();
            // @codeCoverageIgnoreStart
        }
        // @codeCoverageIgnoreEnd

        $result = true;

        if (is_string($this->value)) {
            $result = strpos($this->value, $element) !== false;
        }

        if (is_array($this->value)) {
            $result = in_array($element, $this->value, true);
        }

        if ( ! $result) {
            $this->setMessage(sprintf(
                "ContainMatcher: the given %s does not contain the given %s value.",
                gettype($this->value),
                gettype($element)
            ));

            return false;
        }

        return true;
    }
}

Remove the configuration entry after copying its value.


<?php

namespace UCP\AbsenceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Lesson
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User")
     */
    private $professor;

    /**
     * @ORM\Column(type="string")
     */
    private $label;

    /**
     * @ORM\Column(type="datetime")
     */
    private $start;

    /**
     * @ORM\Column(type="datetime")
     */
    private $end;
}

<?php

namespace UCP\AbsenceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Lesson
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User")
     */
    private $professor;

    /**
     * @ORM\Column(type="string")
     */
    private $label;

    /**
     * @ORM\Column(type="datetime")
     */
    private $start;

    /**
     * @ORM\Column(type="datetime")
     */
    private $end;

    /**
     * @ORM\Column(type="string")
     */
    private $eventId;
}

Add eventId to lesson to keep track of related calendar event


<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 20/10/2016
 * Time: 15:57
 */

namespace vr\api\doc\widgets;

use yii\bootstrap\Widget;
use yii\data\ArrayDataProvider;
use yii\widgets\ListView;

/**
 * Class ControllersListView
 * @package vr\api\doc\widgets
 */
class ControllersListView extends Widget
{
    /**
     * @var null
     */
    public $models = null;

    /**
     * @return string
     * @throws \Exception
     */
    public function run()
    {
        return ListView::widget([
            'dataProvider' => new ArrayDataProvider([
                'allModels' => $this->models,
            ]),
            'layout'       => '{items}',
            'itemView'     => '@api/doc/widgets/views/controller-list-item-view',
        ]);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 20/10/2016
 * Time: 15:57
 */

namespace vr\api\doc\widgets;

use yii\bootstrap\Widget;
use yii\data\ArrayDataProvider;
use yii\widgets\ListView;

/**
 * Class ControllersListView
 * @package vr\api\doc\widgets
 */
class ControllersListView extends Widget
{
    /**
     * @var null
     */
    public $models = null;

    /**
     * @return string
     * @throws \Exception
     */
    public function run()
    {
        return ListView::widget([
            'dataProvider' => new ArrayDataProvider([
                'allModels'  => $this->models,
                'pagination' => false,
            ]),
            'layout'       => '{items}',
            'itemView'     => '@api/doc/widgets/views/controller-list-item-view',
        ]);
    }
}

Remove pagination from controllers data provider to show more than 20 controllers


<?php
/**
 * SampleTask file
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         1.2.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestApp\Shell\Task;

use Cake\Console\Shell;

class SampleTask extends Shell
{

    public function getOptionParser()
    {
        $parser = parent::getOptionParser();
        $parser->addOption('sample', [
            'short' => 's',
            'help' => 'This is a sample option for the sample task.',
        ]);
        return $parser;
    }
}

<?php
/**
 * SampleTask file
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestApp\Shell\Task;

use Cake\Console\Shell;

class SampleTask extends Shell
{

    public function getOptionParser()
    {
        $parser = parent::getOptionParser();
        $parser->addOption('sample', [
            'short' => 's',
            'help' => 'This is a sample option for the sample task.',
        ]);
        return $parser;
    }
}

Remove wrong @since comment in docblock

Remove wrong @since comment in docblock


<?php

namespace BFITech\ZapAdmin;

/**
 * AdminRoute class.
 *
 * This is a thin layer than glues router and storage together.
 * Subclassess extend this instead of abstract AdminStore.
 *
 * @see AdminRouteDefault for limited example.
 */
class AdminRoute extends AdminStore {

	/**
	 * Standard wrapper for Router::route.
	 *
	 * @param string $path Router path.
	 * @param callable $callback Router callback.
	 * @param string|array $method Router request method.
	 */
	public function route($path, $callback, $method='GET') {
		$this->core->route($path, function($args) use($callback){
			# set token if available
			if (isset($args['cookie'][$this->token_name])) {
				# via cookie
				$this->adm_set_user_token(
					$args['cookie'][$this->token_name]);
			} elseif (isset($args['header']['authorization'])) {
				# via request header
				$auth = explode(' ', $args['header']['authorization']);
				if ($auth[0] == $this->token_name) {
					$this->adm_set_user_token($auth[1]);
				}
			}
			# execute calback
			$callback($args);
		}, $method);
	}

}

<?php

namespace BFITech\ZapAdmin;

/**
 * AdminRoute class.
 *
 * This is a thin layer than glues router and storage together.
 * Subclassess extend this instead of abstract AdminStore.
 *
 * @see AdminRouteDefault for limited example.
 */
class AdminRoute extends AdminStore {

	/**
	 * Standard wrapper for Router::route.
	 *
	 * @param string $path Router path.
	 * @param callable $callback Router callback.
	 * @param string|array $method Router request method.
	 * @param bool $is_raw If true, accept raw data instead of parsed
	 */
	public function route($path, $callback, $method='GET', $is_raw=null) {
		$this->core->route($path, function($args) use($callback){
			# set token if available
			if (isset($args['cookie'][$this->token_name])) {
				# via cookie
				$this->adm_set_user_token(
					$args['cookie'][$this->token_name]);
			} elseif (isset($args['header']['authorization'])) {
				# via request header
				$auth = explode(' ', $args['header']['authorization']);
				if ($auth[0] == $this->token_name) {
					$this->adm_set_user_token($auth[1]);
				}
			}
			# execute calback
			$callback($args);
		}, $method, $is_raw);
	}

}

Add is_raw param in route

Add is_raw param in route


<?php

/*
 * This file is part of By Night.
 * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Security;

use App\Entity\User;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        if (!$user instanceof User) {
            return;
        }

        if (!$user->getEnabled()) {
            $exception = new DisabledException('Your user account no longer exists.');
            $exception->setUser($user);
            throw $exception;
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
    }
}

<?php

/*
 * This file is part of By Night.
 * (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Security;

use App\Entity\User;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        if (!$user instanceof User) {
            return;
        }

        if (!$user->getEnabled()) {
            $exception = new DisabledException('Votre compte a été désactivé par un administrateur.');
            $exception->setUser($user);
            throw $exception;
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
    }
}

Update message when account is not enabled


<?hh //strict
class PageIgnoreException extends ErrorException { }

class APIException extends ErrorException {
  public function __construct(string $message = 'Something went wrong') {
    parent::__construct($message);
  }
}
class HTTPException extends ErrorException {
  public int $httpCode;
  public function __construct(int $code) {
    $this->httpCode = (int) $code;
    parent::__construct("HTTP Error $code");
  }
}
class HTTPUnavailableException extends HTTPException {
  public function __construct(string $message) {
    parent::__construct(500);
    $this->message = $message;
  }
}

class HTTPRedirectException extends HTTPException {
  public string $redirectUri;
  public function __construct(string $uri) {
    $this->redirectUri = $uri;
    parent::__construct(302);
  }
}

<?hh //strict
class PageIgnoreException extends ErrorException { }

class APIException extends ErrorException {
  public function __construct(string $message = 'Something went wrong') {
    parent::__construct($message);
  }
}
class HTTPException extends ErrorException {
  public int $httpCode;
  public function __construct(int $code) {
    $this->httpCode = (int) $code;
    parent::__construct("HTTP Error $code");
  }
}
class HTTPUnavailableException extends HTTPException {
  public function __construct(string $message) {
    parent::__construct(500);
    $this->message = $message;
  }
}

class HTTPRedirectException extends HTTPException {
  public string $redirectUri;
  public function __construct(string $uri) {
    parent::__construct(302);
    $this->redirectUri = $uri;
  }
}

:bug: Make sure super is called before anything else

In constructor of an exception


<?php

use Miniflux\Handler;
use Miniflux\Model;
use Miniflux\Session\SessionStorage;
use Pheanstalk\Pheanstalk;

require __DIR__.'/app/common.php';

if (php_sapi_name() !== 'cli') {
    die('This script can run only from the command line.'.PHP_EOL);
}

$connection = new Pheanstalk(BEANSTALKD_HOST);
$session = SessionStorage::getInstance();

while ($job = $connection->reserveFromTube(BEANSTALKD_QUEUE)) {
    $payload = unserialize($job->getData());
    $start_time = microtime(true);

    echo 'Processing feed_id=', $payload['feed_id'], ' for user_id=', $payload['user_id'];

    $session->flush();
    $session->setUser(Model\User\get_user_by_id($payload['user_id']));

    Handler\Feed\update_feed($payload['user_id'], $payload['feed_id']);
    Model\Item\autoflush_read($payload['user_id']);
    Model\Item\autoflush_unread($payload['user_id']);

    echo ', duration='.(microtime(true) - $start_time).' seconds', PHP_EOL;

    Miniflux\Helper\write_debug_file();
    $connection->delete($job);
}

<?php

use Miniflux\Handler;
use Miniflux\Model;
use Miniflux\Session\SessionStorage;
use Pheanstalk\Pheanstalk;

require __DIR__.'/app/common.php';

if (php_sapi_name() !== 'cli') {
    die('This script can run only from the command line.'.PHP_EOL);
}

$connection = new Pheanstalk(BEANSTALKD_HOST);
$session = SessionStorage::getInstance();

while ($job = $connection->reserveFromTube(BEANSTALKD_QUEUE)) {
    $payload = unserialize($job->getData());
    $start_time = microtime(true);

    echo 'Processing feed_id=', $payload['feed_id'], ' for user_id=', $payload['user_id'];
    $user = Model\User\get_user_by_id($payload['user_id']);

    if (empty($user)) {
        echo ', user not found (removed?)'.PHP_EOL;
    } else {
        $session->flush();
        $session->setUser($user);

        Handler\Feed\update_feed($payload['user_id'], $payload['feed_id']);
        Model\Item\autoflush_read($payload['user_id']);
        Model\Item\autoflush_unread($payload['user_id']);

        echo ', duration='.(microtime(true) - $start_time).' seconds', PHP_EOL;

        Miniflux\Helper\write_debug_file();
    }

    $connection->delete($job);
}

Handle the fact that a user can be removed but have feeds in queue


<?php

use OnlyBits\LogicGates\XnorGate;

class XnorGateTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider logicGateTwoInputProvider
     */
    public function testOutputRespectsXnorGateTruthTable($inputs, $out)
    {
        $xnor = new XnorGate;
        $xnor->in($inputs);
        $output = $xnor->out();

        $this->assertEquals($output, $out, "The XOR gate output doesn't respect the truth table!");
    }

    public function logicGateTwoInputProvider()
    {
        return [
            [["1"=>false, "2"=>false], true],
            [["1"=>false, "2"=>true], false],
            [["1"=>true, "2"=>false], false],
            [["1"=>true, "2"=>true], true],
        ];
    }
}

<?php

use OnlyBits\LogicGates\XnorGate;

class XnorGateTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider logicGateTwoInputProvider
     */
    public function testOutputRespectsXnorGateTruthTable($inputs, $out)
    {
        $xnor = new XnorGate;
        $xnor->in($inputs);
        $output = $xnor->out();

        $this->assertEquals($output, $out, "The XNOR gate output doesn't respect the truth table!");
    }

    public function logicGateTwoInputProvider()
    {
        return [
            [["1"=>false, "2"=>false], true],
            [["1"=>false, "2"=>true], false],
            [["1"=>true, "2"=>false], false],
            [["1"=>true, "2"=>true], true],
        ];
    }
}

Correct typo on assertion message.

Correct typo on assertion message.


<?php
/**
 * The Colonel Framework
 *
 * @author Nigel Greenway <nigel_greenway@me.com>
 * @license MIT
 */

namespace Colonel\ConfigurationGenerator;

/**
 * Interface for Configuration Writers
 *
 * @package Colonel\ConfigurationGenerator
 * @author  Nigel Greenway <nigel_greenway@me.com>
 */
interface ConfigurationWriterInterface
{
    /**
     * Write the configuration array to a
     * file
     *
     * @param array $configuration
     *
     * @return void
     */
    public function write(array $configuration = []);
}

<?php
/**
 * The Colonel Framework
 *
 * @author Nigel Greenway <nigel_greenway@me.com>
 * @license MIT
 */

namespace Colonel\ConfigurationGenerator;

/**
 * Interface for Configuration Writers
 *
 * @package Colonel\ConfigurationGenerator
 * @author  Nigel Greenway <nigel_greenway@me.com>
 */
interface ConfigurationWriterInterface
{
    /**
     * Write the configuration array to a
     * file
     *
     * @param string  $configurationPath
     * @param array   $configuration
     * @param integer $spaces
     *
     * @return void
     */
    public static function write(
        $configurationPath,
        array $configuration = [],
        $spaces
    );
}

Add new method params and move to static


<?php

namespace PeterVanDommelen\Parser\Expression\Regex;

use PeterVanDommelen\Parser\Expression\ExpressionResultInterface;
use PeterVanDommelen\Parser\Parser\ParserInterface;

class RegexParser implements ParserInterface
{
    private $regex;

    /**
     * @param $regex
     */
    public function __construct($regex)
    {
        $this->regex = self::wrapRegex($regex);
    }

    private static function wrapRegex($regex) {
        $regex = str_replace('/', '\\/', $regex);
        $regex = "/^(?:" . $regex . ")/s";
        return $regex;
    }

    public function parse($string, ExpressionResultInterface $previous_result = null)
    {
        if ($previous_result !== null) {
            return null;
        }
        $count = preg_match($this->regex, $string, $matches);

        if ($count === 0) {
            return null;
        }
        return new RegexExpressionResult($matches);
    }

}

<?php

namespace PeterVanDommelen\Parser\Expression\Regex;

use PeterVanDommelen\Parser\Expression\ExpressionResultInterface;
use PeterVanDommelen\Parser\Parser\ParserInterface;

class RegexParser implements ParserInterface
{
    private $regex;

    /**
     * @param $regex
     */
    public function __construct($regex)
    {
        $this->regex = self::wrapRegex($regex);
    }

    private static function wrapRegex($regex) {
        $regex = str_replace('/', '\\/', $regex);
        $regex = "/^(?:" . $regex . ")/s";
        return $regex;
    }

    public function parse($string, ExpressionResultInterface $previous_result = null)
    {
        if ($previous_result !== null) {
            return null;
        }
        $count = preg_match($this->regex, $string, $matches);

        if ($count === false) {
            throw new \Exception("Error occured in regex: " . preg_last_error());
        }

        if ($count === 0) {
            return null;
        }
        return new RegexExpressionResult($matches);
    }

}

Throw an exception if the regex fails.

Throw an exception if the regex fails.


<?php declare(strict_types=1);

namespace FilipSedivy\EET\Utils;

class Format
{
    public static function BKB($code): string
    {
        $r = '';
        for ($i = 0; $i < 40; $i++) {
            if ($i % 8 === 0 && $i !== 0) {
                $r .= '-';
            }
            $r .= $code[$i];
        }
        return $r;
    }
}

<?php declare(strict_types=1);

namespace FilipSedivy\EET\Utils;

class Format
{
    public static function BKB(string $code): string
    {
        $r = '';

        for ($i = 0; $i < 40; $i++) {
            if ($i % 8 === 0 && $i !== 0) {
                $r .= '-';
            }

            $r .= $code[$i];
        }

        return $r;
    }
}

:pencil2: Implement PHP 7.x and refactoring by PHPCS


<?php

namespace Bangpound\oEmbed\Negotiation;

class FormatNegotiator extends \Negotiation\FormatNegotiator
{
    protected $formats = array(
      'json' => array('application/json', 'application/x-json', 'application/json+oembed'),
      'xml' => array('text/xml', 'application/xml', 'application/x-xml', 'text/xml+oembed'),
    );
}

<?php

namespace Bangpound\oEmbed\Negotiation;

class FormatNegotiator extends \Negotiation\FormatNegotiator
{
    protected $formats = array(
      'json' => array('application/json', 'application/x-json', 'application/json+oembed', 'text/javascript; charset=UTF-8'),
      'xml' => array('text/xml', 'application/xml', 'application/x-xml', 'text/xml+oembed'),
    );
}

Allow 'text/javascript; charset=UTF-8' as JSON valid format

I'm trying to embed a facebook link using the library and I'm not able because FB oEmbed response is in formar 'text/javascript; charset=UTF-8' instead of 'application/json'
https://developers.facebook.com/docs/plugins/oembed-endpoints
Would be great if you could add this to allow to embed FB posts.

Thanks


<?php
	namespace Bolt;

	use ReflectionClass;
	use ReflectionMethod;

	abstract class Controller extends Base
	{
		public function __toString()
		{
			return "API Object: " . $this->className();
		}

		public function patchData($model, $parameters)
		{
			foreach ($parameters as $key => $value)
			{
				if (is_scalar($value) || $value === null)
				{
					$model->$key($value);
				}
				else
				{
					$model->$key = $this->patchData($model->$key, $value);
				}
			}

			return $model;
		}

		public function endpoints()
		{
			$class = new ReflectionClass($this->className(true));
			$allMethods = $class->getMethods(ReflectionMethod::IS_PUBLIC);

			$methods = array();

			foreach ($allMethods as $next)
			{
				if ($next->name[0] == "_" || in_array($next->name, array("endpoints", "className", "patchData")))
				{
					continue;
				}

				$methods[] = strtoupper($next->name);
			}

			return $methods;
		}
	}
?>

<?php
	namespace Bolt;

	use ReflectionClass;
	use ReflectionMethod;

	abstract class Controller extends Base
	{
		public function __toString()
		{
			return "API Object: " . $this->className();
		}

		public function endpoints()
		{
			$class = new ReflectionClass($this->className(true));
			$allMethods = $class->getMethods(ReflectionMethod::IS_PUBLIC);

			$methods = array();

			foreach ($allMethods as $next)
			{
				if ($next->name[0] == "_" || in_array($next->name, array("endpoints", "className", "patchData")))
				{
					continue;
				}

				$methods[] = strtoupper($next->name);
			}

			return $methods;
		}
	}
?>

Remove legacy method from controller

Remove legacy method from controller