<?php

namespace SleepingOwl\Admin\Traits;

trait MaxFileSizeTrait
{
    /**
     * @var number
     */
    protected $maxFileSize;

    /**
     * @return number
     */
    public function getMaxFileSize()
    {
        if (! $this->maxFileSize) {
            try {
                $this->maxFileSize = $this->convertMB(ini_get('upload_max_filesize'));
            } catch (\Exception $e) {
                $this->maxFileSize = 5;
            }
        }

        return $this->maxFileSize;
    }

    /**
     * Конвертирование значения
     * максимального размера загружаемого файла.
     */
    public function convertMB($value)
    {
        if (is_numeric($value)) {
            return $value;
        } else {
            $value_length = strlen($value);
            $qty = substr($value, 0, $value_length - 1);
            $unit = strtolower(substr($value, $value_length - 1));
            switch ($unit) {
                case 'k':
                $qty /= 1024;
                break;
                case 'm':
                $qty = $qty;
                break;
                case 'g':
                $qty *= 1024;
                break;
            }

            return $qty;
        }
    }
}

<?php

namespace SleepingOwl\Admin\Traits;

trait MaxFileSizeTrait
{
    /**
     * @var number
     */
    protected $maxFileSize;

    /**
     * Возвращает максимальный размер загружаемого файла из конфигурации php.ini
     *
     * @return number Максимальный размер загружаемого файла в килобайтах
     */
    public function getMaxFileSize()
    {
        if (! $this->maxFileSize) {
            try {
                $this->maxFileSize = $this->convertKB(ini_get('upload_max_filesize'));
            } catch (\Exception $e) {
                $this->maxFileSize = 5;
            }
        }

        return $this->maxFileSize;
    }

    /**
     * Конвертация значения размера загружаемого файла.
     *
     * @param string $value
     *
     * @return number Размер файла в килобайтах
     */
    public function convertKB($value)
    {
        if (is_numeric($value)) {
            return $value;
        } else {
            $value_length = strlen($value);
            $qty = substr($value, 0, $value_length - 1);
            $unit = strtolower(substr($value, $value_length - 1));
            switch ($unit) {
                case 'k':
                    $qty = $qty;
                    break;
                case 'm':
                    $qty *= 1024;
                    break;
                case 'g':
                    $qty *= 1048576;
                    break;
            }

            return $qty;
        }
    }
}

Fix значение файла из php.ini конвертируем в килобайты


<?php

use App\Judite\Models\User;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        User::create([
            'name' => 'Administrator',
            'email' => 'contact@hackathonners.org',
            'password' => bcrypt('123456'),
            'is_admin' => true,
        ]);
    }
}

<?php

use App\Judite\Models\User;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        User::create([
            'name' => 'Administrator',
            'email' => env('ADMIN_EMAIL') ?? 'contact@hackathonners.org',
            'password' => bcrypt(env('ADMIN_PASSWORD') ?? '123456'),
            'is_admin' => true,
        ]);
    }
}

Allow admin credentials to be configured in .env file


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

namespace Application\Controller;

use Application\Entity\Group;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class GroupController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }

    public function createAction()
    {
        /** @var \Zend\Form\Form $groupEntity */
        $groupForm = $this->getServiceLocator()->get('Application\Form\Group');
        $groupEntity = new Group();
        $groupForm->bind($groupEntity);

        if ($this->getRequest()->isPost()) {
            $groupForm->setData($this->getRequest()->getPost());
            if ($groupForm->isValid()) {
                $entityManager = $this->getServiceLocator()
                    ->get('Doctrine\ORM\EntityManager');
                $entityManager->persist($groupEntity);
                $entityManager->flush();
                return $this->redirect()->toRoute('group');
            }
        }

        return new ViewModel(['groupForm' => $groupForm]);
    }
}

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

namespace Application\Controller;

use Application\Entity\Group;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class GroupController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }

    public function createAction()
    {
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            $this->flashMessenger()->addErrorMessage('You have to be logged in to create an account');
            return $this->redirect()->toRoute('home');
        }

        /** @var \Zend\Form\Form $groupEntity */
        $groupForm = $this->getServiceLocator()->get('Application\Form\Group');
        $groupEntity = new Group();
        $groupForm->bind($groupEntity);

        if ($this->getRequest()->isPost()) {
            $groupForm->setData($this->getRequest()->getPost());
            if ($groupForm->isValid()) {
                $entityManager = $this->getServiceLocator()
                    ->get('Doctrine\ORM\EntityManager');
                $entityManager->persist($groupEntity);
                $entityManager->flush();
                return $this->redirect()->toRoute('group');
            }
        }

        return new ViewModel(['groupForm' => $groupForm]);
    }
}

Add authentication check in group controller


<?php

require_once(dirname(__FILE__) . '/vendor/autoload.php');
session_start();

spl_autoload_register(function($class) {
    $parts = explode("_", $class);
    $classSlashSeparated = implode('/', $parts);
    $pathToFile = "code/$classSlashSeparated.php";
    $fullPathToFile = dirname(__FILE__) . '/' . $pathToFile;

    if (file_exists($fullPathToFile)) {
        include $fullPathToFile;
    }
});

try {
    Toro::serve(array(
        "/"                                 => "Controller_Index",
        "/available"                        => "Controller_Available",
        "/login"                            => "Controller_Login",
        "/logout"                           => "Controller_Logout",
        "/posts"                            => "Controller_PostList",
        "/posts/new"                        => "Controller_PostNew",
        "/posts/:number"                    => "Controller_Post",
        "/posts/:number/edit"               => "Controller_PostEdit",
        "/posts/:number/notify-comment"     => "Controller_PostCommentNotify",
        "/profile"                          => "Controller_Profile",
        "/user/:number/upvote"              => "Controller_UserUpvote",
        "/:string/posts"                    => "Controller_UserPosts",
        "/(.*)"                             => "Controller_UserProfile",
        "/map"                              => "Controller_Map",
        "/map/users"                        => "Controller_MapUsers",
    ));
} catch (Exception $e) {
    mail("kalen@magemail.co", "MageHero Error", $e->getTraceAsString());
    die("Uh-oh.  Something's not right.  Heroes have been deployed to fix it.");
}

<?php

require_once(dirname(__FILE__) . '/vendor/autoload.php');
session_start();

spl_autoload_register(function($class) {
    $parts = explode("_", $class);
    $classSlashSeparated = implode('/', $parts);
    $pathToFile = "code/$classSlashSeparated.php";
    $fullPathToFile = dirname(__FILE__) . '/' . $pathToFile;

    if (file_exists($fullPathToFile)) {
        include $fullPathToFile;
    }
});

try {
    Toro::serve(array(
        "/"                                 => "Controller_Index",
        "/available"                        => "Controller_Available",
        "/login"                            => "Controller_Login",
        "/logout"                           => "Controller_Logout",
        "/posts"                            => "Controller_PostList",
        "/posts/new"                        => "Controller_PostNew",
        "/posts/:number/edit"               => "Controller_PostEdit",
        "/posts/:number/notify-comment"     => "Controller_PostCommentNotify",
        "/posts/(:number)(/:alpha)?"        => "Controller_Post",
        "/profile"                          => "Controller_Profile",
        "/user/:number/upvote"              => "Controller_UserUpvote",
        "/:string/posts"                    => "Controller_UserPosts",
        "/(.*)"                             => "Controller_UserProfile",
        "/map"                              => "Controller_Map",
        "/map/users"                        => "Controller_MapUsers",
    ));
} catch (Exception $e) {
    mail("kalen@magemail.co", "MageHero Error", $e->getTraceAsString());
    die("Uh-oh.  Something's not right.  Heroes have been deployed to fix it.");
}

Modify Post route to allow for SEO slug suffix.


<?php

namespace BoomCMS\Http\Middleware;

use BoomCMS\Editor\Editor;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class DefineCMSViewSharedVariables
{
    private $app;

    /**
     * @var Editor
     */
    private $editor;

    public function __construct(Application $app, Editor $editor)
    {
        $this->app = $app;
        $this->editor = $editor;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        View::share('button', function ($type, $text, $attrs = []) {
            return new UI\Button($type, $text, $attrs);
        });

        View::share('menu', function () {
            return view('boomcms::menu')->render();
        });

        View::share('menuButton', function () {
            return new UI\MenuButton();
        });

        $jsFile = $this->app->environment('local') ? 'cms.js' : 'cms.min.js';

        View::share('boomJS', "<script type='text/javascript' src='/vendor/boomcms/boom-core/js/$jsFile'></script>");
        View::share('editor', $this->editor);

        return $next($request);
    }
}

<?php

namespace BoomCMS\Http\Middleware;

use BoomCMS\Editor\Editor;
use BoomCMS\Support\Facades\BoomCMS;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class DefineCMSViewSharedVariables
{
    private $app;

    /**
     * @var Editor
     */
    private $editor;

    public function __construct(Application $app, Editor $editor)
    {
        $this->app = $app;
        $this->editor = $editor;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        View::share('button', function ($type, $text, $attrs = []) {
            return new UI\Button($type, $text, $attrs);
        });

        View::share('menu', function () {
            return view('boomcms::menu')->render();
        });

        View::share('menuButton', function () {
            return new UI\MenuButton();
        });

        $jsFile = $this->app->environment('local') ? 'cms.js' : 'cms.min.js';

        View::share('boomJS', "<script type='text/javascript' src='/vendor/boomcms/boom-core/js/$jsFile?".BoomCMS::getVersion()."'></script>");
        View::share('editor', $this->editor);

        return $next($request);
    }
}

Append version to JS url to avoid caching issues when a new version is released


<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Services\Config\Definition;

use Symfony\Component\Config\Definition\TreeBuilder\NodeBuilder;

class HooksDefinition extends AbstractDefinition
{
    /**
     * @var string
     */
    protected $name = 'hooks';

