<?php

namespace Styleguide\Http\Controllers;

use App\Http\Controllers\Controller;
use Factories\Banner;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    /**
     * Display the banner at the top of the page.
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $request->data['banner'] = app(Banner::class)->create(1, true);

        return view('styleguide-childpage', merge($request->data));
    }
}

<?php

namespace Styleguide\Http\Controllers;

use App\Http\Controllers\Controller;
use Factories\Banner;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    /**
     * Display the banner at the top of the page.
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $request->data['base']['banner'] = app(Banner::class)->create(1, true);

        return view('styleguide-childpage', merge($request->data));
    }
}

Fix banner displaying by scoping it to the proper base


<?php
/**
 * symfony
 * User: thomas
 * Date: 20.11.13
 * Time: 17:59
 */

namespace Hampe\Bundle\ZurbInkBundle\Twig;

use Hampe\Bundle\ZurbInkBundle\Service\CssContainer;
use \Twig_Extension;
use \Twig_SimpleFunction;
use \PhpCollection\Sequence;

class InlineCssExtension extends Twig_Extension
{

    protected $inlineCss;

    protected $fileLocator;

    public function __construct($inlineCss, $fileLocator)
    {
        $this->inlineCss = $inlineCss;
        $this->fileLocator = $fileLocator;
    }

    public function getName()
    {
        return "zurb_ink.inlinecss";
    }

    public function getGlobals()
    {
        return array(
            "zurb_ink_inlinecss" => $this->inlineCss,
            "zurb_ink_locator" => $this->fileLocator,
            "zurb_ink_styles" => new CssContainer()
        );

    }

    public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction('includeStyles', array($this, 'includeStyles'))
        );
    }

    public function getTokenParsers()
    {
        return array(
            new InlineCssTokenParser()
        );
    }

    public function includeStyles ($styles)
    {
        $locator = $this->fileLocator;
        $style = "";
        foreach ($styles as $styleFile) {
            $path = $locator->locate($styleFile);
            $style .= "\n\n".file_get_contents($path);
        }

        return $style;
    }
}

<?php
/**
 * symfony
 * User: thomas
 * Date: 20.11.13
 * Time: 17:59
 */

namespace Hampe\Bundle\ZurbInkBundle\Twig;

use Hampe\Bundle\ZurbInkBundle\Service\CssContainer;
use \Twig_Extension;
use \Twig_Extension_GlobalsInterface;
use \Twig_SimpleFunction;
use \PhpCollection\Sequence;

class InlineCssExtension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{

    protected $inlineCss;

    protected $fileLocator;

    public function __construct($inlineCss, $fileLocator)
    {
        $this->inlineCss = $inlineCss;
        $this->fileLocator = $fileLocator;
    }

    public function getName()
    {
        return "zurb_ink.inlinecss";
    }

    public function getGlobals()
    {
        return array(
            "zurb_ink_inlinecss" => $this->inlineCss,
            "zurb_ink_locator" => $this->fileLocator,
            "zurb_ink_styles" => new CssContainer()
        );

    }

    public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction('includeStyles', array($this, 'includeStyles'))
        );
    }

    public function getTokenParsers()
    {
        return array(
            new InlineCssTokenParser()
        );
    }

    public function includeStyles ($styles)
    {
        $locator = $this->fileLocator;
        $style = "";
        foreach ($styles as $styleFile) {
            $path = $locator->locate($styleFile);
            $style .= "\n\n".file_get_contents($path);
        }

        return $style;
    }
}

Implement `Twig_Extension_GlobalsInterface` to Fix Depreciation Warning


<?php
$conf = json_decode(file_get_contents("/etc/conf/local.conf"), 1);
define("DB_USER", $conf["mysql-user"]);
define("DB_HOST", $conf["host"]);
define("HOST", $conf["host"]);
define("DB_PASS", $conf["mysql-password"]);
define("DB_NAME", $conf["db-name"]);

//define("DB_USER", "mysqlUser");
//define("DB_HOST", "dev.xenonapps.com");
//define("DB_PASS", "1k23k4k55j");
//define("DB_NAME", "green_up_vt");
define("BASE_INCLUDE", dirname(__FILE__) );
?>

<?php
$conf = json_decode(file_get_contents("/etc/conf/local.conf"), 1);
/* Fix for conf['host'] being an IP Address within a VirtualHost by Name setup
*/
$conf['host'] = $_SERVER['SERVER_NAME'];
define("DB_USER", $conf["mysql-user"]);
define("DB_HOST", $conf["host"]);
define("HOST", $conf["host"]);
define("DB_PASS", $conf["mysql-password"]);
define("DB_NAME", $conf["db-name"]);

//define("DB_USER", "mysqlUser");
//define("DB_HOST", "dev.xenonapps.com");
//define("DB_PASS", "1k23k4k55j");
//define("DB_NAME", "green_up_vt");
define("BASE_INCLUDE", dirname(__FILE__) );
?>

Fix for Host IP in NamedVirtualHost setup

The servers use an IP Address for the host in the configuration details,
but we're running a NamedVirtualHost setup, so we need to have a
resolution for the curl call done by the index.php during login.

Pulling ServerName as the authoritive configuration for host name.


<?php
namespace AppBundle\Twig;

class TilesTracker extends \Twig_Extension
{
    private $tiles = array();

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('gettiles', array($this, 'getTiles')),
            new \Twig_SimpleFunction('rendertile', array($this, 'renderedTile')),
            new \Twig_SimpleFunction('addtile', array($this, 'addTile')),
            new \Twig_SimpleFunction('settiles', array($this, 'setTiles'))
        );
    }

    public function getTiles()
    {
        return $this->tiles;
    }

    public function renderedTile($index) {
        $this->tiles = array_values(array_filter($this->tiles, function($tile) use($index) {
            return $tile != $index;
        }));
    }

    public function addTile($index, $weight) {
        for($i = 0; $i < $weight; ++$i)
        {
            $this->tiles[] = $index;
        }
    }

    public function setTiles($array)
    {
        $this->tiles = $array;
    }

    public function getName()
    {
        return 'tiles_tracker';
    }
}
?>

<?php
namespace AppBundle\Twig;

class TilesTracker extends \Twig_Extension
{
    /**
     * Array containing tile IDs to choose from. By repeating an ID its weight
     * in the random selection is increased.
     */
    private $tiles = array();

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('gettiles', array($this, 'getTiles')),
            new \Twig_SimpleFunction('rendertile', array($this, 'renderedTile')),
            new \Twig_SimpleFunction('addtile', array($this, 'addTile')),
            new \Twig_SimpleFunction('settiles', array($this, 'setTiles'))
        );
    }

    /**
     * Get the (weighted) array of tile IDs.
     * @returns Array of tile IDs
     */
    public function getTiles()
    {
        return $this->tiles;
    }

    /**
     * Marks a tile as renderd in the array of tiles. Essentially removes all
     * occurences of the ID.
     * @param $index - Tile ID
     */
    public function renderedTile($index) {
        $this->tiles = array_values(array_filter($this->tiles, function($tile) use($index) {
            return $tile != $index;
        }));
    }

    /**
     * Adds the the given tile ID $weight times to the array of IDs to choose
     * from.
     * @param $index - Tile ID
     * @param $weight - Weight of the tile
     */
    public function addTile($index, $weight) {
        for($i = 0; $i < $weight; ++$i)
        {
            $this->tiles[] = $index;
        }
    }

    /**
     * Set the array of tile IDs to choose from.
     * @param $array - Array of tile IDs
     */
    public function setTiles($array)
    {
        $this->tiles = $array;
    }

    public function getName()
    {
        return 'tiles_tracker';
    }
}
?>

Document the tiles tracker so it will be easier to understand in the future, hopefully


<?php
namespace DlcUseCase\Form;

use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;

class EditUseCase extends BaseUseCase
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit use case');
    }
}

<?php
namespace DlcUseCase\Form;

use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;
use Zend\Form\FormInterface;

class EditUseCase extends BaseUseCase
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit use case');
    }

    public function bind($useCase, $flags = FormInterface::VALUES_NORMALIZED)
    {
        parent::bind($useCase, $flags);

        if ($useCase->getType() != null) {
            $this->byName['type']->setValue($useCase->getType()->getId());
        }

        if ($useCase->getCategory() != null) {
            $this->byName['category']->setValue($useCase->getCategory()->getId());
        }

        if ($useCase->getPriority() != null) {
            $this->byName['priority']->setValue($useCase->getPriority()->getId());
        }
    }
}

Fix bug in edit use case form

Fix bug in edit use case form


<?php

require_once(realpath($_SERVER["DOCUMENT_ROOT"]) . '/wp-load.php');
require_once('includes/phpqrcode.php');

if (isset($_GET['order'])) {
    $qrCode = get_post_meta($_GET['order'], 'SEQR Invoice QR Code', true);
    QRcode::png($qrCode, false, QR_ECLEVEL_L, 6, 0);
} else {
    QRcode::png('HTTP://SEQR.COM', false, QR_ECLEVEL_L, 6, 0);
}

<?php

$rootPath = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), 'wp-content'));

require_once("$rootPath/wp-load.php");
require_once('includes/phpqrcode.php');

if (isset($_GET['order'])) {
    $qrCode = get_post_meta($_GET['order'], 'SEQR Invoice QR Code', true);
    QRcode::png($qrCode, false, QR_ECLEVEL_L, 6, 0);
} else {
    QRcode::png('HTTP://SEQR.COM', false, QR_ECLEVEL_L, 6, 0);
}

Fix of issue with Wordpress located not in site root directory


<?php

namespace SiberianWolf\Router;

/**
 * Ensuring that every route in collection is from type Route
 * Class RouteCollection
 * @package SiberianWolf\Router
 */
class RouteCollection implements \ArrayAccess, \IteratorAggregate
{
    /**
     * @var array $routes
     */
    protected $routes;

    /**
     * @param string $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($routes[$offset]);
    }

    /**
     * @param string $offset
     * @return RouteInterface
     */
    public function offsetGet($offset)
    {
        return $this->routes[$offset];
    }