    /**
     * @var string
     */
    protected $description = 'Here you can customize Rocketeer by adding tasks, strategies, etc.';

    /**
     * @param NodeBuilder $node
     *
     * @return NodeBuilder
     */
    protected function getChildren(NodeBuilder $node)
    {
        return $node
            ->arrayNode('events')
                ->children()
                    ->arrayNode('before')
                        ->useAttributeAsKey('name')
                        ->prototype('variable')->end()
                    ->end()
                    ->arrayNode('after')
                        ->useAttributeAsKey('name')
                        ->prototype('variable')->end()
                    ->end()
                ->end()
            ->end()
            ->arrayNode('tasks')
                ->info('Here you can quickly add custom tasks to Rocketeer, as well as to its CLI')
                ->useAttributeAsKey('name')
                ->prototype('variable')->end()
            ->end()
            ->arrayNode('roles')
                ->info('Define roles to assign to tasks'.PHP_EOL."eg. 'db' => ['Migrate']")
                ->useAttributeAsKey('name')
                ->prototype('variable')->end()
            ->end();
    }
}

<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Services\Config\Definition;

use Symfony\Component\Config\Definition\TreeBuilder\NodeBuilder;

class HooksDefinition extends AbstractDefinition
{
    /**
     * @var string
     */
    protected $name = 'hooks';

    /**
     * @var string
     */
    protected $description = 'Here you can customize Rocketeer by adding tasks, strategies, etc.';

    /**
     * @param NodeBuilder $node
     *
     * @return NodeBuilder
     */
    protected function getChildren(NodeBuilder $node)
    {
        return $node
            ->arrayNode('events')
                ->children()
                    ->arrayNode('before')
                        ->useAttributeAsKey('name')
                        ->prototype('array')
                            ->prototype('variable')->end()
                        ->end()
                    ->end()
                    ->arrayNode('after')
                        ->useAttributeAsKey('name')
                        ->prototype('array')
                            ->prototype('variable')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->arrayNode('tasks')
                ->info('Here you can quickly add custom tasks to Rocketeer, as well as to its CLI')
                ->useAttributeAsKey('name')
                ->prototype('variable')->end()
            ->end()
            ->arrayNode('roles')
                ->info('Define roles to assign to tasks'.PHP_EOL."eg. 'db' => ['Migrate']")
                ->useAttributeAsKey('name')
                ->prototype('variable')->end()
            ->end();
    }
}

Enforce events to be arrays

Enforce events to be arrays


<?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade {

	public static function getFacadeAccessor() {
        return class_exists('Imagick') ? 'image/imagick' : 'image/gd';
    }

}

<?php
namespace Concrete\Core\Support\Facade;

class Image extends Facade
{

    public static function getFacadeAccessor()
    {

        if (class_exists('Imagick')) {
            $imagick = new \Imagick();
            $v = $imagick->getVersion();
            list($version, $year, $month, $day, $q, $website) = sscanf(
                $v['versionString'],
                'ImageMagick %s %04d-%02d-%02d %s %s');

            if (version_compare($version, '6.2.9') < 1) {
                return 'image/gd';
            } else {
                return 'image/imagick';
            }
        }

        return 'image/gd';
    }

}

Adjust image facade to detect imagemagick version.

Former-commit-id: 11c81cd4f1955e36813d0c6f7aae855f9ab55e94


<?php

namespace Omnipay\PaymentExpress\Message;

use Omnipay\Common\Message\AbstractResponse;

/**
 * PaymentExpress Response
 */
class Response extends AbstractResponse
{
    public function isSuccessful()
    {
        return 1 === (int) $this->data->Success;
    }

    public function getTransactionReference()
    {
        return empty($this->data->DpsTxnRef) ? null : (string) $this->data->DpsTxnRef;
    }

    public function getTransactionId()
    {
        return empty($this->data->TxnId) ? null : (string) $this->data->TxnId;
    }

    public function getCardReference()
    {
        if (! empty($this->data->Transaction->DpsBillingId)) {
            return (string) $this->data->Transaction->DpsBillingId;
        } elseif (! empty($this->data->DpsBillingId)) {
            return (string) $this->data->DpsBillingId;
        }

        return null;
    }

    public function getMessage()
    {
        if (isset($this->data->HelpText)) {
            return (string) $this->data->HelpText;
        } else {
            return (string) $this->data->ResponseText;
        }
    }
}

<?php

namespace Omnipay\PaymentExpress\Message;

use Omnipay\Common\Message\AbstractResponse;

/**
 * PaymentExpress Response
 */
class Response extends AbstractResponse
{
    public function isSuccessful()
    {
        return 1 === (int) $this->data->Success;
    }

    public function getTransactionReference()
    {
        return empty($this->data->DpsTxnRef) ? null : (string) $this->data->DpsTxnRef;
    }

    public function getTransactionId()
    {
        return empty($this->data->TxnId) ? null : (string) $this->data->TxnId;
    }

    public function getCardReference()
    {
        if (! empty($this->data->Transaction->BillingId)) {
            return (string) $this->data->Transaction->BillingId;
        } elseif (! empty($this->data->BillingId)) {
            return (string) $this->data->BillingId;
        }

        return null;
    }

    public function getMessage()
    {
        if (isset($this->data->HelpText)) {
            return (string) $this->data->HelpText;
        } else {
            return (string) $this->data->ResponseText;
        }
    }
}

Return the BillingId as the card reference


 <?php

namespace WsdlToPhp\DomHandler;

class NameSpaceHandler extends AttributeHandler
{
    /**
     * @var \DOMNameSpaceNode
     */
    protected $nodeNameSpace;
    /**
     * @param \DOMNameSpaceNode $nameSpaceNode
     * @param AbstractDomDocumentHandler $domDocumentHandler
     * @param int $index
     */
    public function __construct(\DOMNameSpaceNode $nameSpaceNode, AbstractDomDocumentHandler $domDocumentHandler, $index = -1)
    {
        parent::__construct(new \DOMAttr($nameSpaceNode->nodeName, $nameSpaceNode->nodeValue), $domDocumentHandler, $index);
        $this->nodeNameSpace = $nameSpaceNode;
    }
    /**
     * value is always with [http|https]:// so we need to keep the full value
     * @param bool $withNamespace
     * @param bool $withinItsType
     * @param string $asType
     * @return mixed
     */
    public function getValue($withNamespace = false, $withinItsType = true, $asType = null)
    {
        return parent::getValue(true, $withinItsType, $asType);
    }
    /**
     * @return null|string
     */
    public function getValueNamespace()
    {
        return null;
    }
}

<?php

namespace WsdlToPhp\DomHandler;

class NameSpaceHandler extends AttributeHandler
{
    /**
     * @var \DOMNameSpaceNode
     */
    private $nodeNameSpace;
    /**
     * @param \DOMNameSpaceNode $nameSpaceNode
     * @param AbstractDomDocumentHandler $domDocumentHandler
     * @param int $index
     */
    public function __construct(\DOMNameSpaceNode $nameSpaceNode, AbstractDomDocumentHandler $domDocumentHandler, $index = -1)
    {
        parent::__construct(new \DOMAttr($nameSpaceNode->nodeName, $nameSpaceNode->nodeValue), $domDocumentHandler, $index);
        $this->nodeNameSpace = $nameSpaceNode;
    }
    /**
     * value is always with [http|https]:// so we need to keep the full value
     * @param bool $withNamespace
     * @param bool $withinItsType
     * @param string $asType
     * @return mixed
     */
    public function getValue($withNamespace = false, $withinItsType = true, $asType = null)
    {
        return parent::getValue(true, $withinItsType, $asType);
    }
    /**
     * @return null|string
     */
    public function getValueNamespace()
    {
        return null;
    }
}

Revert "make the property protected instead of private"

This reverts commit 409669ec1686f71ae3804003540423e45d842f2e.


<?php
	namespace Bolt;

	use ReflectionClass;

	abstract class Enum
	{
		public function expose()
		{
			return $this->identifiers();
		}

		protected function identifiers()
		{
			$refl = new ReflectionClass($this);
			$constants = $refl->getConstants();
			asort($constants);
			return $constants;
		}
	}
?>

<?php
	namespace Bolt;

	use ReflectionClass;

	abstract class Enum
	{
		public static function expose()
		{
			return self::identifiers();
		}

		protected static function identifiers()
		{
			$refl = new ReflectionClass(get_called_class());
			$constants = $refl->getConstants();
			asort($constants);

			return $constants;
		}
	}
?>

Update Emun abstract class to have static methods


<?php
namespace wcf\acp\page;
use wcf\page\SortablePage;

/**
 * Lists the blacklisted usernames
 *
 * @author 	Maximilian Mader
 * @copyright	2013 Maximilian Mader
 * @license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>
 * @package	be.bastelstu.max.wcf.otu
 * @subpackage	acp.page
 * @category	Community Framework
 */
class OTUListPage extends SortablePage {
	/**
	 * @see	\wcf\page\AbstractPage::$activeMenuItem
	 */
	public $activeMenuItem = 'wcf.acp.menu.link.otu.list';

	/**
	 * @see	\wcf\page\SortablePage::$defaultSortField
	 */
	public $defaultSortField = 'username';

	/**
	 * @see	\wcf\page\AbstractPage::$neededPermissions
	 */
	public $neededPermissions = array('admin.system.canEditOption');

	/**
	 * @see	\wcf\page\MultipleLinkPage::$objectListClassName
	 */
	public $objectListClassName = '\wcf\data\user\otu\blacklist\entry\UserOtuBlacklistEntryList';

	/**
	 * @see	\wcf\page\AbstractPage::$templateName
	 */
	public $templateName = 'otuList';

	/**
	 * @see	\wcf\page\SortablePage::$validSortFields
	 */
	public $validSortFields = array('username', 'time', 'lastOwner', 'userID', 'entryID');
}

<?php
namespace wcf\acp\page;
use wcf\page\SortablePage;

/**
 * Lists the blacklisted usernames
 *
 * @author 	Maximilian Mader
 * @copyright	2013 Maximilian Mader
 * @license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>
 * @package	be.bastelstu.max.wcf.otu
 * @subpackage	acp.page
 * @category	Community Framework
 */
class OTUListPage extends SortablePage {
	/**
	 * @see	\wcf\page\AbstractPage::$activeMenuItem
	 */
	public $activeMenuItem = 'wcf.acp.menu.link.user.management.otu';

	/**
	 * @see	\wcf\page\SortablePage::$defaultSortField
	 */
	public $defaultSortField = 'username';

	/**
	 * @see	\wcf\page\AbstractPage::$neededPermissions
	 */
	public $neededPermissions = array('admin.system.canEditOption');

	/**
	 * @see	\wcf\page\MultipleLinkPage::$objectListClassName
	 */
	public $objectListClassName = '\wcf\data\user\otu\blacklist\entry\UserOtuBlacklistEntryList';

	/**
	 * @see	\wcf\page\AbstractPage::$templateName
	 */
	public $templateName = 'otuList';

	/**
	 * @see	\wcf\page\SortablePage::$validSortFields
	 */
	public $validSortFields = array('username', 'time', 'lastOwner', 'userID', 'entryID');
}

Fix active menu item in OTUListPage

Fix active menu item in OTUListPage


<?php

/**
 * This file is part of cocur/slugify.
 *
 * (c) Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocur\Slugify;

/**
 * SlugifyInterface
 *
 * @package   org.cocur.slugify
 * @author    Florian Eckerstorfer <florian@eckerstorfer.co>
 * @author    Marchenko Alexandr
 * @copyright 2012-2014 Florian Eckerstorfer
 * @license   http://www.opensource.org/licenses/MIT The MIT License
 */
interface SlugifyInterface
{
    /**
     * Return a URL safe version of a string.
     *
     * @param string $string
     *
     * @return string
     */
    public function slugify($string);
}

<?php

/**
 * This file is part of cocur/slugify.
 *
 * (c) Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocur\Slugify;

/**
 * SlugifyInterface
 *
 * @package   org.cocur.slugify
 * @author    Florian Eckerstorfer <florian@eckerstorfer.co>
 * @author    Marchenko Alexandr
 * @copyright 2012-2014 Florian Eckerstorfer
 * @license   http://www.opensource.org/licenses/MIT The MIT License
 */
interface SlugifyInterface
{
    /**
     * Return a URL safe version of a string.
     *
     * @param string $string
     *
     * @return string
     */
    public function slugify($string, $separator = '-');
}

Add missing $separator parameter to interface


<?php
$years = $this->em($this->ck->module->name('article'))->publishYears();
?>

    <?php foreach ($years as $year) { ?>

            <a href="<?= $this->ck->url->route([
                'year' => $year['date']->format('Y'),
            ], $this->ck->module->name('main_archive'), true) ?>">
                <?= $year['date']->format('Y') ?>
                (<?= $year['contentCount'] ?>)

                <?php foreach ($year['months'] as $month) { ?>

<a href="<?= $this->ck->url->route([
                        'year'  => $month['date']->format('Y'),
                        'month' => $month['date']->format('m'),
                    ], $this->ck->module->name('main_archive'), true) ?>">
                        <?= $month['date']->format('F') ?>
                        (<?= $month['contentCount'] ?>)

                <?php } ?>

    <?php } ?>

<?php
$years = $this->em($this->ck->module->name('article'))->publishYears();
?>

    <?php foreach ($years as $year) { ?>

            <a href="<?= $this->ck->url->route([
                'year' => $year['year'],
            ], $this->ck->module->name('main_archive'), true) ?>">
                <?= $year['date']->format('Y') ?>
                (<?= $year['contentCount'] ?>)

                <?php foreach ($year['months'] as $month) { ?>

<a href="<?= $this->ck->url->route([
                        'year'  => $month['year'],
                        'month' => $month['month'],
                    ], $this->ck->module->name('main_archive'), true) ?>">
                        <?= $month['date']->format('F') ?>
                        (<?= $month['contentCount'] ?>)

                <?php } ?>

    <?php } ?>

Remove date formatting from archive list urls


<?php

	include "conf.php";
	// Global constants \\
	define('ABSPATH','http://'.$_SERVER['SERVER_NAME'].'/');
	define('DROOT',$_SERVER['DOCUMENT_ROOT'].(preg_match('/\/$/',$_SERVER['DOCUMENT_ROOT'])?'':'/'));
	define('APPATH',dirname(__FILE__).DIRECTORY_SEPARATOR);
	define('RQMTHD',$_SERVER['REQUEST_METHOD']);
	define('REWRITE_REGEX','~^/(?:([\w\.\-]+|-?\d+)(?:/((?:[\w\.\-]+|-?\d+)(?:/(?:[\w\-]+|-?\d+))?))?/?)?$~');
	define('GITHUB_URL','https://github.com/ponydevs/MLPVC-RR');

	// Imports \\
	require 'includes/MysqliDbWrapper.php';
	$Database = new MysqliDbWrapper('mlpvc-rr');
	require 'includes/Cookie.php';
	require 'includes/Utils.php';
	require 'includes/AuthCheck.php';

<?php

	include "conf.php";
	// Global constants \\
	define('ABSPATH','http://'.$_SERVER['SERVER_NAME'].'/');
	define('DROOT',$_SERVER['DOCUMENT_ROOT'].(preg_match('/\/$/',$_SERVER['DOCUMENT_ROOT'])?'':'/'));
	define('APPATH',dirname(__FILE__).DIRECTORY_SEPARATOR);
	define('RQMTHD',$_SERVER['REQUEST_METHOD']);
	define('REWRITE_REGEX','~^/(?:([\w\.\-]+|-?\d+)(?:/((?:[\w\-]+|-?\d+)(?:/(?:[\w\-]+|-?\d+))?))?/?)?$~');
	define('GITHUB_URL','https://github.com/ponydevs/MLPVC-RR');

	// Imports \\
	require 'includes/MysqliDbWrapper.php';
	$Database = new MysqliDbWrapper('mlpvc-rr');
	require 'includes/Cookie.php';
	require 'includes/Utils.php';
	require 'includes/AuthCheck.php';

Fix file direct links triggering navigation


<?php

class Utility {

  public function __construct() {

    //
  }

  public static function displayError($message) {

    // Clear the buffer.
    ob_end_clean();

    // Terminate with an error message.
    exit("Error: {$message}.");
  }

  public static function getRootAddress() {

    $host = $_SERVER["HTTP_HOST"];

    $protocol = $_SERVER["SERVER_PROTOCOL"];

    $protocol =  strtolower(substr($protocol, 0, strpos($protocol, "/")));

    $protocol .= "://";

    $sub_directory = substr(

      dirname(dirname(__DIR__)),

      strlen($_SERVER["DOCUMENT_ROOT"])
    );

    // Return absolute URL of where Kaku is installed.
    return $protocol . $host . $sub_directory;
  }
}

?>

<?php

class Utility {

  public function __construct() {

    //
  }

  public static function displayError($message) {

    // Clear the buffer.
    ob_end_clean();

    // Terminate with an error message.
    exit("Error: {$message}.");
  }

  public static function getRootAddress() {

    $host = $_SERVER["HTTP_HOST"];

    $protocol;

    if (!empty($_SERVER["HTTP_X_FORWARDED_PROTO"])) {

      $protocol = $_SERVER["HTTP_X_FORWARDED_PROTO"] . "://";
    }
    else {

      if (!empty($_SERVER["HTTPS"])) {

        $protocol = "https://";
      }
      else {

        $protocol = "http://";
      }
    }

    $sub_directory = substr(

      dirname(dirname(__DIR__)),

      strlen($_SERVER["DOCUMENT_ROOT"])
    );

    // Return absolute URL of where Kaku is installed.
    return $protocol . $host . $sub_directory;
  }
}

?>

Use HTTPS fallback for reverse proxies

Use HTTPS fallback for reverse proxies

When using a reverse proxy, like CloudFlare, detecting HTTPS with
$_SERVER["HTTPS"] does not work. Instead, HTTPS can be detected through
checking $_SERVER["HTTP_X_FORWARDED_PROTO"].


<?php
use Interop\Container\ContainerInterface;
use DI\Factory\RequestedEntry;

return [
    'ActionListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class),
    'DataFilterListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class),
    'DefaultStaticPostController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class),
    'DefaultStaticPageController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class),
    'Renderer' => DI\object(Sarcofag\View\Renderer\SimpleRenderer::class),
    'GenericMenu' => DI\object(Sarcofag\SPI\Menu\Menu::class),
    'GenericSidebar' => DI\object(Sarcofag\SPI\Sidebar\SidebarEntry::class),
    'MenuRegistry' => DI\object(Sarcofag\SPI\Menu\Registry::class),
    'SidebarRegistry' => DI\object(Sarcofag\SPI\Sidebar\Registry::class),
    'WidgetRegistry' => DI\object(Sarcofag\SPI\Widget\Registry::class)
];

<?php
use Interop\Container\ContainerInterface;
use DI\Factory\RequestedEntry;

return [
    'ActionListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class),
    'DataFilterListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class),
    'DefaultStaticPostController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class),
    'DefaultStaticPageController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class),
    'GenericMenu' => DI\object(Sarcofag\SPI\Menu\Menu::class),
    'GenericSidebar' => DI\object(Sarcofag\SPI\Sidebar\SidebarEntry::class),
    'MenuRegistry' => DI\object(Sarcofag\SPI\Menu\Registry::class),
    'SidebarRegistry' => DI\object(Sarcofag\SPI\Sidebar\Registry::class),
    'WidgetRegistry' => DI\object(Sarcofag\SPI\Widget\Registry::class)
];

Change because of duplication issue

Change because of duplication issue


<?php