    /**
     * @param string $offset
     * @param RouteInterface $value
     */
    public function offsetSet($offset, $value)
    {
        if (!$value instanceof Route) {
            throw new \InvalidArgumentException("Route collection accept only SiberianWolf\\Router\\Route object");
        }
        $this->routes[$offset] = $value;
    }

    /**
     * @param string $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->routes[$offset]);
    }

    /**
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->routes);
    }
}

<?php

namespace SiberianWolf\Router;

/**
 * Ensuring that every route in collection is from type Route
 * Class RouteCollection.
 */
class RouteCollection implements \ArrayAccess, \IteratorAggregate
{
    /**
     * @var array
     */
    protected $routes;

    /**
     * @param string $offset
     *
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($routes[$offset]);
    }

    /**
     * @param string $offset
     *
     * @return RouteInterface
     */
    public function offsetGet($offset)
    {
        return $this->routes[$offset];
    }

    /**
     * @param string         $offset
     * @param RouteInterface $value
     */
    public function offsetSet($offset, $value)
    {
        if (!$value instanceof Route) {
            throw new \InvalidArgumentException('Route collection accept only SiberianWolf\\Router\\Route object');
        }

        $this->routes[$offset] = $value;
    }

    /**
     * @param string $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->routes[$offset]);
    }

    /**
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->routes);
    }
}

Add Exception if element is not instance of RouteInterface


<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

    private $name;
    private $keyId;
    private $genome;
    private $role;
    private $paralysed;
    private $mutated;
    private $alive;

    public function __construct($name)
    {
        return parent::__construct('player');
        $this->name = $name;
    }

    public function setGenome($genome)
    {
        if (!in_array($genome, [self::GENOME_HOST, self::GENOME_RESISTANT, self::GENOME_NORMAL])) {
            $genome = self::GENOME_NORMAL;
        }

        $this->genome = $genome;
    }

    public function mutate()
    {
        if ($this->genome != self::GENOME_RESISTANT) {
            $this->mutated = 1;
        }

        return $this->mutated;
    }

    public function cure()
    {
        if ($this->genome != self::GENOME_HOST) {
            $this->mutated = 0;
        }

        return !$this->mutated;
    }
}

<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

    private $name;
    private $keyId;
    private $genome;
    private $role;
    private $paralysed;
    private $mutated;
    private $alive;

    public function __construct()
    {
        return parent::__construct('player');
    }

    public function setGenome($genome)
    {
        if (!in_array($genome, [self::GENOME_HOST, self::GENOME_RESISTANT, self::GENOME_NORMAL])) {
            $genome = self::GENOME_NORMAL;
        }

        $this->genome = $genome;
    }

    public function mutate()
    {
        if ($this->genome != self::GENOME_RESISTANT) {
            $this->mutated = 1;
        }

        return $this->mutated;
    }

    public function cure()
    {
        if ($this->genome != self::GENOME_HOST) {
            $this->mutated = 0;
        }

        return !$this->mutated;
    }
}

Remove name param from constructor

Remove name param from constructor

Break QueryBuilder::forge() method instantiating objects.


<?php
    class ImageController extends ControllerBase {
        public function create( $image ) {
            require_once 'models/image.php';
            require_once 'models/extentions.php';
            if ( !isset( $_SESSION[ 'user' ] ) ) {
                throw new HTTPUnauthorizedException();
            }
            $user = $_SESSION[ 'user' ];
            $userImage = new Image();
            $userImage->tmp_name = $image[ 'tmp_name' ];
            $userImage->name = $image[ 'name' ];
            $userImage->user = $user;
            $user->image = $userImage;
            try {
                $userImage->save();
                $user->save();
            }
            catch ( ModelValidationException $e ) {
                go( 'user', 'view', [ 'username' => $user->username, $e->error => true ] );
            }
            go( 'user', 'view', [ 'username' => $user->username ] );
        }
    }
?>

<?php
    class ImageController extends ControllerBase {
        public function create( $image ) {
            require_once 'models/image.php';
            require_once 'models/extentions.php';
            if ( !isset( $_SESSION[ 'user' ] ) ) {
                throw new HTTPUnauthorizedException();
            }
            $user = $_SESSION[ 'user' ];
            $userImage = new Image();
            $userImage->tmp_name = $image[ 'tmp_name' ];
            $userImage->name = $image[ 'name' ];
            $userImage->user = $user;
            $user->image = $userImage;
            try {
                $userImage->save();
                $user->save();
            }
            catch ( ModelValidationException $e ) {
                if ( isset( $this->acceptTypes[ 'application/json' ] ) ) {
                    throw new HTTPBadRequestException();
                }
                go( 'user', 'view', [ 'username' => $user->username, $e->error => true ] );
            }
            if ( !isset( $this->acceptTypes[ 'application/json' ] ) ) {
                go( 'user', 'view', [ 'username' => $user->username ] );
            }
            echo json_encode( [] );
        }
    }
?>

Make the controller work with json

Make the controller work with json


<?php

namespace Phuby;

class Kernel {
    function extend($module) {
        return $this->__extend__($module);
    }

    function inspect() {
        return '<'.$this->__class()->name().':'.$this->object_id().'>';
    }

    function is_a($module) {
        $module = (string) $module;
        foreach ($this->singleton_class()->ancestors() as $ancestor)
            if ($ancestor->name() == $module)
                return true;
    }

    function method($method_name) {
        if ($method = $this->singleton_class()->instance_method($method_name))
            return $method->bind($this);
    }

    function methods() {
        return $this->singleton_class()->instance_methods();
    }

    function object_id() {
        return $this->__id__();
    }

    function respond_to($method_name) {
        return !!$this->method($method_name) || $this->respond_to_missing($method_name);
    }

    function respond_to_missing($method_name) {
        return false;
    }

    function send($method_name) {
        return call_user_func_array([$this, '__send__'], func_get_args());
    }

    function splat($method_name, $args) {
        return $this->__splat__($method_name, $args);
    }

    function tap($block) {
        $block($this);
        return $this;
    }

    function to_s() {
        return $this->inspect();
    }
}

<?php

namespace Phuby;

class Kernel {
    static function initialized($self) {
        $self->alias_method('[]', 'array_access_offset_get');
        $self->alias_method('[]=', 'array_access_offset_set');
    }

    function extend($module) {
        return $this->__extend__($module);
    }

    function inspect() {
        return '<'.$this->__class()->name().':'.$this->object_id().'>';
    }

    function is_a($module) {
        $module = (string) $module;
        foreach ($this->singleton_class()->ancestors() as $ancestor)
            if ($ancestor->name() == $module)
                return true;
    }

    function method($method_name) {
        if ($method = $this->singleton_class()->instance_method($method_name))
            return $method->bind($this);
    }

    function methods() {
        return $this->singleton_class()->instance_methods();
    }

    function object_id() {
        return $this->__id__();
    }

    function respond_to($method_name) {
        return !!$this->method($method_name) || $this->respond_to_missing($method_name);
    }

    function respond_to_missing($method_name) {
        return false;
    }

    function send($method_name) {
        return call_user_func_array([$this, '__send__'], func_get_args());
    }

    function splat($method_name, $args) {
        return $this->__splat__($method_name, $args);
    }

    function tap($block) {
        $block($this);
        return $this;
    }

    function to_s() {
        return $this->inspect();
    }
}

Add aliases for [] and []= to Kernel

Add aliases for [] and []= to Kernel


<?php

namespace Northstar\Merge;

use Northstar\Exceptions\NorthstarValidationException;

class Merger
{
    public function merge($field, $target, $duplicate)
    {
        $mergeMethod = 'merge'.studly_case($field);

        if (! method_exists($this, $mergeMethod)) {
            throw new NorthstarValidationException(['Unable to merge '.$field.' field. No merge instructions found.'], ['target' => $target, 'duplicate' => $duplicate]);
        }

        return $this->{$mergeMethod}($target, $duplicate);
    }

    public function mergeLastAuthenticatedAt($target, $duplicate)
    {
        $targetValue = $target->last_authenticated_at;
        $duplicateValue = $duplicate->last_authenticated_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }

    public function mergeLastMessagedAt($target, $duplicate)
    {
        $targetValue = $target->last_messaged_at;
        $duplicateValue = $duplicate->last_messaged_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }

    public function mergeLastAccessedAt($target, $duplicate)
    {
        $targetValue = $target->last_accessed_at;
        $duplicateValue = $duplicate->last_accessed_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }

    public function mergeLanguage($target, $duplicate)
    {
        if ($target->last_accessed_at > $duplicate->last_accessed_at) {
            return $target->language;
        }

        return $duplicate->language;
    }
}

<?php

namespace Northstar\Merge;

use Northstar\Exceptions\NorthstarValidationException;

class Merger
{
    public function merge($field, $target, $duplicate)
    {
        $mergeMethod = 'merge'.studly_case($field);

        if (! method_exists($this, $mergeMethod)) {
            throw new NorthstarValidationException(['Unable to merge '.$field.' field. No merge instructions found.'], ['target' => $target, 'duplicate' => $duplicate]);
        }

        return $this->{$mergeMethod}($target, $duplicate);
    }

    public function mergeLastAuthenticatedAt($target, $duplicate)
    {
        return $this->chooseMostRecentDate('last_authenticated_at', $target, $duplicate);
    }

    public function mergeLastMessagedAt($target, $duplicate)
    {
        return $this->chooseMostRecentDate('last_messaged_at', $target, $duplicate);
    }

    public function mergeLastAccessedAt($target, $duplicate)
    {
        return $this->chooseMostRecentDate('last_accessed_at', $target, $duplicate);
    }

    public function mergeLanguage($target, $duplicate)
    {
        if ($target->last_accessed_at > $duplicate->last_accessed_at) {
            return $target->language;
        }

        return $duplicate->language;
    }

    public function chooseMostRecentDate($field, $target, $duplicate)
    {
        $targetValue = $target->{$field};
        $duplicateValue = $duplicate->{$field};

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }
}

Add chooseMostRecentDate helper and use it


<?php if (isset($msg)): ?>
    <?php foreach ($msg as $type=>$list): ?>
        <div class="single panel <?php echo $type; ?>">

                    <?php echo strtoupper($type); ?>!

                <?php foreach ($list as $value): ?>

<?php echo $value; ?>

                <?php endforeach; ?>

    <?php endforeach; ?>
<?php endif; ?>

Add ul tag before li to prevent left align text


<?php

final class PhabricatorDatasourceURIEngineExtension
  extends PhabricatorDatasourceEngineExtension {

  public function newQuickSearchDatasources() {
    return array();
  }

  public function newJumpURI($query) {
    // If you search for a URI on the local install, just redirect to that
    // URI as though you had pasted it into the URI bar.
    if (PhabricatorEnv::isSelfURI($query)) {
      // Strip off the absolute part of the URI. If we don't, the URI redirect
      // validator will get upset that we're performing an unmarked external
      // redirect.

      // The correct host and protocol may also differ from the host and
      // protocol used in the search: for example, if you search for "http://"
      // we want to redirect to "https://" if an install is HTTPS, and
      // the "isSelfURI()" check includes alternate domains in addition to the
      // canonical domain.

      $uri = id(new PhutilURI($query))
        ->setDomain(null)
        ->setProtocol(null)
        ->setPort(null);

      return phutil_string_cast($uri);
    }

    return null;
  }
}

<?php

final class PhabricatorDatasourceURIEngineExtension
  extends PhabricatorDatasourceEngineExtension {

  public function newQuickSearchDatasources() {
    return array();
  }

  public function newJumpURI($query) {
    // If you search for a URI on the local install, just redirect to that
    // URI as though you had pasted it into the URI bar.
    if (PhabricatorEnv::isSelfURI($query)) {
      // Strip off the absolute part of the URI. If we don't, the URI redirect
      // validator will get upset that we're performing an unmarked external
      // redirect.

      // The correct host and protocol may also differ from the host and
      // protocol used in the search: for example, if you search for "http://"
      // we want to redirect to "https://" if an install is HTTPS, and
      // the "isSelfURI()" check includes alternate domains in addition to the
      // canonical domain.

      $uri = id(new PhutilURI($query))
        ->setDomain(null)
        ->setProtocol(null)
        ->setPort(null);

      $uri = phutil_string_cast($uri);

      // See T13412. If the URI was in the form "http://dev.example.com" with
      // no trailing slash, there may be no path. Redirecting to the empty
      // string is considered an error by safety checks during redirection,
      // so treat this like the user entered the URI with a trailing slash.
      if (!strlen($uri)) {
        $uri = '/';
      }

      return $uri;
    }

    return null;
  }
}

Fix fatal during redirection safety check for searching for Phabricator base-uri with no trailing slash

Summary: Fixes T13412. If you search for "https://phabricator.example.com" with no trailing slash, we currently redirect you to "", which is fouled by a safety check in the redirection flow.

Test Plan:
  - Searched for "https://local.phacility.com"; before: fatal in redirection; after: clean redirect.
  - Searched for other self-URIs, got normal redirects.

Maniphest Tasks: T13412

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


<?php

namespace CommerceGuys\Platform\Cli\Command;

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

class DrushCommand extends PlatformCommand
{

    protected function configure()
    {
        $this
            ->setName('drush')
            ->setDescription('Invoke a drush command using the site alias for the current environment.');
        $this->ignoreValidationErrors();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->ensureDrushInstalled();

        // Try to autodetect the project and environment.
        // There is no point in allowing the user to override them
        // using --project and --environment, in that case they can run
        // drush by themselves and specify the site alias manually.
        $this->project = $this->getCurrentProject();
        if (!$this->project) {
            $output->writeln("<error>You must run this command from a project folder.</error>");
            return;
        }
        $this->environment = $this->getCurrentEnvironment($this->project);
        if (!$this->environment) {
            $output->writeln("<error>Could not determine the current environment.</error>");
            return;
        }

        $alias = $this->project['id'] . '.' . $this->environment['id'];
        $command = 'drush @' . $alias . ' ';
        // Take the entire input string (all arguments and options) after the
        // name of the drush command.
        $command .= substr($input->__toString(), 6);
        passthru($command);
    }
}

<?php

namespace CommerceGuys\Platform\Cli\Command;

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

class DrushCommand extends PlatformCommand
{

    protected function configure()
    {
        $this
            ->setName('drush')
            ->setDescription('Invoke a drush command using the site alias for the current environment.');
        $this->ignoreValidationErrors();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->ensureDrushInstalled();

        // Try to autodetect the project and environment.
        // There is no point in allowing the user to override them
        // using --project and --environment, in that case they can run
        // drush by themselves and specify the site alias manually.
        $this->project = $this->getCurrentProject();
        if (!$this->project) {
            $output->writeln("<error>You must run this command from a project folder.</error>");
            return;
        }
        $this->environment = $this->getCurrentEnvironment($this->project);
        if (!$this->environment) {
            $output->writeln("<error>Could not determine the current environment.</error>");
            return;
        }

        $aliasGroup = isset($this->project['alias-group']) ? $this->project['alias-group'] : $this->project['id'];

        $alias = $aliasGroup . '.' . $this->environment['id'];
        $command = 'drush @' . $alias . ' ';
        // Take the entire input string (all arguments and options) after the
        // name of the drush command.
        $command .= substr($input->__toString(), 6);
        passthru($command);
    }
}

Make the drush command recognize the custom alias name.


<?php

namespace App\Repository;

use App\Entity\Employee;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Contracts\Translation\TranslatorInterface;

class EmployeeRepository extends AbstractRepository
{
    private TranslatorInterface $translator;

    public function __construct(ManagerRegistry $registry, TranslatorInterface $translator)
    {
        parent::__construct($registry, Employee::class);
        $this->translator = $translator;
    }

    /**
     * @return Employee[]
     * @throws \Doctrine\ORM\ORMException
     */
    public function rand(int $limit, int $page, int $seed, string $locale): array
    {
        $qb = $this->createQueryBuilder('e')
            ->setFirstResult(($page-1) * $limit)
            ->setMaxResults($limit);
        if (0 != $seed) {
            $qb->orderBy('RAND(:seed)')
                ->setParameter('seed', $seed);
        } else {
            $qb->orderBy('e.lastName', 'ASC');
        }

        $employees = $qb
            ->getQuery()
            ->execute()
        ;

        $employeesTranslated = [];

        foreach ($employees as $employee) {
            $employee->setLocale($locale);
            $this->_em->refresh($employee);

            if ($employee->getTranslations()) {
                $employee->unsetTranslations();
            }

            $this->translator->setLocale($locale);
            $employee->setPosition($this->translator->trans($employee->getPosition()));

            $employeesTranslated[] = $employee;
        }

        return $employeesTranslated;
    }
}

<?php

namespace App\Repository;

use App\Entity\Employee;
use App\Entity\EmployeeGroup;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Contracts\Translation\TranslatorInterface;

class EmployeeRepository extends AbstractRepository
{
    private TranslatorInterface $translator;

    public function __construct(ManagerRegistry $registry, TranslatorInterface $translator)
    {
        parent::__construct($registry, Employee::class);
        $this->translator = $translator;
    }

    /**
     * @return Employee[]
     * @throws \Doctrine\ORM\ORMException
     */
    public function rand(int $limit, int $page, int $seed, string $locale, ?EmployeeGroup $group = null): array
    {
        $qb = $this->createQueryBuilder('e')
            ->setFirstResult(($page-1) * $limit)
            ->setMaxResults($limit);
        if (0 != $seed) {
            $qb->orderBy('RAND(:seed)')
                ->setParameter('seed', $seed);
        } else {
            $qb->orderBy('e.lastName', 'ASC');
        }

        if ($group) {
            $qb->andWhere('e.employeeGroup = :group')
                ->setParameter('group', $group);
        }

        $employees = $qb
            ->getQuery()
            ->execute()
        ;

        $employeesTranslated = [];

        foreach ($employees as $employee) {
            $employee->setLocale($locale);
            $this->_em->refresh($employee);

            if ($employee->getTranslations()) {
                $employee->unsetTranslations();
            }

            $this->translator->setLocale($locale);
            $employee->setPosition($this->translator->trans($employee->getPosition()));

            $employeesTranslated[] = $employee;
        }

        return $employeesTranslated;
    }
}

THEATRE-113: Sort employees by group if it passed as a parameter


<?php

use GeneaLabs\LaravelMixpanel\Http\Controllers\StripeWebhooksController;
use Illuminate\Support\Facades\View;

Route::controller('genealabs/laravel-mixpanel/stripe', StripeWebhooksController::class);

<?php

use GeneaLabs\LaravelMixpanel\Http\Controllers\StripeWebhooksController;
use Illuminate\Support\Facades\View;

Route::post('genealabs/laravel-mixpanel/stripe', ['uses' => 'GeneaLabs\LaravelMixpanel\Http\Controllers\StripeWebhooksController@postTransaction']);

Resolve routing depreciation in Laravel v5.3

This will remove the Route::controller() call and replace it with an explicit route call.


<?php

namespace MattermostHandler;

use GuzzleHttp\Client;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;

class MattermostHandler extends AbstractProcessingHandler
{
    private $webHookUrl;
    private $client;

    public function __construct($webHookUrl, $level = Logger::DEBUG, $bubble = true, $client = null)
    {
        parent::__construct($level, $bubble);

        $this->webHookUrl = $webHookUrl;
        $this->client = (!$client) ?: new Client();
    }

    protected function write(array $record)
    {
        $client = new Client();
        $client->request('POST', $this->webHookUrl, [
            'form_params' => [
                'payload' => json_encode(['text' => $record['formatted']])
            ]
        ]);
    }
}

<?php

namespace MattermostHandler;

use GuzzleHttp\Client;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;

class MattermostHandler extends AbstractProcessingHandler
{
    private $webHookUrl;
    private $client;