/*
 * This file is part of Laravel TestBench.
 *
 * (c) Graham Campbell <graham@alt-three.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GrahamCampbell\TestBench;

use GrahamCampbell\TestBenchCore\HelperTrait;
use GrahamCampbell\TestBenchCore\MockeryTrait;
use PHPUnit_Framework_TestCase as TestCase;

/**
 * This is the abstract test case class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
abstract class AbstractTestCase extends TestCase
{
    use HelperTrait, MockeryTrait;
}

<?php

/*
 * This file is part of Laravel TestBench.
 *
 * (c) Graham Campbell <graham@alt-three.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GrahamCampbell\TestBench;

use GrahamCampbell\TestBenchCore\HelperTrait;
use GrahamCampbell\TestBenchCore\MockeryTrait;
use PHPUnit\Framework\TestCase;

/**
 * This is the abstract test case class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
abstract class AbstractTestCase extends TestCase
{
    use HelperTrait, MockeryTrait;
}

Use the new phpunit class name

Use the new phpunit class name


<?php
namespace BrockReece\ElasticAnalytics;

class ElasticAnalytics {
    protected $client;

    public function __construct() {
        $this->client = $this->buildClient();
    }

    public static function buildClient() {
        return \Elasticsearch\ClientBuilder::create()
            ->setHosts(config('elasticquent.config.hosts'))
            ->setRetries(config('elasticquent.config.retries'))
            ->build();
    }

    public static function buildClientByIP($ip) {
        return \Elasticsearch\ClientBuilder::create()
            ->setHosts([$ip])
            ->setRetries(config('elasticquent.config.retries'))
            ->build();
    }

    public static function log(array $params) {
        if (!config('elasticquent.active')) {
            return;
        }

        self::buildClient()->index($params);
    }

    public static function magicReplicator($function) {
        if (!config('elasticquent.active')) {
            return;
        }

        foreach (config('elasticquent.clusters') as $ip) {
            $client = self::buildClientByIP($ip);
            $function($client);
        }
    }
}

<?php
namespace BrockReece\ElasticAnalytics;

class ElasticAnalytics {
    protected $client;

    public function __construct() {
        $this->client = $this->buildClient();
    }

    public static function buildClient() {
        return \Elasticsearch\ClientBuilder::create()
            ->setHosts(config('elasticquent.config.hosts'))
            ->setRetries(config('elasticquent.config.retries'))
            ->build();
    }

    public static function buildClientByIP($ip) {
        return \Elasticsearch\ClientBuilder::create()
            ->setHosts($ip)
            ->setRetries(config('elasticquent.config.retries'))
            ->build();
    }

    public static function log(array $params) {
        if (!config('elasticquent.active')) {
            return;
        }

        self::buildClient()->index($params);
    }

    public static function magicReplicator($function) {
        if (!config('elasticquent.active')) {
            return;
        }

        foreach (config('elasticquent.clusters') as $ip) {
            try {
                $client = self::buildClientByIP($ip);
                $function($client);
            }
            catch(\Elasticsearch\Common\Exceptions\NoNodesAvailableException $e) {
                \Log::error($e->getMessage() . ' - Nodes - ' . implode($ip));
            }
        }
    }
}

Add try and catch and log errors

Add try and catch and log errors


<?php
namespace PhpBrew;

class AppStore
{
    public static function all()
    {
        $apps = array(
            'composer' => array('url' => 'https://getcomposer.org/composer.phar', 'as' => 'composer'),
            'phpunit' => array('url' => 'https://phar.phpunit.de/phpunit.phar', 'as' => 'phpunit'),
            'phpmd' => array('url' => 'http://static.phpmd.org/php/latest/phpmd.phar', 'as' => 'phpmd'),
            'behat' => array('url' => 'https://github.com/Behat/Behat/releases/download/v2.5.5/behat.phar', 'as' => 'behat'),
        );
        $phpunitapps = explode(' ','phpunit phpcov phpcpd phpdcd phptok phploc');
        foreach ($phpunitapps as $phpunitapp) {
            $apps[ $phpunitapp ] = array(
                'url' => sprintf('https://phar.phpunit.de/%s.phar', $phpunitapp),
                'as' => $phpunitapp,
            );
        }
        return $apps;
    }
}

<?php
namespace PhpBrew;

class AppStore
{
    public static function all()
    {
        $apps = array(
            'composer'  => array('url' => 'https://getcomposer.org/composer.phar', 'as'                              => 'composer'),
            'phpunit'   => array('url' => 'https://phar.phpunit.de/phpunit.phar', 'as'                               => 'phpunit'),
            'phpmd'     => array('url' => 'http://static.phpmd.org/php/latest/phpmd.phar', 'as'                      => 'phpmd'),
            'behat-2.5' => array('url' => 'https://github.com/Behat/Behat/releases/download/v2.5.5/behat.phar', 'as' => 'behat'),
            'behat-3.5' => array('url' => 'https://github.com/Behat/Behat/releases/download/v3.0.15/behat.phar', 'as' => 'behat'),
        );
        $phpunitapps = explode(' ','phpunit phpcov phpcpd phpdcd phptok phploc');
        foreach ($phpunitapps as $phpunitapp) {
            $apps[ $phpunitapp ] = array(
                'url' => sprintf('https://phar.phpunit.de/%s.phar', $phpunitapp),
                'as' => $phpunitapp,
            );
        }
        return $apps;
    }
}

Add behat 2.5 and 3.0

Add behat 2.5 and 3.0


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

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

        return new View(
            new TemplateRegistry,
            new TemplateRegistry,
            $helpers
        );
    }
}

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

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

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

Add a way to set map and path in factory


<?php

declare(strict_types=1);

namespace App\Generators;

use GuzzleHttp\Promise\Promise;

/**
 * This is the validating generator class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ValidatingGenerator implements GeneratorInterface
{
    /**
     * The generator to wrap.
     *
     * @var \App\Generators\GeneratorInterface
     */
    protected $generator;

    /**
     * Create a new validating generator instance.
     *
     * @param \App\Generators\GeneratorInterface $generator
     *
     * @return void
     */
    public function __construct(GeneratorInterface $generator)
    {
        $this->generator = $generator;
    }

    /**
     * Generate a new image.
     *
     * @param string $text
     *
     * @throws \App\Generators\ExceptionInterface
     *
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function generate(string $text)
    {
        return (new Promise(function () use ($text) {
            if (!$text) {
                throw new ValidationException('No meme text provided!');
            }

            if (preg_match('/^[a-z0-9 .\-]+$/i', $text) !== 1) {
                throw new ValidationException('Invalid meme text provided!');
            }

            if (strlen($text) > 128) {
                throw new ValidationException('Meme text too long!');
            }

            return $this->generator->generate($text);
        }));
    }
}

<?php

declare(strict_types=1);

namespace App\Generators;

use GuzzleHttp\Promise\Promise;

/**
 * This is the validating generator class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ValidatingGenerator implements GeneratorInterface
{
    /**
     * The generator to wrap.
     *
     * @var \App\Generators\GeneratorInterface
     */
    protected $generator;

    /**
     * Create a new validating generator instance.
     *
     * @param \App\Generators\GeneratorInterface $generator
     *
     * @return void
     */
    public function __construct(GeneratorInterface $generator)
    {
        $this->generator = $generator;
    }

    /**
     * Generate a new image.
     *
     * @param string $text
     *
     * @throws \App\Generators\ExceptionInterface
     *
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function generate(string $text)
    {
        return (new Promise(function () use ($text) {
            if (!$text) {
                throw new ValidationException('No meme text provided!');
            }

            if (preg_match('/^[a-z0-9 .\-]+$/i', $text) !== 1) {
                throw new ValidationException('Invalid meme text provided!');
            }

            if (strlen($text) > 128) {
                throw new ValidationException('Meme text too long!');
            }
        }))->then(function () use ($text) {
            return $this->generator->generate($text);
        });
    }
}

Revert "Don't separate the validating generator"

This reverts commit f6851039a91adb5a3f9c130862e652df5aabe674.


<?php

namespace Wdi\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Route;
use Wdi\Entities\Language;
use Wdi\Entities\Paste;

/**
 * Class RouteServiceProvider
 *
 * @package Wdi\Providers
 */
final class RouteServiceProvider extends ServiceProvider
{
    /** {@inheritdoc} */
    public function boot()
    {
        parent::boot();

        Route::model("paste", Paste::class);
        Route::model("language", Language::class);
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapHandlerRoutes();
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    private function mapApiRoutes()
    {
        Route::prefix("api")->namespace("Wdi\Http\Api")->middleware("api")->group(base_path("routes/api.php"));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    private function mapHandlerRoutes()
    {
        Route::middleware("web")->group(base_path("routes/handler.php"));
    }
}

<?php

namespace Wdi\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Route;
use Wdi\Entities\Language;
use Wdi\Entities\Paste;

/**
 * Class RouteServiceProvider
 *
 * @package Wdi\Providers
 */
final class RouteServiceProvider extends ServiceProvider
{
    /** {@inheritdoc} */
    public function boot()
    {
        parent::boot();

        Route::model("language", Language::class);

        Route::bind("paste", function ($slug) {
            return Paste::select(["id", "language_id", "paste_id", "user_id", "slug", "name", "extension", "code", "description", "created_at", "updated_at"])
                ->where("slug", $slug)->firstOrFail();
        });
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapHandlerRoutes();
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    private function mapApiRoutes()
    {
        Route::prefix("api")->namespace("Wdi\Http\Api")->middleware("api")->group(base_path("routes/api.php"));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    private function mapHandlerRoutes()
    {
        Route::middleware("web")->group(base_path("routes/handler.php"));
    }
}

Improve Route model binding query for Paste


<?php

namespace Tests;

use Canvas\Models\Tag;
use Canvas\Models\Post;
use Canvas\Models\User;
use Canvas\TestDatabaseSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;

trait InteractsWithDatabase
{
    use DatabaseMigrations;

    /**
     * Set up the test environment.
     *
     * @return void
     */
    public function setUp()
    {
        // Disable searchable trait to speed up tests.
        Post::disableSearchSyncing();
        Tag::disableSearchSyncing();
        User::disableSearchSyncing();

        $this->runDatabaseMigrations();

        $this->seed(TestDatabaseSeeder::class);
    }

    /**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
//    public function runDatabaseMigrations()
//    {
//        $this->artisan('migrate');
//
//        $this->beforeApplicationDestroyed(function () {
//            $this->artisan('migrate:reset');
//        });
//    }
}

<?php

use Canvas\Models\Tag;
use Canvas\Models\Post;
use Canvas\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;

trait InteractsWithDatabase
{
    use DatabaseTransactions;

    /**
     * Set up the test environment.
     *
     * @return void
     */
    protected function setUp()
    {
        parent::setUp();

        // Disable searchable trait to speed up tests.
        Post::disableSearchSyncing();
        Tag::disableSearchSyncing();
        User::disableSearchSyncing();

        $this->runDatabaseMigrations();

        $this->seed(\Canvas\TestDatabaseSeeder::class);
    }

    /**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
    public function runDatabaseMigrations()
    {
        $this->artisan('migrate');

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:reset');
        });
    }
}

Use transactions instead of migrations for testing database


<?php

require_once('setup.php');

function clean($string)
{
    return preg_replace('/[^A-Za-z0-9_:]/', '', $string); // Removes special chars.
}

$post_data = clean($_POST['data']);
$id = $_POST['id'];
$secret = $_POST['secret'];

if ($post_data && $id && $secret && strlen($post_data) < 20010) {
    if ($id && is_numeric($id)) {
        $db_data = explode(":", $redis->get($id));
        if (hash_equals($secret, $db_data[0])) {
            $redis->set($id, $secret . ":" . $post_data);
            http_response_code(200);
            header('Content-Type: application/json');
            echo(json_encode(["ok"]));
            return;
        } else {
            http_response_code(403);
            return;
        }
    }
}

http_response_code(400);

<?php

require_once('setup.php');

function clean($string)
{
    return preg_replace('/[^A-Za-z0-9_:]/', '', $string); // Removes special chars.
}

$post_data = clean($_POST['data']);
$id = $_POST['id'];

if ($post_data && $id && strlen($post_data) < 20010) {
    if ($id && is_numeric($id)) {
        $db_data = explode(":", $redis->get($id));
        $user_data = explode(":", $post_data);
        if (count($user_data) > 0 && hash_equals($user_data[0], $db_data[0])) {
            $redis->set($id, $post_data);
            http_response_code(200);
            header('Content-Type: application/json');
            echo(json_encode(["ok"]));
            return;
        } else {
            http_response_code(403);
            return;
        }
    }
}

http_response_code(400);

Fix saving not accepting new format with secret


<?php
namespace Guestbook\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $prg          = $this->prg();
        $entryForm    = $this->getServiceLocator()->get('guestbook_entry_form');
        $entryService = $this->getServiceLocator()->get('guestbook_entry_service');

        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg !== false) {
            $entry = $entryService->add($prg);

            if ($entry) {
                return $this->redirect()->toRoute('guestbook');
            }
        }

        return new ViewModel(array(
            'entryForm' => $entryForm,
            'entries'   => $entryService->findAll()
        ));
    }
}

<?php
namespace Guestbook\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {

        $entryForm    = $this->getServiceLocator()->get('guestbook_entry_form');
        $entryService = $this->getServiceLocator()->get('guestbook_entry_service');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = $request->getPost()->toArray();
            $entry = $entryService->add($data);

            if ($entry) {
                return $this->redirect()->toRoute('guestbook');
            }
          }

        return new ViewModel(array(
            'entryForm' => $entryForm,
            'entries'   => $entryService->findAll()
        ));
    }
}

Use post param in controller

Use post param in controller


<?php
// Adds media_type column and moves volumetype data to new column

use munkireport\lib\Schema;

class Migration_disk_report_add_media_type extends Model
{
    /**
     * Migrate up
     *
     * Migrates this table to the current version
     *
     **/
    public function up()
    {
        Schema::table('diskreport', function ($table)
        {
            $table->string('media_type');
            $table->index('media_type');
        });

        // Populate new column
        $sql = "UPDATE diskreport
                SET media_type = volumeType, volumeType = 'hfs+'
                WHERE volumeType IN ('hdd', 'ssd', 'fusion', 'raid')";
        $this->exec($sql);

    }// End function up()

    /**
     * Migrate down
     *
     * Migrates this table to the previous version
     *
     **/
    public function down()
    {
        // There is no down() as this is a bugfix and up() is idempotent
    }
}

<?php
// Adds media_type column and moves volumetype data to new column

use munkireport\lib\Schema;

class Migration_disk_report_add_media_type extends Model
{
    /**
     * Migrate up
     *
     * Migrates this table to the current version
     *
     **/
    public function up()
    {
        Schema::table('diskreport', function ($table)
        {
            $table->string('media_type');
            $table->index('media_type');
        });

        // Populate new column
        $sql = "UPDATE diskreport
                SET media_type = volumeType, volumeType = 'hfs'
                WHERE volumeType IN ('hdd', 'ssd', 'fusion', 'raid')";
        $this->exec($sql);

    }// End function up()

    /**
     * Migrate down
     *
     * Migrates this table to the previous version
     *
     **/
    public function down()
    {
    }
}

Set default volumetype to hfs

Set default volumetype to hfs


<?php

class CM_Console_Cli extends CM_Cli_Runnable_Abstract {

	public function interactive() {
		while ('exit' !== ($code = $this->_getInput()->read('php >'))) {
			$result = null;
			try {
				$code = '$result = ' . $code . ';';
				if (false !== eval($code)) {
					$this->_getOutput()->writeln(print_r($result, true));
				}
			} catch (Exception $e) {
				$this->_getOutput()->writeln($e->getMessage());
				$this->_getOutput()->writeln($e->getTraceAsString());
			}
		}
	}

	public static function getPackageName() {
		return 'console';
	}

}

<?php

class CM_Console_Cli extends CM_Cli_Runnable_Abstract {

	public function interactive() {
		while ('exit' !== ($code = $this->_getInput()->read('php >'))) {
			$result = null;
			try {
				ob_start();
				eval($code . ';');
				$result = ob_get_contents();
				ob_end_clean();
				if ($result) {
					$this->_getOutput()->writeln($result);
				}
			} catch (Exception $e) {
				$this->_getOutput()->writeln($e->getMessage());
				$this->_getOutput()->writeln($e->getTraceAsString());
			}
		}
	}

	public static function getPackageName() {
		return 'console';
	}

}

Remove $result variable; Output buffer eval output


<?PHP  // $Id$

    require("../config.php");

    if (! $site = get_site()) {
        error("Site is misconfigured");
    }
    $strdocumentation = get_string("documentation");
    print_header("$site->shortname: $strdocumentation", "$site->fullname", "$strdocumentation");

?>

<?PHP  // $Id$

    require("../config.php");

    if (! $site = get_site()) {
        error("Site is misconfigured");
    }
    $strdocumentation = get_string("documentation");
    print_header("$site->shortname: $strdocumentation", "$site->fullname", "$strdocumentation", "", "", true, "", navmenu($site));

?>

Put a menu on the documentation

Put a menu on the documentation


<?php

namespace Northstar\Http\Controllers;

use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;

class AvatarController extends Controller
{
    /**
     * Amazon Web Services API wrapper.
     * @var AWS
     */
    protected $phoenix;

    public function __construct(AWS $aws)
    {
        $this->aws = $aws;

        $this->middleware('key:user');
        $this->middleware('auth');
    }

    /**
     * Store a new avatar for a user.
     * POST /users/:id/avatar
     *
     * @param Request $request
     * @param $id - User ID
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        if ($request->file('photo')) {
            $file = $request->file('photo');
        } else {
            $file = $request->photo;
        }

        $this->validate($request, [
            'photo' => 'required',
        ]);

        $filename = $this->aws->storeImage('avatars', $id, $file);

        // Save filename to User model
        $user = User::where('_id', $id)->first();
        $user->photo = $filename;
        $user->save();

        // Respond to user with success and photo URL
        return $this->respond($user);
    }
}

<?php

namespace Northstar\Http\Controllers;

use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;

class AvatarController extends Controller
{
    /**
     * Amazon Web Services API wrapper.
     * @var AWS
     */
    protected $aws;

    public function __construct(AWS $aws)
    {
        $this->aws = $aws;

        $this->middleware('key:user');
        $this->middleware('auth');
    }

    /**
     * Store a new avatar for a user.
     * POST /users/:id/avatar
     *
     * @param Request $request
     * @param $id - User ID
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        if ($request->file('photo')) {
            $file = $request->file('photo');
        } else {
            $file = $request->photo;
        }

        $this->validate($request, [
            'photo' => 'required',
        ]);

        $filename = $this->aws->storeImage('avatars', $id, $file);

        // Save filename to User model
        $user = User::where('_id', $id)->first();
        $user->photo = $filename;
        $user->save();

        // Respond to user with success and photo URL
        return $this->respond($user);
    }
}

Fix typo in dependency-injected property name.


<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-25672552-3', 'auto');
  ga('send', 'pageview');
</script>

Remove script tags from php file

Remove script tags from php file


<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = $_GET;
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = array_merge($_GET, $_POST);
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

ENH: Allow web API parameters to be passed as POST parameters in addition to the normal GET parameters


<?php

namespace Dan\Setup\Configs;

use Dan\Config\Config;
use Dan\Console\OutputStyle;
use Dan\Contracts\ConfigSetupContract;

class Web implements ConfigSetupContract
{
    /**
     * @var \Dan\Console\OutputStyle
     */
    protected $output;

    public function __construct(OutputStyle $output)
    {
        $this->output = $output;
    }

    /**
     * @return Config
     */
    public function setup() : Config
    {
        return $this->defaultConfig();
    }

    /**
     * @return Config
     */
    public function defaultConfig() : Config
    {
        return new Config([
            'web' => [
                'enabled'   => true,
                'host'      => '127.0.0.1',
                'port'      => 6969,
            ],
        ]);
    }

    /**
     * @return mixed
     */
    public function introText()
    {
        return 'Let me setup the defaults for the web listener..';
    }
}

<?php

namespace Dan\Setup\Configs;

use Dan\Config\Config;
use Dan\Console\OutputStyle;
use Dan\Contracts\ConfigSetupContract;

class Web implements ConfigSetupContract
{
    /**
     * @var \Dan\Console\OutputStyle
     */
    protected $output;

    public function __construct(OutputStyle $output)
    {
        $this->output = $output;
    }

    /**
     * @return Config
     */
    public function setup() : Config
    {
        $config = $this->defaultConfig();

        if (!$this->output->confirm('Should the web listener be enabled? This will allow things like a basic web server and GitHub Webhook support.')) {
            $config->set('web.enabled', false);

            return $config;
        }

        $config->set('web.enabled', true);

        $host = $this->output->ask("What host should I bind to? If you plan on using a domain, use that, otherwise please put the public IP of the server.", '127.0.0.1');
        $config->set('web.host', $host);

        $port = $this->output->ask('What port should the web listener use?', 6969);
        $config->set('web.post', $port);

        return $config;
    }

    /**
     * @return Config
     */
    public function defaultConfig() : Config
    {
        return new Config([
            'web' => [
                'enabled'   => true,
                'host'      => '127.0.0.1',
                'port'      => 6969,
            ],
        ]);
    }

    /**
     * @return mixed
     */
    public function introText()
    {
        return "Let's setup the web listener..";
    }
}

Allow web listener customizability on first boot.


<?php
/**
 * commands_richtext_RebuildFiles
 * @package modules.richtext.command
 */
class commands_richtext_RebuildFiles extends commands_AbstractChangeCommand
{
	/**
	 * @return String
	 * @example "<moduleName> <name>"
	 */
	public function getUsage()
	{
		return "";
	}

	/**
	 * @return String
	 * @example "initialize a document"
	 */
	public function getDescription()
	{
		return "rebuild xml and css files";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	public function _execute($params, $options)
	{
		$this->message("== RebuildFiles ==");

		richtext_ModuleService::getInstance()->rebuildFiles();

		$this->quitOk("Command successfully executed");
	}
}

<?php
/**
 * commands_richtext_RebuildFiles
 * @package modules.richtext.command
 */
class commands_richtext_RebuildFiles extends commands_AbstractChangeCommand
{
	/**
	 * @return String
	 */
	public function getUsage()
	{
		return "";
	}

	/**
	 * @return String
	 */
	public function getDescription()
	{
		return "rebuild xml and css files";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	public function _execute($params, $options)
	{
		$this->message("== RebuildFiles ==");

		richtext_ModuleService::getInstance()->rebuildFiles();

		$this->quitOk("Command successfully executed");
	}
}

Enhance the doc for the PHPDoc

[DOC] Enhance the doc for the PHPDoc


<?php

/*
 *	(c) Smalte - 2012 ~ Until the end of the world...
 *
 *	Julien Breux <julien@smalte.org>
 *	Fabien Serny <fabien@smalte.org>
 *	Grégoire Poulain <gregoire@smalte.org>
 *	Alain Folletete <alain@smalte.org>
 *	Raphaël Malié <raphael@smalte.org>
 *
 *	Thanks a lot to our community!
 *
 *	Read LICENCE file for more information.
 */

// Define root path
define('PATH_ROOT', dirname(__FILE__));

// Use composer auto loader (PSR-0 compliant)
$loader = require_once PATH_ROOT.'/libraries/autoload.php';

// Controller namespace
$loader->add('controllers', PATH_ROOT);

// Module namespace
$loader->add('modules', PATH_ROOT);

<?php

/*
 *	(c) Smalte - 2012 ~ Until the end of the world...
 *
 *	Julien Breux <julien@smalte.org>
 *	Fabien Serny <fabien@smalte.org>
 *	Grégoire Poulain <gregoire@smalte.org>
 *	Alain Folletete <alain@smalte.org>
 *	Raphaël Malié <raphael@smalte.org>
 *
 *	Thanks a lot to our community!
 *
 *	Read LICENCE file for more information.
 */

// Define root path
define('PATH_ROOT', dirname(__FILE__));

/**
 *	SECTION: Autoload
 */

// Use composer auto loader (PSR-0 compliant)
$loader = require_once PATH_ROOT.'/libraries/autoload.php';

// Controller namespace
$loader->add('controllers', PATH_ROOT);

// Module namespace
$loader->add('modules', PATH_ROOT);

Add "Autoload section" (for other sections to come)


<?php

namespace Longman\TelegramBot\Entities\ChatMember;

use Longman\TelegramBot\Entities\Entity;
use Longman\TelegramBot\Exception\TelegramException;

class Factory extends \Longman\TelegramBot\Entities\Factory
{
    public function make(array $data, string $bot_username): Entity
    {
        if (! isset($data['status'])) {
            throw new TelegramException('Missing ChatMember status');
        }

        $type = [
            'creator'       => ChatMemberOwner::class,
            'administrator' => ChatMemberAdministrator::class,
            'member'        => ChatMemberMember::class,
            'restricted'    => ChatMemberRestricted::class,
            'left'          => ChatMemberLeft::class,
            'kicked'        => ChatMemberBanned::class,
        ];

        if (! isset($type[$data['status']])) {
            return new ChatMemberNotImplemented($data, $bot_username);
        }

        $class = $type[$data['status']];
        return new $class($data, $bot_username);
    }
}

<?php

namespace Longman\TelegramBot\Entities\ChatMember;

use Longman\TelegramBot\Entities\Entity;
use Longman\TelegramBot\Exception\TelegramException;

class Factory extends \Longman\TelegramBot\Entities\Factory
{
    public function make(array $data, string $bot_username): Entity
    {
        $type = [
            'creator'       => ChatMemberOwner::class,
            'administrator' => ChatMemberAdministrator::class,
            'member'        => ChatMemberMember::class,
            'restricted'    => ChatMemberRestricted::class,
            'left'          => ChatMemberLeft::class,
            'kicked'        => ChatMemberBanned::class,
        ];

        if (! isset($type[$data['status'] ?? ''])) {
            return new ChatMemberNotImplemented($data, $bot_username);
        }

        $class = $type[$data['status']];
        return new $class($data, $bot_username);
    }
}

Return ChatMemberNotImplemented if status is missing from data


<?php

namespace ExpressiveLogger\Factory;

use ExpressiveLogger\Exception\InvalidConfigurationException;
use Interop\Container\ContainerInterface;
use Monolog\Handler\RedisHandler;
use Monolog\Logger;
use Predis\Client;

final class RedisHandlerFactory
{

    public function __invokable(ContainerInterface $container) : RedisHandler
    {
        $config = $container->get('config');

        if (!isset($config['expressiveLogger']['handlers']['redis'])) {
            throw new InvalidConfigurationException('Redis config is not set');
        }

        $redisConfig = $config['expressiveLogger']['handlers']['redis'];

        $redisClient = $container->get($redisConfig['client']);

        if (!$redisClient) {
            throw new InvalidConfigurationException('Redis client not found in container');
        }

        if ($redisClient instanceof Client) {
            throw new InvalidConfigurationException('Redis client have to be instance of Predis\Client');
        }

        $key = $redisConfig['key'] ?? 'default';
        $level = $redisConfig['key'] ?? Logger::DEBUG;

        return new RedisHandler($redisClient, $key, $level);
    }
}

<?php

namespace ExpressiveLogger\Factory;

use ExpressiveLogger\Exception\InvalidConfigurationException;
use Interop\Container\ContainerInterface;
use Monolog\Handler\RedisHandler;
use Monolog\Logger;
use Predis\Client;

final class RedisHandlerFactory
{

    public function __invoke(ContainerInterface $container) : RedisHandler
    {
        $config = $container->get('config');

        if (!isset($config['expressiveLogger']['handlers']['redis'])) {
            throw new InvalidConfigurationException('Redis config is not set');
        }

        $redisConfig = $config['expressiveLogger']['handlers']['redis'];

        $redisClient = $container->get($redisConfig['client']);

        if (!$redisClient) {
            throw new InvalidConfigurationException('Redis client not found in container');
        }

        if ($redisClient instanceof Client) {
            throw new InvalidConfigurationException('Redis client have to be instance of Predis\Client');
        }

        $key = $redisConfig['key'] ?? 'default';
        $level = $redisConfig['key'] ?? Logger::DEBUG;

        return new RedisHandler($redisClient, $key, $level);
    }
}

Fix misspeling in function name

Fix misspeling in function name


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Promotion\Model;

use Sylius\Component\Resource\Model\ResourceInterface;

interface CatalogPromotionRuleInterface extends ResourceInterface
{
    public const TYPE_CONTAINS_VARIANTS = 'contains_variants';

    public function setType(?string $type): void;

    public function getType(): ?string;

    public function getConfiguration(): array;

    public function setConfiguration(array $configuration): void;

    public function getCatalogPromotion(): ?CatalogPromotionInterface;

    public function setCatalogPromotion(?CatalogPromotionInterface $catalogPromotion): void;
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Promotion\Model;

use Sylius\Component\Resource\Model\ResourceInterface;

interface CatalogPromotionRuleInterface extends ResourceInterface
{
    public const TYPE_FOR_VARIANTS = 'for_variants';

    public function setType(?string $type): void;

    public function getType(): ?string;

    public function getConfiguration(): array;

    public function setConfiguration(array $configuration): void;

    public function getCatalogPromotion(): ?CatalogPromotionInterface;

    public function setCatalogPromotion(?CatalogPromotionInterface $catalogPromotion): void;
}

Apply CP on variant and change the rule name


@extends('layouts/default/template')

@section('content')

            Report New Issue

                @forelse($issues as $issue)
                     $issue->id]) }}">
                        #{{$issue->id}}
                        {{ $issue->title }}

                @empty

                        No issue is open.

                @endforelse

            {!! $issues->render() !!}

@endsection

@extends('layouts/default/template')

@section('content')

            Report New Issue

            @if(count($issues))

                    @forelse($issues as $issue)
                         $issue->id]) }}">
                            #{{$issue->id}}
                            {{ $issue->title }}

                    @endforeach

                {!! $issues->render() !!}
            @else

                        No issue is open.

            @endif