    public function __construct($webHookUrl, $level = Logger::DEBUG, $bubble = true, $client = null)
    {
        parent::__construct($level, $bubble);

        $this->webHookUrl = $webHookUrl;
        $this->client = (!$client) ?: new Client();
    }

    public function write(array $record)
    {
        $this->client->request('POST', $this->webHookUrl, [
            'form_params' => [
                'payload' => json_encode(['text' => $record['formatted']])
            ]
        ]);
    }
}

Write method must be public

Write method must be public


<?php namespace JamylBot;

use Illuminate\Database\Eloquent\Model;

class Group extends Model {

	protected $fillable = ['name'];

    public function users()
    {
        $this->belongsToMany('JamylBot\User');
    }

    public function channels()
    {
        $this->belongsToMany('JamylBot\Channel');
    }

}

<?php namespace JamylBot;

use Illuminate\Database\Eloquent\Model;

class Group extends Model {

	protected $fillable = ['name'];

    public function users()
    {
        $this->belongsToMany('JamylBot\User');
    }

    public function channels()
    {
        $this->belongsToMany('JamylBot\Channel');
    }

    public function getOwners()
    {
        return explode(',', $this->owners);
    }

    public function addOwner($newOwner)
    {
        $owners = $this->getOwners();
        $owners[] = $newOwner;
        $this->owners = implode(array_unique($owners));
        $this->save();
    }

    public function isOwner($owner)
    {
        return in_array($owner, $this->getOwners());
    }

}

Add logic to support group owners

Add logic to support group owners


<?php

/**
 * @file
 * Displays the search form block.
 *
 * Available variables:
 * - $search_form: The complete search form ready for print.
 * - $search: Associative array of search elements. Can be used to print each
 *   form element separately.
 *
 * Default elements within $search:
 * - $search['search_block_form']: Text input area wrapped in a div.
 * - $search['actions']: Rendered form buttons.
 * - $search['hidden']: Hidden form elements. Used to validate forms when
 *   submitted.
 *
 * Modules can add to the search form, so it is recommended to check for their
 * existence before printing. The default keys will always exist. To check for
 * a module-provided field, use code like this:
 * @code
 *   <?php if (isset($search['extra_field'])): ?>
 *

 *       <?php print $search['extra_field']; ?>
 *

 *   <?php endif; ?>
 * @endcode
 *
 * @see template_preprocess_search_block_form()
 */
?>

  <?php if (empty($variables['form']['#block']->subject)): ?>
  <?php endif; ?>
  <?php print $search['search_block_form']; ?>
  <?php print $search['hidden']; ?>

<?php

/**
 * @file
 * Displays the search form block.
 *
 * Available variables:
 * - $search_form: The complete search form ready for print.
 * - $search: Associative array of search elements. Can be used to print each
 *   form element separately.
 *
 * Default elements within $search:
 * - $search['search_block_form']: Text input area wrapped in a div.
 * - $search['actions']: Rendered form buttons.
 * - $search['hidden']: Hidden form elements. Used to validate forms when
 *   submitted.
 *
 * Modules can add to the search form, so it is recommended to check for their
 * existence before printing. The default keys will always exist. To check for
 * a module-provided field, use code like this:
 * @code
 *   <?php if (isset($search['extra_field'])): ?>
 *     <div class="extra-field">
 *       <?php print $search['extra_field']; ?>
 *     </div>
 *   <?php endif; ?>
 * @endcode
 *
 * @see template_preprocess_search_block_form()
 */
?>

<?php if (empty($variables['form']['#block']->subject)): ?>
<?php endif; ?>
<?php print $search['search_block_form']; ?>
<?php print $search['hidden']; ?>

Remove unnecessary wrapping div from search block.


<?php
/**
 * Created by PhpStorm.
 * User: titan
 * Date: 02.03.17
 * Time: 21:16
 */

namespace titanproger\redis_models;

class TRedisModelHash extends  TRedisModelBase
{
    public function updateCounters($counters) {
        $key_name = $this->getRedisKeyName();
        foreach($counters as $field => $delta) {
            static::getRedisDb()->cmdHashFieldIncrement($key_name, $field , $delta );
        }
    }

    protected function saveToKey($key_name) {
        $result =  static::getRedisDb()->cmdHashSet( $key_name , $this->getAttributes(), $this->expire_time );
        return $result != null;
    }