@endsection

Change No issue display behave

Change No issue display behave


<?php namespace Aamant\Message\Composer;

class Receive
{
	public function compose($view)
	{
		$mailbox_counter = \Auth::user()
			->received()
			->where('status', 'new')
			->count();
		$mailbox_url = \URL::route('mailbox.show');

		$view->with('mailbox_counter', $mailbox_counter);
		$view->with('mailbox_url', $mailbox_url);
	}
}

<?php namespace Aamant\Message\Composer;

class Receive
{
	public function compose($view)
	{
		if (!\Auth::check())
			$mailbox_counter = 0;
		else {
			$mailbox_counter = \Auth::user()
				->received()
				->where('status', 'new')
				->count();
		}
		$mailbox_url = \URL::route('mailbox.show');

		$view->with('mailbox_counter', $mailbox_counter);
		$view->with('mailbox_url', $mailbox_url);
	}
}

Fix bug when user is not logged

Fix bug when user is not logged


@section('title')
Melee - Cataclysm: Dark Days Ahead
@endsection
@section('content')

Melee

Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2

    Name
    Material
    V
    W
    B
    C
    H

@foreach($items as $item)

  {{ $item->symbol }}
  id)}}">{{ $item->name }}
  {{ $item->materials }}
  {{ $item->volume }}
  {{ $item->weight }}
  {{ $item->bashing }}
  {{ $item->cutting }}
  {{ $item->to_hit }}