    protected function loadFromKey($key_name) {
        $this->setAttributes( $data = static::getRedisDb()->cmdHashGet($key_name) , false);
        return $data != null;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: titan
 * Date: 02.03.17
 * Time: 21:16
 */

namespace titanproger\redis_models;

class TRedisModelHash extends  TRedisModelBase
{
    public function updateCounters($counters) {
        $key_name = $this->getRedisKeyName();
        foreach($counters as $name => $value) {
            static::getRedisDb()->cmdHashFieldIncrement($key_name, $name , $value );
            //duplicates \yii\db\BaseActiveRecord::updateCounters from here
            if (!isset($this->_attributes[$name]))
                $this->_attributes[$name] = $value;
            else
                $this->_attributes[$name] += $value;

            $this->_oldAttributes[$name] = $this->_attributes[$name];
        }
    }

    protected function saveToKey($key_name) {
        $result =  static::getRedisDb()->cmdHashSet( $key_name , $this->getAttributes(), $this->expire_time );
        return $result != null;
    }

    protected function loadFromKey($key_name) {
        $this->setAttributes( $data = static::getRedisDb()->cmdHashGet($key_name) , false);
        return $data != null;
    }
}

Fix - change loacl counters value after updateCounter


<?php
class Elegant {

	function __construct()
	{
		$mod_path = APPPATH . 'models/';
		if(file_exists($mod_path)) $this->_read_model_dir($mod_path);
	}

	// Open model directories recursively and load the models inside
	private function _read_model_dir($dirpath)
	{
		$ci =& get_instance();

		$handle = opendir($dirpath);
		if(!$handle) return;

		while (false !== ($filename = readdir($handle)))
		{
			if($filename == "." or $filename == "..") continue;

			$filepath = $dirpath.$filename;
			if(is_dir($filepath))
				$this->_read_model_dir($filepath);

			elseif(strpos(strtolower($filename), '.php') !== false)
			{
				$name = strtolower($filepath);
				require_once $name;
			}

			else continue;
		}

		closedir($handle);
	}

}

spl_autoload_register(function($class){
	if(strpos($class, "Elegant\\") !== 0) return;

	$classname = str_replace("Elegant\\", "", $class);

	$path = 'src/' . strtolower( str_replace("\\", "/", $classname) ) . ".php";
	require_once $path;
});

<?php
class Elegant {

	function __construct()
	{
		$mod_path = APPPATH . 'models/';
		if(file_exists($mod_path)) $this->_read_model_dir($mod_path);
	}

	// Open model directories recursively and load the models inside
	private function _read_model_dir($dirpath)
	{
		$ci =& get_instance();

		$handle = opendir($dirpath);
		if(!$handle) return;

		while (false !== ($filename = readdir($handle)))
		{
			if($filename == "." or $filename == "..") continue;

			$filepath = $dirpath.$filename;
			if(is_dir($filepath))
				$this->_read_model_dir($filepath);

			elseif(strpos(strtolower($filename), '.php') !== false)
			{
				$name = strtolower($filepath);
				require_once $name;
			}

			else continue;
		}

		closedir($handle);
	}

}

spl_autoload_register(function($class){
	if(strpos($class, "Elegant\\") === 0)
	{
		$classname = str_replace("Elegant\\", "", $class);

		$path = 'src/' . strtolower( str_replace("\\", "/", $classname) ) . EXT;
		require_once $path;
	}

});

Fix spl_autoload_register so it won't conflict with other register


<?php

//define global path to Components' root folder
if(!defined('LINK_EDIT_TOOLS_PATH'))
{
	define('LINK_EDIT_TOOLS_PATH', rtrim(basename(dirname(__FILE__))));
}

Remove now obsolete path to folder

FIX: Remove now obsolete path to folder


<?php

Object::add_extension("DataObject","MappableData");
Object::add_extension("DataList","MappableDataObjectSet");
//define global path to Components' root folder
if(!defined('MAPPABLE_MODULE_PATH'))
{
	define('MAPPABLE_MODULE_PATH', rtrim(basename(dirname(__FILE__))));
}
?>

<?php

Object::add_extension("DataObject","MappableData");
Object::add_extension("DataList","MappableDataObjectSet");
//define global path to Components' root folder
if(!defined('MAPPABLE_MODULE_PATH'))
{
	define('MAPPABLE_MODULE_PATH', rtrim(basename(dirname(__FILE__))));
}

// allow geographical format files to be uploaded
File::$allowed_extensions[] = 'gpx' ;
File::$allowed_extensions[] = 'kml' ;

?>

Allow GPX and KML files to be uploaded

ENHANCEMENT: Allow GPX and KML files to be uploaded


<?php
/*
 * Theme Name: Bootstrap
 * Template: Master
 * Author: Paladin Digital
 */
$theme = 'themes::paladindigital.laravel-bootstrap';

?><!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
@yield('head')
@include($theme . '._meta')
@yield('styles')
</head>
<body>
@include($theme . '._nav')
<div class="container-fluid">
    @yield('content')
    <aside>
        @yield('sidebar')
        @yield('widgets')
    </aside>
</div>
@include($theme . '._footer')
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@yield('scripts')
</body>
</html>

<?php
/*
 * Theme Name: Bootstrap
 * Template: Master
 * Author: Paladin Digital
 */
$theme = 'themes::paladindigital.laravel-bootstrap';

// Allow nav type to be overridden from controllers.
if (!isset($nav)) {
    $nav = 'navbar';
}

?><!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
@yield('head')
@include($theme . '._meta')
@yield('styles')
</head>
<body>
@include($theme . '._' . $nav)
<div class="container-fluid">
    @yield('content')
    <aside>
        @yield('sidebar')
        @yield('widgets')
    </aside>
</div>
@include($theme . '._footer')
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@yield('scripts')
</body>
</html>

Allow nav to be overridden, use navbar by default.


<?php

	class Browsers {

		static function getAll($release) {
			$results = array();

			$types = array('desktop', 'tablet', 'mobile', 'television', 'gaming');

			$db = Factory::Database();

			foreach($types AS $type) {
				$result = $db->query("
					SELECT
						v.platform, IFNULL(v.version,'') AS version, v.nickname, v.details, v.visible, IFNULL(p.related,p.platform) AS id, f.score
					FROM
						data_platforms AS p
						LEFT JOIN data_versions AS v ON (p.platform = v.platform)
						LEFT JOIN scores AS s ON (v.platform = s.platform AND (v.version = s.version OR (v.version IS NULL AND s.version IS NULL)))
						LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint)
					WHERE
						FIND_IN_SET('" . $type . "',v.type) AND
						s.release = '" . $release . "' AND
						f.points != ''
					ORDER BY
						v.platform, ISNULL(v.releasedate), v.releasedate, v.version
				");

				while ($row = $result->fetch_object()) {
					$row->uid = $type . '-' . $row->platform . '-' . $row->version;
					$row->type = $type;
					$row->visible = $row->visible == '1';

					$results[] = $row;
				}
			}

			return $results;
		}

	}

<?php

	class Browsers {

		static function getAll($release) {
			$results = array();

			$types = array('desktop', 'tablet', 'mobile', 'television', 'gaming');

			$db = Factory::Database();

			foreach($types AS $type) {
				$result = $db->query("
					SELECT
						v.platform, IFNULL(v.version,'') AS version, v.nickname, v.details, v.visible, IFNULL(p.related,p.platform) AS id, f.score
					FROM
						data_platforms AS p
						LEFT JOIN data_versions AS v ON (p.platform = v.platform)
						LEFT JOIN scores AS s ON (v.platform = s.platform AND (v.version = s.version OR (v.version IS NULL AND s.version IS NULL)))
						LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint)
					WHERE
						FIND_IN_SET('" . $type . "',v.type) AND
						s.release = '" . $release . "' AND
						f.points != ''
					ORDER BY
						v.platform, v.status='experimental', v.status='upcoming', ISNULL(v.releasedate), v.releasedate, v.version
				");

				while ($row = $result->fetch_object()) {
					$row->uid = $type . '-' . $row->platform . '-' . $row->version;
					$row->type = $type;
					$row->visible = $row->visible == '1';

					$results[] = $row;
				}
			}

			return $results;
		}

	}

Fix sorting of experimental browser in the comparison browser picker


<?php
    class TestrunController extends ControllerBase {
        protected $environment = 'test';

        public function create( $name ) {
            include_once 'tests/base.php';
            $path = 'tests/' . $name . '.php';
            $unittest = include_once $path;
            $unittest->setUp();
            $unittest->run();
            echo $unittest->passCount . ' / ' . $unittest->assertCount . ' tests pass';
        }

        public function createView() {
            include_once 'views/testrun/create.php';
        }
    }
?>

<?php
    class TestrunController extends ControllerBase {
        protected $environment = 'test';

        public function create( $name ) {
            include_once 'tests/base.php';
            $path = 'tests/' . $name . '.php';
            if ( !file_exists( $path ) ) {
                throw new HTTPNotFoundException();
            }
            $unittest = include_once $path;
            $unittest->setUp();
            $unittest->run();
            echo $unittest->passCount . ' / ' . $unittest->assertCount . ' tests pass';
        }

        public function createView() {
            include_once 'views/testrun/create.php';
        }
    }
?>

Check if path exists before inclusion

Check if path exists before inclusion


<?php declare(strict_types=1);
/**
 * Suite runner
 *
 * PHP version 7.0
 *
 * @category   SevenPress\Metrics
 * @package    Cli
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 * @copyright  Copyright (c) 2015 Pieter Hordijk <https://github.com/PeeHaa>
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 * @version    1.0.0
 */
namespace SevenPress\Metrics\Cli;

use SevenPress\Metrics\Tool\Loc\Total as TotalLoc;

require_once __DIR__ . '/../bootstrap.php';

$loc = new TotalLoc($targetDirectory);

var_dump($loc->run());

<?php declare(strict_types=1);
/**
 * Suite runner
 *
 * PHP version 7.0
 *
 * @category   SevenPress\Metrics
 * @package    Cli
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 * @copyright  Copyright (c) 2015 Pieter Hordijk <https://github.com/PeeHaa>
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 * @version    1.0.0
 */
namespace SevenPress\Metrics\Cli;

use SevenPress\Metrics\Tool\Loc\Total as TotalLoc;
use SevenPress\Metrics\Storage\Sql\Loc as LocStorage;

require_once __DIR__ . '/../bootstrap.php';

/**
 * bail if we are missing parameters
 */
if (!isset($argv[1])) exit("No commit supplied\n");

/**
 * Setup LOC calculator and storage
 */
$loc = new TotalLoc($targetDirectory);
$storage = new LocStorage($dbConnection);

// run
$storage->store($argv[1], $loc->run());

Use cli args for commits

Use cli args for commits


<?php

namespace app\components;

use yii\base\Component;
use yii\helpers\Url;
use werx\Url\Builder;

class PhotoManager extends Component
{
    private $builder = null;
    public $baseUrl = null;

    public function getUrl($path)
    {
        if(!Url::isRelative($path))
            return $path;

        if($this->builder == null)
            $this->builder = new Builder($this->baseUrl);

        return $this->builder->asset($path);
    }
}

<?php

namespace app\components;

use yii\base\Component;
use yii\helpers\Url;
use werx\Url\Builder;

class PhotoManager extends Component
{
    private $builder = null;
    public $baseUrl = null;

    public function getUrl($path)
    {
        $path = trim($path);

        if(!Url::isRelative($path))
            return $path;

        if($this->builder == null)
            $this->builder = new Builder($this->baseUrl);

        return $this->builder->asset($path);
    }
}

Trim whitespace from photo url.

Trim whitespace from photo url.


Comments and site feedback can be left in the ChatBox or in the IRC channel #GetDotaStats on GameSurge.

Issues and feature requests can be left in our GitHub issue tracker.

If you like the work we do, feel free to shout us a beer. 1EFa8YBQAfM3s4pSjZEMyobY1f5H34nGBz

Add Bitcoin protocol link for the listed address


<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

Register

Our Committee

Terms

Code of Conduct

Schedule

Sponsorship

<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

Register

Our Committee

Venue

Terms

Code of Conduct

Schedule

Sponsorship

Add venue heading for title bar

Add venue heading for title bar


<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\GoogleAnalyticsBundle\Twig\Extension;

use Endroid\Bundle\BehaviorBundle\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class GoogleAnalyticsExtension extends \Twig_Extension implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function getFunctions()
    {
        return array(
            'google_analytics_tracker' => new \Twig_Function_Method($this, 'tracker', array('is_safe' => array('html'))),
        );
    }

    /**
     * Renders the tracker.
     *
     * @param string $identifier
     * @return mixed
     */
    public function tracker($identifier = 'default')
    {
        $code = $this->container->getParameter('endroid_google_analytics.'.$identifier);

        return $this->container->get('templating')->render('EndroidGoogleAnalyticsBundle::tracker.html.twig', array('code' => $code));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'endroid_google_analytics';
    }
}

<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\GoogleAnalyticsBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GoogleAnalyticsExtension extends \Twig_Extension implements ContainerAwareInterface
{
    /**
     * @var
     */
    protected $container;

    /**
     * Sets the container.
     *
     * @param ContainerInterface $container
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function getFunctions()
    {
        return array(
            'google_analytics_tracker' => new \Twig_Function_Method($this, 'tracker', array('is_safe' => array('html'))),
        );
    }

    /**
     * Renders the tracker.
     *
     * @param string $identifier
     * @return mixed
     */
    public function tracker($identifier = 'default')
    {
        $code = $this->container->getParameter('endroid_google_analytics.'.$identifier);

        return $this->container->get('templating')->render('EndroidGoogleAnalyticsBundle::tracker.html.twig', array('code' => $code));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'endroid_google_analytics';
    }
}

Remove hard dependency on behavior bundle


<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Http\Middleware;

use Closure;
use Illuminate\Config\Repository;

class Localize
{
    /**
     * Array of languages Cachet can use.
     *
     * @var array
     */
    protected $langs;

    /**
     * Config repository.
     *
     * @var \Illuminate\Config\Repository
     */
    protected $config;

    /**
     * Constructs a new localize instance.
     *
     * @param \Illuminate\Config\Repository $config
     *
     * @return void
     */
    public function __construct(Repository $config)
    {
        $this->config = $config;
        $this->langs = $config->get('langs');
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $supportedLanguages = $request->getLanguages();
        $userLanguage = $this->config->get('app.locale');

        foreach ($supportedLanguages as $language) {
            $language = substr($language, 0, 2);

            if (isset($this->langs[$language])) {
                $userLanguage = $language;
                break;
            }
        }

        app('translator')->setLocale($userLanguage);

        return $next($request);
    }
}

<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Http\Middleware;

use Closure;
use Illuminate\Config\Repository;
use Jenssegers\Date\Date;

class Localize
{
    /**
     * Array of languages Cachet can use.
     *
     * @var array
     */
    protected $langs;

    /**
     * Config repository.
     *
     * @var \Illuminate\Config\Repository
     */
    protected $config;

    /**
     * Constructs a new localize instance.
     *
     * @param \Illuminate\Config\Repository $config
     *
     * @return void
     */
    public function __construct(Repository $config)
    {
        $this->config = $config;
        $this->langs = $config->get('langs');
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $supportedLanguages = $request->getLanguages();
        $userLanguage = $this->config->get('app.locale');

        foreach ($supportedLanguages as $language) {
            $language = substr($language, 0, 2);

            if (isset($this->langs[$language])) {
                $userLanguage = $language;
                break;
            }
        }

        app('translator')->setLocale($userLanguage);
        Date::setLocale($userLanguage);

        return $next($request);
    }
}

Set date lang on the localized middleware


<?php namespace Dxi\Commands\Dataset\Contact;

use Dxi\Commands\Command;

class Create extends Command {

    /**
     * Get the payload for the command
     *
     * @return array
     */
    public function getRequiredParams()
    {
        return [
            'firstname',
            'dataset',
            [
                'ddi_home',
                'ddi_mobile',
                'ddi_work'
            ]
        ];
    }

    /**
     * Set the phone number
     *
     * @param $phone
     * @return $this
     */
    public function getPhone($phone)
    {
        $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
        $this->params[$phoneType] = $phone;
        return $this;
    }

    /**
     * Get the method for the command
     *
     * @return string
     */
    public function getMethod()
    {
        return 'ecnow_records';
    }

    /**
     * Get the url path
     *
     * @return string
     */
    public function getUrlPath()
    {
        return '/ecnow.php';
    }

    /**
     * Get the action for the command
     *
     * @return string
     */
    public function getAction()
    {
        return strtolower(class_basename(__CLASS__));
    }
}

<?php namespace Dxi\Commands\Dataset\Contact;

use Dxi\Commands\Command;

class Create extends Command {

    /**
     * Get the payload for the command
     *
     * @return array
     */
    public function getRequiredParams()
    {
        return [
            'firstname',
            'dataset',
            [
                'ddi_home',
                'ddi_mobile',
                'ddi_work'
            ]
        ];
    }

    /**
     * Set the phone number
     *
     * @param $phone
     * @return $this
     */
    public function getPhone($phone)
    {
        $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
        $this->params[$phoneType] = $phone;
        return $this;
    }

    /**
     * Get the method for the command
     *
     * @return string
     */
    public function getMethod()
    {
        return 'ecnow_records';
    }

    /**
     * Get the url path
     *
     * @return string
     */
    public function getUrlPath()
    {
        return '/ecnow.php';
    }

    /**
     * Get the action for the command
     *
     * @return string
     */
    public function getAction()
    {
        return 'create';
    }
}

Remove call to class_basename which only exists when Laravel is used.


<?php

declare(strict_types=1);

namespace Rinvex\Auth\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=all}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Rinvex Auth Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        $this->call('vendor:publish', ['--tag' => 'rinvex/auth::config', '--force' => $this->option('force')]);

        $this->line('');
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Auth\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=* : Specify which resources to publish.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Rinvex Auth Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        collect($this->option('resource'))->each(function ($resource) {
            $this->call('vendor:publish', ['--tag' => "rinvex/auth::{$resource}", '--force' => $this->option('force')]);
        });

        $this->line('');
    }
}

Refactor publish command and allow multiple resource values


<?php

Route::resource('/assemblies', 'AssembliesController', [
    'only' => ['index']
]);

<?php

Route::resource('/assemblies', 'AssembliesController', [
    'only' => ['index', 'show']
]);

Add route to get a single assembly

Add route to get a single assembly


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

return array(

	/**
	 * The file extension used for TAL view files. Default is 'php'.
	 */
	'ext' => 'php',

	/**
	 * List of controllers automatically excluded from TAL processing.
	 * Should be taken from the 'controller' parameter in routes.
	 */
	'exclude' => array(
		'codebench',
		'unittest',
		'userguide',
	),

);

<?php defined('SYSPATH') or die('No direct script access.');
/**
 * KOtal configuration file.
 *
 * @package    KOtal
 * @category   Base
 * @author     Hanson Wong
 * @copyright  (c) 2010 Hanson Wong
 * @license    http://github.com/Dismounted/KOtal/blob/master/LICENSE
 */

return array(

	/**
	 * The file extension used for TAL view files. Default is 'php'.
	 */
	'ext' => 'php',

	/**
	 * List of controllers automatically excluded from TAL processing.
	 * Should be taken from the 'controller' parameter in routes.
	 */
	'exclude' => array(
		'codebench',
		'unittest',
		'userguide',
	),

);

Add header comment to config.

Add header comment to config.


<?php

namespace Olitaz\HomeBundle\Menu;

use Knp\Bundle\MenuBundle\Menu;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;

class MainMenu extends Menu
{
    /**
     * @param Request $request
     * @param Router $router
     */
    public function __construct(Request $request, Router $router)
    {
        parent::__construct();

        $this->setCurrentUri($request->getRequestUri());

        $this->addChild('Home', $router->generate('OlitazHomeBundle_homepage'));
        $this->addChild('Présentation', $router->generate('OlitazHomeBundle_presentation'));
        $this->addChild('Prestations', $router->generate('OlitazHomeBundle_prestations'));
//        $this->addChild('Références', $router->generate('OlitazHomeBundle_homepage'));
        $this->addChild('Contact', $router->generate('OlitazHomeBundle_contact'));
        $this->addChild('Blog', 'http://blog.olitaz.fr/');
    }
}

<?php

namespace Olitaz\HomeBundle\Menu;

use Knp\Bundle\MenuBundle\Menu;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;

class MainMenu extends Menu
{
    /**
     * @param Request $request
     * @param Router $router
     */
    public function __construct(Request $request, Router $router)
    {
        parent::__construct();

        $this->setCurrentUri($request->getRequestUri());

        $this->addChild('Home', $router->generate('OlitazHomeBundle_homepage'));
        $this->addChild('Présentation', $router->generate('OlitazHomeBundle_presentation'));
        $this->addChild('Prestations', $router->generate('OlitazHomeBundle_prestations'));
//        $this->addChild('Références', $router->generate('OlitazHomeBundle_homepage'));
        $this->addChild('Contact', $router->generate('OlitazHomeBundle_contact'));
    }
}

Remove link blog in menu

Remove link blog in menu


<?php

namespace Rudolf\Framework\Controller;

use Rudolf\Component\Http\Response;

abstract class BaseController
{
    protected $request;

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

        if (method_exists($this, 'init')) {
            $this->init();
        }
    }

    /**
     * Redirect to `up`, if curent page is 1.
     *
     * @param int $page
     * @param int $code
     *
     * @return int|redirection
     */
    protected function firstPageRedirect($page, $code = 301, $location = '..')
    {
        if (1 == $page) {
            $this->redirect($location, $code);
        } elseif (0 === $page) {
            return 1;
        }

        return $page;
    }

    protected function redirect($path = DIR, $code = 301, $response = '')
    {
        $response = new Response($response, $code);
        $response->setHeader(['Location', $path]);
        $response->send();
        exit;
    }

    public function redirectTo($path)
    {
        $this->redirect($path);
    }
}

<?php

namespace Rudolf\Framework\Controller;

use Rudolf\Component\Http\Response;

abstract class BaseController
{
    protected $request;

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

        if (method_exists($this, 'init')) {
            $this->init();
        }
    }

    /**
     * Redirect to `up`, if curent page is 1.
     *
     * @param int $page
     * @param int $code
     *
     * @return int|redirection
     */
    protected function firstPageRedirect($page, $code = 301, $location = '..')
    {
        if (1 == $page) {
            $this->redirect($location, $code);
        } elseif (0 === $page) {
            return 1;
        }

        return $page;
    }

    protected function redirect($path = DIR, $code = 301)
    {
        $response = new Response('', $code);
        $response->setHeader(['Location', $path]);
        $response->send();
        exit;
    }

    public function redirectTo($path)
    {
        $this->redirect($path);
    }
}

Delete useless param $response in redirect()


@extends('mconsole::app')

@section('content')

TEST

                        Мудрость

“ {{ $quote['text'] }} „

                                    {{ $quote['author'] }}

@endsection

@extends('mconsole::app')

@section('content')

                        Мудрость

“ {{ $quote['text'] }} „

                                    {{ $quote['author'] }}

@endsection

Remove test button from dashboard

Remove test button from dashboard


<?php

namespace Vikpe;

class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase
{
    const TEST_FILES_DIR = __DIR__.'/file/';

    private function getTestFileContents($filename)
    {
        return file_get_contents(self::TEST_FILES_DIR.$filename);
    }

    public function assertHtmlStringEqualsHtmlString($expect, $actual)
    {
        $expectedDom = new \DOMDocument();
        $expectedDom->loadHtml($expect);
        $expectedDom->preserveWhiteSpace = false;

        $actualDom = new \DOMDocument();
        $actualDom->loadHTML($actual);
        $actualDom->preserveWhiteSpace = false;

        $this->assertEquals(
            $expectedDom->saveHTML(),
            $actualDom->saveHTML()
        );
    }

    /**
     * @dataProvider normalizeDataProvider
     */
    public function testNormalizeSimpleHtmlStrings($html, $expect)
    {
        $actual = HtmlHeadingNormalizer::normalize($html);

        $this->assertEquals($expect, $actual);
    }

    public function normalizeDataProvider()
    {
        return [
            ['', ''],
            ['
foo
', '
foo
'],
        ];
    }

    public function testNormalizePromoteHtmlDocument()
    {
        $inputHtml = $this->getTestFileContents('document.base1.html');
        $normalizedHtml = HtmlHeadingNormalizer::normalize($inputHtml, 3);

        $expectedHtml = $this->getTestFileContents('document.base1.promote3.html');

        $this->assertHtmlStringEqualsHtmlString($expectedHtml, $normalizedHtml);
    }
}

<?php

namespace Vikpe;

class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase
{
    const TEST_FILES_DIR = __DIR__.'/file/';

    private function getTestFileContents($filename)
    {
        return file_get_contents(self::TEST_FILES_DIR.$filename);
    }

    public function assertHtmlStringEqualsHtmlString($expect, $actual)
    {
        $expectedDom = new \DOMDocument();
        $expectedDom->loadHtml($expect);
        $expectedDom->preserveWhiteSpace = false;

        $actualDom = new \DOMDocument();
        $actualDom->loadHTML($actual);
        $actualDom->preserveWhiteSpace = false;

        $this->assertEquals(
            $expectedDom->saveHTML(),
            $actualDom->saveHTML()
        );
    }