@endforeach

@endsection

Sort the melee catalog by bash and cutting.


<?php

namespace Vitaminate\Routing;

use Vitaminate\Http\Request;
use Vitaminate\Routing\Route;
use Vitaminate\Routing\Contracts\RouteCollectionInterface;

/**
 * Class Matcher
 *
 * @author Mystro Ken <mystroken@gmail.com>
 * @package Vitaminate\Routing
 */
class RouteMatcher
{

    /**
     * Get the matched route from the request.
     *
     * @param Request $request
     * @param RouteCollectionInterface $routeCollection
     * @return null|\Vitaminate\Routing\Route
     */
    public function getRoute(Request $request, RouteCollectionInterface $routeCollection)
    {
        $routeMatch = null;

        $url = parse_url($request->getRequestUri());
        $parameters = $request->query->all();
        $path = $url["path"];

        /**
         * @var Route $route
         */
        foreach ($routeCollection->getRoutes() as $route)
        {
            $routePath = $route->getPath();
            $routeParameters = $route->getParameters();

            if( $path != $routePath ) continue;
            if( sizeof($parameters) !== sizeof($routeParameters) ) continue;
            if( serialize($parameters) !== serialize($routeParameters) ) continue;

            $routeMatch = $route;
            break;
        }

        return $routeMatch;
    }
}

<?php

namespace Vitaminate\Routing;

use Vitaminate\Http\Request;
use Vitaminate\Routing\Route;
use Vitaminate\Routing\Contracts\RouteCollectionInterface;

/**
 * Class Matcher
 *
 * @author Mystro Ken <mystroken@gmail.com>
 * @package Vitaminate\Routing
 */
class RouteMatcher
{

    /**
     * Get the matched route from the request.
     *
     * @param Request $request
     * @param RouteCollectionInterface $routeCollection
     * @return null|\Vitaminate\Routing\Route
     */
    public function getRoute(Request $request, RouteCollectionInterface $routeCollection)
    {
        $routeMatch = null;

        $url = parse_url($request->getRequestUri());
        $parameters = $request->query->all();
        $path = $url["path"];

        /**
         * @var Route $route
         */
        foreach ($routeCollection->getRoutes() as $route)
        {
            $routePath = $route->getPath();
            $routeParameters = $route->getParameters();
            $parametersMatch = array_intersect($routeParameters, $parameters)

            if( $path != $routePath ) continue;
            if( sizeof($parametersMatch) !== sizeof($routeParameters) ) continue;
            if( serialize($parametersMatch) !== serialize($routeParameters) ) continue;

            $routeMatch = $route;
            break;
        }

        return $routeMatch;
    }
}

Fix the routing match issue

Fix the routing match issue


<?php
// report all errors
error_reporting(-1);

setlocale(LC_ALL, 'en_US');
date_default_timezone_set('UTC');

// composer
require_once __DIR__ . '/../vendor/autoload.php';

// environment
call_user_func(function () {
    $dotenv = new \Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    $dotenv->required('testMssql')->allowedValues(['yes', 'no']);
});

<?php
// report all errors
error_reporting(-1);

setlocale(LC_ALL, 'en_US');
date_default_timezone_set('UTC');

// composer
require_once __DIR__ . '/../vendor/autoload.php';

// environment
call_user_func(function () {
    $dotenv = new \Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    $dotenv->required('testMssql')->allowedValues(['yes', 'no']);
    $dotenv->required('testMysqli')->allowedValues(['yes', 'no']);
});

Add allowed values for testMysqli

Add allowed values for testMysqli


<?php

/**
 * This file is part of phpcq/branch-alias-validation.
 *
 * (c) 2014 Christian Schiffler, Tristan Lins
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * This project is provided in good faith and hope to be usable by anyone.
 *
 * @package    phpcq/branch-alias-validation
 * @author     Christian Schiffler <c.schiffler@cyberspectrum.de>
 * @author     Tristan Lins <tristan@lins.io>
 * @copyright  Christian Schiffler <c.schiffler@cyberspectrum.de>, Tristan Lins <tristan@lins.io>
 * @link       https://github.com/phpcq/branch-alias-validation
 * @license    https://github.com/phpcq/branch-alias-validation/blob/master/LICENSE MIT
 * @filesource
 */

error_reporting(E_ALL);

function includeIfExists($file)
{
	return file_exists($file) ? include $file : false;
}

if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
	echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
		'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
		'php composer.phar install'.PHP_EOL;
	exit(1);
}

<?php

/**
 * This file is part of phpcq/doctrine-validation.
 *
 * (c) 2014 Tristan Lins
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * This project is provided in good faith and hope to be usable by anyone.
 *
 * @package    phpcq/doctrine-validation
 * @author     Tristan Lins <tristan@lins.io>
 * @copyright  Tristan Lins <tristan@lins.io>
 * @link       https://github.com/phpcq/doctrine-validation
 * @license    https://github.com/phpcq/doctrine-validation/blob/master/LICENSE MIT
 * @filesource
 */

error_reporting(E_ALL);

function includeIfExists($file)
{
	return file_exists($file) ? include $file : false;
}

if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
	echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
		'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
		'php composer.phar install'.PHP_EOL;
	exit(1);
}

Fix wrong copy-pasted file documentation header.


<?php declare(strict_types=1);

namespace Onion\Console\Router\Factory;

use Onion\Framework\Console\Interfaces\ArgumentParserInterface;
use Onion\Framework\Dependency\Interfaces\FactoryInterface;
use Onion\Console\Router\Router;
use Psr\Container\ContainerInterface as Container;

class RouterFactory implements FactoryInterface
{
    /**
     * Method that is called by the container, whenever a new
     * instance of the application is necessary. It is the only
     * method called when creating instances and thus, should
     * produce/return the fully configured object it is intended
     * to build.
     *
     * @param Container $container
     *
     * @return Router
     */
    public function build(Container $container): Router
    {
        $commands = $container->get('commands');
        $router = new Router(
            $container->get(ArgumentParserInterface::class)
        );
        foreach ($commands as $command) {
            $command = array_merge([
                'flags' => [],
                'parameters' => [],
            ], $command);

            $name = $command['name'];
            $handler = $container->get($command['handler']);
            unset($command['name'], $command['handler']);

            $router->addCommand($name, $handler, $command);
        }
        return $router;
    }
}

<?php declare(strict_types=1);

namespace Onion\Console\Router\Factory;

use Onion\Framework\Console\Interfaces\ArgumentParserInterface;
use Onion\Framework\Dependency\Interfaces\FactoryInterface;
use Onion\Console\Router\Router;
use Psr\Container\ContainerInterface as Container;

class RouterFactory implements FactoryInterface
{
    /**
     * Method that is called by the container, whenever a new
     * instance of the application is necessary. It is the only
     * method called when creating instances and thus, should
     * produce/return the fully configured object it is intended
     * to build.
     *
     * @param Container $container
     *
     * @return Router
     */
    public function build(Container $container): Router
    {
        $commands = $container->get('commands');
        $router = new Router(
            $container->get(ArgumentParserInterface::class)
        );
        foreach ($commands as $command) {
            $command = array_merge([
                'parameters' => [],
            ], $command);

            $name = $command['name'];
            $handler = $container->get($command['handler']);
            unset($command['name'], $command['handler']);

            $router->addCommand($name, $handler, $command);
        }
        return $router;
    }
}

Remove the obsolete `flags` key

Remove the obsolete `flags` key


<?php
/**
 * HTML footer
 *
 * @url         $URL$
 * @date        $Date$
 * @version     $Revision$
 * @author      $Author$
 *
 * @package     Beirdobot
 *
/**/
?>

IRC Logs collected by
BeirdoBot.

Please use the above link to report any bugs.

Comment out the google ads

Comment out the google ads

git-svn-id: 798f9e0ce1eefcecf757a5f2b692a26d86a9651c@418 c66dcb5a-e80b-0410-ab0e-bb6a4f3ddef9


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

use \Phramework\Models\Request;
use \Phramework\Validate\Validate;
use \Phramework\Models\Util;
use \Phramework\Models\Filter;
use \Phramework\Models\Operator;
use \Phramework\Exceptions\RequestException;

/**
 * Base JSONAPI controller
 * @since 1.0.0
 * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @author Xenofon Spafaridis <nohponex@gmail.com>
 */
abstract class Controller extends \Phramework\JSONAPI\Controller\DELETE
{
}

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

/**
 * Base JSONAPI controller
 * @since 1.0.0
 * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @author Xenofon Spafaridis <nohponex@gmail.com>
 */
abstract class Controller extends \Phramework\JSONAPI\Controller\DELETE
{
}

DELETE use statements. Resolve conflicts with another class


<?php

namespace App\Http\Controllers\Admin;

use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;

class HouseholdController extends AdminController
{
    /**
     * Display a listing of the users.
     *
     * @param UserDataTable $dataTable
     */
    public function index(HouseholdDataTable $dataTable)
    {
        return $dataTable->render($this->viewPath());
    }

    /**
     * Store a newly created user in storage
     */
    public function store(HouseholdRequest $request)
    {
        return $this->createFlashRedirect(Household::class, $request, $this->imageColumn);
    }

    /**
     * Display the specified user.
     */
    public function show(Household $household)
    {
       return $this->viewPath("show", $household);
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(Household $household)
    {
        $household->child;
        return $this->getForm($household);
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Household $household, HouseholdRequest $request)
    {
        return $this->saveFlashRedirect($household, $request);
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(Household $user)
    {
        # TODO: Not sure we want to do this... :S
    }
}

<?php

namespace App\Http\Controllers\Admin;

use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;

class HouseholdController extends AdminController
{
    /**
     * Display a listing of the users.
     *
     * @param UserDataTable $dataTable
     */
    public function index(HouseholdDataTable $dataTable)
    {
        return $dataTable->render($this->viewPath());
    }

    /**
     * Store a newly created user in storage
     */
    public function store(HouseholdRequest $request)
    {
        $request['nominator_user_id'] = Auth::user()->id;
        return $this->createFlashRedirect(Household::class, $request);
    }

    /**
     * Display the specified user.
     */
    public function show(Household $household)
    {
       return $this->viewPath("show", $household);
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(Household $household)
    {
        $household->child;
        return $this->getForm($household);
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Household $household, HouseholdRequest $request)
    {
        return $this->saveFlashRedirect($household, $request);
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(Household $user)
    {
        # TODO: Not sure we want to do this... :S
    }
}

Append nominator user id when nominating a household


<?php
namespace Gitter\Statistics;

use Gitter\Util\Collection;
use Gitter\Model\Commit\Commit;

/**
 * Aggregate statistics based on contributor
 */
class Contributors extends Collection implements StatisticsInterface
{
    /**
     * @param Commit $commit
     */
    public function addCommit(Commit $commit)
    {
        $email      = $commit->getAuthor()->getEmail();
        $commitDate = $commit->getCommiterDate()->format('Y-m-d');

        $this->items[$email][$commitDate][] = $commit;
    }
}

<?php
namespace Gitter\Statistics;

use Gitter\Util\Collection;
use Gitter\Model\Commit\Commit;

/**
 * Aggregate statistics based on contributor
 */
class Contributors extends Collection implements StatisticsInterface
{
    /**
     * @param Commit $commit
     */
    public function addCommit(Commit $commit)
    {
        $email      = $commit->getAuthor()->getEmail();
        $commitDate = $commit->getCommiterDate()->format('Y-m-d');

        if (!isset($this->items[$email])) {
            $this->items[$email] = new Collection;
        }

        $commits = $this->items[$email];
        $commits->items[$commitDate][] = $commit;
    }
}

Handle contributor commits in own collections


<?php
/**
 * Provides resource to access memcache server.
 *
 * Parameters:
 *  - [memcache.host]
 *  - [memcache.port]
 *  - [memcache.unix_socket]
 *  - [memcache.namespace]
 *
 * Services:
 *  - [memcache] instance of CacheCollection
**/
namespace Ob_Ivan\DropboxProxy\ResourceProvider;

use Ob_Ivan\Cache\Driver\MemcacheDriver;
use Ob_Ivan\Cache\CacheCollection;
use Ob_Ivan\ResourceContainer\ResourceContainer;
use Ob_Ivan\ResourceContainer\ResourceProviderInterface;

class MemcacheResourceProvider implements ResourceProviderInterface
{
    function populate(ResourceContainer $container)
    {
        $container->register('memcache', function ($container) {
            $params = [];
            if (isset($container['memcache.unix_socket'])) {
                $params['host'] = 'unix://' . $container['memcache.unix_socket'];
                $params['port'] = 0;
            } elseif (isset($container['memcache.host']) && isset($container['memcache.port'])) {
                $params['host'] = $container['memcache.host'];
                $params['port'] = $container['memcache.port'];
            }
            return new CacheCollection(
                new MemcacheDriver($params),
                $container['memcache.namespace']
            );
        });
    }
}

<?php
/**
 * Provides resource to access memcache server.
 *
 * Parameters:
 *  - [memcache.host]
 *  - [memcache.port]
 *  - [memcache.unix_socket]
 *  - [memcache.namespace]
 *
 * Services:
 *  - [memcache] instance of CacheCollection
**/
namespace Ob_Ivan\DropboxProxy\ResourceProvider;

use Ob_Ivan\Cache\Driver\MemcacheDriver;
use Ob_Ivan\Cache\CacheCollection;
use Ob_Ivan\ResourceContainer\ResourceContainer;
use Ob_Ivan\ResourceContainer\ResourceProviderInterface;

class MemcacheResourceProvider implements ResourceProviderInterface
{
    function populate(ResourceContainer $container)
    {
        $container->register('memcache', function ($container) {
            $params = [];
            if (isset($container['memcache.unix_socket'])) {
                $params['host'] = 'unix://' . $container['memcache.unix_socket'];
                $params['port'] = 0;
            } elseif (isset($container['memcache.host']) && isset($container['memcache.port'])) {
                $params['host'] = $container['memcache.host'];
                $params['port'] = $container['memcache.port'];
            } else {
                throw new Exception('No server parameters provided for memcache resource.');
            }
            return new CacheCollection(
                new MemcacheDriver($params),
                isset($container['memcache.namespace'])
                    ? $container['memcache.namespace']
                    : ''
            );
        });
    }
}

Add config check to memcache resource provider


<?php

class TemplateOverrideExtensionTest extends SapphireTest {

	protected static $fixture_file = 'template-override/tests/pages.yml';

	public function setUpOnce() {
		parent::setupOnce();
	}

	public function testUpdateCMSFields() {
		$page = $this->objFromFixture('Page', 'page1');
		$fields = $page->getCMSFields();
		$tab = $fields->findOrMakeTab('Root.Template');
		$fields = $tab->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}
		$expected = array('AlternativeTemplate', 'infofield');
		$this->assertEquals($expected, $names);
	}
}

<?php

class TemplateOverrideExtensionTest extends SapphireTest {

	protected static $fixture_file = 'template-override/tests/pages.yml';

	public function testUpdateCMSFields() {
		$page = $this->objFromFixture('Page', 'page1');
		$fields = $page->getCMSFields();
		$tab = $fields->findOrMakeTab('Root.Template');
		$fields = $tab->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}
		$expected = array('AlternativeTemplate', 'infofield');
		$this->assertEquals($expected, $names);
	}
}

MINOR: Remove setup method that was not showing in coverage tests


<?php

namespace OAuthBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

use WordPressBundle\Entity\Post;

class LoadPostData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {

        $post1 = new Post();
        $post1->setPostAuthor(1);
        $post1->setPostDate(new \DateTime("now"));
        $post1->setPostDateGmt(new \DateTime("now"));
        $post1->setPostContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam eligendi provident quam eveniet sint nesciunt consequuntur reprehenderit velit est molestiae, quisquam, repellendus, aliquid delectus natus! Et optio asperiores, commodi dignissimos.");
        $post1->setPostTitle("Lorem ipsum");
        $post1->setPostExcerpt("lorem ipsum dolor sit");
        $post1->setPostModified(new \DateTime("now"));
        $post1->setPostModifiedGmt(new \DateTime("now"));

        $manager->persist($post1);
        $manager->flush();

    }

    public function getOrder(){
        return 1;
    }
}

<?php

namespace OAuthBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

use WordPressBundle\Entity\Post;

class LoadPostData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {

        $post1 = new Post();
        $post1->setPostAuthor(1);
        $post1->setPostDate(new \DateTime("now"));
        $post1->setPostDateGmt(new \DateTime("now"));
        $post1->setPostContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam eligendi provident quam eveniet sint nesciunt consequuntur reprehenderit velit est molestiae, quisquam, repellendus, aliquid delectus natus! Et optio asperiores, commodi dignissimos.");
        $post1->setPostTitle("Lorem ipsum");
        $post1->setPostExcerpt("lorem ipsum dolor sit");
        $post1->setPostModified(new \DateTime("now"));
        $post1->setPostModifiedGmt(new \DateTime("now"));

        $this->addReference('post-1', $post1);

        $manager->persist($post1);
        $manager->flush();

    }

    public function getOrder(){
        return 1;
    }
}

Add post fixture on reference

:wrench: Add post fixture on reference


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

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

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
    'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
    'files' => array('src', 'tests', 'build.php'),
    'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

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

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

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
    'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
    'files' => array('src', 'tests', 'build.php'),
    'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Remove --dev from composer install.

Remove --dev from composer install.

--dev is the default.