    /**
     * @dataProvider normalizeDataProvider
     */
    public function testNormalizeSimpleHtmlStrings($html, $expect)
    {
        $actual = HtmlHeadingNormalizer::normalize($html);

        $this->assertEquals($expect, $actual);
    }

    public function normalizeDataProvider()
    {
        return array(
            array('', ''),
            array('
foo
', '
foo
'),
        );
    }

    public function testNormalizePromoteHtmlDocument()
    {
        $inputHtml = $this->getTestFileContents('document.base1.html');
        $normalizedHtml = HtmlHeadingNormalizer::normalize($inputHtml, 3);

        $expectedHtml = $this->getTestFileContents('document.base1.promote3.html');

        $this->assertHtmlStringEqualsHtmlString($expectedHtml, $normalizedHtml);
    }
}

Use long array syntax to support PHP 5.x.


<?php namespace Destiny;

class ClientTest extends TestCase {

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Test fetching an Xbox player.
     *
     * @throws \Exception
     */
    public function testFetchXboxPlayer()
    {
        $player = $this->destiny->fetchXboxPlayer('aFreshMelon');

        $this->assertInstanceOf('Destiny\Game\Player', $player);
    }

    /**
     * Test fetching a PSN player.
     *
     * @throws \Exception
     */
    public function testFetchPsnPlayer()
    {
        $player = $this->destiny->fetchPsnPlayer('Chrakker');

        $this->assertInstanceOf('Destiny\Game\Player', $player);
    }

    /**
     * Test whether characters are being fetched.
     *
     * @throws \Exception
     */
    public function testAutomaticCharacterFetching()
    {
        $this->assertInstanceOf('Destiny\Game\CharacterCollection', $this->player->characters);
    }

    /**
     * Test the example in the readme.
     */
    public function testExampleInReadme()
    {
        $firstCharacter = $this->player->characters->first();

        $this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->get(0));

        $this->assertInternalType('int', $firstCharacter->characterLevel);
    }

}

<?php namespace Destiny;

class ClientTest extends TestCase {

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Test fetching an Xbox player.
     *
     * @throws \Exception
     */
    public function testFetchXboxPlayer()
    {
        $player = $this->destiny->fetchXboxPlayer('aFreshMelon');

        $this->assertInstanceOf('Destiny\Game\Player', $player);
    }

    /**
     * Test fetching a PSN player.
     *
     * @throws \Exception
     */
    public function testFetchPsnPlayer()
    {
        $player = $this->destiny->fetchPsnPlayer('Chrakker');

        $this->assertInstanceOf('Destiny\Game\Player', $player);
    }

    /**
     * Test whether characters are being fetched.
     *
     * @throws \Exception
     */
    public function testAutomaticCharacterFetching()
    {
        $this->assertInstanceOf('Destiny\Game\CharacterCollection', $this->player->characters);

        $this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->first());
    }

    /**
     * Test the example in the readme.
     */
    public function testExampleInReadme()
    {
        $firstCharacter = $this->player->characters->first();

        $this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->get(0));

        $this->assertInternalType('int', $firstCharacter->characterLevel);
    }

}

Add a test for the character fetching

Add a test for the character fetching


<?php

namespace Knp\Component\Pager\Event\Subscriber\Sortable;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;

class PropelQuerySubscriber implements EventSubscriberInterface
{
    public function items(ItemsEvent $event)
    {
        $query = $event->target;
        if ($query instanceof \ModelCriteria) {
            if (isset($_GET[$event->options['sortFieldParameterName']])) {
                $direction = strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc';
                $part = $_GET[$event->options['sortFieldParameterName']];

                if (isset($event->options['sortFieldWhitelist'])) {
                    if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
                        throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
                    }
                }

                $query->orderBy($part, $direction);
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            'knp_pager.items' => array('items', 1)
        );
    }
}

<?php

namespace Knp\Component\Pager\Event\Subscriber\Sortable;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;

class PropelQuerySubscriber implements EventSubscriberInterface
{
    public function items(ItemsEvent $event)
    {
        $query = $event->target;
        if ($query instanceof \ModelCriteria) {
            if (isset($_GET[$event->options['sortFieldParameterName']])) {
                $part = $_GET[$event->options['sortFieldParameterName']];
                $directionParam = $event->options['sortDirectionParameterName'];

                $direction = (isset($_GET[$directionParam]) && strtolower($_GET[$directionParam]) === 'asc')
                                ? 'asc' : 'desc';

                if (isset($event->options['sortFieldWhitelist'])) {
                    if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
                        throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
                    }
                }

                $query->orderBy($part, $direction);
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            'knp_pager.items' => array('items', 1)
        );
    }
}

Fix exception in propel subscriber

Fix exception in propel subscriber


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'label'       => false,
            'attr'        => array(
                'class' => 'title_field',
            ),
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'text';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'darvin_utils_anti_spam';
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    const ANTI_SPAM_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'label'       => false,
            'attr'        => array(
                'class' => 'title_field',
            ),
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'text';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'darvin_utils_anti_spam';
    }
}

Replace form type names with FQCN.

Replace form type names with FQCN.


<?php

namespace Enhavo\Bundle\ShopBundle\Block;

use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductListBlockType extends AbstractBlockType
{
    public function createViewData(BlockInterface $block, $resource, array $options)
    {
        $data = parent::createViewData($block, $resource, $options);
        $data['products'] = $this->container->get('sylius.repository.product')->findAll();
        return $data;
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);

        $optionsResolver->setDefaults([
            'model' => ProductListBlock::class,
            'parent' => ProductListBlock::class,
            'form' => ProductListBlockFormType::class,
            'factory' => ProductListBlockFactory::class,
            'repository' => 'ProductListBlock::class',
            'template' => 'theme/block/product-list.html.twig',
            'label' => 'ProductList',
            'translation_domain' => 'EnhavoShopBundle',
            'groups' => ['default', 'content']
        ]);
    }

    public function getType()
    {
        return 'shop_product_list';
    }
}

<?php

namespace Enhavo\Bundle\ShopBundle\Block;

use Enhavo\Bundle\AppBundle\View\ViewData;
use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductListBlockType extends AbstractBlockType
{
    public function createViewData(BlockInterface $block, ViewData $viewData, $resource, array $options)
    {
        $viewData['products'] = $this->container->get('sylius.repository.product')->findAll();
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);

        $optionsResolver->setDefaults([
            'model' => ProductListBlock::class,
            'parent' => ProductListBlock::class,
            'form' => ProductListBlockFormType::class,
            'factory' => ProductListBlockFactory::class,
            'repository' => 'ProductListBlock::class',
            'template' => 'theme/block/product-list.html.twig',
            'label' => 'ProductList',
            'translation_domain' => 'EnhavoShopBundle',
            'groups' => ['default', 'content']
        ]);
    }

    public function getType()
    {
        return 'shop_product_list';
    }
}

Fix blocks and use ViewData

Fix blocks and use ViewData


<?php

namespace Orchestra\Config\Console;

use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;

class ConfigCacheCommand extends BaseCommand
{
    /**
     * Boot a fresh copy of the application configuration.
     *
     * @return array
     */
    protected function getFreshConfiguration()
    {
        $app = require $this->laravel->basePath().'/bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();
        $config = $app->make('config');

        $files = \array_merge(
            $config->get('compile.config', []), $this->getConfigurationFiles()
        );

        foreach ($files as $file) {
            $config[$file];
        }

        return $config->all();
    }

    /**
     * Get all of the configuration files for the application.
     *
     * @return array
     */
    protected function getConfigurationFiles()
    {
        $files = [];
        $path = $this->laravel->configPath();
        $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);

        foreach ($found as $file) {
            $files[] = \basename($file->getRealPath(), '.php');
        }

        return $files;
    }
}

<?php

namespace Orchestra\Config\Console;

use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;

class ConfigCacheCommand extends BaseCommand
{
    /**
     * Boot a fresh copy of the application configuration.
     *
     * @return array
     */
    protected function getFreshConfiguration()
    {
        $app = require $this->laravel->bootstrapPath('app.php');

        $app->make(Kernel::class)->bootstrap();
        $config = $app->make('config');

        $files = \array_merge(
            $this->configToCache(), $this->getConfigurationFiles()
        );

        foreach ($files as $file) {
            $config[$file];
        }

        return $config->all();
    }

    /**
     * Get all of the configuration files for the application.
     *
     * @return array
     */
    protected function getConfigurationFiles()
    {
        $files = [];
        $path = $this->laravel->configPath();
        $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);

        foreach ($found as $file) {
            $files[] = \basename($file->getRealPath(), '.php');
        }

        return $files;
    }

    /**
     * Get all of the package names that should be ignored.
     *
     * @return array
     */
    protected function configToCache()
    {
        if (! file_exists($this->laravel->basePath('composer.json')) {
            return [];
        }
        return json_decode(file_get_contents(
            $this->laravel->basePath('composer.json')
        ), true)['extra']['config-cache'] ?? [];
    }
}

Use config to cache from composer.json

Use config to cache from composer.json

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
  $meta = get_post_meta($post->ID);
?>

<a href="<?php the_permalink() ?>">
  <article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
    <?php the_post_thumbnail('col6-16to9', array('class' => 'margin-bottom-micro only-desktop')); ?>
    <?php the_post_thumbnail('mobile-16to9', array('class' => 'only-mobile')); ?>

    <?php
      $sub_category = get_the_sub_category($post->ID);

      if ($sub_category) {
    ?>

<?php echo $sub_category; ?>

    <?php
      }
    ?>

<?php the_title(); ?>

<?php
  $meta = get_post_meta($post->ID);
?>

<a href="<?php the_permalink() ?>">
  <article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
    <?php
      if (!empty($meta['_cmb_alt_thumb_id'])) {
        echo wp_get_attachment_image($meta['_cmb_alt_thumb_id'][0], 'col6-16to9', false, array('class' => 'margin-bottom-micro only-desktop'));
        echo wp_get_attachment_image($meta['_cmb_alt_thumb_id'][0], 'mobile-16to9', false, array('class' => 'only-mobile'));
      } else {
        the_post_thumbnail('col6-16to9', array('class' => 'margin-bottom-micro only-desktop'));
        the_post_thumbnail('mobile-16to9', array('class' => 'only-mobile'));
      }
    ?>

    <?php
      $sub_category = get_the_sub_category($post->ID);

      if ($sub_category) {
    ?>

<?php echo $sub_category; ?>

    <?php
      }
    ?>

<?php the_title(); ?>

Use alt thumb for front page tysky block

if set


<?php
class Kwf_Util_Https
{
    /**
     * Returns if the current request is https
     */
    public static function supportsHttps()
    {
        return isset($_SERVER['HTTPS']);
    }

    /**
     * Returns if the current request would support https and ensureHttps() would redirect to https
     */
    public static function domainSupportsHttps($domain)
    {
        if (Kwf_Config::getValue('server.https') === true) {
            if ($domains = Kwf_Config::getValueArray('server.httpsDomains')) {
                if ($domains && !in_array($domain, $domains)) {
                    return false; //current host is not in server.httpsDomains, don't use https
                }
            }
            return true;
        }
        return false;
    }

    /**
     * IE unter <=XP kann kein SNI
    private static function _supportsHttps()
    {
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return true;
        }
        //               IE                    2000, XP, 98, 95
        if (preg_match('#MSIE [^;]+; Windows (NT (4|5)|98|95)#', $_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }

        return true;
    }
    */
}

<?php
class Kwf_Util_Https
{
    /**
     * Returns if the current request is https
     */
    public static function supportsHttps()
    {
        return isset($_SERVER['HTTPS']);
    }

    /**
     * Returns if the current request would support https and ensureHttps() would redirect to https
     */
    public static function domainSupportsHttps($domain)
    {
        if (Kwf_Config::getValue('server.https') === true) {
            if ($domains = Kwf_Config::getValueArray('server.httpsDomains')) {
                if ($domains && !in_array($domain, $domains)) {
                    foreach ($domains as $d) {
                        if (substr($d, 0, 2) == '*.') {
                            if (substr($d, 1) == substr($domain, strpos($domain, '.'))) {
                                return true;
                            }
                        }
                    }
                    return false; //current host is not in server.httpsDomains, don't use https
                }
            }
            return true;
        }
        return false;
    }

    /**
     * IE unter <=XP kann kein SNI
    private static function _supportsHttps()
    {
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return true;
        }
        //               IE                    2000, XP, 98, 95
        if (preg_match('#MSIE [^;]+; Windows (NT (4|5)|98|95)#', $_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }

        return true;
    }
    */
}

Add support for wildcard in server.httpsDomains


<?php
/**
 * Custom ResourceLoader module that loads a custom WikiLove.js per-wiki.
 */
class WikiLoveLocal extends ResourceLoaderWikiModule {

	/**
	 * @param $context ResourceLoaderContext
	 * @return array
	 */
	protected function getPages( ResourceLoaderContext $context ) {
		return array(
			'MediaWiki:WikiLove.js'      => array( 'type' => 'script' ),
		);
	}

	/**
	 * @return array
	 */
	public function getMessages() {
		global $wgWikiLoveOptionMessages;
		return $wgWikiLoveOptionMessages;
	}
}

<?php
/**
 * Custom ResourceLoader module that loads a custom WikiLove.js per-wiki.
 */
class WikiLoveLocal extends ResourceLoaderWikiModule {

	/**
	 * @param $context ResourceLoaderContext
	 * @return array
	 */
	protected function getPages( ResourceLoaderContext $context ) {
		return array(
			'MediaWiki:WikiLove.js'      => array( 'type' => 'script' ),
		);
	}
}

Remove broken and obsolete WikiLoveLocal::getMessages() method

This returns NULL instead of Array due to the global no longer
existing as of 6e96cb0.

Change-Id: Ic89d3ee3e436a8b0d896c2362be1f408baeebd1f


<?php

/**
 * @file
 * Contains Drupal\Console\Command\GeneratorFormBaseCommand.
 */

namespace Drupal\Console\Command;

class FormBaseCommand extends FormCommand
{
    protected function configure()
    {
        $this->setFormType('FormBase');
        $this->setCommandName('generate:form');
        parent::configure();
    }
}

<?php

/**
 * @file
 * Contains Drupal\Console\Command\GeneratorFormBaseCommand.
 */

namespace Drupal\Console\Command\Generate;

use Drupal\Console\Command\Generate\FormCommand;

class FormBaseCommand extends FormCommand
{
    protected function configure()
    {
        $this->setFormType('FormBase');
        $this->setCommandName('generate:form');
        parent::configure();
    }
}

Modify the form base command

Modify the form base command


<?php declare(strict_types=1);

namespace Symplify\FlexLoader\Flex;

use function Safe\glob;

final class FlexPathsFactory
{
    /**
     * @return string[]
     */
    public function createServicePaths(string $projectDir, string $environment): array
    {
        $servicePaths = [
            $projectDir . '/config/packages/*',
            $projectDir . '/config/packages/' . $environment . '/**/*',
            $projectDir . '/config/services',
            $projectDir . '/config/services_' . $environment,
        ];

        return $this->filterExistingPaths($servicePaths);
    }

    /**
     * @return string[]
     */
    public function createRoutingPaths(string $projectDir, string $environment): array
    {
        $routingPaths = [
            $projectDir . '/config/routes/*',
            $projectDir . '/config/routes/' . $environment . '/**/*',
            $projectDir . '/config/routes',
        ];

        return $this->filterExistingPaths($routingPaths);
    }

    /**
     * This is needed, because $config->load() throws exception on non-existing glob paths
     * @param string[] $globPaths
     * @return string[]
     */
    private function filterExistingPaths(array $globPaths): array
    {
        $existingGlobPaths = [];
        foreach ($globPaths as $globPath) {
            if (glob($globPath)) {
                $existingGlobPaths[] = $globPath;
            }
        }

        return $existingGlobPaths;
    }
}

<?php declare(strict_types=1);

namespace Symplify\FlexLoader\Flex;

use Nette\Utils\Strings;
use function Safe\glob;

final class FlexPathsFactory
{
    /**
     * @return string[]
     */
    public function createServicePaths(string $projectDir, string $environment): array
    {
        $servicePaths = [
            $projectDir . '/config/packages/*',
            $projectDir . '/config/packages/' . $environment . '/**/*',
            $projectDir . '/config/services',
            $projectDir . '/config/services_' . $environment,
        ];

        return $this->filterExistingPaths($servicePaths);
    }

    /**
     * @return string[]
     */
    public function createRoutingPaths(string $projectDir, string $environment): array
    {
        $routingPaths = [
            $projectDir . '/config/routes/*',
            $projectDir . '/config/routes/' . $environment . '/**/*',
            $projectDir . '/config/routes',
        ];

        return $this->filterExistingPaths($routingPaths);
    }

    /**
     * This is needed, because $config->load() throws exception on non-existing glob paths
     * @param string[] $globPaths
     * @return string[]
     */
    private function filterExistingPaths(array $globPaths): array
    {
        $existingGlobPaths = [];
        foreach ($globPaths as $globPath) {
            // the final glob is decorated with *, so we need to check it here too
            if (! Strings::endsWith($globPath, '*')) {
                $checkedGlobPath = $globPath . '*';
            } else {
                $checkedGlobPath = $globPath;
            }

            if (glob($checkedGlobPath)) {
                $existingGlobPaths[] = $globPath;
            }
        }

        return $existingGlobPaths;
    }
}

[FlexLoader] Check for * missing paths in FlexPathsFatcory


<?php

require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';

PicoTools\container('db', function() {

    $db = new PicoDb\Database(array(
        'driver' => 'sqlite',
        'filename' => 'data/db.sqlite'
    ));

    if ($db->schema()->check(1)) {

        return $db;
    }
    else {

        die('Unable to migrate database schema.');
    }
});

<?php

require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';

function get_db_filename()
{
    return 'data/db.sqlite';
}

PicoTools\container('db', function() {

    $db = new PicoDb\Database(array(
        'driver' => 'sqlite',
        'filename' => get_db_filename()
    ));

    if ($db->schema()->check(1)) {

        return $db;
    }
    else {

        die('Unable to migrate database schema.');
    }
});

Replace hardcoded database path by a function (for future usage)


<?php
	include 'header.php';
 	require_once 'dbconfig.php';
 	require_once 'database.php';
 	$db = new Database(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
	$db->openConnection();

	if(!$db->isConnected()) {
		header("Location: cannotConnect.php");
		exit();
	}

	$sittings = $db->getSitting();

	$db->closeConnection();

 ?>

		Sittningar HT15

		<?php
			foreach($sittings as $row => $s) {
				$date = date('j/n', strtotime($s[0]));
				?>
				<div class="event-window" id="<?php echo $date; ?>">

						<?php echo $date; ?>

						Antal platser: 200

						 Se mer

					<button class="event-remove-button">Remove</button>

		<?php } ?>

<?php include 'footer.php'; ?>

<?php
	require_once 'header.php';
 	$dbHandler = new DatabaseHandler();
	$restaurant = $dbHandler->getRestaurant('Nilles nation');
	$sitting = $dbHandler->getSitting($_GET['sittDate']);
	$parties = $dbHandler->getParties($_GET['sittDate']);
	$dbHandler->disconnect();

 ?>

		Sittning <?php echo $sitting->date; ?>

Välkomna!

						Sällskap
						Antal

					<?php
						foreach ($parties as $key => $p) {
							?>

									<?php echo $p->name?>
									<?php echo $p->prel?>

							<?php
						}
					?>

<?php include 'footer.php'; ?>

Refactor to use dataconverted results

Refactor to use dataconverted results